@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.
Files changed (110) hide show
  1. package/dist/assets/txt/tool/agent-client.txt +6 -10
  2. package/dist/chunks/acp-AJ7O6XNE.mjs +22 -0
  3. package/dist/chunks/adapter-loader-VUS3UYMT.mjs +1 -0
  4. package/dist/chunks/{agent-CYRU65IN.mjs → agent-SKRC54QG.mjs} +1 -1
  5. package/dist/chunks/{agent-JHX64CI6.mjs → agent-VUPXBEWR.mjs} +1 -1
  6. package/dist/chunks/agent-service-registry-DPO5SSXA.mjs +1 -0
  7. package/dist/chunks/app-EPNEAPMS.mjs +58 -0
  8. package/dist/chunks/{auth-SUHJJM24.mjs → auth-34JK273T.mjs} +1 -1
  9. package/dist/chunks/bootstrap-3KXRWM6D.mjs +1 -0
  10. package/dist/chunks/build-program-2AR3LYQJ.mjs +11 -0
  11. package/dist/chunks/bus-QOWILU5Z.mjs +1 -0
  12. package/dist/chunks/chunk-2YNYVTYT.mjs +2 -0
  13. package/dist/chunks/{chunk-D4GDS5UI.mjs → chunk-3472MC45.mjs} +1 -1
  14. package/dist/chunks/{chunk-X7KLQIAQ.mjs → chunk-4OHDEBAX.mjs} +1 -1
  15. package/dist/chunks/chunk-BDS2JWYG.mjs +2 -0
  16. package/dist/chunks/{chunk-KTMZPMCI.mjs → chunk-EB3OP6TL.mjs} +1 -1
  17. package/dist/chunks/chunk-IJVW4VME.mjs +1 -0
  18. package/dist/chunks/{chunk-75IQNF4I.mjs → chunk-J6VEDKPT.mjs} +1 -1
  19. package/dist/chunks/{chunk-IEQ4VD66.mjs → chunk-JTVO3U27.mjs} +1 -1
  20. package/dist/chunks/chunk-LGMGGNPW.mjs +1 -0
  21. package/dist/chunks/{chunk-TYD2M4SP.mjs → chunk-MYI75W3D.mjs} +1 -1
  22. package/dist/chunks/{chunk-R4BPTF6V.mjs → chunk-PEMUENKB.mjs} +1 -1
  23. package/dist/chunks/{chunk-UBCLKZWP.mjs → chunk-WGJIT5HU.mjs} +1 -1
  24. package/dist/chunks/chunk-XMIQEMED.mjs +1051 -0
  25. package/dist/chunks/{command-CPT2YSIR.mjs → command-CJGBEATT.mjs} +1 -1
  26. package/dist/chunks/compaction-R4RTVEDY.mjs +1 -0
  27. package/dist/chunks/config-YSZNIWZT.mjs +1 -0
  28. package/dist/chunks/debug-GZCL57Q7.mjs +3 -0
  29. package/dist/chunks/event-2JDHF3UV.mjs +1 -0
  30. package/dist/chunks/file-G4WHJKUX.mjs +1 -0
  31. package/dist/chunks/gateway-D6XCB2OA.mjs +16 -0
  32. package/dist/chunks/gateway-loader-OH3VCEUD.mjs +1 -0
  33. package/dist/chunks/{generate-4UO6UCUB.mjs → generate-NYQCTBY7.mjs} +1 -1
  34. package/dist/chunks/{github-XIWTIRCK.mjs → github-IGWZXZRB.mjs} +2 -2
  35. package/dist/chunks/global-5WFCDQ45.mjs +1 -0
  36. package/dist/chunks/{import-K45ZW3NR.mjs → import-TYN474UK.mjs} +1 -1
  37. package/dist/chunks/installation-6S6OCY6F.mjs +1 -0
  38. package/dist/chunks/instance-YVRWMB6M.mjs +1 -0
  39. package/dist/chunks/loader-VV3FV5NS.mjs +1 -0
  40. package/dist/chunks/loader-XGUYA6ZM.mjs +1 -0
  41. package/dist/chunks/lsp-J7UR4JNX.mjs +1 -0
  42. package/dist/chunks/{mcp-JBHKJN6X.mjs → mcp-FYDYPGLE.mjs} +1 -1
  43. package/dist/chunks/mcp-GEZSPY2W.mjs +1 -0
  44. package/dist/chunks/models-JNSS4QSZ.mjs +1 -0
  45. package/dist/chunks/{pr-MCLQ6KQO.mjs → pr-DQZIG2CT.mjs} +1 -1
  46. package/dist/chunks/preferences-QCM3RIAL.mjs +1 -0
  47. package/dist/chunks/project-53ZMRKRI.mjs +1 -0
  48. package/dist/chunks/prompt-XYHKPB7Q.mjs +1 -0
  49. package/dist/chunks/provider-2RFHZVX4.mjs +1 -0
  50. package/dist/chunks/registry-GGSZXBFC.mjs +1 -0
  51. package/dist/chunks/revert-7RBPZDWL.mjs +1 -0
  52. package/dist/chunks/ripgrep-U54LYBZO.mjs +1 -0
  53. package/dist/chunks/{run-EGRUZXP2.mjs → run-EQ5GHPKF.mjs} +1 -1
  54. package/dist/chunks/scheduler-3AYHIZGY.mjs +1 -0
  55. package/dist/chunks/server-ITUF2HX7.mjs +1 -0
  56. package/dist/chunks/session-5OU5P7UF.mjs +1 -0
  57. package/dist/chunks/{session-VCIKEQYZ.mjs → session-R2LCLNAY.mjs} +1 -1
  58. package/dist/chunks/session-XA4RMN7D.mjs +1 -0
  59. package/dist/chunks/share-45SYUA47.mjs +1 -0
  60. package/dist/chunks/snapshot-YC3DAH7Q.mjs +1 -0
  61. package/dist/chunks/{stats-RPGHGZUR.mjs → stats-TREO4CFV.mjs} +1 -1
  62. package/dist/chunks/storage-6F64537E.mjs +1 -0
  63. package/dist/chunks/{tui-ZMS6CJQ7.mjs → tui-FVQHBIJ7.mjs} +1 -1
  64. package/dist/chunks/types-OIHWEQYC.mjs +1 -0
  65. package/dist/chunks/{update-KDCCJIPI.mjs → update-V3GTL4TX.mjs} +1 -1
  66. package/dist/cli.mjs +5 -5
  67. package/package.json +15 -14
  68. package/dist/chunks/acp-D5UOHKRU.mjs +0 -22
  69. package/dist/chunks/adapter-loader-SHO4LOSU.mjs +0 -1
  70. package/dist/chunks/app-S6QDTGNJ.mjs +0 -1
  71. package/dist/chunks/bootstrap-FHSG4M5N.mjs +0 -1
  72. package/dist/chunks/build-program-YDOM5ROT.mjs +0 -11
  73. package/dist/chunks/bus-7GPWVWOA.mjs +0 -1
  74. package/dist/chunks/chunk-CCRIJZBK.mjs +0 -1
  75. package/dist/chunks/chunk-EM2QJ5NQ.mjs +0 -59
  76. package/dist/chunks/chunk-FWVB6X4X.mjs +0 -1050
  77. package/dist/chunks/chunk-GRDTQW6K.mjs +0 -2
  78. package/dist/chunks/chunk-SB4J2R54.mjs +0 -2
  79. package/dist/chunks/chunk-ZBRXNYEM.mjs +0 -1
  80. package/dist/chunks/compaction-JR5FOLBX.mjs +0 -1
  81. package/dist/chunks/config-O5EE574O.mjs +0 -1
  82. package/dist/chunks/debug-BWJVMW7Q.mjs +0 -3
  83. package/dist/chunks/event-NO7SFKKX.mjs +0 -1
  84. package/dist/chunks/file-Q52INNX3.mjs +0 -1
  85. package/dist/chunks/gateway-XSXBPTB7.mjs +0 -16
  86. package/dist/chunks/gateway-loader-6P6BTWQP.mjs +0 -1
  87. package/dist/chunks/global-XQYOBWZR.mjs +0 -1
  88. package/dist/chunks/installation-55Z2PXMV.mjs +0 -1
  89. package/dist/chunks/instance-S5GBRS3K.mjs +0 -1
  90. package/dist/chunks/loader-JAKTXQ6M.mjs +0 -1
  91. package/dist/chunks/loader-S2BSLSAZ.mjs +0 -1
  92. package/dist/chunks/lsp-4VYPJGAN.mjs +0 -1
  93. package/dist/chunks/mcp-ZGGTG6YT.mjs +0 -1
  94. package/dist/chunks/models-TI5SNTLO.mjs +0 -1
  95. package/dist/chunks/preferences-LWCCEUB3.mjs +0 -1
  96. package/dist/chunks/project-OEBG6JHE.mjs +0 -1
  97. package/dist/chunks/prompt-JSZCNKQD.mjs +0 -1
  98. package/dist/chunks/provider-TU4AF2GP.mjs +0 -1
  99. package/dist/chunks/registry-NITFPORZ.mjs +0 -1
  100. package/dist/chunks/revert-PDDRJVNK.mjs +0 -1
  101. package/dist/chunks/ripgrep-7VVA7THG.mjs +0 -1
  102. package/dist/chunks/scheduler-VUQ33E5B.mjs +0 -1
  103. package/dist/chunks/server-3RDX4X3L.mjs +0 -1
  104. package/dist/chunks/session-GQAYKB6Q.mjs +0 -1
  105. package/dist/chunks/session-TXC5Z4O2.mjs +0 -1
  106. package/dist/chunks/share-RUV4SIRB.mjs +0 -1
  107. package/dist/chunks/snapshot-PXRGQ6JR.mjs +0 -1
  108. package/dist/chunks/storage-3T5H5KBY.mjs +0 -1
  109. package/dist/chunks/tui-5BQORL3N.mjs +0 -1
  110. package/dist/chunks/types-RWQQETDC.mjs +0 -1
@@ -1,1050 +0,0 @@
1
- import {b as b$2,a as a$a,c as c$2}from'./chunk-CCRIJZBK.mjs';import {a as a$8}from'./chunk-D4GDS5UI.mjs';import {f,e as e$1,c as c$3}from'./chunk-75IQNF4I.mjs';import {a as a$4,b,c as c$1}from'./chunk-ZBRXNYEM.mjs';import {b as b$4,a as a$b}from'./chunk-UBCLKZWP.mjs';import {e,h,g,i,f as f$1,o,m,r,q,l,n,p}from'./chunk-2RSIOAZV.mjs';import {a as a$9}from'./chunk-AAJAKVQY.mjs';import {i as i$1}from'./chunk-UNBJ6Y7L.mjs';import {a as a$3}from'./chunk-X7KLQIAQ.mjs';import {a as a$2,b as b$3}from'./chunk-KTMZPMCI.mjs';import {a as a$5}from'./chunk-CJTCCLW4.mjs';import {a as a$6}from'./chunk-GRDTQW6K.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-SB4J2R54.mjs';import {a as a$7,b as b$1,c,d}from'./chunk-X6ISXWBN.mjs';import U,{z}from'zod';import {PKG,Filesystem,Archive,$,NamedError,lazy,fn as fn$1,Identifier,whichSync,Shell,Wildcard,loadTextFile,parseModelId,lazyAsync,abortAfterAny,Fetch,iife,formatLocalISOCompact,git,AsyncQueue,defer,Slug,Context,PackageRegistry,proxied,withTimeout,Ignore,Token,createPkgShell,SessionTitle,Glob,TruncateContent,work,shell,loadTextFileAsync,retry}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 Ce from'path';import Ce__default,{join,sep}from'path';import {Decimal}from'decimal.js';import {convertToModelMessages,APICallError,LoadAPIKeyError,tool,jsonSchema,streamText,wrapLanguageModel,streamObject,generateObject,NoSuchModelError,asSchema,dynamicTool}from'ai';import nc from'os';import {mergeDeep,mapValues,pipe,values,sortBy,splitWhen,unique,clone,filter,map,fromEntries,pickBy,omit}from'remeda';import gl,{createReadStream,existsSync,readFileSync,constants}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 hy 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 vx from'open';import {HookEvent}from'@easbot/plugin';export{HookEvent as Ia}from'@easbot/plugin';import {initLog,createMemorySystem}from'@easbot/memory';import {initLog as initLog$1,createNoteKnowledge}from'@easbot/note';import {initLog as initLog$2,createCodebase}from'@easbot/codebase';import'@easbot/types';import {LRUCache}from'lru-cache';import {ndJsonStream,ClientSideConnection}from'@agentclientprotocol/sdk';import {GatewayClient}from'@easbot/gateway';import {glob}from'glob';import Uv from'bash-parser';import {createRequire}from'module';import {createInterface}from'readline';import rC from'turndown';import {parse}from'node-html-parser';import*as wC from'node-pty';import {createHash}from'crypto';import {ulid}from'ulid';import {zodToJsonSchema}from'zod-to-json-schema';import {HTTPException}from'hono/http-exception';import XA from'bonjour-service';import {serve}from'@hono/node-server';import {spawn}from'child_process';import qR from'zod/v4';var xn;(se=>{let e=a.create({service:"lsp.server"}),t=process.platform==="win32"?"cmd":void 0;function o(Q,q=[],F){let te=q.length>0?`${Q} ${q.join(" ")}`:Q,G=process.platform==="win32"?{...F,windowsHide:true}:F;return Shell.spawn(t,te,G)}function n(Q,q){let F=process.platform==="win32"?{...q,windowsHide:true}:q;return Shell.spawn(t,Q.join(" "),F)}function s(Q,q=[],F){return PKG.spawn([Q,...q],F)}async function r(Q,q){let F=process.platform==="win32"?{...q,windowsHide:true}:q;return Shell.run(t,Q,F)}let i=async Q=>Tt__default.stat(Q).then(()=>true).catch(()=>false),c=(Q,q)=>async F=>{if(q){let J=Filesystem.up({targets:q,start:Ce__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:Ce__default.dirname(F),stop:R.directory}),G=await te.next();return await te.return(void 0),G.value?Ce__default.dirname(G.value):R.directory};se.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 se.ServerInitTimeout)return se.ServerInitTimeout[Q];let q=Q.replace(/\s+/g,"_");if(q in se.ServerInitTimeout)return se.ServerInitTimeout[q];let F=Q.split(/\s+/).pop();return F&&F in se.ServerInitTimeout?se.ServerInitTimeout[F]:a$2.EASBOT_LSP_INIT_TIMEOUT}se.getServerInitTimeout=d,se.Deno={id:"deno",initTimeout:se.ServerInitTimeout.deno,root:async Q=>{let q=Filesystem.up({targets:["deno.json","deno.jsonc"],start:Ce__default.dirname(Q),stop:R.directory}),F=await q.next();if(await q.return(void 0),!!F.value)return Ce__default.dirname(F.value)},extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(Q){let q=await PKG.which("deno");if(!q){e.info("deno not found, please install deno first");return}return {process:o(q,["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"}];se.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:se.ServerInitTimeout.typescript,async spawn(Q){e.info("typescript server spawn",{PATH:process.env.PATH});let q=null,F;for(let J of f){if(e.info(`trying to find ${J.name}...`),q=await PKG.which(J.command),q){e.info(`${J.name} found`,{binary:q}),F=J;break}let oe=await PKG.resolve(J.name,R.directory).catch(()=>{});if(oe){q=oe,e.info(`${J.name} resolved`,{binary:q}),F=J;break}}if(!q||!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:q});let te=F.command==="vtsls"?["--stdio"]:["--stdio"];return {process:o(q,te,{cwd:Q,env:{...process.env},stderr:"ignore"})}}},se.Vue={id:"vue",initTimeout:se.ServerInitTimeout.vue,extensions:[".vue"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let q=await PKG.which("vue-language-server"),F=[];if(!q){let J=Ce__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 ce=await PKG.which();if(!ce)return;await o(ce,["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;q=oe,F.push("run",J);}if(!q)return;let te=await PKG.which();return te?{process:o(te,F,{cwd:Q}),initialization:{}}:void 0}},se.ESLint={id:"eslint",initTimeout:se.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=Ce__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=Ce__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=Ce__default.join(a$1.Path.bin,"vscode-eslint-main"),pe=Ce__default.join(a$1.Path.bin,"vscode-eslint");await Tt__default.stat(pe).catch(()=>{})&&(e.info("removing old eslint installation",{path:pe}),await Tt__default.rm(pe,{force:true,recursive:true})),await Tt__default.rename(me,pe);let qe=process.platform==="win32"?"npm.cmd":"npm";await $`${qe} install`.cwd(pe).quiet(),await $`${qe} run compile`.cwd(pe).quiet(),e.info("installed VS Code ESLint server",{serverPath:F});}let te=await PKG.which();return te?{process:o(te,[F,"--stdio"],{cwd:Q,env:{...process.env},stderr:"ignore"})}:void 0}},se.Oxlint={id:"oxlint",initTimeout:se.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 q=process.platform==="win32"?".cmd":"",F=Ce__default.join("node_modules",".bin","oxc_language_server"+q),te=Ce__default.join("node_modules",".bin","oxlint"+q),G=async ce=>{let me=Ce__default.join(Q,ce);if(await PKG.file(me).exists())return me;let pe=Filesystem.up({targets:[ce],start:Q,stop:R.worktree}),xe=await pe.next();if(await pe.return(void 0),xe.value)return xe.value},J=await G(te);if(!J){let ce=await PKG.which("oxlint");ce&&(J=ce);}if(J){let ce=o(J,["--help"],{stdout:"pipe"});if(await ce.exited,(await PKG.nodeReadableStreamToText(ce.stdout)).includes("--lsp"))return {process:o(J,["--lsp"],{cwd:Q,stderr:"ignore"})}}let oe=await G(F);if(!oe){let ce=await PKG.which("oxc_language_server");ce&&(oe=ce);}if(oe)return {process:o(oe,[],{cwd:Q,stderr:"ignore"})};e.info("oxlint not found, please install oxlint");}},se.Biome={id:"biome",initTimeout:se.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 q=process.platform==="win32",F=Ce__default.join(Q,"node_modules",".bin",q?"biome.cmd":"biome");if(await PKG.file(F).exists())return {process:o(F,["lsp-proxy","--stdio"],{cwd:Q,env:process.env,stderr:"ignore"})};let te=await PKG.which("biome");if(te)return {process:o(te,["lsp-proxy","--stdio"],{cwd:Q,env:process.env,stderr:"ignore"})};if(q){let ce=await PKG.which("biome.cmd");if(ce)return {process:o(ce,["lsp-proxy","--stdio"],{cwd:Q,env:process.env,stderr:"ignore"})}}let G=Ce__default.join(a$1.Path.bin,"node_modules","@biomejs","biome","bin","biome");if(!await PKG.file(G).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD){e.info("Biome LSP download disabled by flag");return}e.info("Installing @biomejs/biome...");let ce=await PKG.which();if(!ce){e.warn("Package manager not found");return}try{await o(ce,["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:o(J,["run",G,"lsp-proxy","--stdio"],{cwd:Q,env:process.env,timeout:false,stderr:"ignore"})}:void 0}},se.Gopls={id:"gopls",initTimeout:se.ServerInitTimeout.gopls,root:async Q=>{let q=await c(["go.work"])(Q);return q||c(["go.mod","go.sum"])(Q)},extensions:[".go"],async spawn(Q){let q=await PKG.which("gopls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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}q=Ce__default.join(a$1.Path.bin,"gopls"+(process.platform==="win32"?".exe":"")),e.info("installed gopls",{bin:q});}if(q)return {process:o(q)}}},se.Rubocop={id:"ruby-lsp",initTimeout:se.ServerInitTimeout.ruby_lsp,root:c(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(Q){let q=await PKG.which("rubocop",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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 G=await r(`gem install rubocop --bindir "${a$1.Path.bin}"`);if(G.code!==0){e.error("Failed to install rubocop",{stderr:G.stderr});return}q=Ce__default.join(a$1.Path.bin,"rubocop"+(process.platform==="win32"?".exe":"")),e.info("installed rubocop",{bin:q});}if(q)return {process:o(q,["--lsp"],{cwd:Q,stderr:"ignore"})}}},se.Ty={id:"ty",initTimeout:se.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 q=await PKG.which("ty"),F={},te=[process.env.VIRTUAL_ENV,Ce__default.join(Q,".venv"),Ce__default.join(Q,"venv")].filter(J=>J!==void 0);for(let J of te){let ce=process.platform==="win32"?Ce__default.join(J,"Scripts","python.exe"):Ce__default.join(J,"bin","python");if(await PKG.file(ce).exists()){F.pythonPath=ce;break}}if(!q)for(let J of te){let ce=process.platform==="win32"?Ce__default.join(J,"Scripts","ty.exe"):Ce__default.join(J,"bin","ty");if(await PKG.file(ce).exists()){q=ce;break}}if(!q){e.error("ty not found, please install ty first");return}return {process:o(q,["server"],{cwd:Q,stderr:"ignore"}),initialization:F}}},se.Pyright={id:"pyright",initTimeout:se.ServerInitTimeout.pyright,extensions:[".py",".pyi"],root:c(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(Q){let q=await PKG.which("pyright-langserver"),F=[];if(!q){let oe=Ce__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 ce=await PKG.which();if(!ce)return;q=ce,F.push("run",oe);}F.push("--stdio");let te={},G=[process.env.VIRTUAL_ENV,Ce__default.join(Q,".venv"),Ce__default.join(Q,"venv")].filter(oe=>oe!==void 0);for(let oe of G){let me=process.platform==="win32"?Ce__default.join(oe,"Scripts","python.exe"):Ce__default.join(oe,"bin","python");if(await PKG.file(me).exists()){te.pythonPath=me;break}}return q?{process:o(q,F,{cwd:Q,env:{...process.env},stderr:"ignore"}),initialization:te}:void 0}},se.ElixirLS={id:"elixir-ls",initTimeout:se.ServerInitTimeout.elixir_ls,extensions:[".ex",".exs"],root:c(["mix.exs","mix.lock"]),async spawn(Q){let q=await PKG.which("elixir-ls");if(!q){let F=Ce__default.join(a$1.Path.bin,"elixir-ls");if(q=Ce__default.join(a$1.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await PKG.file(q).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 G=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!G.ok)return;let J=Ce__default.join(a$1.Path.bin,"elixir-ls.zip");if(await PKG.write(J,G),!await Archive.extractZip(J,a$1.Path.bin).then(()=>true).catch(ce=>(e.error("Failed to extract elixir-ls archive",{error:ce}),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(Ce__default.join(a$1.Path.bin,"elixir-ls-master")).env({MIX_ENV:"prod",...process.env}),e.info("installed elixir-ls",{path:F});}}if(q)return {process:o(q)}}},se.Zls={id:"zls",initTimeout:se.ServerInitTimeout.zls,extensions:[".zig",".zon"],root:c(["build.zig"]),async spawn(Q){let q=await PKG.which("zls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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 G=await te.json(),J=process.platform,oe=process.arch,ce="",me=oe;oe==="arm64"?me="aarch64":oe==="x64"?me="x86_64":oe==="ia32"&&(me="x86");let pe=J;J==="darwin"?pe="macos":J==="win32"&&(pe="windows");let xe=J==="win32"?"zip":"tar.xz";if(ce=`zls-${me}-${pe}.${xe}`,!["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(ce)){e.error(`Platform ${J} and architecture ${oe} is not supported by zls`);return}let Ie=G.assets.find(Ae=>Ae.name===ce);if(!Ie){e.error(`Could not find asset ${ce} in latest zls release`);return}let we=Ie.browser_download_url,re=await fetch(we);if(!re.ok){e.error("Failed to download zls");return}let Ee=Ce__default.join(a$1.Path.bin,ce);if(await PKG.write(Ee,re),xe==="zip"){if(!await Archive.extractZip(Ee,a$1.Path.bin).then(()=>true).catch(_t=>(e.error("Failed to extract zls archive",{error:_t}),false)))return}else await $`tar -xf ${Ee}`.cwd(a$1.Path.bin).quiet().nothrow();if(await Tt__default.rm(Ee,{force:true}),q=Ce__default.join(a$1.Path.bin,"zls"+(J==="win32"?".exe":"")),!await PKG.file(q).exists()){e.error("Failed to extract zls binary");return}J!=="win32"&&await $`chmod +x ${q}`.quiet().nothrow(),e.info("installed zls",{bin:q});}return {process:o(q,[],{cwd:Q,stderr:"ignore"})}}},se.CSharp={id:"csharp",initTimeout:se.ServerInitTimeout.csharp,root:c([".slnx",".sln",".csproj","global.json"]),extensions:[".cs"],async spawn(Q){let q=await PKG.which("csharp-ls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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}q=Ce__default.join(a$1.Path.bin,"csharp-ls"+(process.platform==="win32"?".exe":"")),e.info("installed csharp-ls",{bin:q});}return {process:o(q,[],{cwd:Q,stderr:"ignore"})}}},se.FSharp={id:"fsharp",initTimeout:se.ServerInitTimeout.fsharp,root:c([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(Q){let q=await PKG.which("fsautocomplete",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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}q=Ce__default.join(a$1.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":"")),e.info("installed fsautocomplete",{bin:q});}if(q)return {process:o(q,[],{cwd:Q,stderr:"ignore"})}}},se.SourceKit={id:"sourcekit-lsp",initTimeout:se.ServerInitTimeout.sourcekit_lsp,extensions:[".swift",".objc","objcpp"],root:c(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(Q){let q=await PKG.which("sourcekit-lsp");if(q)return {process:o(q,[],{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 G=await te.text();if(G)return {process:o(G.trim(),[],{cwd:Q,stderr:"ignore"})}}},se.RustAnalyzer={id:"rust",initTimeout:se.ServerInitTimeout.rust,root:async Q=>{let q=await c(["Cargo.toml","Cargo.lock"])(Q);if(q===void 0)return;let F=q;for(;F!==Ce__default.dirname(F);){let te=Ce__default.join(F,"Cargo.toml");try{if((await PKG.file(te).text()).includes("[workspace]"))return F}catch{}let G=Ce__default.dirname(F);if(G===F||(F=G,!F.startsWith(R.worktree)))break}return q},extensions:[".rs"],async spawn(Q){let q=await PKG.which("rust-analyzer");if(!q){e.info("rust-analyzer not found in path, please install it");return}return {process:s(q,[],{cwd:Q,stderr:"ignore"})}}},se.Clangd={id:"clangd",initTimeout:se.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 q=["--background-index","--clang-tidy"],F=await PKG.which("clangd");if(F)return {process:s(F,q,{cwd:Q,stderr:"ignore"})};let te=process.platform==="win32"?".exe":"",G=Ce__default.join(a$1.Path.bin,"clangd"+te);if(await PKG.file(G).exists())return {process:s(G,q,{cwd:Q,stderr:"ignore"})};let J=await Tt__default.readdir(a$1.Path.bin,{withFileTypes:true}).catch(()=>[]);for(let It of J){if(!It.isDirectory()||!It.name.startsWith("clangd_"))continue;let tr=Ce__default.join(a$1.Path.bin,It.name,"bin","clangd"+te);if(await PKG.file(tr).exists())return {process:s(tr,q,{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 ce=await oe.json(),me=ce.tag_name;if(!me){e.error("clangd release did not include a tag name");return}let pe=process.platform,qe={darwin:"mac",linux:"linux",win32:"windows"}[pe];if(!qe){e.error(`Platform ${pe} is not supported by clangd auto-download`);return}let Ie=ce.assets??[],we=It=>!It.name||!It.browser_download_url||!It.name.includes(qe)?false:It.name.includes(me),re=Ie.find(It=>we(It)&&It.name?.endsWith(".zip"))??Ie.find(It=>we(It)&&It.name?.endsWith(".tar.xz"))??Ie.find(It=>we(It));if(!re?.name||!re.browser_download_url){e.error("clangd could not match release asset",{tag:me,platform:pe});return}let Ee=re.name,Ae=await fetch(re.browser_download_url);if(!Ae.ok){e.error("Failed to download clangd");return}let _t=Ce__default.join(a$1.Path.bin,Ee),ko=await Ae.arrayBuffer();if(ko.byteLength===0){e.error("Failed to write clangd archive");return}await PKG.write(_t,Buffer.from(ko));let Do=Ee.endsWith(".zip"),Po=Ee.endsWith(".tar.xz");if(!Do&&!Po){e.error("clangd encountered unsupported asset",{asset:Ee});return}if(Do&&!await Archive.extractZip(_t,a$1.Path.bin).then(()=>true).catch(tr=>(e.error("Failed to extract clangd archive",{error:tr}),false)))return;Po&&await $`tar -xf ${_t}`.cwd(a$1.Path.bin).quiet().nothrow(),await Tt__default.rm(_t,{force:true});let Gt=Ce__default.join(a$1.Path.bin,"clangd_"+me,"bin","clangd"+te);if(!await PKG.file(Gt).exists()){e.error("Failed to extract clangd binary");return}return pe!=="win32"&&await $`chmod +x ${Gt}`.quiet().nothrow(),await Tt__default.unlink(Ce__default.join(a$1.Path.bin,"clangd")).catch(()=>{}),await Tt__default.symlink(Gt,Ce__default.join(a$1.Path.bin,"clangd")).catch(()=>{}),e.info("installed clangd",{bin:Gt}),{process:o(Gt,q,{cwd:Q,stderr:"ignore"})}}},se.Svelte={id:"svelte",initTimeout:se.ServerInitTimeout.svelte,extensions:[".svelte"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let q=await PKG.which("svelteserver"),F=[];if(!q){let G=Ce__default.join(a$1.Path.bin,"node_modules","svelte-language-server","bin","server.js");if(!await PKG.file(G).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;q=J,F.push("run",G);}return q?(F.push("--stdio"),{process:o(q,F,{cwd:Q,env:{...process.env},stderr:"ignore"}),initialization:{}}):void 0}},se.Astro={id:"astro",initTimeout:se.ServerInitTimeout.astro,extensions:[".astro"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let q=await PKG.resolve("typescript/lib/tsserver.js",R.directory).catch(()=>{});if(!q){e.info("typescript not found, required for Astro language server");return}let F=Ce__default.dirname(q),te=await PKG.which("astro-ls"),G=[];if(!te){let oe=Ce__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 ce=await PKG.which();if(!ce)return;te=ce,G.push("run",oe);}return te?(G.push("--stdio"),{process:o(te,G,{cwd:Q,env:{...process.env},stderr:"ignore"}),initialization:{typescript:{tsdk:F}}}):void 0}},se.JDTLS={id:"jdtls",initTimeout:se.ServerInitTimeout.jdtls,root:c(["pom.xml","build.gradle","build.gradle.kts",".project",".classpath"]),extensions:[".java"],async spawn(Q){let q=await PKG.which("java");if(!q){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 we=/"(\d+)\.\d+\.\d+"/.exec(F.stderr?.toString()??"");return we?.[1]?parseInt(we[1],10):void 0})();if(te==null||te<21){e.error("JDTLS requires at least Java 21.");return}let G=Ce__default.join(a$1.Path.bin,"jdtls"),J=Ce__default.join(G,"plugins");if(!await i(J)){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading JDTLS LSP server."),await Tt__default.mkdir(G,{recursive:true});let we="https://www.eclipse.org/downloads/download.php?file=/jdtls/snapshots/jdt-language-server-latest.tar.gz",re="release.tar.gz";e.info("Downloading JDTLS archive",{url:we,dest:G});let Ee=await $`curl -L -o ${re} '${we}'`.cwd(G).quiet().nothrow();if(Ee.exitCode!==0){e.error("Failed to download JDTLS",{exitCode:Ee.exitCode,stderr:Ee.stderr.toString()});return}e.info("Extracting JDTLS archive");let Ae=await $`tar -xzf ${re}`.cwd(G).quiet().nothrow();if(Ae.exitCode!==0){e.error("Failed to extract JDTLS",{exitCode:Ae.exitCode,stderr:Ae.stderr.toString()});return}await Tt__default.rm(Ce__default.join(G,re),{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 pe=Ce__default.join(J,me);if(!await i(pe)){e.error(`Failed to locate the JDTLS launcher module in the installed directory: ${G}.`);return}let xe=Ce__default.join(G,(()=>{switch(process.platform){case "darwin":return "config_mac";case "linux":return "config_linux";case "win32":return "config_win";default:return "config_linux"}})()),qe=await Tt__default.mkdtemp(Ce__default.join(nc.tmpdir(),"easbot-jdtls-data"));return {process:n([q,"-jar",pe,"-configuration",xe,"-data",qe,"-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})}}},se.KotlinLS={id:"kotlin-ls",initTimeout:se.ServerInitTimeout.kotlin_ls,extensions:[".kt",".kts"],root:async Q=>{let q=await c(["settings.gradle.kts","settings.gradle"])(Q);if(q)return q;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 q=Ce__default.join(a$1.Path.bin,"kotlin-ls"),F=process.platform==="win32"?Ce__default.join(q,"kotlin-lsp.cmd"):Ce__default.join(q,"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 G=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!G.ok){e.error("Failed to fetch kotlin-lsp release info");return}let oe=(await G.json()).name?.replace(/^v/,"");if(!oe){e.error("Could not determine Kotlin LSP version from release");return}let ce=process.platform,me=process.arch,pe=me;me==="arm64"?pe="aarch64":me==="x64"&&(pe="x64");let xe=ce;ce==="darwin"?xe="mac":ce==="linux"?xe="linux":ce==="win32"&&(xe="win");let qe=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],Ie=`${xe}-${pe}`;if(!qe.includes(Ie)){e.error(`Platform ${ce}/${me} is not supported by Kotlin LSP`);return}let we=`kotlin-lsp-${oe}-${xe}-${pe}.zip`,re=`https://download-cdn.jetbrains.com/kotlin-lsp/${oe}/${we}`;await Tt__default.mkdir(q,{recursive:true});let Ee=Ce__default.join(q,"kotlin-ls.zip");if(await $`curl -L -o '${Ee}' '${re}'`.quiet().nothrow(),!await Archive.extractZip(Ee,q).then(()=>true).catch(_t=>(e.error("Failed to extract Kotlin LS archive",{error:_t}),false)))return;await Tt__default.rm(Ee,{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: ${q}.`);return}return {process:o(F,["--stdio"],{cwd:Q,stderr:"ignore"})}}},se.YamlLS={id:"yaml-ls",initTimeout:se.ServerInitTimeout.yaml,extensions:[".yaml",".yml"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Q){let q=await PKG.which("yaml-language-server"),F=[];if(!q){let G=Ce__default.join(a$1.Path.bin,"node_modules","yaml-language-server","out","server","src","server.js");if(!await PKG.file(G).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let ce=await PKG.which();if(!ce)return;await r(`${ce} install yaml-language-server`,{cwd:a$1.Path.bin,env:{...process.env}});}let oe=await PKG.which();if(!oe)return;q=oe,F.push("run",G);}return q?(F.push("--stdio"),{process:o(q,F,{cwd:Q,env:{...process.env},stderr:"ignore"})}):void 0}},se.LuaLS={id:"lua-ls",initTimeout:se.ServerInitTimeout.lua,root:c([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(Q){let q=await PKG.which("lua-language-server",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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(),G=process.platform,J=process.arch,oe="",ce=J;J==="arm64"?ce="arm64":J==="x64"?ce="x64":J==="ia32"&&(ce="ia32");let me=G;G==="darwin"?me="darwin":G==="linux"?me="linux":G==="win32"&&(me="win32");let pe=G==="win32"?"zip":"tar.gz";oe=`lua-language-server-${te.tag_name}-${me}-${ce}.${pe}`;let xe=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],qe=`${me}-${ce}.${pe}`;if(!xe.includes(qe)){e.error(`Platform ${G} and architecture ${J} is not supported by lua-language-server`);return}let Ie=te.assets.find(ko=>ko.name===oe);if(!Ie){e.error(`Could not find asset ${oe} in latest lua-language-server release`);return}let we=Ie.browser_download_url,re=await fetch(we);if(!re.ok){e.error("Failed to download lua-language-server");return}let Ee=Ce__default.join(a$1.Path.bin,oe);await PKG.write(Ee,re);let Ae=Ce__default.join(a$1.Path.bin,`lua-language-server-${ce}-${me}`);if(await Tt__default.stat(Ae).catch(()=>{})&&await Tt__default.rm(Ae,{force:true,recursive:true}),await Tt__default.mkdir(Ae,{recursive:true}),pe==="zip"){if(!await Archive.extractZip(Ee,Ae).then(()=>true).catch(Do=>(e.error("Failed to extract lua-language-server archive",{error:Do}),false)))return}else if(!await $`tar -xzf ${Ee} -C ${Ae}`.quiet().then(()=>true).catch(Do=>(e.error("Failed to extract lua-language-server archive",{error:Do}),false)))return;if(await Tt__default.rm(Ee,{force:true}),q=Ce__default.join(Ae,"bin","lua-language-server"+(G==="win32"?".exe":"")),!await PKG.file(q).exists()){e.error("Failed to extract lua-language-server binary");return}if(G!=="win32"&&!await $`chmod +x ${q}`.quiet().catch(Do=>{e.error("Failed to set executable permission for lua-language-server binary",{error:Do});}))return;e.info("installed lua-language-server",{bin:q});}return {process:o(q,[],{cwd:Q,stderr:"ignore"})}}},se.PHPIntelephense={id:"php intelephense",initTimeout:se.ServerInitTimeout.intelephense,extensions:[".php"],root:c(["composer.json","composer.lock",".php-version"]),async spawn(Q){let q=await PKG.which("intelephense"),F=[];if(!q){let G=Ce__default.join(a$1.Path.bin,"node_modules","intelephense","lib","intelephense.js");if(!await PKG.file(G).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;q=J,F.push("run",G);}return q?(F.push("--stdio"),{process:o(q,F,{cwd:Q,env:{...process.env}}),initialization:{telemetry:{enabled:false}}}):void 0}},se.Prisma={id:"prisma",initTimeout:se.ServerInitTimeout.prisma,extensions:[".prisma"],root:c(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(Q){let q=await PKG.which("prisma");if(!q){e.info("prisma not found, please install prisma");return}return {process:o(q,["language-server"],{cwd:Q,stderr:"ignore"})}}},se.Dart={id:"dart",initTimeout:se.ServerInitTimeout.dart,extensions:[".dart"],root:c(["pubspec.yaml","analysis_options.yaml"]),async spawn(Q){let q=await PKG.which("dart");if(!q){e.info("dart not found, please install dart first");return}return {process:s(q,["language-server","--lsp"],{cwd:Q,stderr:"ignore"})}}},se.Ocaml={id:"ocaml-lsp",initTimeout:se.ServerInitTimeout.ocaml_lsp,extensions:[".ml",".mli"],root:c(["dune-project","dune-workspace",".merlin","opam"]),async spawn(Q){let q=await PKG.which("ocamllsp");if(!q){e.info("ocamllsp not found, please install ocaml-lsp-server");return}return {process:s(q,[],{cwd:Q,stderr:"ignore"})}}},se.BashLS={id:"bash",initTimeout:se.ServerInitTimeout.bash,extensions:[".sh",".bash",".zsh",".ksh"],root:async()=>R.directory,async spawn(Q){let q=await PKG.which("bash-language-server"),F=[];if(!q){let G=Ce__default.join(a$1.Path.bin,"node_modules","bash-language-server","out","cli.js");if(!await PKG.file(G).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;q=J,F.push("run",G);}return q?(F.push("start"),{process:o(q,F,{cwd:Q,env:{...process.env}})}):void 0}},se.TerraformLS={id:"terraform",initTimeout:se.ServerInitTimeout.terraform,extensions:[".tf",".tfvars"],root:c([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(Q){let q=await PKG.which("terraform-ls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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(),G=te.tag_name?.replace("v","");if(!G){e.error("terraform-ls release did not include a version tag");return}let J=process.platform,ce=process.arch==="arm64"?"arm64":"amd64",pe=`terraform-ls_${G}_${J==="win32"?"windows":J}_${ce}.zip`,qe=(te.assets??[]).find(Ee=>Ee.name===pe);if(!qe?.browser_download_url){e.error(`Could not find asset ${pe} in terraform-ls release`);return}let Ie=await fetch(qe.browser_download_url);if(!Ie.ok){e.error("Failed to download terraform-ls");return}let we=Ce__default.join(a$1.Path.bin,pe);if(await PKG.write(we,Ie),!await Archive.extractZip(we,a$1.Path.bin).then(()=>true).catch(Ee=>(e.error("Failed to extract terraform-ls archive",{error:Ee}),false)))return;if(await Tt__default.rm(we,{force:true}),q=Ce__default.join(a$1.Path.bin,"terraform-ls"+(J==="win32"?".exe":"")),!await PKG.file(q).exists()){e.error("Failed to extract terraform-ls binary");return}J!=="win32"&&await $`chmod +x ${q}`.quiet().nothrow(),e.info("installed terraform-ls",{bin:q});}return {process:s(q,["serve"],{cwd:Q,stderr:"ignore"}),initialization:{experimentalFeatures:{prefillRequiredFields:true,validateOnSave:true}}}}},se.TexLab={id:"texlab",initTimeout:se.ServerInitTimeout.texlab,extensions:[".tex",".bib"],root:c([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(Q){let q=await PKG.which("texlab",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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,ce=process.arch==="arm64"?"aarch64":"x86_64",me=J==="darwin"?"macos":J==="win32"?"windows":"linux",pe=J==="win32"?"zip":"tar.gz",xe=`texlab-${ce}-${me}.${pe}`,Ie=(te.assets??[]).find(Ee=>Ee.name===xe);if(!Ie?.browser_download_url){e.error(`Could not find asset ${xe} in texlab release`);return}let we=await fetch(Ie.browser_download_url);if(!we.ok){e.error("Failed to download texlab");return}let re=Ce__default.join(a$1.Path.bin,xe);if(await PKG.write(re,we),pe==="zip"&&!await Archive.extractZip(re,a$1.Path.bin).then(()=>true).catch(Ae=>(e.error("Failed to extract texlab archive",{error:Ae}),false)))return;if(pe==="tar.gz"&&await $`tar -xzf ${re}`.cwd(a$1.Path.bin).quiet().nothrow(),await Tt__default.rm(re,{force:true}),q=Ce__default.join(a$1.Path.bin,"texlab"+(J==="win32"?".exe":"")),!await PKG.file(q).exists()){e.error("Failed to extract texlab binary");return}J!=="win32"&&await $`chmod +x ${q}`.quiet().nothrow(),e.info("installed texlab",{bin:q});}return {process:s(q,[],{cwd:Q,stderr:"ignore"})}}},se.DockerfileLS={id:"dockerfile",initTimeout:se.ServerInitTimeout.dockerfile,extensions:[".dockerfile","Dockerfile"],root:async()=>R.directory,async spawn(Q){let q=await PKG.which("docker-langserver"),F=[];if(!q){let G=Ce__default.join(a$1.Path.bin,"node_modules","dockerfile-language-server-nodejs","lib","server.js");if(!await PKG.file(G).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;q=J,F.push("run",G);}return q?(F.push("--stdio"),{process:o(q,F,{cwd:Q,env:{...process.env}})}):void 0}},se.Gleam={id:"gleam",initTimeout:se.ServerInitTimeout.gleam,extensions:[".gleam"],root:c(["gleam.toml"]),async spawn(Q){let q=await PKG.which("gleam");if(!q){e.info("gleam not found, please install gleam first");return}return {process:s(q,["lsp"],{cwd:Q,stderr:"ignore"})}}},se.Clojure={id:"clojure-lsp",initTimeout:se.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 q=await PKG.which("clojure-lsp");if(!q&&process.platform==="win32"&&(q=await PKG.which("clojure-lsp.exe")),!q){e.info("clojure-lsp not found, please install clojure-lsp first");return}return {process:s(q,["listen"],{cwd:Q,stderr:"ignore"})}}},se.Nixd={id:"nixd",initTimeout:se.ServerInitTimeout.nixd,extensions:[".nix"],root:async Q=>{let q=await c(["flake.nix"])(Q);return q&&q!==R.directory?q:R.worktree&&R.worktree!==R.directory?R.worktree:R.directory},async spawn(Q){let q=await PKG.which("nixd");if(!q){e.info("nixd not found, please install nixd first");return}return {process:s(q,[],{cwd:Q,env:{...process.env},stderr:"ignore"})}}},se.Tinymist={id:"tinymist",initTimeout:se.ServerInitTimeout.tinymist,extensions:[".typ",".typc"],root:c(["typst.toml"]),async spawn(Q){let q=await PKG.which("tinymist",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!q){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(),G=process.platform,oe=process.arch==="arm64"?"aarch64":"x86_64",ce,me;G==="darwin"?(ce="apple-darwin",me="tar.gz"):G==="win32"?(ce="pc-windows-msvc",me="zip"):(ce="unknown-linux-gnu",me="tar.gz");let pe=`tinymist-${oe}-${ce}.${me}`,qe=(te.assets??[]).find(re=>re.name===pe);if(!qe?.browser_download_url){e.error(`Could not find asset ${pe} in tinymist release`);return}let Ie=await fetch(qe.browser_download_url);if(!Ie.ok){e.error("Failed to download tinymist");return}let we=Ce__default.join(a$1.Path.bin,pe);if(await PKG.write(we,Ie),me==="zip"){if(!await Archive.extractZip(we,a$1.Path.bin).then(()=>true).catch(Ee=>(e.error("Failed to extract tinymist archive",{error:Ee}),false)))return}else await $`tar -xzf ${we} --strip-components=1`.cwd(a$1.Path.bin).quiet().nothrow();if(await Tt__default.rm(we,{force:true}),q=Ce__default.join(a$1.Path.bin,"tinymist"+(G==="win32"?".exe":"")),!await PKG.file(q).exists()){e.error("Failed to extract tinymist binary");return}G!=="win32"&&await $`chmod +x ${q}`.quiet().nothrow(),e.info("installed tinymist",{bin:q});}return {process:s(q,[],{cwd:Q,stderr:"ignore"})}}},se.HLS={id:"haskell-language-server",initTimeout:se.ServerInitTimeout.haskell_language_server,extensions:[".hs",".lhs"],root:c(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(Q){let q=await PKG.which("haskell-language-server-wrapper");if(!q){e.info("haskell-language-server-wrapper not found, please install haskell-language-server");return}return {process:s(q,["--lsp"],{cwd:Q,stderr:"ignore"})}}};})(xn||(xn={}));var jp=(n=>(n.STDIO="stdio",n.HTTP="http",n.WS="websocket",n))(jp||{});function zy(e){return e==="local"?"stdio":e}var Lp=z.object({command:z.string(),args:z.array(z.string())}),Dp=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)}),qy=z.object({stdio:Lp.optional(),http:Dp.optional(),ws:$p.optional()});function Hy(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 By=z.object({id:z.string().min(1),options:z.record(z.string(),z.unknown()).optional()}),Gy=z.object({agent:z.string().optional(),model:By.optional()}),Fp=z.object({directory:z.string().default(process.cwd()),enabled:z.boolean().default(true),channel:z.preprocess(zy,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),agentId:z.string().optional(),stdio:Lp.optional(),http:Dp.optional(),ws:$p.optional(),agent:Gy.optional()}).refine(e=>!!Hy(e.hostname),{message:"Invalid hostname format",path:["hostname"]}).transform(e=>{let o={stdio:"stdio",http:"http",websocket:"websocket"}[e.channel]??"websocket";return {...e,channel:o}}),Wy=z.object({id:z.string().min(1),name:z.string().min(1),type:z.enum(["easbot","custom"]),agentId:z.string().optional(),channel:z.enum(["stdio","http","websocket"]).optional(),connection:qy,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 n={stdio:"stdio",http:"http",websocket:"websocket"}[t]??"websocket";return {...e,channel:n}}),Np=z.object({clients:z.array(Wy).min(1),defaultClientId:z.string().optional()});z.object({server:Fp});z.object({clients:Np});var zd=z.object({server:Fp,clients:Np.optional()}),Up={enabled:true,directory:process.cwd(),channel:"websocket",port:3e3,hostname:"localhost",timeout:3e4};var qd=U.object({model:U.string().optional().describe("Embedding model, defaults to config embedding model"),batchSize:U.number().int().positive().optional().describe("Batch size for embedding operations"),dimensions:U.number().int().positive().optional().describe("Embedding dimensions (optional, auto-detect)")}).optional(),Hd=U.object({maxResults:U.number().int().positive().optional().describe("Max search results"),minScore:U.number().min(0).max(1).optional().describe("Min score threshold (default: 0.3)"),hybrid:U.object({enabled:U.boolean().optional().describe("Enable hybrid search"),vectorWeight:U.number().min(0).max(1).optional().describe("Vector search weight (default: 0.7)"),textWeight:U.number().min(0).max(1).optional().describe("FTS text search weight (default: 0.3)")}).optional().describe("Hybrid search configuration")}).optional().describe("Search configuration"),zp=U.object({ignorePatterns:U.array(U.string()).optional().describe("File patterns to ignore"),batchSize:U.number().int().positive().optional().describe("Batch size for indexing"),incremental:U.boolean().optional().describe("Enable incremental indexing")}).optional(),qp=U.object({onBoot:U.boolean().optional().describe("Sync on boot"),onSearch:U.boolean().optional().describe("Sync on search"),onSessionStart:U.boolean().optional().describe("Sync on session start"),intervalMs:U.number().int().positive().optional().describe("Sync interval in milliseconds")}).optional().describe("Sync configuration"),Bd=U.object({dictPath:U.array(U.string()).optional().describe("Custom dictionary paths")}).optional().describe("Tokenizer configuration"),Vy=U.object({model:U.string().optional().describe("Rerank model, defaults to config rerank_model"),topK:U.number().int().positive().optional().describe("Number of candidates for reranking")}).optional().describe("Rerank configuration"),Hp=U.object({model:U.string().optional().describe("Graph LLM model, defaults to config graph_model"),entityExtractionPrompt:U.string().optional().describe("Entity extraction prompt template"),relationExtractionPrompt:U.string().optional().describe("Relation extraction prompt template")}).optional().describe("Graph LLM configuration for entity and relation extraction"),Ea=U.object({enabled:U.boolean().optional().describe("Enable codebase knowledge base"),database:U.string().optional().describe("Codebase database path"),embedding:qd,search:Hd,indexer:zp,tokenizer:Bd,sync:qp,parser:U.object({languages:U.array(U.string()).optional().describe("Supported languages"),lazyLoad:U.boolean().optional().describe("Lazy load parsers")}).optional().describe("Code parser configuration")}).optional().describe("Codebase knowledge base configuration"),Aa=U.object({enabled:U.boolean().optional().describe("Enable memory knowledge base"),workspaceDir:U.string().optional().describe("Memory workspace directory (contains MEMORY.md, active/, archive/)"),sessionsDir:U.string().optional().describe("Sessions directory for extracting historical long-term memory"),database:U.string().optional().describe("Memory database path"),embedding:qd,graph:Hp,search:Hd,tokenizer:Bd,archiveDays:U.number().int().positive().optional().describe("Days before archiving memories (default: 30)"),shortTermMaxRounds:U.number().int().positive().optional().describe("Max rounds for short-term memory (default: 20)")}).optional().describe("Memory knowledge base configuration"),Ra=U.object({enabled:U.boolean().optional().describe("Enable note knowledge base"),database:U.string().optional().describe("Note database path"),search:Hd,indexer:zp,tokenizer:Bd,sync:qp,embedding:qd,graph:Hp,rerank:Vy,extraPaths:U.array(U.string()).optional().describe("Extra search paths (extended directories)"),sources:U.array(U.enum(["docs"])).optional().describe("Source types"),chunkSize:U.number().int().positive().optional().describe("Chunk size"),chunkOverlap:U.number().int().min(0).optional().describe("Chunk overlap size")}).optional().describe("Note knowledge base configuration"),To=a.create({service:"knowledge-loader"});async function sr(){try{let t=(await he.get())?.note;if(!t){To.debug("No note config found in Config.Info");return}let o=Ra.safeParse(t);if(o.success)return To.debug("Note config loaded"),o.data;To.warn("Invalid note config",{issues:o.error.issues});return}catch(e){To.error("Failed to load note config",{error:e});return}}async function rr(){try{let t=(await he.get())?.codebase;if(!t){To.debug("No codebase config found in Config.Info");return}let o=Ea.safeParse(t);if(o.success)return To.debug("Codebase config loaded"),o.data;To.warn("Invalid codebase config",{issues:o.error.issues});return}catch(e){To.error("Failed to load codebase config",{error:e});return}}async function ir(){try{let e=await he.get();To.debug("loadMemory() configState.memory",{memoryConfig:e?.memory});let t=e?.memory;if(!t){To.debug("No memory config found in Config.Info");return}let o=Aa.safeParse(t);if(o.success)return To.debug("Memory config loaded",{data:o.data}),o.data;To.warn("Invalid memory config",{issues:o.error.issues});return}catch(e){To.error("Failed to load memory config",{error:e});return}}async function Gd(){let e={},[t,o,n]=await Promise.all([sr(),rr(),ir()]);return t&&(e.note=t),o&&(e.codebase=o),n&&(e.memory=n),To.debug("Knowledge configs loaded",{types:Object.keys(e),count:Object.keys(e).length}),e}var Bp="easbot-oauth-dummy-key",Qe;(d=>{d.Oauth=U.object({type:U.literal("oauth"),refresh:U.string(),access:U.string(),expires:U.number(),accountId:U.string().optional(),enterpriseUrl:U.string().optional()}).meta({ref:"OAuth"}),d.Api=U.object({type:U.literal("api"),key:U.string()}).meta({ref:"ApiAuth"}),d.WellKnown=U.object({type:U.literal("wellknown"),key:U.string(),token:U.string()}).meta({ref:"WellKnownAuth"}),d.Info=U.discriminatedUnion("type",[d.Oauth,d.Api,d.WellKnown]).meta({ref:"Auth"});let s=Ce__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 rn(e,t){let o=mergeDeep(e,t);return e.plugin&&t.plugin&&(o.plugin=Array.from(new Set([...e.plugin,...t.plugin]))),e.instructions&&t.instructions&&(o.instructions=Array.from(new Set([...e.instructions,...t.instructions]))),o}var Vd=a.create({service:"config"});async function sb(e){try{return await Tt__default.access(e,constants.W_OK),!0}catch{return false}}async function ci(e){if(!await sb(e))return Vd.debug("config dir is not writable, skipping dependency install",{dir:e}),false;let o=Ce__default.join(e,"node_modules");if(!existsSync(o))return true;let n=Ce__default.join(e,"package.json"),s=PKG.file(n);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)?(Vd.info("Cached version is outdated, proceeding with install",{pkg:"@easbot/plugin",cachedVersion:l}),true):false:l!==d}async function di(e){let t=Ce__default.join(e,"package.json"),o=b$3.isLocal()?"*":b$3.getVersion(),n=await PKG.file(t).json().catch(()=>({}));n.dependencies={...n.dependencies,"@easbot/plugin":o},await PKG.write(t,JSON.stringify(n,null,2)),await new Promise(d=>setTimeout(d,3e3));let s=Ce__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){Vd.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 Jd=a.create({service:"config"}),Mn=NamedError.create("ConfigJsonError",U.object({path:U.string(),message:U.string().optional()})),an=NamedError.create("ConfigInvalidError",U.object({path:U.string(),issues:U.custom().optional(),message:U.string().optional()}));async function cn(e){Jd.info("loading",{path:e});let t=await PKG.file(e).text().catch(o=>{if(o.code!=="ENOENT")throw new Mn({path:e},{cause:o})});return t?cr(t,e):{}}async function cr(e,t){let o=e;e=e.replace(/\{env:([^}]+)\}/g,(c,l)=>process.env[l]||"");let n=e.match(/\{file:[^}]+\}/g);if(n){let c=Ce__default.dirname(t),l=e.split(`
3
- `);for(let d of n){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=Ce__default.join(nc.homedir(),a.slice(2)));let p=Ce__default.isAbsolute(a)?a:Ce__default.resolve(c,a),u=(await PKG.file(p).text().catch(h=>{let g=`bad file reference: "${d}"`;throw h.code==="ENOENT"?new an({path:t,message:g+` ${p} does not exist`},{cause:h}):new an({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 Mn({path:t,message:`
9
- --- JSONC Input ---
10
- ${e}
11
- --- Errors ---
12
- ${l}
13
- --- End ---`})}let i=lr.safeParse(r);if(i.success){if(!i.data.$schema){i.data.$schema="https://easbot.cn/config.json";let l=o.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 Jd.error("Configuration validation failed",{path:t,issues:i.error.issues}),new an({path:t,issues:i.error.issues})}function dr(e,t){let o=[],n=parse$1(e,o,{allowTrailingComma:true});if(o.length>0){let r=e.split(`
15
- `),i=o.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 Mn({path:t,message:`
20
- --- JSONC Input ---
21
- ${e}
22
- --- Errors ---
23
- ${i}
24
- --- End ---`})}let s=lr.safeParse(n);if(s.success)return s.data;throw Jd.error("Configuration validation failed",{path:t,issues:s.error.issues}),new an({path:t,issues:s.error.issues})}var lb=a.create({service:"config"});function ub(e,t){for(let o of t){let n=e.indexOf(o);if(n!==-1)return e.slice(n+o.length)}}function pb(e){let t=Ce__default.extname(e);return t.length>0?e.slice(0,-t.length):e}var mb=new PKG.Glob("{agent,agents}/**/*.md");async function li(e){let{Agent:t}=await import('./types-RWQQETDC.mjs'),o={};for await(let n of mb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e})){let s=await a$9.parse(n).catch(async m=>{let f=a$9.FrontmatterError.isInstance(m)?m.data.message:`Failed to parse agent ${n}`,{Session:a}=await import('./session-TXC5Z4O2.mjs');await ue.publish(a.Event.Error,{error:new NamedError.Unknown({message:f}).toObject()}),lb.error("failed to load agent",{agent:n,err:m});});if(!s)continue;let i=ub(n,["/.easbot/agent/","/.easbot/agents/","/agent/","/agents/"])??Ce__default.basename(n),l={name:pb(i),...s.data,prompt:s.content.trim()},d=t.safeParse(l);if(d.success){o[l.name]=d.data;continue}throw new an({path:n,issues:d.error.issues},{cause:d.error})}return o}var yb=a.create({service:"config"});function bb(e,t){for(let o of t){let n=e.indexOf(o);if(n!==-1)return e.slice(n+o.length)}}function wb(e){let t=Ce__default.extname(e);return t.length>0?e.slice(0,-t.length):e}var xb=new PKG.Glob("{command,commands}/**/*.md");async function ui(e){let{Command:t}=await import('./types-RWQQETDC.mjs'),o={};for await(let n of xb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e})){let s=await a$9.parse(n).catch(async m=>{let f=a$9.FrontmatterError.isInstance(m)?m.data.message:`Failed to parse command ${n}`,{Session:a}=await import('./session-TXC5Z4O2.mjs');await ue.publish(a.Event.Error,{error:new NamedError.Unknown({message:f}).toObject()}),yb.error("failed to load command",{command:n,err:m});});if(!s)continue;let i=bb(n,["/.easbot/command/","/.easbot/commands/","/command/","/commands/"])??Ce__default.basename(n),l={name:wb(i),...s.data,template:s.content.trim()},d=t.safeParse(l);if(d.success){o[l.name]=d.data;continue}throw new an({path:n,issues:d.error.issues},{cause:d.error})}return o}var kb=new PKG.Glob("{plugin,plugins}/*.{ts,js}");async function pi(e){let t=[];for await(let o of kb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e}))t.push(pathToFileURL(o).href);return t}function Oa(e){if(e.startsWith("file://"))return Ce__default.parse(new URL(e).pathname).name;let t=e.lastIndexOf("@");return t>0?e.substring(0,t):e}function mi(e){let t=new Set,o=[];for(let n of e.toReversed()){let s=Oa(n);t.has(s)||(t.add(s),o.push(n));}return o.toReversed()}var ur=a.create({service:"config"}),Yp=process.env.EASBOT_TEST_MANAGED_CONFIG_DIR||Ob();function Ob(){switch(process.platform){case "darwin":return "/Library/Application Support/easbot";case "win32":return Ce__default.join(process.env.ProgramData||"C:\\ProgramData","easbot");default:return "/etc/easbot"}}var Xd;function jb(){return Xd||(Xd=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,ur.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=rn(t,await cr(JSON.stringify(l),`${s}/.well-known/easbot`)),ur.debug("loaded remote config from well-known",{url:s});}if(t=rn(t,await hi()),!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=rn(t,await cn(i));}a$2.EASBOT_CONFIG&&(t=rn(t,await cn(a$2.EASBOT_CONFIG)),ur.debug("loaded custom config",{path:a$2.EASBOT_CONFIG})),t.agent=t.agent||{},t.plugin=t.plugin||[];let o=[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&&(o.push(a$2.EASBOT_CONFIG_DIR),ur.debug("loading config from EASBOT_CONFIG_DIR",{path:a$2.EASBOT_CONFIG_DIR}));let n=[];for(let s of unique(o)){if(s.endsWith(".easbot")||s===a$2.EASBOT_CONFIG_DIR)for(let r of ["easbot.json"])ur.debug(`loading config from ${Ce__default.join(s,r)}`),t=rn(t,await cn(Ce__default.join(s,r))),t.agent??(t.agent={}),t.plugin??(t.plugin=[]);n.push(iife(async()=>{await ci(s)&&await di(s);})),t.command=mergeDeep(t.command??{},await ui(s)),t.agent=mergeDeep(t.agent,await li(s)),t.plugin.push(...await pi(s));}if(a$2.EASBOT_CONFIG_CONTENT&&(t=rn(t,JSON.parse(a$2.EASBOT_CONFIG_CONTENT)),ur.debug("loaded custom config from EASBOT_CONFIG_CONTENT")),existsSync(Yp))for(let s of ["easbot.json"])t=rn(t,await cn(Ce__default.join(Yp,s)));if(a$2.EASBOT_PERMISSION&&(t.permission=mergeDeep(t.permission??{},JSON.parse(a$2.EASBOT_PERMISSION))),t.tools){await import('./types-RWQQETDC.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=nc.userInfo().username),t.autoshare===true&&!t.share&&(t.share="auto"),!t.keybinds){let{Info:s}=await import('./types-RWQQETDC.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=mi(t.plugin??[]),{config:t,directories:o,deps:n}})),Xd}function pr(){return jb()()}async function Qd(){let e=await pr().then(t=>t.deps);await Promise.all(e);}async function On(){return pr().then(e=>e.config)}async function Zd(){return pr().then(e=>e.directories)}var hi=lazy(async()=>{let e={},{pipe:t}=await import('remeda');return e=t({},mergeDeep(await cn(Ce__default.join(a$1.Path.config,"easbot.json")))),e});async function el(){return hi()}var Db=U.object({enabled:U.boolean().optional(),timeThresholdMs:U.number().int().nonnegative().optional(),keepRecentTools:U.number().int().positive().optional(),tokenThreshold:U.number().int().nonnegative().optional(),protectedTools:U.array(U.string()).optional()}),$b=U.object({enabled:U.boolean().optional(),ttlMs:U.number().int().positive().optional(),maxSizeBytes:U.number().int().positive().optional(),maxEntries:U.number().int().positive().optional(),persist:U.boolean().optional()}),tl=U.object({auto:U.boolean().optional(),prune:Db.optional(),reserved:U.number().int().min(0).optional(),backup:$b.optional()}),Qp=a.create({service:"compaction-loader"}),Zp={enabled:true,timeThresholdMs:3e5,keepRecentTools:3,tokenThreshold:5e3,protectedTools:["skill"]},em={enabled:true,ttlMs:3e5,maxSizeBytes:25*1024*1024,maxEntries:100,persist:false},tm={auto:true};async function yi(){try{let t=(await On())?.compaction??{},o={prune:mergeDeep(Zp,t.prune??{}),backup:mergeDeep(em,t.backup??{}),auto:t.auto??tm.auto,reserved:t.reserved};return Qp.debug("compaction config loaded",{auto:o.auto,pruneEnabled:o?.prune?.enabled,backupEnabled:o?.backup?.enabled}),o}catch(e){return Qp.warn("failed to load compaction config, using defaults",{error:String(e)}),{prune:Zp,backup:em,auto:tm.auto}}}async function ol(){return yi()}async function Fb(){return (await ol()).auto!==false}async function Nb(){return (await ol())?.prune?.enabled!==false}async function Ub(){return (await ol())?.backup?.enabled!==false}var Hb=U.enum(e),Bb=U.enum(h),Gb=U.enum(["read","write"]),Wb=U.object({name:U.string(),description:U.string().optional(),type:U.enum(["system","extension"]).default("extension"),scope:Bb.default("all"),priority:U.number().int().default(1e3),owner:U.array(U.string()).optional(),share:U.array(U.string()).optional(),permission:Gb.default("read"),dynamic:U.boolean().optional()}),Vb=U.record(U.string(),U.array(U.string())),Kb=U.object({maxEntries:U.number().int().positive().optional(),maxBytes:U.number().int().positive().optional(),timestampCheck:U.boolean().optional()}),Jb=U.object({charsPerToken:U.number().positive().optional()}),nl=U.object({mode:Hb.optional(),fileCache:Kb.optional(),tokenEstimation:Jb.optional(),maxTokens:U.number().int().nonnegative().optional(),searchMaxResults:U.number().int().positive().optional(),files:U.record(U.string(),Wb).optional(),contextFiles:Vb.optional()}),om=a.create({service:"context-loader"}),Yb={maxEntries:100,maxBytes:25*1024*1024,timestampCheck:true},Xb={charsPerToken:4},nm={mode:"general",maxTokens:2e3,searchMaxResults:3};function Qb(){return Yb}function Zb(){return Xb}async function bi(){try{let t=(await On()).context??{},o=mergeDeep(nm,t);return om.debug("loaded context config",{context:o}),o}catch(e){return om.warn("failed to load context config from config, using defaults",{error:String(e)}),nm}}var sm=a.create({service:"subagent-loader"}),ja=U.enum(["ephemeral","persistent"]).meta({ref:"SubAgentRunMode"}),sl=U.enum(["stdio","http","websocket","cli"]).meta({ref:"SubAgentTransportType"}),rl=U.object({modelId:U.string().describe("Model ID"),providerId:U.string().describe("Provider ID")}).strict().meta({ref:"SubAgentModel"}),il=U.object({name:U.string().describe("Unique name for this agent"),role:U.string().describe("Agent role type (e.g., researcher, planner, coder, executor)"),transport:sl.describe("Transport type for communication"),runMode:ja.describe("Run mode: ephemeral or persistent"),uri:U.string().optional().describe("Connection URI for HTTP/WebSocket transport"),command:U.string().optional().describe("Command to execute for StdIO/CLI transport"),args:U.string().array().optional().describe("Command line arguments"),env:U.record(U.string(),U.string()).optional().describe("Environment variables to pass to subprocess"),timeout:U.number().int().positive().optional().describe("Timeout in milliseconds"),maxConcurrent:U.number().int().positive().optional().describe("Maximum concurrent instances"),cwd:U.string().optional().describe("Working directory for subprocess"),mcpServers:U.string().array().optional().describe("MCP server list to pass to subprocess"),agentConfig:U.object({model:rl.optional().describe("Model configuration"),system:U.string().optional().describe("System prompt"),tools:U.record(U.string(),U.boolean()).optional().describe("Tools to enable")}).strict().optional().describe("Agent-specific configuration")}).strict().meta({ref:"SubAgentConfig"}),La=U.object({enabled:U.boolean().optional().default(true).describe("Enable SubAgent system"),defaultRunMode:ja.optional().default("ephemeral").describe("Default run mode"),timeout:U.number().int().positive().optional().default(12e4).describe("Global timeout in milliseconds"),maxConcurrent:U.number().int().positive().optional().default(5).describe("Maximum concurrent agents"),idleTimeout:U.number().int().positive().optional().default(1800*1e3).describe("Idle timeout in milliseconds"),idleCheckInterval:U.number().int().positive().optional().default(300*1e3).describe("Idle cleanup check interval in milliseconds"),agents:U.array(il).optional().default([]).describe("List of SubAgent configurations")}).strict().meta({ref:"SubAgentConfigSchema"}),rm={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 mr(){try{let t=(await On())?.subagent??{},{agents:o,...n}=rm;t.agents=o.concat(t?.agents??[]);let s=mergeDeep(n,t);return sm.debug("subagent config loaded",{enabled:s.enabled,agentCount:s.agents.length}),s}catch(e){return sm.warn("failed to load subagent config, using defaults",{error:String(e)}),rm}}async function ow(){return mr()}var Is=U.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"}),Da=U.object({type:U.literal("local").describe("Type of MCP server connection"),command:U.string().describe("Command to run the MCP server"),args:U.string().array().optional().describe("Arguments to pass to the command"),env:U.record(U.string(),U.string()).optional().describe("Environment variables to set when running the MCP server"),enabled:U.boolean().optional().describe("Enable or disable the MCP server on startup"),timeout:U.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),description:U.string().optional().describe("Description of the MCP server"),scope:U.enum(h).optional().default(g.All).describe("Context mode scope for the MCP server: all/general/coder. Defaults to all.")}).strict().meta({ref:"McpLocalConfig"}),$a=U.object({clientId:U.string().optional().describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),clientSecret:U.string().optional().describe("OAuth client secret (if required by the authorization server)"),scope:U.string().optional().describe("OAuth scopes to request during authorization")}).strict().meta({ref:"McpOAuthConfig"}),Fa=U.object({type:U.literal("remote").describe("Type of MCP server connection"),url:U.string().describe("URL of the remote MCP server"),enabled:U.boolean().optional().describe("Enable or disable the MCP server on startup"),headers:U.record(U.string(),U.string()).optional().describe("Headers to send with the request"),oauth:U.union([$a,U.literal(false)]).optional().describe("OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection."),timeout:U.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),description:U.string().optional().describe("Description of the MCP server"),scope:U.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"}),Na=U.discriminatedUnion("type",[Da,Fa]),Xo=U.enum(["ask","allow","deny"]).meta({ref:"PermissionActionConfig"}),Ua=U.record(U.string(),Xo).meta({ref:"PermissionObjectConfig"}),gt=U.union([Xo,Ua]).meta({ref:"PermissionRuleConfig"}),sw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?{__originalKeys:Object.keys(e),...e}:e,rw=e=>{if(typeof e=="string")return {"*":e};let t=e,{__originalKeys:o,...n}=t;if(!o)return n;let s={};for(let r of o)r in n&&(s[r]=n[r]);return s},wi=U.preprocess(sw,U.object({__originalKeys:U.string().array().optional(),read:gt.optional(),edit:gt.optional(),glob:gt.optional(),grep:gt.optional(),list:gt.optional(),bash:gt.optional(),task:gt.optional(),external_directory:gt.optional(),todo:Xo.optional(),question:Xo.optional(),webfetch:Xo.optional(),websearch:Xo.optional(),codesearch:Xo.optional(),lsp:gt.optional(),doom_loop:Xo.optional(),skill:gt.optional(),pty_session:gt.optional(),pty_manage:gt.optional(),write:gt.optional(),multiedit:gt.optional(),note:gt.optional(),memory:gt.optional(),codebase:gt.optional(),agent_client:gt.optional(),gateway:gt.optional(),apply_patch:gt.optional(),batch:gt.optional(),plan:gt.optional()}).catchall(gt).or(Xo)).transform(rw).meta({ref:"PermissionConfig"}),za=U.object({template:U.string(),description:U.string().optional(),agent:U.string().optional(),model:Is.optional(),subtask:U.boolean().optional(),scope:U.enum(h).optional().describe("Context mode scope")}),qa=U.object({paths:U.array(U.string()).optional().describe("Additional paths to skill folders"),urls:U.array(U.string()).optional().describe("URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)")}),dn=U.object({model:Is.optional(),variant:U.string().optional().describe("Default model variant for this agent (applies only when using the agent's configured model)."),temperature:U.number().optional(),top_p:U.number().optional(),prompt:U.string().optional(),tools:U.record(U.string(),U.boolean()).optional().describe("@deprecated Use 'permission' field instead"),disable:U.boolean().optional(),description:U.string().optional().describe("Description of when to use the agent"),mode:U.enum(["subagent","primary","all"]).optional(),hidden:U.boolean().optional().describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),options:U.record(U.string(),U.any()).optional(),color:U.union([U.string().regex(/^#[0-9a-fA-F]{6}$/,"Invalid hex color format"),U.enum(["primary","secondary","accent","success","warning","error","info"])]).optional().describe("Hex color code (e.g., #FF5733) or theme color (e.g., primary)"),steps:U.number().int().positive().optional().describe("Maximum number of agentic iterations before forcing text-only response"),maxSteps:U.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),permission:wi.optional()}).catchall(U.any()).transform((e,t)=>{let o=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools"]),n={...e.options};for(let[i,c]of Object.entries(e))o.has(i)||(n[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:n,permission:s,steps:r}}).meta({ref:"AgentConfig"}),Ha=U.object({leader:U.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),app_exit:U.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),editor_open:U.string().optional().default("<leader>e").describe("Open external editor"),theme_list:U.string().optional().default("<leader>t").describe("List available themes"),sidebar_toggle:U.string().optional().default("<leader>b").describe("Toggle sidebar"),scrollbar_toggle:U.string().optional().default("none").describe("Toggle session scrollbar"),username_toggle:U.string().optional().default("none").describe("Toggle username visibility"),status_view:U.string().optional().default("<leader>s").describe("View status"),session_export:U.string().optional().default("<leader>x").describe("Export session to editor"),session_new:U.string().optional().default("<leader>n").describe("Create a new session"),session_list:U.string().optional().default("<leader>l").describe("List all sessions"),session_timeline:U.string().optional().default("<leader>g").describe("Show session timeline"),session_fork:U.string().optional().default("none").describe("Fork session from message"),session_rename:U.string().optional().default("ctrl+r").describe("Rename session"),session_delete:U.string().optional().default("ctrl+d").describe("Delete session"),stash_delete:U.string().optional().default("ctrl+d").describe("Delete stash entry"),model_provider_list:U.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),model_favorite_toggle:U.string().optional().default("ctrl+f").describe("Toggle model favorite status"),session_share:U.string().optional().default("none").describe("Share current session"),session_unshare:U.string().optional().default("none").describe("Unshare current session"),session_interrupt:U.string().optional().default("escape").describe("Interrupt current session"),session_compact:U.string().optional().default("<leader>c").describe("Compact the session"),messages_page_up:U.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),messages_page_down:U.string().optional().default("pagedown,ctrl+alt+f").describe("Scroll messages down by one page"),messages_line_up:U.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),messages_line_down:U.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),messages_half_page_up:U.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),messages_half_page_down:U.string().optional().default("ctrl+alt+d").describe("Scroll messages down by half page"),messages_first:U.string().optional().default("ctrl+g,home").describe("Navigate to first message"),messages_last:U.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),messages_next:U.string().optional().default("none").describe("Navigate to next message"),messages_previous:U.string().optional().default("none").describe("Navigate to previous message"),messages_last_user:U.string().optional().default("none").describe("Navigate to last user message"),messages_copy:U.string().optional().default("<leader>y").describe("Copy message"),messages_undo:U.string().optional().default("<leader>u").describe("Undo message"),messages_redo:U.string().optional().default("<leader>r").describe("Redo message"),messages_toggle_conceal:U.string().optional().default("<leader>h").describe("Toggle code block concealment in messages"),tool_details:U.string().optional().default("none").describe("Toggle tool details visibility"),model_list:U.string().optional().default("<leader>m").describe("List available models"),model_cycle_recent:U.string().optional().default("f2").describe("Next recently used model"),model_cycle_recent_reverse:U.string().optional().default("shift+f2").describe("Previous recently used model"),model_cycle_favorite:U.string().optional().default("none").describe("Next favorite model"),model_cycle_favorite_reverse:U.string().optional().default("none").describe("Previous favorite model"),command_list:U.string().optional().default("ctrl+p").describe("List available commands"),agent_list:U.string().optional().default("<leader>a").describe("List agents"),agent_cycle:U.string().optional().default("tab").describe("Next agent"),agent_cycle_reverse:U.string().optional().default("shift+tab").describe("Previous agent"),variant_cycle:U.string().optional().default("ctrl+t").describe("Cycle model variants"),input_clear:U.string().optional().default("ctrl+c").describe("Clear input field"),input_paste:U.string().optional().default("ctrl+v").describe("Paste from clipboard"),input_submit:U.string().optional().default("return").describe("Submit input"),input_newline:U.string().optional().default("shift+return,ctrl+return,alt+return,ctrl+j").describe("Insert newline in input"),input_move_left:U.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),input_move_right:U.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),input_move_up:U.string().optional().default("up").describe("Move cursor up in input"),input_move_down:U.string().optional().default("down").describe("Move cursor down in input"),input_select_left:U.string().optional().default("shift+left").describe("Select left in input"),input_select_right:U.string().optional().default("shift+right").describe("Select right in input"),input_select_up:U.string().optional().default("shift+up").describe("Select up in input"),input_select_down:U.string().optional().default("shift+down").describe("Select down in input"),input_line_home:U.string().optional().default("ctrl+a").describe("Move to start of line in input"),input_line_end:U.string().optional().default("ctrl+e").describe("Move to end of line in input"),input_select_line_home:U.string().optional().default("ctrl+shift+a").describe("Select to start of line in input"),input_select_line_end:U.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),input_visual_line_home:U.string().optional().default("alt+a").describe("Move to start of visual line in input"),input_visual_line_end:U.string().optional().default("alt+e").describe("Move to end of visual line in input"),input_select_visual_line_home:U.string().optional().default("alt+shift+a").describe("Select to start of visual line in input"),input_select_visual_line_end:U.string().optional().default("alt+shift+e").describe("Select to end of visual line in input"),input_buffer_home:U.string().optional().default("home").describe("Move to start of buffer in input"),input_buffer_end:U.string().optional().default("end").describe("Move to end of buffer in input"),input_select_buffer_home:U.string().optional().default("shift+home").describe("Select to start of buffer in input"),input_select_buffer_end:U.string().optional().default("shift+end").describe("Select to end of buffer in input"),input_delete_line:U.string().optional().default("ctrl+shift+d").describe("Delete line in input"),input_delete_to_line_end:U.string().optional().default("ctrl+k").describe("Delete to end of line in input"),input_delete_to_line_start:U.string().optional().default("ctrl+u").describe("Delete to start of line in input"),input_backspace:U.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),input_delete:U.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),input_undo:U.string().optional().default("ctrl+-,super+z").describe("Undo in input"),input_redo:U.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),input_word_forward:U.string().optional().default("alt+f,alt+right,ctrl+right").describe("Move word forward in input"),input_word_backward:U.string().optional().default("alt+b,alt+left,ctrl+left").describe("Move word backward in input"),input_select_word_forward:U.string().optional().default("alt+shift+f,alt+shift+right").describe("Select word forward in input"),input_select_word_backward:U.string().optional().default("alt+shift+b,alt+shift+left").describe("Select word backward in input"),input_delete_word_forward:U.string().optional().default("alt+d,alt+delete,ctrl+delete").describe("Delete word forward in input"),input_delete_word_backward:U.string().optional().default("ctrl+w,ctrl+backspace,alt+backspace").describe("Delete word backward in input"),history_previous:U.string().optional().default("up").describe("Previous history item"),history_next:U.string().optional().default("down").describe("Next history item"),session_child_cycle:U.string().optional().default("<leader>right").describe("Next child session"),session_child_cycle_reverse:U.string().optional().default("<leader>left").describe("Previous child session"),session_parent:U.string().optional().default("<leader>up").describe("Go to parent session"),terminal_suspend:U.string().optional().default("ctrl+z").describe("Suspend terminal"),terminal_title_toggle:U.string().optional().default("none").describe("Toggle terminal title"),tips_toggle:U.string().optional().default("<leader>h").describe("Toggle tips on home screen"),display_thinking:U.string().optional().default("none").describe("Toggle thinking blocks visibility")}).strict().meta({ref:"KeybindsConfig"}),Ba=U.object({scroll_speed:U.number().min(.001).optional().describe("TUI scroll speed"),scroll_acceleration:U.object({enabled:U.boolean().describe("Enable scroll acceleration")}).optional().describe("Scroll acceleration settings"),diff_style:U.enum(["auto","stacked"]).optional().describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column")}),Ga=U.object({port:U.number().int().positive().optional().describe("Port to listen on"),hostname:U.string().optional().describe("Hostname to listen on"),mdns:U.boolean().optional().describe("Enable mDNS service discovery"),mdnsDomain:U.string().optional().describe("Custom domain name for mDNS service (default: easbot.local)"),cors:U.array(U.string()).optional().describe("Additional domains to allow for CORS")}).strict().meta({ref:"ServerConfig"}),Wa=U.enum(["auto","stretch"]).meta({ref:"LayoutConfig"}),Va=a$3.Provider.partial().extend({whitelist:U.array(U.string()).optional(),blacklist:U.array(U.string()).optional(),models:U.record(U.string(),a$3.Model.partial().extend({variants:U.record(U.string(),U.object({disabled:U.boolean().optional().describe("Disable this variant for the model")}).catchall(U.any())).optional().describe("Variant-specific configuration")})).optional(),options:U.object({apiKey:U.string().optional(),baseURL:U.string().optional(),enterpriseUrl:U.string().optional().describe("GitHub Enterprise URL for copilot authentication"),setCacheKey:U.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),timeout:U.union([U.number().int().positive().describe("Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."),U.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(U.any()).optional()}).strict().meta({ref:"ProviderConfig"}),lr=U.object({$schema:U.string().optional().describe("JSON schema reference for configuration validation"),theme:U.string().optional().describe("Theme name to use for the interface"),keybinds:Ha.optional().describe("Custom keybind configurations"),logLevel:a.Level.optional().describe("Log level"),tui:Ba.optional().describe("TUI specific settings"),server:Ga.optional().describe("Server configuration for easbot serve and web commands"),command:U.record(U.string(),za).optional().describe("Command configuration, see https://easbot.cn/docs/commands"),skills:qa.optional().describe("Additional skill folder paths"),watcher:U.object({ignore:U.array(U.string()).optional()}).optional(),plugin:U.string().array().optional(),snapshot:U.boolean().optional(),share:U.enum(["manual","auto","disabled"]).optional().describe("Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing"),autoshare:U.boolean().optional().describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),autoupdate:U.union([U.boolean(),U.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:U.array(U.string()).optional().describe("Disable providers that are loaded automatically"),enabled_providers:U.array(U.string()).optional().describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),model:Is.describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),small_model:Is.describe("Small model to use for tasks like title generation in the format of provider/model").optional(),default_agent:U.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:U.string().optional().describe("Custom username to display in conversations instead of system username"),agent:U.object({plan:dn.optional(),build:dn.optional(),general:dn.optional(),explore:dn.optional(),title:dn.optional(),summary:dn.optional(),compaction:dn.optional()}).catchall(dn).optional().describe("Agent configuration, see https://easbot.cn/docs/agents"),provider:U.record(U.string(),Va).optional().describe("Custom provider configurations and model overrides"),mcp:U.record(U.string(),U.union([Na,U.object({enabled:U.boolean()}).strict()])).optional().describe("MCP (Model Context Protocol) server configurations"),acp:zd.optional(),gateway:a$4.optional().describe("Gateway configuration for multi-channel communication"),subagent:La.optional().describe("SubAgent system configuration"),formatter:U.union([U.literal(false),U.record(U.string(),U.object({disabled:U.boolean().optional(),command:U.array(U.string()).optional(),environment:U.record(U.string(),U.string()).optional(),extensions:U.array(U.string()).optional()}))]).optional(),lsp:U.union([U.literal(false),U.record(U.string(),U.union([U.object({disabled:U.literal(true)}),U.object({command:U.array(U.string()),extensions:U.array(U.string()).optional(),disabled:U.boolean().optional(),env:U.record(U.string(),U.string()).optional(),initialization:U.record(U.string(),U.any()).optional()})]))]).optional().refine(e=>{if(!e||typeof e=="boolean")return true;let t=new Set(Object.values(xn).filter(o=>"id"in o&&"extensions"in o&&"spawn"in o).map(o=>o.id));return Object.entries(e).every(([o,n])=>n.disabled||t.has(o)?true:!!n.extensions)},{error:"For custom LSP servers, 'extensions' array is required."}),instructions:U.array(U.string()).optional().describe("Additional instruction files or patterns to include"),layout:Wa.optional().describe("@deprecated Always uses stretch layout."),permission:wi.optional(),tools:U.record(U.string(),U.boolean()).optional(),enterprise:U.object({url:U.string().optional().describe("Enterprise URL")}).optional(),compaction:tl.optional(),context:nl.optional(),embedding_model:U.string().optional().describe("Embedding model, defaults to easbot-local/bge-base-zh-v1.5"),graph_model:U.string().optional().describe("Graph model for entity and relation extraction, defaults to easbot-local/qwen2.5-7b-instruct"),rerank_model:U.string().optional().describe("Rerank model for search result reranking, defaults to easbot-local/qwen2.5-7b-instruct"),codebase:Ea.optional(),memory:Aa.optional(),note:Ra.optional(),local:U.string().optional(),timezone:U.string().optional(),experimental:U.object({disable_paste_summary:U.boolean().optional(),batch_tool:U.boolean().optional().describe("Enable the batch tool"),openTelemetry:U.boolean().optional().describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),primary_tools:U.array(U.string()).optional().describe("Tools that should only be available to primary agents."),continue_loop_on_deny:U.boolean().optional().describe("Continue the agent loop when a tool call is denied"),mcp_timeout:U.number().int().positive().optional().describe("Timeout in milliseconds for model context protocol (MCP) requests")}).optional()}).strict().meta({ref:"Config"});var mt=new EventEmitter;function uw(){let e=["easbot.json"].map(t=>Ce__default.join(a$1.Path.config,t));for(let t of e)if(existsSync(t))return t;return e[0]}function pw(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function cm(e,t,o=[]){if(!pw(t)){let n=modify(e,o,t,{formattingOptions:{insertSpaces:true,tabSize:2}});return applyEdits(e,n)}return Object.entries(t).reduce((n,[s,r])=>r===void 0?n:cm(n,r,[...o,s]),e)}async function al(e){let t=Ce__default.join(R.directory,"config.json"),o=await cn(t);await PKG.write(t,JSON.stringify(mergeDeep(o,e),null,2)),await R.dispose();}async function cl(e){let{global:t}=await import('./loader-JAKTXQ6M.mjs'),o=uw();if(!o)throw new Mn({path:"global",message:"Could not determine global config file path"});let n=await PKG.file(o).text().catch(r=>{if(r.code==="ENOENT")return "{}";throw new Mn({path:o},{cause:r})}),s=await(async()=>{if(!o.endsWith(".jsonc")){let c=dr(n,o),l=mergeDeep(c,e);return await PKG.write(o,JSON.stringify(l,null,2)),l}let r=cm(n,e),i=dr(r,o);return await PKG.write(o,r),i})();return t.reset(),R.disposeAll().catch(()=>{}).finally(()=>{mt.emit("event",{directory:"global",payload:{type:a$a.Disposed.type,properties:{}}});}),s}var fr=a.create({service:"adapter-loader"});async function xi(){try{let t=(await he.get())?.acp;if(!t){fr.debug("No ACP config found in Config.Info");return}let n={server:dm(t.server),clients:t.clients};return fr.info("ACP config loaded",{config:n}),n}catch(e){fr.error("Failed to load ACP config",{error:e});return}}async function Ja(){let e=await xi();return e?.server?e.server:dm(Up)}async function fw(){return (await xi())?.clients}function dm(e){let t={...e};if(process.env.ACP_CHANNEL){let o=process.env.ACP_CHANNEL.toLowerCase();["stdio","http","websocket"].includes(o)?t.channel=o:fr.warn("Invalid ACP_CHANNEL environment variable",{value:process.env.ACP_CHANNEL});}if(process.env.ACP_PORT){let o=parseInt(process.env.ACP_PORT,10);!Number.isNaN(o)&&o>0&&o<=65535?t.port=o:fr.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 o=parseInt(process.env.ACP_TIMEOUT,10);!Number.isNaN(o)&&o>0?t.timeout=o:fr.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 dl(){return (await Ja()).agent}async function gw(){return (await dl())?.model}async function hw(){return (await dl())?.agent}var ww=NamedError.create("ConfigDirectoryTypoError",U.object({path:U.string(),dir:U.string(),suggestion:U.string()})),xw=ww,he;(F=>(F.ModelId=Is,F.McpLocal=Da,F.McpOAuth=$a,F.McpRemote=Fa,F.Mcp=Na,F.PermissionAction=Xo,F.PermissionObject=Ua,F.PermissionRule=gt,F.Permission=wi,F.Command=za,F.Skills=qa,F.Agent=dn,F.Keybinds=Ha,F.TUI=Ba,F.Server=Ga,F.Layout=Wa,F.Provider=Va,F.Info=lr,F.mergeConfigConcatArrays=rn,F.needsInstall=ci,F.installDependencies=di,F.loadFile=cn,F.load=cr,F.parseConfig=dr,F.JsonError=Mn,F.InvalidError=an,F.loadAgent=li,F.loadCommand=ui,F.loadPlugin=pi,F.getPluginName=Oa,F.deduplicatePlugins=mi,F.loadNote=sr,F.loadCodebase=rr,F.loadMemory=ir,F.loadKnowledge=Gd,F.update=al,F.updateGlobal=cl,F.state=pr,F.waitForDependencies=Qd,F.get=On,F.directories=Zd,F.global=hi,F.getGlobal=el,F.loadACPConfig=xi,F.getACPServerConfig=Ja,F.loadCompaction=yi,F.loadContextConfig=bi,F.loadGatewayConfig=b,F.loadSubAgentConfig=mr,F.ConfigDirectoryTypoError=xw))(he||(he={}));var lm={".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 Pw=150;a$2.EASBOT_LSP_INIT_TIMEOUT;var um=a$2.EASBOT_LSP_DIAGNOSTICS_TIMEOUT,Tw=1,Ew=2,Aw=2,Xa;(u=>{let e=a.create({service:"lsp.client"}),t=new Map;function o(h){return t.get(h)}u.getActiveClient=o;function n(h){return t.has(h)}u.hasActiveClient=n;function s(h){t.delete(h);}u.removeActiveClient=s,u.InitializeError=NamedError.create("LSPInitializeError",U.object({serverId:U.string()})),u.Event={Diagnostics:a$5.define("lsp.client.diagnostics",U.object({serverId:U.string(),path:U.string()}))};function c(h){if(!h)return;let g=h.textDocumentSync;return typeof g=="number"?g:g?.change}async function l(h,g){let v=h.server.capabilities;if(!v)return;let P=pathToFileURL(h.root+"/").href,I=3e4,A=async()=>{if(v.workspace?.symbolProvider===void 0)try{await withTimeout(g.sendRequest("workspace/symbol",{query:""}),I),v.workspace=v.workspace||{},v.workspace.symbolProvider=!0,e.debug("probed workspaceSymbol capability",{serverId:h.serverId});}catch(y){let b=y instanceof Error?y.message:String(y);(b.includes("methodNotFound")||b.includes("not found")||b.includes("undefined method"))&&(v.workspace=v.workspace||{},v.workspace.symbolProvider=false,e.debug("probed workspaceSymbol capability: not supported",{serverId:h.serverId}));}},S=async()=>{if(v.implementationProvider===void 0)try{await withTimeout(g.sendRequest("textDocument/implementation",{textDocument:{uri:P},position:{line:0,character:0}}),I),v.implementationProvider=!0,e.debug("probed implementation capability",{serverId:h.serverId});}catch(y){let b=y instanceof Error?y.message:String(y);(b.includes("methodNotFound")||b.includes("not found")||b.includes("undefined method"))&&(v.implementationProvider=false,e.debug("probed implementation capability: not supported",{serverId:h.serverId}));}},w=async()=>{if(v.callHierarchyProvider===void 0)try{await withTimeout(g.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:P},position:{line:0,character:0}}),I),v.callHierarchyProvider=!0,e.debug("probed callHierarchy capability",{serverId:h.serverId});}catch(y){let b=y instanceof Error?y.message:String(y);(b.includes("methodNotFound")||b.includes("not found")||b.includes("undefined method"))&&(v.callHierarchyProvider=false,e.debug("probed callHierarchy capability: not supported",{serverId:h.serverId}));}};setTimeout(()=>{A().catch(()=>{}),S().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(v=>{let P=JSON.stringify({code:v.code,severity:v.severity,message:v.message,source:v.source,range:v.range});return g.has(P)?false:(g.add(P),true)})}function f(h,g){return g?g.split(".").reduce((P,I)=>{if(!(!P||typeof P!="object"||!(I in P)))return P[I]},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 v=`${h.serverId}:${h.root}`;if(t.has(v)){let $=t.get(v);if($.createdAt>Date.now()-5e3)return g.warn("duplicate LSP client detected, reusing existing client",{clientKey:v}),$;g.info("removing stale LSP client",{clientKey:v});try{await $.shutdown();}catch{}t.delete(v);}let P=h.initTimeout??xn.getServerInitTimeout(h.serverId),I=createMessageConnection(new StreamMessageReader(h.server.process.stdout),new StreamMessageWriter(h.server.process.stdin));h.server.process.stderr?.on("data",$=>{let K=$.toString().trim();K&&g.debug("server stderr",{text:K.slice(0,1e3)});});let A=new Map,S=new Map,w=new Map,y=$=>m([...A.get($)??[],...S.get($)??[]]),b=($,K)=>{A.set($,K),ue.publish(u.Event.Diagnostics,{path:$,serverId:h.serverId});};I.onNotification("textDocument/publishDiagnostics",$=>{let K=Filesystem.normalize(fileURLToPath($.uri));if(K){if(g.info("textDocument/publishDiagnostics",{path:K,count:$.diagnostics.length,version:$.version}),w.set(K,{at:Date.now(),version:typeof $.version=="number"?$.version:void 0}),a$1(h.serverId)&&!A.has(K)){A.set(K,$.diagnostics);return}b(K,$.diagnostics);}}),I.onRequest("window/workDoneProgress/create",$=>(g.info("window/workDoneProgress/create",$),null)),I.onRequest("workspace/configuration",async $=>($.items??[]).map(ee=>f(h.server.initialization,ee.section))),I.onRequest("client/registerCapability",async()=>{}),I.onRequest("client/unregisterCapability",async()=>{}),I.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:pathToFileURL(h.root).href}]),I.onRequest("workspace/diagnostic/refresh",async()=>null),I.listen(),g.info("sending initialize",{timeout:P});let C=await withTimeout(I.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}}}}),P).catch($=>{throw g.error("initialize error",{error:$,timeout:P}),new u.InitializeError({serverId:h.serverId},{cause:$})}),E=c(C.capabilities);h.server.capabilities=C.capabilities,l(h,I).catch(()=>{}),await I.sendNotification("initialized",{}),h.server.initialization&&await I.sendNotification("workspace/didChangeConfiguration",{settings:h.server.initialization});let O={},D={root:h.root,get serverId(){return h.serverId},get connection(){return I},get capabilities(){return h.server.capabilities},notify:{async open($){$.path=Ce__default.isAbsolute($.path)?$.path:Ce__default.resolve(R.directory,$.path);let K=await Filesystem.readText($.path),ee=Ce__default.extname($.path),N=lm[ee]??"plaintext",M=O[$.path];if(M!==void 0){g.info("workspace/didChangeWatchedFiles",$),await I.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pathToFileURL($.path).href,type:Ew}]});let T=M.version+1;return O[$.path]={version:T,text:K},g.info("textDocument/didChange",{path:$.path,version:T}),await I.sendNotification("textDocument/didChange",{textDocument:{uri:pathToFileURL($.path).href,version:T},contentChanges:E===Aw?[{range:{start:{line:0,character:0},end:d(M.text)},text:K}]:[{text:K}]}),T}return g.info("workspace/didChangeWatchedFiles",$),await I.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pathToFileURL($.path).href,type:Tw}]}),g.info("textDocument/didOpen",$),A.delete($.path),S.delete($.path),await I.sendNotification("textDocument/didOpen",{textDocument:{uri:pathToFileURL($.path).href,languageId:N,version:0,text:K}}),O[$.path]={version:0,text:K},0}},get diagnostics(){let $=new Map;for(let K of new Set([...A.keys(),...S.keys()]))$.set(K,y(K));return $},async waitForDiagnostics($){let K=Filesystem.normalize(Ce__default.isAbsolute($.path)?$.path:Ce__default.resolve(R.directory,$.path));g.info("waiting for diagnostics",{path:K,timeout:um});let ee,N;return await withTimeout(new Promise(M=>{ee=ue.subscribe(u.Event.Diagnostics,T=>{T.properties.path===K&&T.properties.serverId===D.serverId&&(N&&clearTimeout(N),N=setTimeout(()=>{g.info("got diagnostics",{path:K}),ee?.(),M();},Pw));});}),um).catch(()=>{}).finally(()=>{N&&clearTimeout(N),ee?.();})},async shutdown(){g.info("shutting down"),I.end(),I.dispose(),h.server.process.kill(),t.delete(v),g.info("shutdown");},clientKey:v,createdAt:Date.now()};return t.set(v,D),g.info("initialized"),D}u.create=p;})(Xa||(Xa={}));var pm=3,Mw=1e3,We;(j=>{let e=a.create({service:"lsp"});j.Event={Updated:a$5.define("lsp.updated",U.object({}))},j.Range=U.object({start:U.object({line:U.number(),character:U.number()}),end:U.object({line:U.number(),character:U.number()})}).meta({ref:"Range"}),j.LspSymbol=U.object({name:U.string(),kind:U.number(),location:U.object({uri:U.string(),range:j.Range})}).meta({ref:"LspSymbol"}),j.DocumentSymbol=U.object({name:U.string(),detail:U.string().optional(),kind:U.number(),range:j.Range,selectionRange:j.Range}).meta({ref:"DocumentSymbol"});let r=x=>{a$2.EASBOT_LSP_TY?x.pyright&&(e.info("LSP server pyright is disabled because EASBOT_LSP_TY is enabled"),delete x.pyright):x.ty&&delete x.ty;},i;async function c(){let x=[],k={},_=await he.get();if(_.lsp===false)return e.info("all LSPs are disabled"),{servers:k,clients:x,broken:new Set,spawning:new Map};for(let L of Object.values(xn))"id"in L&&"extensions"in L&&"spawn"in L&&(k[L.id]=L);r(k);for(let[L,H]of Object.entries(_.lsp??{})){let Y=k[L];if(H.disabled){e.info(`LSP server ${L} is disabled`),delete k[L];continue}k[L]={...Y,id:L,root:Y?.root??(async()=>R.directory),extensions:H.extensions??Y?.extensions??[],initTimeout:Y?.initTimeout??xn.getServerInitTimeout(L),spawn:async X=>({process:PKG.spawn([H.command[0],...H.command.slice(1)],{cwd:X,env:{...process.env,...H.env}}),initialization:H.initialization})};}return e.info("enabled LSP servers",{serverIds:Object.values(k).map(L=>L.id).join(", ")}),{servers:k,clients:x,broken:new Set,spawning:new Map}}async function l(x){await Promise.all(x.clients.map(k=>k.shutdown()));}function d(){return i||(i=R.state(c,l)),i}function m(){return d()()}async function f(){return m()}j.init=f;async function a$1(x){if(!a$2.EASBOT_LSP_TOOL||!x)return false;let{Session:k}=await import('./session-GQAYKB6Q.mjs'),_=await k.getContextMode(x);return !(_&&_!=="coder")}j.isAvailable=a$1,j.Status=U.object({id:U.string(),name:U.string(),root:U.string(),status:U.union([U.literal("connected"),U.literal("error")])}).meta({ref:"LSPStatus"});async function u(){return m().then(x=>{let k=[];for(let _ of x.clients)k.push({id:_.serverId,name:x.servers[_.serverId]?.id??"unknown",root:Ce__default.posix.relative(R.directory,_.root),status:"connected"});return k})}j.status=u;async function h(x,k){try{let _=await g(k);if(_.length===0)return !1;let L=_[0]?.capabilities;if(!L)return !1;switch(x){case "workspaceSymbol":return !!L.workspace?.symbolProvider;case "callHierarchy":return !!L.callHierarchyProvider;case "implementation":return !!L.implementationProvider;default:return !1}}catch{return false}}j.hasCapability=h;async function g(x){let k=await m(),_=Ce__default.parse(x).ext||x,L=[],H=new Map;async function Y(X,ne,ae){let le;try{le=await X.spawn(ne);}catch(Q){k.broken.add(ae),e.error(`Failed to spawn LSP server ${X.id}`,{error:Q,root:ne});return}if(!le){k.broken.add(ae),e.warn(`LSP server ${X.id} spawn returned undefined`,{root:ne});return}le.initTimeout=X.initTimeout??xn.getServerInitTimeout(X.id),e.info("spawned lsp server",{serverId:X.id,initTimeout:le.initTimeout,root:ne}),le.process.exited.catch(Q=>{let q=Q instanceof Error?Q.message:String(Q),F=Q instanceof Error?Q.stack:void 0;e.error("LSP process exited with error",{serverId:X.id,root:ne,error:q,stack:F});let te=k.clients.findIndex(J=>J.root===ne&&J.serverId===X.id);te!==-1&&(k.clients.splice(te,1),e.info("removed disconnected LSP client",{serverId:X.id,root:ne}));let G=H.get(ae)??0;G<pm?(H.set(ae,G+1),e.info(`LSP server ${X.id} will restart (attempt ${G+1}/${pm})`,{serverId:X.id,root:ne}),setTimeout(async()=>{if(!k.broken.has(ae)){let J=await Y(X,ne,ae);J&&(L.push(J),await ue.publish(j.Event.Updated,{}));}},Mw)):(e.error(`LSP server ${X.id} exceeded max restart attempts, marking as broken`,{serverId:X.id,root:ne}),k.broken.add(ae),H.delete(ae));});let be;try{be=await Xa.create({serverId:X.id,server:le,root:ne,initTimeout:X.initTimeout});}catch(Q){k.broken.add(ae),e.error(`Failed to initialize LSP client ${X.id}`,{error:Q,root:ne}),le.process.kill();return}let se=k.clients.find(Q=>Q.root===ne&&Q.serverId===X.id);return se?(le.process.kill(),se):(H.delete(ae),k.clients.push(be),be)}for(let X of Object.values(k.servers)){if(X.extensions.length>0&&!X.extensions.includes(_))continue;let ne=await X.root(x);if(!ne||k.broken.has(ne+X.id))continue;let ae=k.clients.find(Q=>Q.root===ne&&Q.serverId===X.id);if(ae){L.push(ae);continue}let le=k.spawning.get(ne+X.id);if(le){let Q=await le;if(!Q)continue;L.push(Q);continue}let be=Y(X,ne,ne+X.id);k.spawning.set(ne+X.id,be),await be.finally(()=>{k.spawning.get(ne+X.id)===be&&k.spawning.delete(ne+X.id);});let se=await be;se&&(L.push(se),await ue.publish(j.Event.Updated,{}));}return L}j.getClients=g;async function v(x){let k=await m(),_=Ce__default.parse(x).ext||x;for(let L of Object.values(k.servers)){if(L.extensions.length>0&&!L.extensions.includes(_))continue;let H=await L.root(x);if(H&&!k.broken.has(H+L.id))return true}return false}j.hasClients=v;async function P(x,k){e.info("touching file",{file:x});let _=await g(x);await Promise.all(_.map(async L=>{let H=k?L.waitForDiagnostics({path:x}):Promise.resolve();return await L.notify.open({path:x}),H})).catch(L=>{e.error("failed to touch file",{err:L,file:x});});}j.touchFile=P;async function I(){let x={};for(let k of await N(async _=>_.diagnostics))for(let[_,L]of k.entries()){let H=x[_]||[];H.push(...L),x[_]=H;}return x}j.diagnostics=I;async function A(x){let k=await g(x),_=Filesystem.normalize(x),L=[];for(let H of k){let Y=H.diagnostics.get(_);Y&&L.push(...Y);}return L}j.getFileDiagnostics=A;async function S(x){return M(x.file,k=>k.connection.sendRequest("textDocument/hover",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null))}j.hover=S;let w;(re=>(re[re.File=1]="File",re[re.Module=2]="Module",re[re.Namespace=3]="Namespace",re[re.Package=4]="Package",re[re.Class=5]="Class",re[re.Method=6]="Method",re[re.Property=7]="Property",re[re.Field=8]="Field",re[re.Constructor=9]="Constructor",re[re.Enum=10]="Enum",re[re.Interface=11]="Interface",re[re.Function=12]="Function",re[re.Variable=13]="Variable",re[re.Constant=14]="Constant",re[re.String=15]="String",re[re.Number=16]="Number",re[re.Boolean=17]="Boolean",re[re.Array=18]="Array",re[re.Object=19]="Object",re[re.Key=20]="Key",re[re.Null=21]="Null",re[re.EnumMember=22]="EnumMember",re[re.Struct=23]="Struct",re[re.Event=24]="Event",re[re.Operator=25]="Operator",re[re.TypeParameter=26]="TypeParameter"))(w||(w={}));let y=[5,12,6,11,13,14,23,10];async function b(x,k){let _=k??await R.directory+"/package.json",L=await g(_);if(L.length===0)throw new Error("No LSP client available");let H=L[0]?.capabilities;if(H&&!H.workspace?.symbolProvider)throw new Error("LSP server does not support workspaceSymbol");return M(_,Y=>Y.connection.sendRequest("workspace/symbol",{query:x}).then(X=>!X||!Array.isArray(X)?[]:X.filter(ne=>y.includes(ne.kind))).then(X=>X.slice(0,10)).catch(X=>(e.debug("workspaceSymbol request failed",{error:X}),[]))).then(Y=>Y.flat())}j.workspaceSymbol=b;async function C(x){let k=pathToFileURL(x.file).href;return M(x.file,_=>_.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:k}}).catch(()=>[])).then(_=>_.flat()).then(_=>_.filter(Boolean))}j.documentSymbol=C;async function E(x){return M(x.file,k=>k.connection.sendRequest("textDocument/definition",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null)).then(k=>k.flat().filter(Boolean))}j.definition=E;async function O(x){return M(x.file,k=>k.connection.sendRequest("textDocument/references",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character},context:{includeDeclaration:true}}).catch(()=>[])).then(k=>k.flat().filter(Boolean))}j.references=O;async function D(x){let k=await g(x.file);if(k.length>0){let _=k[0]?.capabilities;if(_&&!_.implementationProvider)throw new Error("LSP server does not support implementation")}return M(x.file,_=>_.connection.sendRequest("textDocument/implementation",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>null)).then(_=>_.flat().filter(Boolean))}j.implementation=D;async function $(x){let k=await g(x.file);if(k.length>0){let _=k[0]?.capabilities;if(_&&!_.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return M(x.file,_=>_.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character}}).catch(()=>[])).then(_=>_.flat().filter(Boolean))}j.prepareCallHierarchy=$;async function K(x){let k=await g(x.file);if(k.length>0){let _=k[0]?.capabilities;if(_&&!_.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return M(x.file,async _=>{try{let L=await _.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character}}).catch(Y=>(e.debug("prepareCallHierarchy failed",{error:Y}),[]));return L?.length===0?[]:await _.connection.sendRequest("callHierarchy/incomingCalls",{item:L[0]}).catch(Y=>(e.debug("callHierarchy/incomingCalls failed",{error:Y}),[]))}catch(L){return e.debug("incomingCalls error",{error:L,file:x.file,line:x.line,character:x.character}),[]}}).then(_=>_.flat().filter(Boolean))}j.incomingCalls=K;async function ee(x){let k=await g(x.file);if(k.length>0){let _=k[0]?.capabilities;if(_&&!_.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return M(x.file,async _=>{try{let L=await _.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(x.file).href},position:{line:x.line,character:x.character}}).catch(Y=>(e.debug("prepareCallHierarchy failed",{error:Y}),[]));return L?.length===0?[]:await _.connection.sendRequest("callHierarchy/outgoingCalls",{item:L[0]}).catch(Y=>(e.debug("callHierarchy/outgoingCalls failed",{error:Y}),[]))}catch(L){return e.debug("outgoingCalls error",{error:L,file:x.file,line:x.line,character:x.character}),[]}}).then(_=>_.flat().filter(Boolean))}j.outgoingCalls=ee;async function N(x){let k=await m().then(L=>L.clients);return (await Promise.allSettled(k.map(L=>x(L)))).filter(L=>L.status==="fulfilled").map(L=>L.value)}async function M(x,k){try{let _=await g(x);await Promise.all(_.map(H=>H.notify.open({path:x})));let L=_.map(H=>k(H));return await Promise.all(L)}catch(_){return e.error("LSP run failed",{file:x,error:_}),[]}}(k=>{function x(_){let H={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[_.severity||1],Y=_.range.start.line+1,X=_.range.start.character+1;return `${H} [${Y}:${X}] ${_.message}`}k.pretty=x;})(j.Diagnostic||(j.Diagnostic={}));})(We||(We={}));var ht;(p=>{let e=a.create({service:"snapshot"}),t="7.days";async function o(){try{let{Scheduler:u}=await import('./scheduler-VUQ33E5B.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=o;async function n(){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 v=await $`git --git-dir ${h} --work-tree ${R.worktree} gc --prune=${t}`.quiet().cwd(R.directory).nothrow();if(v.exitCode!==0){e.warn("cleanup failed",{exitCode:v.exitCode,stderr:v.stderr.toString(),stdout:v.stdout.toString()});return}e.info("cleanup",{prune:t});}p.cleanup=n;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=U.object({hash:U.string(),files:U.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 v=g.text();return {hash:u,files:v.trim().split(`
25
- `).map(P=>P.trim()).filter(Boolean).map(P=>Ce__default.join(R.worktree,P))}}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 v of u)for(let P of v.files){if(h.has(P))continue;if(e.info("reverting",{file:P,hash:v.hash}),(await $`git --git-dir ${g} --work-tree ${R.worktree} checkout ${v.hash} -- ${P}`.quiet().cwd(R.worktree).nothrow()).exitCode!==0){let A=Ce__default.posix.relative(R.worktree,P),S=await $`git --git-dir ${g} --work-tree ${R.worktree} ls-tree ${v.hash} -- ${A}`.quiet().cwd(R.worktree).nothrow();S.exitCode===0&&S.text().trim()?e.info("file existed in snapshot but checkout failed, keeping",{file:P}):(e.info("file did not exist in snapshot, deleting",{file:P}),await Tt__default.unlink(P).catch(()=>{}));}h.add(P);}}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=U.object({file:U.string(),before:U.string(),after:U.string(),additions:U.number(),deletions:U.number(),status:U.enum(["added","deleted","modified"]).optional()}).meta({ref:"FileDiff"});async function f(u,h){let g=a$2(),v=[],P=new Map,I=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 S of I.trim().split(`
26
- `)){if(!S)continue;let[w,y]=S.split(" ");if(!w||!y)continue;let b=w.startsWith("A")?"added":w.startsWith("D")?"deleted":"modified";P.set(y,b);}let A=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 S of A){if(!S)continue;let w=S.split(" ");if(w.length<3)continue;let[y,b,C]=w;if(!y||!b||!C)continue;let E=y==="-"&&b==="-",O=E?"":await $`git -c core.autocrlf=false --git-dir ${g} --work-tree ${R.worktree} show ${u}:${C}`.quiet().nothrow().text(),D=E?"":await $`git -c core.autocrlf=false --git-dir ${g} --work-tree ${R.worktree} show ${h}:${C}`.quiet().nothrow().text(),$$1=E?0:parseInt(y,10),K=E?0:parseInt(b,10);v.push({file:C,before:O,after:D,additions:Number.isFinite($$1)?$$1:0,deletions:Number.isFinite(K)?K:0,status:P.get(C)??"modified"});}return v}p.diffFull=f;function a$2(){let u=R.project;return Ce__default.join(a$1.Path.data,"snapshot",u.id)}})(ht||(ht={}));var Ci;(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 o(d){return e.some(m=>m.test(d))?true:/^4(00|13)\s*(status code)?\s*\(no body\)/i.test(d)}function n(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=n(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(o(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;})(Ci||(Ci={}));var ve;(F=>{function e(te){return te.startsWith("image/")||te==="application/pdf"}F.isMedia=e,F.OutputLengthError=NamedError.create("MessageOutputLengthError",U.object({})),F.AbortedError=NamedError.create("MessageAbortedError",U.object({message:U.string()})),F.StructuredOutputError=NamedError.create("StructuredOutputError",U.object({message:U.string(),retries:U.number()})),F.AuthError=NamedError.create("ProviderAuthError",U.object({providerId:U.string(),message:U.string()})),F.APIError=NamedError.create("APIError",U.object({message:U.string(),statusCode:U.number().optional(),isRetryable:U.boolean(),responseHeaders:U.record(U.string(),U.string()).optional(),responseBody:U.string().optional(),metadata:U.record(U.string(),U.string()).optional()})),F.ContextOverflowError=NamedError.create("ContextOverflowError",U.object({message:U.string(),responseBody:U.string().optional()})),F.OutputFormatText=U.object({type:U.literal("text")}).meta({ref:"OutputFormatText"}),F.OutputFormatJsonSchema=U.object({type:U.literal("json_schema"),schema:U.record(U.string(),U.any()).meta({ref:"JSONSchema"}),retryCount:U.number().int().min(0).default(2)}).meta({ref:"OutputFormatJsonSchema"}),F.Format=U.discriminatedUnion("type",[F.OutputFormatText,F.OutputFormatJsonSchema]).meta({ref:"OutputFormat"});let m=U.object({id:U.string(),sessionId:U.string(),messageId:U.string()});F.SnapshotPart=m.extend({type:U.literal("snapshot"),snapshot:U.string()}).meta({ref:"SnapshotPart"}),F.PatchPart=m.extend({type:U.literal("patch"),hash:U.string(),files:U.string().array()}).meta({ref:"PatchPart"}),F.TextPart=m.extend({type:U.literal("text"),text:U.string(),synthetic:U.boolean().optional(),ignored:U.boolean().optional(),time:U.object({start:U.number(),end:U.number().optional()}).optional(),metadata:U.record(U.string(),U.any()).optional()}).meta({ref:"TextPart"}),F.ReasoningPart=m.extend({type:U.literal("reasoning"),text:U.string(),metadata:U.record(U.string(),U.any()).optional(),time:U.object({start:U.number(),end:U.number().optional()})}).meta({ref:"ReasoningPart"});let h=U.object({text:U.object({value:U.string(),start:U.number().int(),end:U.number().int()}).meta({ref:"FilePartSourceText"})});F.FileSource=h.extend({type:U.literal("file"),path:U.string()}).meta({ref:"FileSource"}),F.SymbolSource=h.extend({type:U.literal("symbol"),path:U.string(),range:We.Range,name:U.string(),kind:U.number().int()}).meta({ref:"SymbolSource"}),F.ResourceSource=h.extend({type:U.literal("resource"),clientName:U.string(),uri:U.string()}).meta({ref:"ResourceSource"}),F.FilePartSource=U.discriminatedUnion("type",[F.FileSource,F.SymbolSource,F.ResourceSource]).meta({ref:"FilePartSource"}),F.FilePart=m.extend({type:U.literal("file"),mime:U.string(),filename:U.string().optional(),url:U.string(),source:F.FilePartSource.optional()}).meta({ref:"FilePart"}),F.AgentPart=m.extend({type:U.literal("agent"),name:U.string(),source:U.object({value:U.string(),start:U.number().int(),end:U.number().int()}).optional()}).meta({ref:"AgentPart"}),F.CompactionPart=m.extend({type:U.literal("compaction"),auto:U.boolean(),overflow:U.boolean().optional()}).meta({ref:"CompactionPart"}),F.MemoryPart=m.extend({type:U.literal("memory"),status:U.enum(["pending","processing","completed","failed","skipped"]),time:U.object({start:U.number(),end:U.number().optional()}),result:U.string().optional(),error:U.string().optional(),reason:U.string().optional()}).meta({ref:"MemoryPart"}),F.SubtaskPart=m.extend({type:U.literal("subtask"),taskId:U.string().describe("Task unique identifier"),prompt:U.string(),description:U.string(),agent:U.string(),model:U.object({providerId:U.string(),modelId:U.string()}).optional(),command:U.string().optional()}).meta({ref:"SubtaskPart"}),F.SubtaskResultPart=m.extend({type:U.literal("subtask-result"),taskId:U.string().describe("Task unique identifier"),source:U.enum(["tool","scheduler","cli","api","agent-client"]).describe("Task source"),agent:U.string().describe("Agent name"),status:U.enum(["pending","running","completed","error"]).describe("Task status"),result:U.string().optional().describe("Task result content"),error:U.string().optional().describe("Error message if failed"),duration:U.number().optional().describe("Duration in milliseconds"),time:U.object({start:U.number().describe("Start timestamp"),end:U.number().optional().describe("End timestamp")}).optional().describe("Task time"),rounds:U.object({current:U.number(),max:U.number()}).optional().describe("Interaction rounds"),thinking:U.string().optional().describe("Thinking content"),tools:U.array(U.object({name:U.string(),status:U.string(),input:U.record(U.string(),U.unknown()).optional(),output:U.string().optional()})).optional().describe("Tool calls during task"),attachments:U.array(U.lazy(()=>F.FilePart)).optional().describe("Result attachments"),metadata:U.record(U.string(),U.unknown()).optional().describe("Source-specific metadata")}).meta({ref:"SubtaskResultPart"});function E(te){let G=[];if(G.push("=== SubAgent Result ==="),G.push(`Task ID: ${te.taskId}`),G.push(`Source: ${te.source}`),G.push(`Agent: ${te.agent}`),G.push(`Status: ${te.status}`),te.duration&&G.push(`Duration: ${te.duration}ms`),te.rounds&&G.push(`Rounds: ${te.rounds.current}/${te.rounds.max}`),te.time&&(G.push(`Start(Local): ${formatLocalISOCompact(new Date(te.time.start))}`),te.time.end&&G.push(`End(Local): ${formatLocalISOCompact(new Date(te.time.end))}`)),te.metadata&&Object.keys(te.metadata).length>0){G.push("");for(let[J,oe]of Object.entries(te.metadata))G.push(`${J}: ${oe}`);}if(te.thinking&&G.push("","<think>",te.thinking,"</think>"),(te?.tools?.length??0)>0){G.push("","<tool_calls>");for(let J of te?.tools??[])G.push(`- ${J.name}: ${String(J.input)}`);G.push("</tool_calls>");}return G.push(""),te.status==="error"?G.push("Error:",te.error??"Unknown error"):G.push("Result:",te.result??""),G.push("=================="),G.join(`
27
- `)}F.formatSubtaskResultPart=E,F.RetryPart=m.extend({type:U.literal("retry"),attempt:U.number(),error:F.APIError.Schema,time:U.object({created:U.number()})}).meta({ref:"RetryPart"}),F.StepStartPart=m.extend({type:U.literal("step-start"),snapshot:U.string().optional()}).meta({ref:"StepStartPart"}),F.StepFinishPart=m.extend({type:U.literal("step-finish"),reason:U.string(),snapshot:U.string().optional(),cost:U.number(),tokens:U.object({total:U.number().optional(),input:U.number(),output:U.number(),reasoning:U.number(),cache:U.object({read:U.number(),write:U.number()})})}).meta({ref:"StepFinishPart"}),F.ToolStatePending=U.object({status:U.literal("pending"),input:U.record(U.string(),U.any()),raw:U.string()}).meta({ref:"ToolStatePending"}),F.ToolStateRunning=U.object({status:U.literal("running"),input:U.record(U.string(),U.any()),title:U.string().optional(),metadata:U.record(U.string(),U.any()).optional(),time:U.object({start:U.number()})}).meta({ref:"ToolStateRunning"}),F.ToolStateCompleted=U.object({status:U.literal("completed"),input:U.record(U.string(),U.any()),output:U.string(),title:U.string(),metadata:U.record(U.string(),U.any()),time:U.object({start:U.number(),end:U.number(),compacted:U.number().optional()}),attachments:F.FilePart.array().optional()}).meta({ref:"ToolStateCompleted"}),F.ToolStateError=U.object({status:U.literal("error"),input:U.record(U.string(),U.any()),error:U.string(),metadata:U.record(U.string(),U.any()).optional(),time:U.object({start:U.number(),end:U.number()})}).meta({ref:"ToolStateError"}),F.ToolState=U.discriminatedUnion("status",[F.ToolStatePending,F.ToolStateRunning,F.ToolStateCompleted,F.ToolStateError]).meta({ref:"ToolState"}),F.ToolPart=m.extend({type:U.literal("tool"),callId:U.string(),tool:U.string(),state:F.ToolState,metadata:U.record(U.string(),U.any()).optional()}).meta({ref:"ToolPart"});let x=U.object({id:U.string(),sessionId:U.string()});F.User=x.extend({role:U.literal("user"),time:U.object({created:U.number()}),format:F.Format.optional(),summary:U.object({title:U.string().optional(),body:U.string().optional(),diffs:ht.FileDiff.array()}).optional(),agent:U.string(),model:U.object({providerId:U.string(),modelId:U.string()}),system:U.string().optional(),tools:U.record(U.string(),U.boolean()).optional(),variant:U.string().optional()}).meta({ref:"UserMessage"}),F.Part=U.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=x.extend({role:U.literal("assistant"),time:U.object({created:U.number(),completed:U.number().optional()}),error:U.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:U.string(),modelId:U.string(),providerId:U.string(),mode:U.string(),agent:U.string(),path:U.object({cwd:U.string(),root:U.string()}),summary:U.boolean().optional(),cost:U.number(),tokens:U.object({total:U.number().optional(),input:U.number(),output:U.number(),reasoning:U.number(),cache:U.object({read:U.number(),write:U.number()})}),structured:U.any().optional(),variant:U.string().optional(),finish:U.string().optional()}).meta({ref:"AssistantMessage"}),F.Info=U.discriminatedUnion("role",[F.User,F.Assistant]).meta({ref:"Message"}),F.Event={Updated:a$5.define("message.updated",U.object({info:F.Info})),Removed:a$5.define("message.removed",U.object({sessionId:U.string(),messageId:U.string()})),PartUpdated:a$5.define("message.part.updated",U.object({part:F.Part,delta:U.string().optional(),time:U.number()})),PartRemoved:a$5.define("message.part.removed",U.object({sessionId:U.string(),messageId:U.string(),partId:U.string()}))},F.WithParts=U.object({info:F.Info,parts:U.array(F.Part)});async function ne(te,G,J){let oe=new Set,ce=(()=>{if(G.api.npm==="@ai-sdk/anthropic"||G.api.npm==="@ai-sdk/openai"||G.api.npm==="@ai-sdk/amazon-bedrock"||G.api.npm==="@ai-sdk/google-vertex/anthropic")return true;if(G.api.npm==="@ai-sdk/google"){let Ie=G.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 we=Ie,re=(we.attachments??[]).filter(Ae=>Ae.url.startsWith("data:")&&Ae.url.includes(","));return {type:"content",value:[{type:"text",text:we.text??we.output??"[Tool result content missing]"},...re.map(Ae=>({type:"media",mediaType:Ae.mime,data:iife(()=>{let _t=Ae.url.indexOf(",");return _t===-1?Ae.url:Ae.url.slice(_t+1)})}))]}}return {type:"json",value:Ie}},pe=[];for(let Ie of te)if(Ie.parts.length!==0){if(Ie.info.role==="user"){let we={id:Ie.info.id,role:"user",parts:[]};pe.push(we);for(let re of Ie.parts)re.type==="text"&&!re.ignored&&we.parts.push({type:"text",text:re.text}),re.type==="file"&&re.mime!=="text/plain"&&re.mime!=="application/x-directory"&&(J?.stripMedia&&e(re.mime)?we.parts.push({type:"text",text:`[Attached ${re.mime}: ${re.filename??"file"}]`}):we.parts.push({type:"file",url:re.url,mediaType:re.mime,filename:re.filename})),re.type==="compaction"&&we.parts.push({type:"text",text:"What did we do so far?"}),re.type==="subtask"&&we.parts.push({type:"text",text:"The following tool was executed by user"}),re.type==="subtask-result"&&we.parts.push({type:"text",text:F.formatSubtaskResultPart(re)});}if(Ie.info.role==="assistant"){let we=`${G.providerId}/${G.id}`!=`${Ie.info.providerId}/${Ie.info.modelId}`,re=[];if(Ie.info.error&&!(F.AbortedError.isInstance(Ie.info.error)&&Ie.parts.some(Ae=>Ae.type!=="step-start"&&Ae.type!=="reasoning")))continue;let Ee={id:Ie.info.id,role:"assistant",parts:[]};for(let Ae of Ie.parts){if(Ae.type==="text"&&Ee.parts.push({type:"text",text:Ae.text,...we?{}:{providerMetadata:Ae.metadata}}),Ae.type==="step-start"&&Ee.parts.push({type:"step-start"}),Ae.type==="tool"){if(oe.add(Ae.tool),Ae.state.status==="completed"){let _t=Ae.state.time.compacted?"[Old tool result content cleared]":Ae.state.output??"[Tool result content missing]",ko=Ae.state.time.compacted||J?.stripMedia?[]:Ae.state.attachments??[],Do=Sa=>Sa.mime.startsWith("image/")||Sa.mime==="application/pdf",Po=ko.filter(Do),Gt=ko.filter(Sa=>!Do(Sa));!ce&&Po.length>0&&re.push(...Po);let It=ce?ko:Gt,tr=It.length>0?{text:_t,attachments:It}:_t;Ee.parts.push({type:"tool-"+Ae.tool,state:"output-available",toolCallId:Ae.callId,input:Ae.state.input,output:tr,...we?{}:{callProviderMetadata:Ae.metadata}});}Ae.state.status==="error"&&Ee.parts.push({type:"tool-"+Ae.tool,state:"output-error",toolCallId:Ae.callId,input:Ae.state.input,errorText:Ae.state.error,...we?{}:{callProviderMetadata:Ae.metadata}}),(Ae.state.status==="pending"||Ae.state.status==="running")&&Ee.parts.push({type:"tool-"+Ae.tool,state:"output-error",toolCallId:Ae.callId,input:Ae.state.input,errorText:"[Tool execution was interrupted]",...we?{}:{callProviderMetadata:Ae.metadata}});}Ae.type==="reasoning"&&Ee.parts.push({type:"reasoning",text:Ae.text,...we?{}:{providerMetadata:Ae.metadata}});}Ee.parts.length>0&&(pe.push(Ee),re.length>0&&pe.push({id:Identifier.ascending("message"),role:"user",parts:[{type:"text",text:"Attached image(s) from tool result:"},...re.map(Ae=>({type:"file",url:Ae.url,mediaType:Ae.mime,providerMetadata:void 0}))]}));}}let xe=Object.fromEntries(Array.from(oe).map(Ie=>[Ie,{toModelOutput:me}])),qe=pe.filter(Ie=>Ie.parts.some(we=>we.type!=="step-start"));return await convertToModelMessages(qe,{tools:xe})}F.toModelMessages=ne,F.stream=fn$1(Identifier.schema("session"),async function*(te){let G=await Array.fromAsync(await a$6.list(["message",te]));for(let J=G.length-1;J>=0;J--){let oe=G[J]?.[2];oe&&(yield await(0, F.get)({sessionId:te,messageId:oe}));}}),F.parts=fn$1(Identifier.schema("message"),async te=>{let G=[];for(let J of await a$6.list(["part",te])){let oe=await a$6.read(J);G.push(oe);}return G.sort((J,oe)=>J.id>oe.id?1:-1),G}),F.get=fn$1(U.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 se(te){let G=[],J=new Set;for await(let oe of te){if(G.push(oe),oe.info.role==="user"&&J.has(oe.info.id)&&oe.parts.some(ce=>ce.type==="compaction"))break;oe.info.role==="assistant"&&oe.info.summary&&oe.info.finish&&J.add(oe.info.parentId);}return G.reverse(),G}F.filterCompacted=se;async function Q(te,G){let J=await se((0, F.stream)(te)),oe=J;G?.maxMessages&&G.maxMessages>0&&(oe=J.slice(-G.maxMessages));let ce,me,pe,xe,qe;for(let Ie=oe.length-1;Ie>=0;Ie--){let we=oe[Ie];if(we&&(!ce&&we.info.role==="user"&&(ce=we.info,me=we),!pe&&we.info.role==="assistant"&&(pe=we.info),!xe&&we.info.role==="assistant"&&we.info.finish&&(xe=we),G?.filterByText!==false&&!qe&&we.info.role==="assistant"&&we.parts.some(re=>re.type==="text")&&(qe=we),ce&&qe&&xe))break}return {lastUser:ce,lastUserMessage:me,lastAssistant:pe,lastFinished:xe,lastAssistantWithText:qe}}F.getLastMessages=Q;function q(te,G){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:G.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 G.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=Ci.parseAPICallError({providerId:G.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=Ci.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=q;})(ve||(ve={}));var yt;(S=>{let e=a.create({service:"file"});S.Info=U.object({path:U.string(),added:U.number().int(),removed:U.number().int(),status:U.enum(["added","deleted","modified"])}).meta({ref:"File"}),S.Node=U.object({name:U.string(),path:U.string(),absolute:U.string(),type:U.enum(["file","directory"]),ignored:U.boolean()}).meta({ref:"FileNode"}),S.Content=U.object({type:U.enum(["text","binary"]),content:U.string(),diff:U.string().optional(),patch:U.object({oldFileName:U.string(),newFileName:U.string(),oldHeader:U.string().optional(),newHeader:U.string().optional(),hunks:U.array(U.object({oldStart:U.number(),oldLines:U.number(),newStart:U.number(),newLines:U.number(),lines:U.array(U.string())})),index:U.string().optional()}).optional(),encoding:U.literal("base64").optional(),mimeType:U.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 y=Filesystem.extname(w).toLowerCase().slice(1);return r.has(y)}function c$1(w){let y=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"}[y]||"image/"+y}function l(w){let y=Filesystem.extname(w).toLowerCase().slice(1);return s.has(y)}function d$1(w){return w.startsWith("image/")}async function m(w){let y=w.type?.toLowerCase();if(e.info("shouldEncode",{type:y}),!y||y.startsWith("text/")||y.includes("charset="))return false;let C=y.split("/",2)[0];return !!["image","audio","video","font","model","multipart"].includes(C)}S.Event={Edited:a$5.define("file.edited",U.object({file:U.string()}))};async function a$2(){let w={files:[],dirs:[]},y=false,b=R.directory===a$1.Path.home&&R.project.id==="global",C=async E=>{if(R.directory===Ce__default.parse(R.directory).root)return;if(y=true,b){let D=new Set,$=new Set;process.platform==="darwin"&&$.add("Library"),process.platform==="win32"&&$.add("AppData");let K=new Set(["node_modules","dist","build","target","vendor"]),ee=T=>T.startsWith(".")||$.has(T),N=T=>T.startsWith(".")||K.has(T),M=await gl.promises.readdir(R.directory,{withFileTypes:true}).catch(()=>[]);for(let T of M){if(!T.isDirectory()||ee(T.name))continue;D.add(T.name+"/");let j=Filesystem.join(R.directory,T.name),x=await gl.promises.readdir(j,{withFileTypes:true}).catch(()=>[]);for(let k of x)k.isDirectory()&&(N(k.name)||D.add(T.name+"/"+k.name+"/"));}E.dirs=Array.from(D).toSorted(),w=E,y=false;return}let O=new Set;for await(let D of a$8.files({cwd:R.directory})){E.files.push(D);let $=D;for(;;){let K=Ce__default.posix.dirname($);if(K==="."||K===$)break;$=K,!O.has(K)&&(O.add(K),E.dirs.push(K+"/"));}}w=E,y=false;};return await C(w),{async files(){return y||await C({files:[],dirs:[]}),w}}}let p;function u(){return p||(p=R.state(a$2)),p}function h(){return u()()}function g(){h();}S.init=g;async function v(){if(R.project.vcs!=="git")return [];let y=await $`git -c core.quotepath=false diff --numstat HEAD`.cwd(R.directory).quiet().nothrow().text(),b=[];if(y.trim()){let O=y.trim().split(`
28
- `);for(let D of O){let $=D.split(" "),K=$[2];K&&b.push({path:K,added:$[0]==="-"?0:parseInt($[0]||"0",10),removed:$[1]==="-"?0:parseInt($[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(`
29
- `);for(let D of O)try{let K=(await PKG.file(Filesystem.join(R.directory,D)).text()).split(`
30
- `).length;b.push({path:D,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(`
31
- `);for(let D of O)b.push({path:D,added:0,removed:0,status:"deleted"});}return b.map(O=>({...O,path:Ce__default.posix.relative(R.directory,O.path)}))}S.status=v;async function P(w){var K=[];try{let y=c(K,e.time("read",{file:w}));let b=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 T=PKG.file(C);if(await T.exists()){let j=await T.arrayBuffer().catch(()=>new ArrayBuffer(0)),x=Buffer.from(j).toString("base64"),k=c$1(w);return {type:"text",content:x,mimeType:k,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 D=E.type||"application/octet-stream";if(O&&!d$1(D))return {type:"binary",content:"",mimeType:D};if(O){let T=await E.bytes().catch(()=>new Uint8Array(0));return {type:"text",content:Buffer.from(T).toString("base64"),mimeType:D,encoding:"base64"}}let $$1=await E.text().catch(()=>"").then(T=>T.trim());if(b.vcs==="git"){let T=await $`git diff ${w}`.cwd(R.directory).quiet().nothrow().text();if(T.trim()||(T=await $`git diff --staged ${w}`.cwd(R.directory).quiet().nothrow().text()),T.trim()){let j=await $`git show HEAD:${w}`.cwd(R.directory).quiet().nothrow().text(),x=structuredPatch(w,w,j,$$1,"old","new",{context:1/0,ignoreWhitespace:!0}),k=formatPatch(x);return {type:"text",content:$$1,patch:{oldFileName:x.oldFileName??w,newFileName:x.newFileName??w,oldHeader:x.oldHeader,newHeader:x.newHeader,hunks:x.hunks,index:x.index},diff:k}}}return {type:"text",content:$$1}}catch(ee){var N=ee,M=true;}finally{d(K,N,M);}}S.read=P;async function I(w){let y=[".git",".DS_Store"],b=R.project,C=D=>false;if(b.vcs==="git"){let D=Ignore.create(),$=PKG.file(Filesystem.join(R.worktree,".gitignore"));await $.exists()&&D.add((await $.text()).split(`
32
- `));let K=PKG.file(Filesystem.join(R.worktree,".ignore"));await K.exists()&&D.add((await K.text()).split(`
33
- `)),C=D.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 D of await gl.promises.readdir(E,{withFileTypes:true}).catch(()=>[])){if(y.includes(D.name))continue;let $=Filesystem.join(E,D.name),K=Ce__default.posix.relative(R.directory,$),ee=D.isDirectory()?"directory":"file";O.push({name:D.name,path:K,absolute:$,type:ee,ignored:C(ee==="directory"?K+"/":K)});}return O.sort((D,$)=>D.type!==$.type?D.type==="directory"?-1:1:D.name.localeCompare($.name))}S.list=I;async function A(w){let y=w.query.trim(),b=w.limit??100,C=w.type??(w.dirs===false?"file":"all");e.info("search",{query:y,kind:C});let E=await(await h()).files(),O=T=>T.replaceAll("\\","/").replace(/\/+$/,"").split("/").some(x=>x.startsWith(".")&&x.length>1),D=y.startsWith(".")||y.includes("/."),$=T=>{if(D)return T;let j=[],x=[];for(let k of T){let _=O(k);_&&x.push(k),_||j.push(k);}return [...j,...x]};if(!y)return C==="file"?E.files.slice(0,b):$(E.dirs.toSorted()).slice(0,b);let K=C==="file"?E.files:C==="directory"?E.dirs:[...E.files,...E.dirs],ee=C==="directory"&&!D?b*20:b,N=hy.go(y,K,{limit:ee}).map(T=>T.target),M=C==="directory"?$(N).slice(0,b):N;return e.info("search",{query:y,kind:C,results:M.length}),M}S.search=A;})(yt||(yt={}));var yl={};a$7(yl,{biome:()=>Ww,clang:()=>Kw,dart:()=>tx,gleam:()=>rx,gofmt:()=>qw,htmlbeautifier:()=>ex,ktlint:()=>Jw,latexindent:()=>sx,mix:()=>Hw,nixfmt:()=>ax,ocamlformat:()=>ox,ormolu:()=>lx,oxfmt:()=>Gw,pint:()=>dx,prettier:()=>Bw,rlang:()=>Yw,rubocop:()=>Qw,ruff:()=>hm,rustfmt:()=>cx,shfmt:()=>ix,standardrb:()=>Zw,terraform:()=>nx,uvformat:()=>Xw,zig:()=>Vw});var qw={name:"gofmt",command:["gofmt","-w","$FILE"],extensions:[".go"],async enabled(){return await PKG.which("gofmt")!==null}},Hw={name:"mix",command:["mix","format","$FILE"],extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){return await PKG.which("mix")!==null}},Bw={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 o=await PKG.file(t).json();if(o.dependencies?.prettier||o.devDependencies?.prettier)return true}return false}},Gw={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 o=await PKG.file(t).json();if(o.dependencies?.oxfmt||o.devDependencies?.oxfmt)return true}return false}},Ww={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}},Vw={name:"zig",command:["zig","fmt","$FILE"],extensions:[".zig",".zon"],async enabled(){return await PKG.which("zig")!==null}},Kw={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}},Jw={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 o of e){let n=await Filesystem.findUp(o,R.directory,R.worktree);if(n.length>0)if(o==="pyproject.toml"){if((await PKG.file(n[0]).text()).includes("[tool.ruff]"))return true}else return true}let t=["requirements.txt","pyproject.toml","Pipfile"];for(let o of t){let n=await Filesystem.findUp(o,R.directory,R.worktree);if(n.length>0&&(await PKG.file(n[0]).text()).includes("ruff"))return true}return false}},Yw={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,o=Shell.spawn(t,"air --help",{stdout:"pipe",stderr:"pipe"});await o.exited;let s=(await PKG.nodeReadableStreamToText(o.stdout)).split(`
34
- `)[0];if(!s)return !1;let r=s.includes("R language"),i=s.includes("formatter");return r&&i}catch{return false}}},Xw={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}},Qw={name:"rubocop",command:["rubocop","--autocorrect","$FILE"],extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){return await PKG.which("rubocop")!==null}},Zw={name:"standardrb",command:["standardrb","--fix","$FILE"],extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){return await PKG.which("standardrb")!==null}},ex={name:"htmlbeautifier",command:["htmlbeautifier","$FILE"],extensions:[".erb",".html.erb"],async enabled(){return await PKG.which("htmlbeautifier")!==null}},tx={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}},nx={name:"terraform",command:["terraform","fmt","$FILE"],extensions:[".tf",".tfvars"],async enabled(){return await PKG.which("terraform")!==null}},sx={name:"latexindent",command:["latexindent","-w","-s","$FILE"],extensions:[".tex"],async enabled(){return await PKG.which("latexindent")!==null}},rx={name:"gleam",command:["gleam","format","$FILE"],extensions:[".gleam"],async enabled(){return await PKG.which("gleam")!==null}},ix={name:"shfmt",command:["shfmt","-w","$FILE"],extensions:[".sh",".bash"],async enabled(){return await PKG.which("shfmt")!==null}},ax={name:"nixfmt",command:["nixfmt","$FILE"],extensions:[".nix"],async enabled(){return await PKG.which("nixfmt")!==null}},cx={name:"rustfmt",command:["rustfmt","$FILE"],extensions:[".rs"],async enabled(){return await PKG.which("rustfmt")!==null}},dx={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 o=await PKG.file(t).json();if(o.require?.["laravel/pint"]||o["require-dev"]?.["laravel/pint"])return true}return false}},lx={name:"ormolu",command:["ormolu","-i","$FILE"],extensions:[".hs"],async enabled(){return await PKG.which("ormolu")!==null}};var vs;(m=>{let e=a.create({service:"format"});m.Status=U.object({name:U.string(),extensions:U.string().array(),enabled:U.boolean()}).meta({ref:"FormatterStatus"});async function o(){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 n;function s(){return n||(n=R.state(o)),n}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"),ue.subscribe(yt.Event.Edited,async f=>{let a=f.properties.file;e.debug("formatting",{file:a});let p=Ce__default.extname(a);for(let u of await c(p)){e.debug("running",{command:u.command});try{let h=u.command.map(v=>v.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;})(vs||(vs={}));var Ao;(v=>{v.Tokens=U.object({accessToken:U.string(),refreshToken:U.string().optional(),expiresAt:U.number().optional(),scope:U.string().optional()}),v.ClientInfo=U.object({clientId:U.string(),clientSecret:U.string().optional(),clientIdIssuedAt:U.number().optional(),clientSecretExpiresAt:U.number().optional()}),v.Entry=U.object({tokens:v.Tokens.optional(),clientInfo:v.ClientInfo.optional(),codeVerifier:U.string().optional(),oauthState:U.string().optional(),serverUrl:U.string().optional()});let n=Ce__default.join(a$1.Path.data,"mcp-auth.json");async function s(P){return (await i())[P]}v.get=s;async function r(P,I){let A=await s(P);if(A&&A.serverUrl&&A.serverUrl===I)return A}v.getForUrl=r;async function i(){return PKG.file(n).json().catch(()=>({}))}v.all=i;async function c(P,I,A){PKG.file(n);let w=await i();A&&(I.serverUrl=A),await PKG.write(n,JSON.stringify({...w,[P]:I},null,2));}v.set=c;async function l(P){PKG.file(n);let A=await i();delete A[P],await PKG.write(n,JSON.stringify(A,null,2));}v.remove=l;async function d(P,I,A){let S=await s(P)??{};S.tokens=I,await c(P,S,A);}v.updateTokens=d;async function m(P,I,A){let S=await s(P)??{};S.clientInfo=I,await c(P,S,A);}v.updateClientInfo=m;async function f(P,I){let A=await s(P)??{};A.codeVerifier=I,await c(P,A);}v.updateCodeVerifier=f;async function a(P){let I=await s(P);I&&(delete I.codeVerifier,await c(P,I));}v.clearCodeVerifier=a;async function p(P,I){let A=await s(P)??{};A.oauthState=I,await c(P,A);}v.updateOAuthState=p;async function u(P){return (await s(P))?.oauthState}v.getOAuthState=u;async function h(P){let I=await s(P);I&&(delete I.oauthState,await c(P,I));}v.clearOAuthState=h;async function g(P){let I=await s(P);return I?.tokens?I.tokens.expiresAt?I.tokens.expiresAt<Date.now()/1e3:false:null}v.isTokenExpired=g;})(Ao||(Ao={}));a.create({service:"mcp.oauth"});var hr=19876,ym="/mcp/oauth/callback";var yr=a.create({service:"mcp.oauth-callback"}),yx=`<!DOCTYPE html>
35
- <html>
36
- <head>
37
- <title>EasBot - Authorization Successful</title>
38
- <style>
39
- 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; }
40
- .container { text-align: center; padding: 2rem; }
41
- h1 { color: #4ade80; margin-bottom: 1rem; }
42
- p { color: #aaa; }
43
- </style>
44
- </head>
45
- <body>
46
- <div class="container">
47
- <h1>Authorization Successful</h1>
48
- <p>You can close this window and return to EasBot.</p>
49
- </div>
50
- <script>setTimeout(() => window.close(), 2000);</script>
51
- </body>
52
- </html>`,ec=e=>`<!DOCTYPE html>
53
- <html>
54
- <head>
55
- <title>EasBot - Authorization Failed</title>
56
- <style>
57
- 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; }
58
- .container { text-align: center; padding: 2rem; }
59
- h1 { color: #f87171; margin-bottom: 1rem; }
60
- p { color: #aaa; }
61
- .error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
62
- </style>
63
- </head>
64
- <body>
65
- <div class="container">
66
- <h1>Authorization Failed</h1>
67
- <p>An error occurred during authorization.</p>
68
- <div class="error">${e}</div>
69
- </div>
70
- </body>
71
- </html>`,br;(d=>{let e,t=new Map,o=300*1e3;async function n(){if(e)return;if(await i()){yr.info("oauth callback server already running on another instance",{port:hr});return}e=createServer((f,a)=>{let p=new URL(f.url||"",`http://localhost:${hr}`);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"),v=p.searchParams.get("error_description");if(yr.info("received oauth callback",{hasCode:!!u,state:h,error:g}),!h){let I="Missing required state parameter - potential CSRF attack";yr.error("oauth callback missing state parameter",{url:p.toString()}),a.writeHead(400,{"Content-Type":"text/html"}),a.end(ec(I));return}if(g){let I=v||g;if(t.has(h)){let A=t.get(h);clearTimeout(A.timeout),t.delete(h),A.reject(new Error(I));}a.writeHead(200,{"Content-Type":"text/html"}),a.end(ec(I));return}if(!u){a.writeHead(400,{"Content-Type":"text/html"}),a.end(ec("No authorization code provided"));return}if(!t.has(h)){let I="Invalid or expired state parameter - potential CSRF attack";yr.error("oauth callback with invalid state",{state:h,pendingStates:Array.from(t.keys())}),a.writeHead(400,{"Content-Type":"text/html"}),a.end(ec(I));return}let P=t.get(h);clearTimeout(P.timeout),t.delete(h),P.resolve(u),a.writeHead(200,{"Content-Type":"text/html"}),a.end(yx);}).listen(hr),yr.info("oauth callback server started",{port:hr});}d.ensureRunning=n;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")));},o);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:hr});f.on("connect",()=>{f.end(),m(true);}),f.on("error",()=>{m(false);});})}d.isPortInUse=i;async function c(){e&&(e.close(),e=void 0,yr.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;})(br||(br={}));var Ue;(j=>{let e=a.create({service:"mcp"}),t=3e4;j.ToolsChanged=a$5.define("mcp.tools.changed",U.object({server:U.string()})),j.BrowserOpenFailed=a$5.define("mcp.browser.open.failed",U.object({mcpName:U.string(),url:U.string()})),j.Failed=NamedError.create("MCPFailed",U.object({name:U.string()}));function r(x){return typeof x=="object"&&x!==null&&"type"in x}async function i(){let k=(await he.get()).mcp??{},_={},L={};return await Promise.all(Object.entries(k).map(async([H,Y])=>{if(!r(Y)){e.error("Ignoring MCP config entry without type",{key:H});return}if(Y.enabled===false)return;let X=await p(H,Y).catch(()=>{});X&&(_[H]=X),L[H]={name:H,config:Y,scope:Y.scope};})),{clients:_,configInfo:L}}let c;function l(){return c||(c=R.state(i,async x=>{await initLog$3({logDir:a$1.Path.log,logFile:"mcp.log",level:a.getLevel(),print:false}),await Promise.all(Object.values(x.clients).map(k=>k.disconnect().catch(_=>{e.error("Failed to close MCP client",{error:_});}))),O.clear();})),c}async function d(){return l()()}function m(x){return x?x.status:{status:"disconnected"}}async function f(x,k){let _=await k.listPrompts().catch(H=>(e.error("failed to get prompts",{clientName:x,error:H.message}),[])),L={};for(let H of _){let Y=x.replace(/[^a-zA-Z0-9_-]/g,"_"),X=H.name.replace(/[^a-zA-Z0-9_-]/g,"_"),ne=Y+":"+X;L[ne]={...H,client:x};}return L}async function a$2(x,k){let _=await k.listResources().catch(H=>(e.error("failed to get resources",{clientName:x,error:H.message}),[])),L={};for(let H of _){let Y=x.replace(/[^a-zA-Z0-9_-]/g,"_"),X=H.name.replace(/[^a-zA-Z0-9_-]/g,"_"),ne=Y+":"+X;L[ne]={...H,client:x};}return L}async function p(x,k){if(k.enabled===false){e.info("mcp server disabled",{key:x});return}e.info("found",{key:x,type:k.type});let _=new MCPClient;if(k.type==="remote"){let H=k.oauth===false,Y=typeof k.oauth=="object"?k.oauth:void 0,X={type:"remote",url:k.url,headers:k.headers,oauth:H?false:Y,timeout:k.timeout},ne=k.timeout??t;try{await bl(_.connect(x,X),ne),_.setToolListChangedHandler(async()=>{e.info("tools list changed notification received",{server:x}),await ue.publish(j.ToolsChanged,{server:x});}),e.info("connected",{key:x});}catch(ae){_.isAuthRequired()?(O.set(x,_),ue.publish(b$2.ToastShow,{title:"MCP Authentication Required",message:`Server "${x}" requires authentication. Run: easbot mcp auth ${x}`,variant:"warning",duration:8e3}).catch(le=>e.debug("failed to show toast",{error:le}))):_.isClientRegistrationRequired()?ue.publish(b$2.ToastShow,{title:"MCP Authentication Required",message:`Server "${x}" requires a pre-registered client ID. Add clientId to your config.`,variant:"warning",duration:8e3}).catch(le=>e.debug("failed to show toast",{error:le})):e.error("remote mcp connection failed",{key:x,error:ae instanceof Error?ae.message:String(ae)});}}if(k.type==="local"){if(!k.command){e.error("MCP command is empty",{key:x});return}let H={type:"local",command:[k.command,...k.args??[]],cwd:R.directory,environment:k.env,timeout:k.timeout},Y=k.timeout??t;try{await bl(_.connect(x,H),Y),_.setToolListChangedHandler(async()=>{e.info("tools list changed notification received",{server:x}),await ue.publish(j.ToolsChanged,{server:x});}),e.info("local mcp connected",{key:x});}catch(X){e.error("local mcp startup failed",{key:x,command:k.command,args:k.args,cwd:R.directory,error:X instanceof Error?X.message:String(X)});}}if(_.status.status!=="connected")return _;let L=await bl(Promise.resolve(_.listTools()).then(H=>({tools:Object.values(H).map(Y=>Y)})),k.timeout??t).catch(H=>{e.error("failed to get tools from client",{key:x,error:H});});if(!L){await _.disconnect().catch(H=>{e.error("Failed to close MCP client",{error:H});});return}return e.info("create() successfully created client",{key:x,toolCount:L.tools.length}),_}async function u(x,k){let _=await d(),L=await p(x,k);if(!L)return {status:await h()};let H=_.clients[x];return H&&await H.disconnect().catch(Y=>{e.error("Failed to close existing MCP client",{name:x,error:Y});}),_.clients[x]=L,{status:await h()}}j.add=u;async function h(){let x=await d(),_=(await he.get()).mcp??{},L={};for(let[H,Y]of Object.entries(_)){if(!r(Y))continue;let X=x.clients[H];Y.enabled===false?L[H]={status:"disabled"}:L[H]=m(X);}return L}j.status=h;async function g(){return d().then(x=>x.clients)}j.clients=g;async function v(){return d().then(x=>x.configInfo)}j.configInfo=v;async function P(x){return (await v())[x]}j.getConfig=P;async function I(x){let L=((await he.get()).mcp??{})[x];if(!L){e.error("MCP config not found",{name:x});return}if(!r(L)){e.error("Ignoring MCP connect request for config without type",{name:x});return}let H=await p(x,L),Y=await d();if(H){let X=Y.clients[x];X&&await X.disconnect().catch(ne=>{e.error("Failed to close existing MCP client",{name:x,error:ne});}),Y.clients[x]=H;}}j.connect=I;async function A(x){let k=await d(),_=k.clients[x];_&&(await _.disconnect().catch(L=>{e.error("Failed to close MCP client",{name:x,error:L});}),delete k.clients[x]);}j.disconnect=A;async function S(){let x={},k=await he.get(),_=await g(),L=k.experimental?.mcp_timeout;for(let[H,Y]of Object.entries(_)){if(Y.status.status!=="connected")continue;let X=await Y.listTools().catch(ne=>(e.error("failed to get tools",{clientName:H,error:ne.message}),{}));for(let[ne,ae]of Object.entries(X)){let le=ae,be=H.replace(/[^a-zA-Z0-9_-]/g,"_"),se=ne.replace(/[^a-zA-Z0-9_-]/g,"_"),Q=be+"_"+se;x[Q]=await w(le,Y,L);}}return x}j.tools=S;async function w(x,k,_){let L=x.inputSchema,H={...L,type:"object",properties:L.properties??{},additionalProperties:false};return dynamicTool({description:x.description??"",inputSchema:jsonSchema(H),execute:async Y=>{let X=await k.callTool(x.name,Y||{},_);return {content:X.content.map(ne=>ne.type==="text"?{type:"text",text:ne.text??""}:ne.type==="image"?{type:"image",data:ne.data??"",mimeType:ne.mimeType}:ne.type==="resource"&&ne.resource?{type:"resource",resource:ne.resource}:{type:"text",text:String(ne)}),metadata:X.metadata}}})}async function y(){let x=await g(),k=await v(),_=[];for(let[L,H]of Object.entries(x)){if(H.status.status!=="connected")continue;let Y=await f(L,H),ne=k[L]?.scope??"all";for(let[ae,le]of Object.entries(Y))_.push([ae,{...le,scope:ne}]);}return Object.fromEntries(_)}j.prompts=y;async function b(){let x=await g();return Object.fromEntries((await Promise.all(Object.entries(x).map(async([_,L])=>L.status.status!=="connected"?[]:Object.entries(await a$2(_,L))))).flat())}j.resources=b;async function C(x,k,_){let H=(await g())[x];if(!H){e.warn("client not found for prompt",{clientName:x});return}return H.getPrompt(k,_).catch(Y=>{e.error("failed to get prompt from MCP server",{clientName:x,promptName:k,error:Y.message});})}j.getPrompt=C;async function E(x,k){let L=(await g())[x];if(!L){e.warn("client not found for resource",{clientName:x});return}return L.readResource(k).catch(H=>{e.error("failed to read resource from MCP server",{clientName:x,resourceUri:k,error:H.message});})}j.readResource=E;let O=new Map;async function D(x){let _=(await he.get()).mcp?.[x];if(!_)throw new Error(`MCP server not found: ${x}`);if(!r(_))throw new Error(`MCP server ${x} is disabled or missing configuration`);if(_.type!=="remote")throw new Error(`MCP server ${x} is not a remote server`);if(_.oauth===false)throw new Error(`MCP server ${x} has OAuth explicitly disabled`);await br.ensureRunning();let L=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(X=>X.toString(16).padStart(2,"0")).join("");await Ao.updateOAuthState(x,L);let H=typeof _.oauth=="object"?_.oauth:void 0,Y=new MCPClient;try{return await Y.connect(x,{type:"remote",url:_.url,headers:_.headers,oauth:H,timeout:_.timeout}),{authorizationUrl:""}}catch(X){if(Y.isAuthRequired())return O.set(x,Y),{authorizationUrl:Y.getAuthorizationUrl()};throw X}}j.startAuth=D;async function $(x){let{authorizationUrl:k}=await D(x);if(!k){let ne=(await d()).clients[x];return m(ne)}let _=await Ao.getOAuthState(x);if(!_)throw new Error("OAuth state not found");e.info("opening browser for oauth",{mcpName:x,url:k,state:_});let L=br.waitForCallback(_);try{let X=await vx(k);await new Promise((ne,ae)=>{let le=setTimeout(()=>ne(),500);X.on("error",be=>{clearTimeout(le),ae(be);}),X.on("exit",be=>{be!==null&&be!==0&&(clearTimeout(le),ae(new Error(`Browser open failed with exit code ${be}`)));});});}catch(X){e.warn("failed to open browser, user must open URL manually",{mcpName:x,error:X}),await ue.publish(j.BrowserOpenFailed,{mcpName:x,url:k});}let H=await L;if(await Ao.getOAuthState(x)!==_)throw await Ao.clearOAuthState(x),new Error("OAuth state mismatch");return await Ao.clearOAuthState(x),K(x,H)}j.authenticate=$;async function K(x,k){let _=O.get(x);if(!_)throw new Error(`No pending OAuth flow for MCP server: ${x}`);try{await _.finishAuth(k),await Ao.clearCodeVerifier(x);let H=(await he.get()).mcp?.[x];if(!H||!r(H))throw new Error(`MCP server not found: ${x}`);O.delete(x),await u(x,H);let Y=await d();return m(Y.clients[x])}catch(L){return e.error("failed to finish oauth",{mcpName:x,error:L}),{status:"failed",error:L instanceof Error?L.message:String(L)}}}j.finishAuth=K;async function ee(x){await Ao.remove(x),br.cancelPending(x),O.delete(x),await Ao.clearOAuthState(x),e.info("removed oauth credentials",{mcpName:x});}j.removeAuth=ee;async function N(x){let _=(await he.get()).mcp?.[x];return !_||!r(_)?false:_.type==="remote"&&_.oauth!==false}j.supportsOAuth=N;async function M(x){return !!(await Ao.get(x))?.tokens}j.hasStoredTokens=M;async function T(x){return await M(x)?await Ao.isTokenExpired(x)?"expired":"authenticated":"not_authenticated"}j.getAuthStatus=T;})(Ue||(Ue={}));function bl(e,t){return new Promise((o,n)=>{let s=setTimeout(()=>n(new Error(`Operation timed out after ${t}ms`)),t);e.then(r=>{clearTimeout(s),o(r);}).catch(r=>{clearTimeout(s),n(r);});})}var ss={};a$7(ss,{create:()=>ZI,createAgent:()=>cf,getAgent:()=>Tc,getDefaultAgent:()=>XI,list:()=>QI,listAgents:()=>af});var Oe;(y=>{let e=a.create({service:"permission"});function t(b){return b.startsWith("~/")?nc.homedir()+b.slice(1):b==="~"?nc.homedir():b.startsWith("$HOME/")?nc.homedir()+b.slice(5):b.startsWith("$HOME")?nc.homedir()+b.slice(5):b}y.Action=U.enum(["allow","deny","ask"]).meta({ref:"PermissionAction"}),y.Rule=U.object({permission:U.string(),pattern:U.string(),action:y.Action}).meta({ref:"PermissionRule"}),y.Ruleset=y.Rule.array().meta({ref:"PermissionRuleset"});function r(b){let C=[];for(let[E,O]of Object.entries(b)){if(typeof O=="string"){C.push({permission:E,action:O,pattern:"*"});continue}C.push(...Object.entries(O).map(([D,$])=>({permission:E,pattern:t(D),action:$})));}return C}y.fromConfig=r;function i(...b){return b.flat()}y.merge=i,y.Request=U.object({id:Identifier.schema("permission"),sessionId:Identifier.schema("session"),permission:U.string(),patterns:U.string().array(),metadata:U.record(U.string(),U.any()),always:U.string().array(),tool:U.object({messageId:U.string(),callId:U.string()}).optional()}).meta({ref:"PermissionRequest"}),y.Reply=U.enum(["once","always","reject"]),y.Approval=U.object({providerId:U.string(),patterns:U.string().array()}),y.Event={Asked:a$5.define("permission.asked",y.Request),Replied:a$5.define("permission.replied",U.object({sessionId:U.string(),requestId:U.string(),reply:y.Reply}))};let f;function a$1(){return f||(f=R.state(async()=>{let b=R.project.id,C=await a$6.read(["permission",b]).catch(()=>[]);return {pending:{},approved:C}})),f}function p(){return a$1()()}y.ask=fn$1(y.Request.partial({id:true}).extend({ruleset:y.Ruleset}),async b=>{let C=await p(),{ruleset:E,...O}=b;for(let D of O.patterns??[]){let $=g(O.permission,D,E,C.approved);if(e.debug("evaluated",{permission:O.permission,pattern:D,action:$}),$.action==="deny")throw new S(E.filter(K=>Wildcard.match(O.permission,K.permission)));if($.action==="ask"){let K=b.id??Identifier.ascending("permission");return new Promise((ee,N)=>{let M={id:K,...O};C.pending[K]={info:M,resolve:ee,reject:N},ue.publish(y.Event.Asked,M);})}}}),y.reply=fn$1(U.object({requestId:Identifier.schema("permission"),reply:y.Reply,message:U.string().optional()}),async b=>{let C=await p(),E=C.pending[b.requestId];if(E){if(delete C.pending[b.requestId],await ue.publish(y.Event.Replied,{sessionId:E.info.sessionId,requestId:E.info.id,reply:b.reply}),b.reply==="reject"){E.reject(b.message?new A(b.message):new I);let O=E.info.sessionId;for(let[D,$]of Object.entries(C.pending))$.info.sessionId===O&&(delete C.pending[D],await ue.publish(y.Event.Replied,{sessionId:$.info.sessionId,requestId:$.info.id,reply:"reject"}),$.reject(new I));return}if(b.reply==="once"){E.resolve();return}if(b.reply==="always"){for(let D of E.info.always)C.approved.push({permission:E.info.permission,pattern:D,action:"allow"});E.resolve();let O=E.info.sessionId;for(let[D,$]of Object.entries(C.pending))$.info.sessionId!==O||!$.info.patterns.every(ee=>g($.info.permission,ee,C.approved).action==="allow")||(delete C.pending[D],await ue.publish(y.Event.Replied,{sessionId:$.info.sessionId,requestId:$.info.id,reply:"always"}),$.resolve());return}}});function g(b,C,...E){let O=i(...E);return e.debug("evaluate",{permission:b,pattern:C,ruleset:O}),O.findLast($=>Wildcard.match(b,$.permission)&&Wildcard.match(C,$.pattern))??{action:"ask",permission:b,pattern:"*"}}y.evaluate=g;let v=["edit","write","patch","multiedit"];function P(b,C){let E=new Set;for(let O of b){let D=v.includes(O)?"edit":O,$=C.findLast(K=>Wildcard.match(D,K.permission));$&&$.pattern==="*"&&$.action==="deny"&&E.add(O);}return E}y.disabled=P;class I extends Error{constructor(){super("The user rejected permission to use this specific tool call.");}}y.RejectedError=I;class A extends Error{constructor(C){super(`The user rejected permission to use this specific tool call with the following feedback: ${C}`);}}y.CorrectedError=A;class S 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);}}y.DeniedError=S;async function w(){return p().then(b=>Object.values(b.pending).map(C=>C.info))}y.list=w;})(Oe||(Oe={}));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-VUQ33E5B.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?Oe.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,v=p.direction??"head",P=a.split(`
72
- `),I=Buffer.byteLength(a,"utf-8");if(P.length<=h&&I<=g)return {content:a,truncated:false};let A=[],S=0,w=0;if(v==="head")for(S=0;S<P.length&&S<h;S++){let N=P[S];if(!N)continue;let M=Buffer.byteLength(N,"utf-8")+(S>0?1:0);if(w+M>g){break}A.push(N),w+=M;}else for(S=P.length-1;S>=0&&A.length<h;S--){let N=P[S];if(!N)continue;let M=Buffer.byteLength(N,"utf-8")+(A.length>0?1:0);if(w+M>g){break}A.unshift(N),w+=M;}let b=P.length-A.length,C=I-w,E=A.join(`
73
- `),O=Identifier.ascending("tool"),D=Filesystem.join(f.DIR,O);await Tt__default.mkdir(f.DIR,{recursive:true}).catch(()=>{}),await Tt__default.writeFile(D,a,"utf-8");let $=l(u)?`The tool call succeeded but the output was truncated. Full output saved to: ${D}
74
- 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: ${D}
75
- Use Grep to search the full content or Read with offset/limit to view specific sections.`,K=`${b}/${P.length} lines (${C}/${I} bytes) truncated`;return {content:v==="head"?`${E}
76
-
77
- ...${K}...
78
-
79
- ${$}`:`...${K}...
80
-
81
- ${$}
82
-
83
- ${E}`,truncated:true,outputPath:D}}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}
84
- 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}
85
- 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 Cx(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 bt;(P=>{P.OUTPUT_TOKEN_MAX=a$2.EASBOT_OUTPUT_TOKEN_MAX||32e3;function t(I){switch(I){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 o(I,A,S){if(A.api.npm==="@ai-sdk/anthropic"&&(I=I.map(w=>{if(typeof w.content=="string")return w.content===""?void 0:w;if(!Array.isArray(w.content))return w;let y=w.content.filter(b=>b.type==="text"||b.type==="reasoning"?b.text!=="":true);if(y.length!==0)return {...w,content:y}}).filter(w=>w!==void 0&&w.content!=="")),A.api.id.includes("claude"))return I.map(w=>((w.role==="assistant"||w.role==="tool")&&Array.isArray(w.content)&&(w.content=w.content.map(y=>(y.type==="tool-call"||y.type==="tool-result")&&"toolCallId"in y?{...y,toolCallId:y.toolCallId.replace(/[^a-zA-Z0-9_-]/g,"_")}:y)),w));if(A.providerId==="mistral"||A.api.id.toLowerCase().includes("mistral")||A.api.id.toLocaleLowerCase().includes("devstral")){let w=[];for(let y=0;y<I.length;y++){let b=I[y];if(!b)continue;let C=I[y+1];(b.role==="assistant"||b.role==="tool")&&Array.isArray(b.content)&&(b.content=b.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(b),b.role==="tool"&&C?.role==="user"&&w.push({role:"assistant",content:[{type:"text",text:"Done."}]});}return w}if(typeof A.capabilities.interleaved=="object"&&A.capabilities.interleaved.field){let w=A.capabilities.interleaved.field;return I.map(y=>{if(y.role==="assistant"&&Array.isArray(y.content)){let C=y.content.filter(O=>O.type==="reasoning").map(O=>O.text).join(""),E=y.content.filter(O=>O.type!=="reasoning");return C?{...y,content:E,providerOptions:{...y.providerOptions,openaiCompatible:{...y.providerOptions?.openaiCompatible,[w]:C}}}:{...y,content:E}}return y})}return I}function n(I,A){let S=I.filter(b=>b.role==="system").slice(0,2),w=I.filter(b=>b.role!=="system").slice(-2),y={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 b of unique([...S,...w])){if(!(A==="anthropic"||A.includes("bedrock"))&&Array.isArray(b.content)&&b.content.length>0){let O=b.content[b.content.length-1];if(O&&typeof O=="object"){O.providerOptions=mergeDeep(O.providerOptions??{},y);continue}}b.providerOptions=mergeDeep(b.providerOptions??{},y);}return I}function s(I,A){return I.map(S=>{if(S.role!=="user"||!Array.isArray(S.content))return S;let w=S.content.map(y=>{if(y.type!=="file"&&y.type!=="image")return y;if(y.type==="image"){let D=y.image.toString();if(D.startsWith("data:")){let $=D.match(/^data:([^;]+);base64,(.*)$/);if($&&(!$[2]||$[2].length===0))return {type:"text",text:"ERROR: Image file is empty or corrupted. Please provide a valid image."}}}let b=y.type==="image"?y.image?.toString()?.split(";")?.[0]?.replace("data:",""):y.mediaType,C=y.type==="file"?y.filename:void 0,E=Cx(b??"");return !E||A.capabilities.input[E]?y:{type:"text",text:`ERROR: Cannot read ${C?`"${C}"`:E} (this model does not support ${E} input). Inform the user.`}});return {...S,content:w}})}function r(I,A,S){I=s(I,A),I=o(I,A),(A.providerId==="anthropic"||A.api.id.includes("anthropic")||A.api.id.includes("claude")||A.id.includes("anthropic")||A.id.includes("claude")||A.api.npm==="@ai-sdk/anthropic")&&(I=n(I,A.providerId));let w=t(A.api.npm);if(w&&w!==A.providerId&&A.api.npm!=="@ai-sdk/azure"){let y=b=>{if(!b||!(A.providerId in b))return b;let C={...b};return C[w]=C[A.providerId],delete C[A.providerId],C};I=I.map(b=>Array.isArray(b.content)?{...b,providerOptions:y(b.providerOptions),content:b.content.map(C=>({...C,providerOptions:y(C.providerOptions)}))}:{...b,providerOptions:y(b.providerOptions)});}return I}P.message=r;function i(I){let A=I.id.toLowerCase();if(A.includes("qwen"))return .55;if(!A.includes("claude")){if(A.includes("gemini")||A.includes("glm-4.6")||A.includes("glm-4.7")||A.includes("minimax-m2"))return 1;if(A.includes("kimi-k2"))return A.includes("thinking")||A.includes("k2.")||A.includes("k2p")?1:.6}}P.temperature=i;function c(I){let A=I.id.toLowerCase();if(A.includes("qwen"))return 1;if(A.includes("minimax-m2")||A.includes("kimi-k2.5")||A.includes("kimi-k2p5")||A.includes("gemini"))return .95}P.topP=c;function l(I){let A=I.id.toLowerCase();if(A.includes("minimax-m2"))return A.includes("m2.1")?40:20;if(A.includes("gemini"))return 64}P.topK=l;let d=["low","medium","high"],m=["none","minimal",...d,"xhigh"];function f(I){if(!I.capabilities.reasoning)return {};let A=I.id.toLowerCase();if(A.includes("deepseek")||A.includes("minimax")||A.includes("glm")||A.includes("mistral")||A.includes("kimi")||A.includes("k2p5"))return {};if(A.includes("grok")&&A.includes("grok-3-mini"))return I.api.npm==="@openrouter/ai-sdk-provider"?{low:{reasoning:{effort:"low"}},high:{reasoning:{effort:"high"}}}:{low:{reasoningEffort:"low"},high:{reasoningEffort:"high"}};if(A.includes("grok"))return {};switch(I.api.npm){case "@openrouter/ai-sdk-provider":return !I.id.includes("gpt")&&!I.id.includes("gemini-3")?{}:Object.fromEntries(m.map(S=>[S,{reasoning:{effort:S}}]));case "@ai-sdk/gateway":return Object.fromEntries(m.map(S=>[S,{reasoningEffort:S}]));case "@ai-sdk/github-copilot":{if(I.id.includes("gemini"))return {};if(I.id.includes("claude"))return {thinking:{thinking_budget:4e3}};let S=iife(()=>A.includes("5.1-codex-max")||A.includes("5.2")||A.includes("5.3")?[...d,"xhigh"]:d);return Object.fromEntries(S.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(S=>[S,{reasoningEffort:S}]));case "@ai-sdk/azure":{if(A==="o1-mini")return {};let S=["low","medium","high"];return (A.includes("gpt-5-")||A==="gpt-5")&&S.unshift("minimal"),Object.fromEntries(S.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/openai":{if(A==="gpt-5-pro")return {};let S=iife(()=>{if(A.includes("codex"))return A.includes("5.2")||A.includes("5.3")?[...d,"xhigh"]:d;let w=[...d];return (A.includes("gpt-5-")||A==="gpt-5")&&w.unshift("minimal"),I.release_date>="2025-11-13"&&w.unshift("none"),I.release_date>="2025-12-04"&&w.push("xhigh"),w});return Object.fromEntries(S.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(I.limit.output/2-1))}},max:{thinking:{type:"enabled",budgetTokens:Math.min(31999,I.limit.output-1)}}};case "@ai-sdk/amazon-bedrock":return I.api.id.includes("anthropic")?{high:{reasoningConfig:{type:"enabled",budgetTokens:16e3}},max:{reasoningConfig:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(d.map(S=>[S,{reasoningConfig:{type:"enabled",maxReasoningEffort:S}}]));case "@ai-sdk/google-vertex":case "@ai-sdk/google":return A.includes("2.5")?{high:{thinkingConfig:{includeThoughts:true,thinkingBudget:16e3}},max:{thinkingConfig:{includeThoughts:true,thinkingBudget:24576}}}:Object.fromEntries(["low","high"].map(S=>[S,{includeThoughts:true,thinkingLevel:S}]));case "@ai-sdk/mistral":return {};case "@ai-sdk/cohere":return {};case "@ai-sdk/groq":{let S=["none",...d];return Object.fromEntries(S.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 I.api.id.includes("anthropic")?{high:{thinking:{type:"enabled",budgetTokens:16e3}},max:{thinking:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(d.map(S=>[S,{reasoningEffort:S}]))}return {}}P.variants=f;function a(I){let A={};(I.model.providerId==="openai"||I.model.api.npm==="@ai-sdk/openai"||I.model.api.npm==="@ai-sdk/github-copilot")&&(A.store=false),I.model.api.npm==="@openrouter/ai-sdk-provider"&&(A.usage={include:true},I.model.api.id.includes("gemini-3")&&(A.reasoning={effort:"high"})),(I.model.providerId==="baseten"||I.model.providerId==="easbot"&&["kimi-k2-thinking","glm-4.6"].includes(I.model.api.id))&&(A.chat_template_args={enable_thinking:true}),["zai","zhipuai"].includes(I.model.providerId)&&I.model.api.npm==="@ai-sdk/openai-compatible"&&(A.thinking={type:"enabled",clear_thinking:false}),(I.model.providerId==="openai"||I.providerOptions?.setCacheKey)&&(A.promptCacheKey=I.sessionId),(I.model.api.npm==="@ai-sdk/google"||I.model.api.npm==="@ai-sdk/google-vertex")&&(A.thinkingConfig={includeThoughts:true},I.model.api.id.includes("gemini-3")&&(A.thinkingConfig.thinkingLevel="high"));let S=I.model.api.id.toLowerCase();return (I.model.api.npm==="@ai-sdk/anthropic"||I.model.api.npm==="@ai-sdk/google-vertex/anthropic")&&(S.includes("k2p5")||S.includes("kimi-k2.5")||S.includes("kimi-k2p5"))&&(A.thinking={type:"enabled",budgetTokens:Math.min(16e3,Math.floor(I.model.limit.output/2-1))}),I.model.providerId==="alibaba-cn"&&I.model.capabilities.reasoning&&I.model.api.npm==="@ai-sdk/openai-compatible"&&!S.includes("kimi-k2-thinking")&&(A.enable_thinking=true),I.model.api.id.includes("gpt-5")&&!I.model.api.id.includes("gpt-5-chat")&&(I.model.api.id.includes("gpt-5-pro")||(A.reasoningEffort="medium",A.reasoningSummary="auto"),I.model.api.id.includes("gpt-5.")&&!I.model.api.id.includes("codex")&&!I.model.api.id.includes("-chat")&&I.model.providerId!=="azure"&&(A.textVerbosity="low"),I.model.providerId.startsWith("easbot")&&(A.promptCacheKey=I.sessionId,A.include=["reasoning.encrypted_content"],A.reasoningSummary="auto")),I.model.providerId==="venice"&&(A.promptCacheKey=I.sessionId),A}P.options=a;function p(I){return I.providerId==="openai"||I.api.npm==="@ai-sdk/openai"||I.api.npm==="@ai-sdk/github-copilot"?I.api.id.includes("gpt-5")?I.api.id.includes("5.")?{store:false,reasoningEffort:"low"}:{store:false,reasoningEffort:"minimal"}:{store:false}:I.providerId==="google"?I.api.id.includes("gemini-3")?{thinkingConfig:{thinkingLevel:"minimal"}}:{thinkingConfig:{thinkingBudget:0}}:I.providerId==="openrouter"?I.api.id.includes("google")?{reasoning:{enabled:false}}:{reasoningEffort:"minimal"}:{}}P.smallOptions=p;let u={amazon:"bedrock"};function h(I,A){if(I.api.npm==="@ai-sdk/gateway"){let w=I.api.id.indexOf("/"),y=w>0?I.api.id.slice(0,w):void 0,b=y?u[y]??y:void 0,C=A.gateway,E=Object.fromEntries(Object.entries(A).filter(([$])=>$!=="gateway")),O=Object.keys(E).length>0,D={};return C!==void 0&&(D.gateway=C),O&&(b?D[b]=E:C&&typeof C=="object"&&!Array.isArray(C)?D.gateway={...C,...E}:D.gateway=E),D}return {[t(I.api.npm)??I.providerId]:A}}P.providerOptions=h;function g(I){return Math.min(I.limit.output,P.OUTPUT_TOKEN_MAX)||P.OUTPUT_TOKEN_MAX}P.maxOutputTokens=g;function v(I,A){if(I.providerId==="google"||I.api.id.includes("gemini")){let S=w=>{if(w===null||typeof w!="object")return w;if(Array.isArray(w))return w.map(S);let y={};for(let[b,C]of Object.entries(w))b==="enum"&&Array.isArray(C)?(y[b]=C.map(E=>String(E)),(y.type==="integer"||y.type==="number")&&(y.type="string")):typeof C=="object"&&C!==null?y[b]=S(C):y[b]=C;return y.type==="object"&&y.properties&&Array.isArray(y.required)&&(y.required=y.required.filter(b=>b in y.properties)),y.type==="array"&&(y.items==null&&(y.items={}),typeof y.items=="object"&&!Array.isArray(y.items)&&!y.items.type&&(y.items.type="string")),y.type&&y.type!=="object"&&(delete y.properties,delete y.required),y};A=S(A);}return A}P.schema=v;})(bt||(bt={}));function Jt(e,t){let o=typeof e=="string"?e:"anonymous",n=typeof e=="string"?t:e,{init:s}=n,r=s instanceof Function?s:()=>s;return {name:o,init:r}}var Ei=a.create({service:"forked-agent"}),wr;(o=>{async function e(n){let{source:s,title:r,agent:i,parts:c,model:l,system:d,tools:m,syncMessages:f,metadata:a}=n,p=await Z.fork({sessionId:s});try{let u=await Ke.lastUserMessage(s),h=i??u?.agent??await Ne.defaultAgent(),g;if(l?.providerId&&l.modelId?g={providerId:l.providerId,modelId:l.modelId}:g=(await Ne.get(h))?.model,!l){let{Provider:A}=await import('./provider-TU4AF2GP.mjs');g=u?.model??await A.defaultModel();}Ei.debug("forked started and session created",{sessionId:p.id,source:s,title:r,agent:h,model:g}),await Ke.prompt({sessionId:p.id,system:d,tools:m,agent:h,model:g,parts:c??[]}),Ei.debug("forked agent prompt sent",{sessionId:p.id,agent:h});let v=await ve.getLastMessages(p.id,{filterByText:!0}),P="";v.lastAssistantWithText&&(P=v.lastAssistantWithText.parts.filter(A=>A.type==="text").map(A=>A.text).join(""));let I={title:r,output:P,metadata:{...a,sessionId:p.id,source:s,agent:h,userMessage:v.lastUser,assistantMessage:v.lastAssistant}};if(f&&v.lastUser&&v.lastFinished){let A=await t(p.id,s,v,h);I.metadata.userMessage=A.userMessage,I.metadata.assistantMessage=A.assistantMessage;}return Ei.debug("forked agent completed",{sessionId:p.id,source:s,title:r,agent:h,contentLength:P.length,hasText:P.length>0,lastUser:v.lastUser?.id,lastAssistant:v.lastAssistant?.id,lastFinished:v.lastFinished?.info?.id}),I}finally{await Z.remove(p.id),Ei.debug("forked session removed",{sessionId:p.id});}}o.run=e;async function t(n,s,r,i){if(!r.lastUser||!r.lastFinished)throw new Error("Messages not found in forked session");let c=i??r.lastUser.agent??await Ne.defaultAgent(),l=Identifier.ascending("message"),d={...r.lastUser,id:l,agent:c,sessionId:s};await Z.updateMessage(d);for(let a of r.lastUserMessage.parts)await Z.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 Z.updateMessage(f);for(let a of r.lastFinished.parts)await Z.updatePart({...a,id:Identifier.ascending("part"),messageId:m,sessionId:s});return Ei.debug("messages synced",{fromSessionID:n,toSessionID:s,userMessageId:l,assistantMessageId:m}),{userMessage:d,assistantMessage:f}}o.syncMessagesToParent=t;})(wr||(wr={}));var wo;(f=>{let e=a.create({service:"knowledge.memory"}),t;async function o(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),v=h||"easbot-local",P=g||"bge-base-zh-v1.5",I=await Se.getEmbedding(v,P),A=a?.graph?.model||p.graph_model,S,w;if(A){let{provider:b,model:C}=parseModelId(A);S=b||"easbot-local",w=C||A;}else {let b=await Se.defaultModel();S=b.providerId,w=b.modelId;}let y;try{let b=await Se.getModel(S,w);y=await Se.getLanguage(b);}catch(b){e.error("memory loadModels graphLlm failed",{graphProvider:S,graphModel:w,error:String(b)});}return e.debug("memory loadModels result",{embeddingLlm:!!I,graphLlm:!!y,graphModelId:A}),{embeddingLlm:I,graphLlm:y}}function n(){return t||(t=R.state(async()=>{let a$1=await ir();if(e.info("Memory.init() cfg",{cfg:a$1,enabled:a$1?.enabled}),!a$1||a$1.enabled===false)return e.debug("memory knowledge base disabled",{reason:a$1?"enabled is false":"cfg is undefined"}),{system:null,config:null,rootDir:"",initialized:true};let{Global:p}=await import('./global-XQYOBWZR.mjs'),u=R.directory,h=Filesystem.normalize(a$1?.workspaceDir?Ce__default.isAbsolute(a$1.workspaceDir)?a$1.workspaceDir:Ce__default.resolve(u,a$1.workspaceDir):Ce__default.join(u,".easbot","memory")),g=Filesystem.normalize(a$1?.database?Ce__default.isAbsolute(a$1.database)?a$1.database:Ce__default.resolve(u,a$1.database):Ce__default.join(R.worktree,".easbot","db","memory.db")),{embeddingLlm:v,graphLlm:P}=await o(a$1);await initLog({logDir:p.Path.log,logFile:"memory.log",level:a.getLevel(),print:false});let I=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:v,graphLlm:P});return e.debug("memory system initialized",{memoryRootDir:h,dbPath:g}),{system:I,config:a$1??null,rootDir:h,initialized:true}},async a=>{a.system&&await a?.system?.close().catch(()=>{});})),t}function s(){return n()()}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;})(wo||(wo={}));var Yt;(p=>{let e=a.create({service:"knowledge.note"}),t;async function o(u){let h=await he.get(),g=u?.embedding?.model||h.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:v,model:P}=parseModelId(g),I=v||"easbot-local",A=P||"bge-base-zh-v1.5",S=await Se.getEmbedding(I,A),w=u?.graph?.model??h.graph_model,y,b;if(w){let{provider:K,model:ee}=parseModelId(w);y=K||"easbot-local",b=ee||w;}else {let K=await Se.defaultModel();y=K.providerId,b=K.modelId;}let C;try{let K=await Se.getModel(y,b);C=await Se.getLanguage(K);}catch(K){e.error("note loadModels graphLlm failed",{graphProvider:y,graphModel:b,error:String(K)});}let E=u?.rerank?.model||h.rerank_model,O,D;if(E){let{provider:K,model:ee}=parseModelId(E);O=K||"easbot-local",D=ee||E;}else {let K=await Se.defaultModel();O="easbot-local",D=`rerank-${K.providerId}/${K.modelId}`;}let $;try{$=await Se.getRerank(O,D);}catch(K){e.error("note loadModels rerankLlm failed",{rerankProvider:O,rerankModel:D,error:String(K)});}return e.debug("loadModels result",{embeddingLoaded:S?"yes":"no",graphLlmLoaded:C?"yes":"no",graphModelId:w,rerankLlmLoaded:$?"yes":"no"}),{embeddingLlm:S,graphLlm:C,rerankLlm:$}}function n(){return t||(t=R.state(async()=>{let u=await sr();if(!u||u.enabled===false)return e.debug("note knowledge base disabled or not configured"),{kb:null,config:null,rootDir:"",sources:[],initialized:true};let{Global:h}=await import('./global-XQYOBWZR.mjs'),g=R.worktree??R.directory,v=Filesystem.normalize(Ce__default.join(g,".easbot","knowledge")),P=Filesystem.normalize(u.database?Ce__default.isAbsolute(u.database)?u.database:Ce__default.resolve(g,u.database):Ce__default.join(R.worktree,".easbot","db","note.db")),{embeddingLlm:I,graphLlm:A,rerankLlm:S}=await o(u),w=(u?.sources?.length??0)>0?u.sources:["docs","tasks"];for(let C of w??[]){let E=Filesystem.normalize(Ce__default.join(v,C));await Filesystem.exists(E)||(await Filesystem.mkdir(E),e.debug("created source directory",{sourceDir:E}));}let y={workspaceDir:v,vectorDims:u.embedding?.dimensions??1,embeddingLlm:I,graphLlm:A,rerankLlm:S,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(Ce__default.join(R.worktree,".gitignore"))).filter(C=>!C.includes(".easbot"))],incremental:u.indexer?.incremental??true},sync:u.sync,sources:w};P&&(y.database={path:P,walMode:true}),await initLog$1({logDir:h.Path.log,logFile:"note.log",level:a.getLevel(),print:false});let b=await createNoteKnowledge(y);return u.sync?.onBoot&&await b.sync().catch(C=>e.warn("note sync on boot failed",{error:String(C)})),e.info("note knowledge base initialized",{noteRootDir:v,dbPath:P}),{kb:b,config:u??null,rootDir:v,sources:w??[],initialized:true}},async u=>{u.kb&&await u?.kb?.close().catch(()=>{});})),t}function s(){return n()()}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 jn;(p=>{let e=a.create({service:"knowledge.codebase"}),t;async function o(u){let h=await he.get(),g=u?.embedding?.model||h.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:v,model:P}=parseModelId(g),I=v||"easbot-local",A=P||"bge-base-zh-v1.5";try{return await Se.getEmbedding(I,A)}catch(S){return e.warn("failed to load embedding model, using easbot-local/bge-base-zh-v1.5",{error:S}),Se.getEmbedding("easbot-local","bge-base-zh-v1.5")}}function n(){return t||(t=R.state(async()=>{let u=await rr();if(!u||u.enabled===false)return e.debug("codebase knowledge base disabled or not configured"),{codebase:null,config:null,rootDir:"",initialized:true};let{Global:h}=await import('./global-XQYOBWZR.mjs'),g=Filesystem.normalize(R.worktree??R.directory),v=Filesystem.normalize(u.database?Ce__default.isAbsolute(u.database)?u.database:Ce__default.resolve(g,u.database):Ce__default.join(R.worktree,".easbot","db","codebase.db")),P=await o(u);await initLog$2({logDir:h.Path.log,logFile:"codebase.log",level:a.getLevel(),print:false});let I=await createCodebase({workspaceDir:g,database:{path:v,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(Ce__default.join(R.worktree,".gitignore"))).filter(A=>!A.includes(".easbot"))],incremental:u.indexer?.incremental??true},sync:u.sync,embeddingLlm:P});return u.sync?.onBoot&&await I.sync().catch(A=>e.warn("codebase sync on boot failed",{error:String(A)})),e.info("codebase knowledge base initialized",{workspaceDir:g,dbPath:v}),{codebase:I,config:u,rootDir:g,initialized:true}},async u=>{u.codebase&&await u?.codebase?.close().catch(()=>{});})),t}function s(){return n()()}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;})(jn||(jn={}));var es=a.create({service:"hook.builtin.memory"}),Em=2e3,xl=new Map;function Am(e,t){return `${e}:${t??"default"}`}async function Lx(e,t,o){let n=[];if(t){let r=t.parts.filter(i=>i.type==="text").map(i=>i.text).join("");r&&n.push({role:"user",content:r});}let s=await ve.get({sessionId:e,messageId:o});if(s){let r=s.parts.filter(i=>i.type==="text").map(i=>i.text).join("");r&&n.push({role:"assistant",content:r});}return n}async function Dx(e){if(e.length===0)return "";let t=`### Our Conversation
86
-
87
- `;for(let o of e.slice(-4)){let n=Token.estimate(o.content),s=o.content,r=false;if(n>Em){s=o.content.slice(-8e3),r=true;}r?t+=`**${o.role==="user"?"User":"Me"}**: ${s}
88
-
89
- [Content truncated from ${n} tokens]
90
-
91
- `:t+=`**${o.role==="user"?"User":"Me"}**: ${s||"(empty)"}
92
-
93
- `;}return t}function $x(){return `### My Reflection
94
-
95
- After reading this conversation, I ask myself:
96
-
97
- **Mistakes & Corrections:**
98
- - Did I make any mistakes the user corrected?
99
- - What errors should I avoid next time?
100
- - Is there a pattern I keep getting wrong?
101
-
102
- **Better Approaches:**
103
- - Was there a smarter way to solve this?
104
- - What approach would be more efficient?
105
- - Any workflow improvements I discovered?
106
-
107
- **Knowledge & Context:**
108
- - What new insights did I gain?
109
- - What preferences did the user show?
110
- - What context is important for future work?
111
-
112
- **Evolution:**
113
- - How can I do better next time?
114
- - What should I remember to improve my effectiveness?
115
-
116
- If nothing special happened, don't save anything.
117
-
118
- Importance 1-10, skip 1-3`}var Il=Jt("memory",{async init(){return await wo.isEnabled()?{isEnabled:()=>true,handlers:[{name:HookEvent.StepStart,handler:(t,o)=>{let n=t;if(!n.userMessageId)return {modified:false,input:t};let s=Am(n.sessionId,n.userMessageId);return xl.set(s,{startTime:Date.now()}),es.debug("step start recorded",{key:s}),{modified:false,input:t}}},{name:HookEvent.StepFinish,handler:async(t,o)=>{let n=t;if(!n.userMessageId)return es.debug("step.finish: no userMessageId, skip"),{modified:false,input:t};let s=Am(n.sessionId,n.userMessageId);es.debug("step.finish: memory extract started",{convKey:s,finishReason:n.finishReason,messageId:n.messageId});let r=await ve.get({sessionId:n.sessionId,messageId:n.userMessageId});if(r?.parts.some(u=>u.type==="memory"))return es.debug("step.finish: skip memory extract, already processing"),{modified:false,input:t};let i=Identifier.ascending("part"),c=Date.now(),l={id:i,sessionId:n.sessionId,messageId:n.userMessageId,type:"memory",status:"processing",time:{start:c}};await Z.updatePart(l);let d=xl.get(s);xl.delete(s);let m="";d&&(m=`Step Duration: ${((Date.now()-d.startTime)/1e3).toFixed(1)}s`);let f=await Lx(n.sessionId,r,n.messageId);if(!f.some(u=>u.role==="assistant"&&u.content))return es.debug("step.finish: skip memory extract, no assistant text content",{convKey:s,finishReason:n.finishReason,messageId:n.messageId}),await Z.updatePart({...l,status:"skipped",time:{start:c,end:Date.now()},reason:`No assistant text content (finish: ${n.finishReason})`}),{modified:false,input:t};let p=`## Conversation Reflection
119
-
120
- Local Time: ${formatLocalISOCompact(new Date)}
121
- Finish Reason: ${n.finishReason}
122
- ${m?`${m}
123
- `:""}${n.tokens?`Tokens Used: ${n.tokens.total??0}
124
- `:""}}
125
-
126
- ${await Dx(f)}
127
-
128
- ${$x()}`;return wr.run({source:n.sessionId,title:"memory-extract",agent:"memory",syncMessages:false,parts:[{type:"memory",status:"processing",time:{start:c}},{type:"text",text:p}]}).then(async u=>{es.debug("memory extract completed",{outputLength:u.output.length}),await Z.updatePart({...l,status:"completed",time:{start:c,end:Date.now()},result:u.output});}).catch(async u=>{es.error("memory extract failed",{error:u.message}),await Z.updatePart({...l,status:"failed",time:{start:c,end:Date.now()},error:u.message});}),{modified:false,input:t}}}]}:(es.debug("memory hook disabled, skipping"),{isEnabled:()=>false,handlers:[]})}});var vr;(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;})(vr||(vr={}));var Mt;(l=>{l.Info=U.union([U.object({type:U.literal("idle")}),U.object({type:U.literal("retry"),attempt:U.number(),message:U.string(),next:U.number()}),U.object({type:U.literal("busy")})]).meta({ref:"SessionStatus"}),l.Event={Status:a$5.define("session.status",U.object({sessionId:U.string(),status:l.Info}))};let o;function n(){return o||(o=R.state(async()=>({}))),o}function s(){return n()()}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 ue.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 ts;(s=>{let e=a.create({service:"llm"});s.OUTPUT_TOKEN_MAX=bt.OUTPUT_TOKEN_MAX;async function o(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([Se.getLanguage(r.model),he.get(),Se.getProvider(r.model.providerId),Qe.get(r.model.providerId)]),f=d?.id==="openai"&&m?.type==="oauth",a=[r.system.filter(E=>E).join(`
129
- `)],p=a[0];if(a.length>2&&a[0]===p){let E=a.slice(1);a.length=0,a.push(p,E.join(`
130
- `));}let u=!r.small&&r.model.variants&&r.user.variant?r.model.variants[r.user.variant]:{},h=r.small?bt.smallOptions(r.model):bt.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(`
131
- `));let v=await Le.triggerEvent(HookEvent.LlmParams,{sessionId:r.sessionId,agent:r.agent.name,model:r.model,provider:d,message:r.user}),P=Object.assign({temperature:r.model.capabilities.temperature?r.agent.temperature??bt.temperature(r.model):void 0,topP:r.agent.topP??bt.topP(r.model),topK:bt.topK(r.model),options:g},v.output??{}),A=(await Le.triggerEvent(HookEvent.LlmHeaders,{sessionId:r.sessionId,agent:r.agent.name,model:r.model,provider:d,message:r.user})).output?.headers??{},S=f||d?.id?.includes("github-copilot")?void 0:bt.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&&n(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 b=[...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:P.temperature,topP:P.topP,topK:P.topK,providerOptions:bt.providerOptions(r.model,P.options??{}),activeTools:Object.keys(w).filter(E=>E!=="invalid"),tools:w,maxOutputTokens:S,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,...A},maxRetries:r.retries??0,system:b,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=bt.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=o;function n(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=n;})(ts||(ts={}));var Xt=a.create({service:"compaction.cache"}),Mm=100,Om=25*1024*1024,jm=300*1e3,Rm="cache.json",Kx={maxEntries:Mm,maxSizeBytes:Om,ttlMs:jm,persist:false};function kl(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??Mm,maxSizeBytes:t?.maxSizeBytes??Om,ttlMs:t?.ttlMs??jm,persist:t?.persist??false,sessionId:t?.sessionId},this.cache=new LRUCache({max:this.config.maxEntries,maxSize:this.config.maxSizeBytes,sizeCalculation:o=>{let n=o.value,s=typeof n=="string"?n:n==null?"":typeof n=="object"?JSON.stringify(n):String(n);return Math.max(1,Buffer.byteLength(s,"utf8"))},ttl:this.config.ttlMs,updateAgeOnGet:true,updateAgeOnHas:true}),Xt.debug("compaction cache initialized",{maxEntries:this.config.maxEntries,maxSizeBytes:this.config.maxSizeBytes,ttlMs:this.config.ttlMs});}get(t){let o=this.cache.get(t);if(o!==void 0)return this.hits++,Xt.debug("cache hit",{key:t,hits:this.hits,misses:this.misses}),o.value;this.misses++,Xt.debug("cache miss",{key:t,hits:this.hits,misses:this.misses});}set(t,o){let n={value:o,timestamp:Date.now()};return this.cache.set(t,n),Xt.debug("cache set",{key:t,size:this.cache.size}),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,Xt.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){Xt.debug("persist skipped: persistence disabled or no sessionId");return}let t=kl(this.config.sessionId),o=join(t,Rm),n={entries:this.entries(),stats:this.getStats(),timestamp:Date.now()};try{await mkdir(t,{recursive:!0}),await writeFile(o,JSON.stringify(n),"utf-8"),Xt.info("cache persisted",{path:o,entries:n.entries.length});}catch(s){throw Xt.error("cache persist failed",{error:String(s)}),s}}async restoreFromFile(){if(!this.config.persist||!this.config.sessionId){Xt.debug("restore skipped: persistence disabled or no sessionId");return}let t=kl(this.config.sessionId),o=join(t,Rm);try{let n=await readFile(o,"utf-8"),s=JSON.parse(n);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);Xt.info("cache restored",{path:o,entries:this.cache.size});}catch(n){Xt.warn("cache restore failed, starting fresh",{error:String(n)});}}dump(){return {entries:this.entries(),stats:this.getStats()}}load(t){for(let[o,n]of t.entries)Date.now()-n.timestamp<this.config.ttlMs&&this.cache.set(o,n);Xt.debug("cache loaded",{entries:this.cache.size});}};function Jx(e){return new dc(e)}async function Yx(e){let t=kl(e);try{await rm$1(t,{recursive:!0,force:!0}),Xt.info("session cache cleared",{sessionId:e,path:t});}catch(o){Xt.warn("failed to clear session cache",{sessionId:e,error:String(o)});}}function Xx(){ue.subscribe(Z.Event.Deleted,async e=>{Xt.debug("session.deleted event received",{sessionId:e.properties.info.id}),await Yx(e.properties.info.id);}),Xt.info("cache events subscribed");}var Pl=class{constructor(t){b$1(this,"cache");b$1(this,"config");let o={ttlMs:3e5,maxSizeBytes:26214400,maxEntries:100,persist:false};this.config={...o,...t},this.cache=new LRUCache({max:this.config.maxEntries,maxSize:this.config.maxSizeBytes,sizeCalculation:n=>Buffer.byteLength(n.originalOutput,"utf8")+Buffer.byteLength(JSON.stringify(n.metadata),"utf8"),ttl:this.config.ttlMs,updateAgeOnGet:true}),Xt.debug("compaction backup cache initialized",{ttlMs:this.config.ttlMs,maxSizeBytes:this.config.maxSizeBytes,maxEntries:this.config.maxEntries});}getKey(t,o){return `${t}:${o}`}async backup(t){let o=this.getKey(t.sessionId,t.partId);this.cache.set(o,t),Xt.debug("backup created",{sessionId:t.sessionId,partId:t.partId});}get(t,o){let n=this.getKey(t,o);return this.cache.get(n)}has(t,o){let n=this.getKey(t,o);return this.cache.has(n)}delete(t,o){let n=this.getKey(t,o);return this.cache.delete(n)}clearSession(t){let o=`${t}:`;for(let n of this.cache.keys())n.startsWith(o)&&this.cache.delete(n);Xt.debug("session backups cleared",{sessionId:t});}clear(){this.cache.clear();}size(){return this.cache.size}getStats(){return {size:this.cache.size,calculatedSize:this.cache.calculatedSize??0}}},Sl;function os(){return Sl||(Sl=new Pl),Sl}var Ri={async backup(e){await os().backup(e);},get(e,t){return os().get(e,t)},has(e,t){return os().has(e,t)},delete(e,t){return os().delete(e,t)},clearSession(e){os().clearSession(e);},clear(){os().clear();},size(){return os().size()},getStats(){return os().getStats()}};var Ot;(h=>{let e=a.create({service:"question"});h.Option=U.object({label:U.string().describe("Display text (1-5 words, concise)"),description:U.string().describe("Explanation of choice")}).meta({ref:"QuestionOption"}),h.Info=U.object({question:U.string().describe("Complete question"),header:U.string().describe("Very short label (max 30 chars)"),options:U.array(h.Option).describe("Available choices"),multiple:U.boolean().optional().describe("Allow selecting multiple choices"),custom:U.boolean().optional().describe("Allow typing a custom answer (default: true)")}).meta({ref:"QuestionInfo"}),h.Request=U.object({id:Identifier.schema("question"),sessionId:Identifier.schema("session"),questions:U.array(h.Info).describe("Questions to ask"),tool:U.object({messageId:U.string(),callId:U.string()}).optional()}).meta({ref:"QuestionRequest"}),h.Answer=U.array(U.string()).meta({ref:"QuestionAnswer"}),h.Reply=U.object({answers:U.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",U.object({sessionId:U.string(),requestId:U.string(),answers:U.array(h.Answer)})),Rejected:a$5.define("question.rejected",U.object({sessionId:U.string(),requestId:U.string()}))};let c;function l(){return c||(c=R.state(async()=>({pending:{}}))),c}function d(){return l()()}async function m(g){let v=await d(),P=Identifier.ascending("question");return e.info("asking",{id:P,questions:g.questions.length}),new Promise((I,A)=>{let S={id:P,sessionId:g.sessionId,questions:g.questions,tool:g.tool};v.pending[P]={info:S,resolve:I,reject:A},ue.publish(h.Event.Asked,S);})}h.ask=m;async function f(g){let v=await d(),P=v.pending[g.requestId];if(!P){e.warn("reply for unknown request",{requestId:g.requestId});return}delete v.pending[g.requestId],e.info("replied",{requestId:g.requestId,answers:g.answers}),await ue.publish(h.Event.Replied,{sessionId:P.info.sessionId,requestId:P.info.id,answers:g.answers}),P.resolve(g.answers);}h.reply=f;async function a$1(g){let v=await d(),P=v.pending[g];if(!P){e.warn("reject for unknown request",{requestId:g});return}delete v.pending[g],e.info("rejected",{requestId:g}),await ue.publish(h.Event.Rejected,{sessionId:P.info.sessionId,requestId:P.info.id}),P.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(v=>v.info))}h.list=u;})(Ot||(Ot={}));var Cr;(n=>{let t=a.create({service:"session.processor"});function o(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 ts.stream(f);for await(let v of g.fullStream){switch(s.abort.throwIfAborted(),v.type){case "start":await Mt.set(s.sessionId,{type:"busy"});break;case "reasoning-start":if(v.id in h)continue;h[v.id]={id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"reasoning",text:"",time:{start:Date.now()},metadata:v.providerMetadata},await Z.updatePart(h[v.id]);break;case "reasoning-delta":if(v.id in h){let P=h[v.id];if(!P){t.warn("reasoning-delta: part not found in map",{id:v.id});break}let I=v.delta||v.text||"";P.text+=I,v.providerMetadata&&(P.metadata=v.providerMetadata),P.text&&await Z.updatePart({part:P,delta:I});}break;case "reasoning-end":if(v.id in h){let P=h[v.id];if(!P){t.warn("reasoning-end: part not found in map",{id:v.id});break}P.text=P.text.trimEnd(),P.time={...P.time,end:Date.now()},v.providerMetadata&&(P.metadata=v.providerMetadata),await Z.updatePart(P),delete h[v.id];}break;case "tool-input-start":{let P=await Z.updatePart({id:r[v.id]?.id??Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"tool",tool:v.toolName,callId:v.id,state:{status:"pending",input:{},raw:""}});r[v.id]=P;break}case "tool-input-delta":break;case "tool-input-end":break;case "tool-call":{let P=r[v.toolCallId];if(P){let I=await Z.updatePart({...P,tool:v.toolName,state:{status:"running",input:v.input,time:{start:Date.now()}},metadata:v.providerMetadata});r[v.toolCallId]=I;let S=(await ve.parts(s.assistantMessage.id)).slice(-3);if(S.length===3&&S.every(w=>w.type==="tool"&&w.tool===v.toolName&&w.state.status!=="pending"&&JSON.stringify(w.state.input)===JSON.stringify(v.input))){let w=await Ne.get(s.assistantMessage.agent);if(!w)break;await Oe.ask({permission:"doom_loop",patterns:[v.toolName],sessionId:s.assistantMessage.sessionId,metadata:{tool:v.toolName,input:v.input},always:[v.toolName],ruleset:w.permission});}}break}case "tool-result":{let P=r[v.toolCallId];if(P&&P.state.status==="running"){let I;v.output.attachments&&v.output.attachments.length>0&&(I=v.output.attachments.map(A=>({...A,id:A.id??Identifier.ascending("part"),sessionId:A.sessionId??P.sessionId,messageId:A.messageId??P.messageId}))),await Z.updatePart({...P,state:{status:"completed",input:v.input??P.state.input,output:v.output.output,metadata:v.output.metadata,title:v.output.title,time:{start:P.state.time.start,end:Date.now()},attachments:I}}),delete r[v.toolCallId];}break}case "tool-error":{let P=r[v.toolCallId];P&&P.state.status==="running"&&(await Z.updatePart({...P,state:{status:"error",input:v.input??P.state.input,error:v.error instanceof Error?v.error.message:String(v.error),time:{start:P.state.time.start,end:Date.now()}}}),(v.error instanceof Oe.RejectedError||v.error instanceof Ot.RejectedError)&&(i=a),delete r[v.toolCallId]);break}case "error":throw v.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 Z.updatePart({id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.sessionId,type:"step-start"});break;case "finish-step":{let P=Z.getUsage({model:s.model,usage:v.usage,metadata:v.providerMetadata});s.assistantMessage.finish=v.finishReason,s.assistantMessage.cost+=P.cost,s.assistantMessage.tokens=P.tokens,await Z.updatePart({id:Identifier.ascending("part"),reason:v.finishReason,messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"step-finish",tokens:P.tokens,cost:P.cost}),await Z.updateMessage(s.assistantMessage),await Le.triggerEvent(HookEvent.StepFinish,{sessionId:s.sessionId,userMessageId:s.assistantMessage.parentId,messageId:s.assistantMessage.id,model:s.model,finishReason:v.finishReason},{sessionId:s.sessionId,model:s.model?.id}),!s.assistantMessage.summary&&await io.isOverflow({tokens:P.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:v.providerMetadata},await Z.updatePart(u);break;case "text-delta":if(u){let P=v.delta||v.text||"";u.text+=P,v.providerMetadata&&(u.metadata=v.providerMetadata),u.text&&await Z.updatePart({part:u,delta:P});}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()},v.providerMetadata&&(u.metadata=v.providerMetadata),await Z.updatePart(u)):t.warn("text-end: no currentText available or time not set"),u=void 0;break;case "finish":break;default:t.info("unhandled",{...v});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,ue.publish(Z.Event.Error,{sessionId:s.sessionId,error:g});else {let v=vr.retryable(g);if(v!==void 0){c++;let P=vr.delay(c,ve.APIError.isInstance(g)?g:void 0);await Mt.set(s.sessionId,{type:"retry",attempt:c,message:v,next:Date.now()+P}),await vr.sleep(P,s.abort).catch(()=>{});continue}s.assistantMessage.error=g,await ue.publish(Z.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 Z.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 Z.updateMessage(s.assistantMessage),l?"compact":i||s.assistantMessage.error?"stop":"continue"}}}}n.create=o;})(Cr||(Cr={}));var Lm=`Provide a detailed summary of the conversation above that will help continue the work.
132
-
133
- 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 Qx(e){return `<compaction_summary>
134
- ${e}
135
- </compaction_summary>`}function Dm(e,t){let o=[Qx(e)];return o.push("Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed."),t?.customInstructions&&o.push(t.customInstructions),o.join(`
136
-
137
- `)}var wt=a.create({service:"compaction"}),io;(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 yi(),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(T){let j=await p(),x=Date.now(),k=j.compactionAttempts.get(T);if(k){let _=x-k.firstAttemptTime;if(_<6e4){if(k.count>=3)return wt.warn("compaction skipped: time window circuit breaker open",{sessionId:T,attempts:k.count,elapsed:_,windowMs:6e4,threshold:3}),await ue.publish(M.Event.CircuitBreakerOpened,{sessionId:T,consecutiveFailures:k.count,maxFailures:3}),true;k.count++;}else k.count=1,k.firstAttemptTime=x;}else j.compactionAttempts.set(T,{count:1,firstAttemptTime:x});return false}async function g(T){(await p()).compactionAttempts.delete(T);}M.resetTimeWindowAttempts=g;async function v(T){return (await p()).consecutiveFailures.get(T)??0}async function P(T){let j=await p(),k=(j.consecutiveFailures.get(T)??0)+1;return j.consecutiveFailures.set(T,k),k}async function I(T){(await p()).consecutiveFailures.set(T,0);}M.resetSessionFailures=I;function A(T){if(a$2.EASBOT_AUTO_COMPACT_WINDOW)return a$2.EASBOT_AUTO_COMPACT_WINDOW;let j=bt.maxOutputTokens(T),x=Math.min(j,2e4),k=T.limit.context??0,L=(k>0?k:Se.DEFAULT_CONTEXT_LIMIT)-x;return Math.max(L,5e4)}M.getEffectiveContextWindowSize=A;function S(T,j){let x=A(j),k=Math.max(0,(x-T)/x*100),_=x-2e4,L=x-13e3;a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE&&(L=x*(1-a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE/100));let H=x-1e3;return a$2.EASBOT_BLOCKING_LIMIT_OVERRIDE&&(H=a$2.EASBOT_BLOCKING_LIMIT_OVERRIDE),{percentLeft:k,isAboveWarningThreshold:T>=_,isAboveAutoCompactThreshold:T>=L,isAtBlockingLimit:T>=H}}M.calculateTokenUsageState=S;async function w(T){if(a$2.EASBOT_DISABLE_COMPACT||a$2.EASBOT_DISABLE_AUTO_COMPACT)return false;let j=await u();if(j.auto===false)return false;let x=T.model.limit.context??0,k=x>0?x:Se.DEFAULT_CONTEXT_LIMIT;if(k===0)return false;let _=bt.maxOutputTokens(T.model),L=j.reserved??Math.min(2e4,_),H=T.model.limit.input?T.model.limit.input-L:k-L,Y=Math.max(H,5e4);if(a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE)return T.tokens?Token.total(T.tokens)>=Y*(1-a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE/100):false;if(T.tokens)return Token.total(T.tokens)>=Y;if(!T.sessionId)return false;let X=await Z.messages({sessionId:T.sessionId});for(let ne=X.length-1;ne>=0;ne--){let ae=X[ne];if(ae&&ae.info.role==="assistant"&&!ae.info.summary)return Token.total(ae.info.tokens)>=H}return false}M.isOverflow=w;async function y(T){let j=await u(),x=j.prune;if(x?.enabled===false)return wt.debug("prune skipped: config.compaction.prune.enabled is false"),{prunedCount:0,prunedTokens:0,success:true};let k=x?.timeThresholdMs??3e5,_=x?.keepRecentTools??3,L=x?.tokenThreshold??5e3,H=x?.protectedTools??M.PRUNE_PROTECTED_TOOLS,Y=j?.backup?.enabled!==false;wt.debug("pruning started",{sessionId:T.sessionId,timeThresholdMs:k,keepRecentTools:_,tokenThreshold:L,backupEnabled:Y});let X=await Z.messages({sessionId:T.sessionId}),ne=Date.now(),ae=0,le=0,be=0,se=[],Q=[],q=0;e:for(let te=X.length-1;te>=0;te--){let G=X[te];if(G&&(G.info.role==="user"&&q++,!(q<2))){if(G.info.role==="assistant"&&G.info.summary)break;for(let J=G.parts.length-1;J>=0;J--){let oe=G.parts[J];if(oe&&oe.type==="tool"&&oe.state.status==="completed"){if(H.includes(oe.tool))continue;if(oe.state.time.compacted)break e;let me=ne-(oe.state.time.end??0)>k;if(Q.length<_){Q.push(oe.id);continue}if(!me)continue;let pe=Token.estimate(oe.state.output??"");ae+=pe,ae>4e4&&(le+=pe,se.push(oe));}}}}wt.debug("pruning analysis",{totalToolTokens:ae,prunedTokens:le,toPruneCount:se.length,timeThresholdMs:k});let F=le>L;if(F&&se.length>0){let te=T.reason??"prune";for(let G of se)G.type==="tool"&&G.state.status==="completed"&&(Y&&G.state.output&&(await Ri.backup({sessionId:T.sessionId,messageId:G.messageId,partId:G.id,tool:G.tool,originalOutput:G.state.output,metadata:{input:G.state.input??{},title:G.state.title,attachments:G.state.attachments},compactedAt:ne,reason:te}),be++),G.state.time.compacted=ne,await Z.updatePart(G));wt.debug("pruning completed",{count:se.length,tokens:le,backups:be});}else wt.debug("pruning skipped: insufficient benefit",{prunedTokens:le,minimum:L});return {prunedCount:se.length,prunedTokens:le,success:F,backups:be}}M.prune=y;async function b(T){wt.debug("restore started",T);let j=await Z.messages({sessionId:T.sessionId}),x=0,k=0;for(let _ of j)if(!(T.messageId&&_.info.id!==T.messageId))for(let L of _.parts){if(T.partId&&L.id!==T.partId||L.type!=="tool"||L.state.status!=="completed"||!L.state.time.compacted)continue;let H=Ri.get(T.sessionId,L.id);if(!H){wt.warn("restore skipped: no backup found",{partId:L.id});continue}L.state.output=H.originalOutput,L.state.time.compacted=void 0,await Z.updatePart(L),x++,k+=Token.estimate(H.originalOutput),wt.debug("restore completed",{partId:L.id,tokens:Token.estimate(H.originalOutput)});}return wt.info("restore completed",{restoredCount:x,restoredTokens:k}),{restoredCount:x,restoredTokens:k,success:true}}M.restore=b;function C(){return Ri}M.getBackupCache=C;function E(T){Ri.clearSession(T);}M.clearBackups=E;async function O(T){let j=await v(T.sessionId);if(j>=3)return wt.warn("compaction skipped: circuit breaker open (failures)",{sessionId:T.sessionId,consecutiveFailures:j,maxFailures:3}),await ue.publish(M.Event.CircuitBreakerOpened,{sessionId:T.sessionId,consecutiveFailures:j,maxFailures:3}),await Ke.cancel(T.sessionId),"stop";if(await h(T.sessionId))return await Ke.cancel(T.sessionId),"stop";wt.debug("compaction started",{sessionId:T.sessionId,auto:T.auto});let x=T.messages.findLast(ae=>ae.info.id===T.parentId).info,k=await Ne.get("compaction");if(!k)return wt.error("compaction agent not found"),"stop";let _=k.model?await Se.getModel(k.model.providerId,k.model.modelId):await Se.getModel(x.model.providerId,x.model.modelId),L=await Z.updateMessage({id:Identifier.ascending("message"),role:"assistant",parentId:T.parentId,sessionId:T.sessionId,mode:"compaction",agent:"compaction",variant:x.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()}}),H=Cr.create({assistantMessage:L,sessionId:T.sessionId,model:_,abort:T.abort}),Y=[],X;try{let ae=await Le.triggerEvent(HookEvent.SessionCompacting,{sessionId:T.sessionId,auto:T.auto});if(ae.success&&ae.output){let le=ae.output;le.context&&Y.push(...le.context),le.prompt&&(X=le.prompt);}}catch(ae){wt.warn("session.compacting hook error, using default",{error:String(ae)});}let ne=X??[Lm,...Y].join(`
138
-
139
- `);try{if(await H.process({user:x,agent:k,abort:T.abort,sessionId:T.sessionId,tools:{},system:k.prompt?[k.prompt]:[],messages:[...await ve.toModelMessages(T.messages.filter(le=>!le.parts.some(be=>be.type==="compaction")),_),{role:"user",content:[{type:"text",text:ne}]}],model:_})==="continue"&&T.auto){let be=(await ve.parts(L.id)).find(q=>q.type==="text")?.text??"",se=Dm(be,{continuePrompt:!0}),Q=await Z.updateMessage({id:Identifier.ascending("message"),role:"user",sessionId:T.sessionId,time:{created:Date.now()},agent:x.agent,model:x.model});await Z.updatePart({id:Identifier.ascending("part"),messageId:Q.id,sessionId:T.sessionId,type:"text",synthetic:!0,text:se,time:{start:Date.now(),end:Date.now()}});}return H.message.error?(wt.error("compaction failed: processor error",{error:H.message.error}),await P(T.sessionId),"stop"):(await ue.publish(M.Event.Compacted,{sessionId:T.sessionId}),wt.debug("compaction completed successfully",{sessionId:T.sessionId}),await I(T.sessionId),"continue")}catch(ae){let le=await P(T.sessionId);throw wt.error("compaction failed",{sessionId:T.sessionId,error:String(ae),consecutiveFailures:le,maxFailures:3}),ae}}M.compactConversation=O;async function D(T){if(a$2.EASBOT_DISABLE_COMPACT||a$2.EASBOT_DISABLE_AUTO_COMPACT)return wt.debug("auto compact skipped: disabled by flag"),"not_needed";if((await u()).auto===false)return wt.debug("auto compact skipped: config.compaction.auto is false"),"not_needed";if(!await w({sessionId:T.sessionId,model:T.model,tokens:T.tokens}))return wt.debug("no overflow detected, skipping auto compact"),"not_needed";wt.debug("auto compact triggered",{sessionId:T.sessionId});let k=await ve.filterCompacted(ve.stream(T.sessionId));if(k.length===0)return wt.debug("auto compact skipped: no uncompacted messages",{sessionId:T.sessionId}),"not_needed";let _=k.findLast(X=>X?.info.role==="user"&&!X.parts.some(ne=>ne.type==="compaction"));if(!_)return wt.error("no user message found for compaction"),"not_needed";let L=new AbortController,H=T.sessionId?Object.assign(L.signal,{sessionId:T.sessionId}):L.signal,Y=await O({sessionId:T.sessionId,parentId:_.info.id,messages:k,abort:H,auto:true});return await M.prune({sessionId:T.sessionId}),Y==="continue"?(wt.debug("auto compact succeeded",{sessionId:T.sessionId}),"compacted"):"not_needed"}M.autoCompactIfNeeded=D;async function $(T){await I(T),wt.debug("circuit breaker reset",{sessionId:T});}M.resetCircuitBreaker=$;async function K(T){return v(T)}M.getConsecutiveFailures=K,M.Event={Compacted:a$5.define("session.compacted",U.object({sessionId:U.string()})),CircuitBreakerOpened:a$5.define("session.compaction.circuit_breaker_opened",U.object({sessionId:U.string(),consecutiveFailures:U.number(),maxFailures:U.number()}))},M.create=fn$1(U.object({sessionId:Identifier.schema("session"),agent:U.string().optional(),model:U.object({providerId:U.string(),modelId:U.string()}).optional(),auto:U.boolean()}),async T=>{let{sessionId:j,model:x,agent:k="compaction",auto:_=false}=T,L;x?.providerId&&x.modelId?L={providerId:x.providerId,modelId:x.modelId}:L=(await Ne.get(k))?.model??await Ke.lastModel(j);let H=await Z.updateMessage({id:Identifier.ascending("message"),role:"user",model:L,sessionId:j,agent:k,time:{created:Date.now()}});await Z.updatePart({id:Identifier.ascending("part"),messageId:H.id,sessionId:H.sessionId,type:"compaction",auto:_}),wt.debug("compaction task created",{sessionId:j,auto:_});});})(io||(io={}));var Fm=a.create({service:"hook.builtin.compaction"}),El=Jt("compaction",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.SessionStart,handler:async(e,t)=>{let o=e;return Fm.debug("session.start hook triggered, resetting compaction failure counter",{sessionId:o.sessionId,agent:o.agent}),await io.resetSessionFailures(o.sessionId),{modified:false,input:e}}},{name:HookEvent.StepFinish,handler:async(e,t)=>{let o=e;return Fm.debug("step.finish hook triggered, resetting compaction failure counter",{sessionId:o.sessionId,agent:o.agent,finishReason:o.finishReason}),await io.resetSessionFailures(o.sessionId),{modified:false,input:e}}}]}}});var Cs=a.create({service:"hook.builtin.coder"}),Al=new Map,Rl=Jt("coder",{async init(){return {scope:g.Coder,isEnabled:()=>true,handlers:[{name:HookEvent.StepStart,handler:async(e,t)=>{let o=e;try{Cs.debug("coder.step-start hook triggered",{sessionId:o.sessionId,messageId:o.messageId});let n=await ht.track();Al.set(o.sessionId,n);let r=(await ve.parts(o.messageId)).find(i=>i.type==="step-start");r&&n&&await Z.updatePart({...r,snapshot:n}),Cs.debug("coder.step-start hook completed",{sessionId:o.sessionId,hasSnapshot:!!n});}catch(n){Cs.error("coder.step-start hook error",{sessionId:o.sessionId,error:String(n)});}return {modified:false,input:e}}},{name:HookEvent.StepFinish,handler:async(e,t)=>{let o=e;try{Cs.debug("coder.step-finish hook triggered",{sessionId:o.sessionId,messageId:o.messageId,finishReason:o.finishReason});let n=Al.get(o.sessionId);if(n){let r=(await ve.parts(o.messageId)).find(c=>c.type==="step-finish");r&&await Z.updatePart({...r,snapshot:n});let i=await ht.patch(n);i.files.length>0&&(await Z.updatePart({id:Identifier.ascending("part"),messageId:o.messageId,sessionId:o.sessionId,type:"patch",hash:i.hash,files:i.files}),Cs.debug("coder.step-finish patch generated",{sessionId:o.sessionId,hash:i.hash,fileCount:i.files.length})),Al.delete(o.sessionId);}Cs.debug("coder.step-finish hook completed",{sessionId:o.sessionId});}catch(n){Cs.error("coder.step-finish hook error",{sessionId:o.sessionId,error:String(n)});}return {modified:false,input:e}}}]}}});var Ln=a.create({service:"hook.builtin.gateway"}),_l=new Map,Ml=Jt("gateway",{async init(){return {handlers:[{name:HookEvent.GatewayMessageReceive,handler:async(e,t)=>{let o=e,n=t.messageStore;return n?(await n.store(o),Ln.info("gateway message stored",{id:o.id,sessionId:o.sessionId,type:o.type}),{modified:false,input:e}):(Ln.debug("messageStore not available in context"),{modified:false,input:e})}},{name:HookEvent.GatewayMessageProcess,handler:async(e,t)=>{let o=e,n=o.id,s=t.messageStore;return s?(_l.set(n,o.timestamp??Date.now()),await s.updateStatus(n,"processing",{processorId:o.processorId,processType:o.processType,agent:o.agent}),Ln.info("gateway message processing",{id:n}),{modified:false,input:e}):(Ln.debug("messageStore not available in context"),{modified:false,input:e})}},{name:HookEvent.GatewayMessageComplete,handler:async(e,t)=>{let o=e,n=o.id,s=t.messageStore;if(!s)return Ln.debug("messageStore not available in context"),{modified:false,input:e};let r=_l.get(n);return _l.delete(n),await s.updateStatus(n,o.status??"completed",{error:o.error,responseMessageId:o.responseMessageId,tokens:o.tokens,duration:o.duration??(r?Date.now()-r:void 0),processedBy:o.processorId??o.agent}),Ln.info("gateway message completed",{id:n,status:o.status}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageSend,handler:async(e,t)=>{let o=e,n=t.messageStore;if(n){let s=o.processorId||o.agent||"gateway";await n.store({id:o.id,sessionId:o.sessionId,type:o.type,content:o.content||[],channel:o.channel,replyToMessageId:o.replyToMessageId,proactive:o.proactive??!o.replyToMessageId,timestamp:o.timestamp,processorId:o.processorId,agent:o.agent},"completed"),o.replyToMessageId&&await n.updateStatus(o.replyToMessageId,"completed",{processedBy:s});}return Ln.info("gateway message sent",{id:o.id,proactive:o.proactive}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageDelivered,handler:async(e,t)=>{let o=e,n=t.messageStore;return n&&await n.updateStatus(o.id,"delivered",{deliveredAt:o.timestamp}),Ln.info("gateway message delivered",{id:o.id}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageRead,handler:async(e,t)=>{let o=e,n=t.messageStore;return n&&await n.updateStatus(o.id,"read",{readAt:o.timestamp}),Ln.info("gateway message read",{id:o.id}),{modified:false,input:e}}}]}}});var Ol=a.create({service:"hook.executor.prompt"}),ks=class ks{constructor(){b$1(this,"type","prompt");}static getInstance(){return ks._instance||(ks._instance=new ks),ks._instance}canExecute(t){return t?.type==="prompt"}async execute(t,o,n){let s=Date.now(),r=t.runMode??"session";try{return Ol.debug("Execute Prompt Hook",{partsCount:t.parts?.length,model:t.model,runMode:r,context:n?.sessionId}),r==="fork"?await this.executeInFork(t,o,n,s):await this.executeInSession(t,o,n,s)}catch(i){return Ol.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,o,n,s){let r=s??Date.now(),i=n?.sessionId??"",c=Identifier.ascending("message"),d=(await Ke.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:o.modified,input:o.input,output:d,duration:Date.now()-r}}async executeInFork(t,o,n,s){let r=s??Date.now(),i=n?.sessionId??"";if(!i)return {success:false,modified:false,error:"Fork mode requires sessionId in context",duration:Date.now()-r};Ol.debug("Fork session for Prompt Hook",{sourceSessionID:i});let c=await Z.fork({sessionId:i});try{let l=Identifier.ascending("message"),m=(await Ke.prompt({messageId:l,sessionId:c.id,model:t.model,system:t.system,agent:n?.agent,parts:t.parts})).parts.findLast(f=>f.type==="text")?.text??"";return {success:!0,modified:o.modified,input:o.input,output:m,duration:Date.now()-r}}finally{await Z.remove(c.id);}}};b$1(ks,"_instance");var _i=ks;var qm=a.create({service:"hook.builtin.heartbeat"});var jl=Jt("heartbeat.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.HeartbeatTrigger,handler:async(e,t)=>{let o=e;return qm.info("Heartbeat trigger event received",{timestamp:o.timestamp,name:o.name}),{modified:false,input:e}}},{name:HookEvent.HeartbeatComplete,handler:(e,t)=>{let o=e;return qm.info("Heartbeat complete event received",{timestamp:o.timestamp,duration:o.duration}),{modified:false,input:e}}}]}}});var Ps=class Ps{constructor(){b$1(this,"type","function");}static getInstance(){return Ps._instance||(Ps._instance=new Ps),Ps._instance}canExecute(t){return t?.type==="function"}async execute(t,o,n){try{let s=t.handler,r=await s(o.input,n??{});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(Ps,"_instance");var lc=Ps;var Hm=a.create({service:"hook.executor.command"}),Ts=class Ts{constructor(){b$1(this,"type","command");}static getInstance(){return Ts._instance||(Ts._instance=new Ts),Ts._instance}canExecute(t){return t?.type==="command"}async execute(t,o,n){let s=Date.now();try{Hm.debug("Execute Command Hook",{command:t.command,context:n});let i=await createPkgShell({cwd:n?.cwd,env:{...process.env,...o.input}})`${t.command}`.nothrow();return i.exitCode===0?{success:!0,modified:o.modified,input:o.input,stdout:i.text(),stderr:i.stderr.toString(),duration:Date.now()-s}:{success:!1,modified:o.modified,input:o.input,stdout:i.text(),stderr:i.stderr.toString(),exitCode:i.exitCode,duration:Date.now()-s}}catch(r){return Hm.error("Command Hook execution failed",{error:r?.message}),{success:false,modified:false,error:r?.message??String(r),duration:Date.now()-s}}}};b$1(Ts,"_instance");var uc=Ts;var Bm=a.create({service:"hook.executor.http"}),Es=class Es{constructor(){b$1(this,"type","http");}static getInstance(){return Es._instance||(Es._instance=new Es),Es._instance}canExecute(t){return t?.type==="http"}async execute(t,o,n){let s=Date.now(),r=t.timeout??3e4,i=t.method??"GET";try{Bm.debug("Execute HTTP Hook",{url:t.url,method:i,context:n});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(o.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:o.modified,input:o.input,output:a,stdout:f,exitCode:m.ok?0:m.status,duration:Date.now()-s}}catch(c){return Bm.error("HTTP Hook execution failed",{error:c?.message}),{success:false,modified:false,error:c?.message??String(c),duration:Date.now()-s}}}};b$1(Es,"_instance");var pc=Es;function Ll(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 Dl(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 o=new URL(t);return `${o.protocol}//${o.host}`}catch{let o=t.match(/^(https?:\/\/[^/]+)/);return o?o[1]:t}}var He=a.create({service:"acp-client-connection"}),Fl=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 o=t.url;o.startsWith("acp-ws://")&&(o=o.replace("acp-ws://","ws://")),o.includes("/acp")||(o=o.replace(/\/$/,"")+"/acp"),this.config={...t,url:o};}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,o)=>{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 n=>{let s;if(typeof n.data=="string")s=n.data;else if(n.data instanceof Blob){let r=await n.data.arrayBuffer();s=new TextDecoder("utf-8").decode(r);}else n.data instanceof ArrayBuffer?s=new TextDecoder("utf-8").decode(n.data):s=String(n.data);this.handleMessage(s);},this.ws.onerror=n=>{He.error("WebSocketConnection: error",{error:String(n)}),this._state==="connecting"&&o(new Error("WebSocket connection error"));},this.ws.onclose=()=>{He.debug("WebSocketConnection: closed"),this._state="disconnected";for(let[,n]of this.pendingRequests)n.reject(new Error("Connection closed"));this.pendingRequests.clear(),this.handleReconnect();};}catch(n){this._state="disconnected",o(n);}}),{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,o]of this.pendingRequests)o.reject(new Error("Connection closed"));this.pendingRequests.clear(),this.subscriptions.clear();}async send(t,o){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");let n=this.requestId++,s={jsonrpc:"2.0",id:n,method:t,params:o};return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingRequests.delete(n),i(new Error(`Request timeout: ${t}`));},this.config.timeout??3e5);this.pendingRequests.set(n,{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:n});})}subscribe(t,o){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(n=>{He.error("WebSocketConnection: subscribe failed",{sessionId:t,error:String(n)});})),this.subscriptions.get(t).add(o),He.debug("WebSocketConnection: callback added",{sessionId:t,callbackCount:this.subscriptions.get(t)?.size}),()=>{He.debug("WebSocketConnection: unsubscribe called",{sessionId:t});let n=this.subscriptions.get(t);n&&(n.delete(o),He.debug("WebSocketConnection: callback removed",{sessionId:t,remainingCallbacks:n.size}),n.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 o=JSON.parse(t);if(He.debug("WebSocketConnection: parsed message",{method:o.method,id:o.id,hasParams:!!o.params}),o.id!==void 0&&o.id!==null){He.debug("WebSocketConnection: handling response",{id:o.id});let n=this.pendingRequests.get(o.id);if(n){this.pendingRequests.delete(o.id),n.resolve(o);return}He.debug("WebSocketConnection: no handler for response",{id:o.id});return}if(o.jsonrpc==="2.0"&&o.method&&!o.id){He.debug("WebSocketConnection: notification",{method:o.method});let n=o.params||{},s=n.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:o.method,properties:n};for(let c of r)try{c(i);}catch(l){He.error("WebSocketConnection: notification callback error",{method:o.method,error:String(l)});}}else He.debug("WebSocketConnection: no callbacks for notification",{method:o.method,sessionId:s});}else He.debug("WebSocketConnection: no sessionId in notification",{method:o.method});}}catch(o){He.warn("WebSocketConnection: failed to parse message",{error:String(o)});}}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 o of this.subscriptions.keys())await this.send("session.subscribe",{sessionId:o});}catch(o){He.error("WebSocketConnection: reconnect failed",{error:String(o)});}},t);}},Nl=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 o=t.url.replace(/\/$/,"");o.includes("/acp")||(o+="/acp"),this.config={...t,url:o};}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,o){let n=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;o&&typeof o=="object"&&"sessionId"in o&&(c=o.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:o};r.includes(t)&&(s="POST");let d=await Fetch.request(n,{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,o){return this.subscriptions.has(t)||(this.subscriptions.set(t,new Set),this.startSSE(t).catch(n=>{He.error("HTTPConnection: startSSE failed",{sessionId:t,error:String(n)});})),this.subscriptions.get(t).add(o),()=>{let n=this.subscriptions.get(t);n&&(n.delete(o),n.size===0&&this.subscriptions.delete(t));}}isConnected(){return this._state==="connected"}async startSSE(t){let o=this.config.url,n={};this.config.token&&(n.Authorization=`Bearer ${this.config.token}`),this.connectionId&&(n["Acp-Connection-Id"]=this.connectionId,n["Acp-Session-Id"]=t),this.abortController=new AbortController,this.sseAbortFn=Fetch.sse(o,{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:n});}},Ul=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 o=this.process.stdin,n=this.process.stdout,s=new WritableStream({write:d=>new Promise((m,f)=>{o.write(d,a=>{a?f(a):m();});})}),r=new ReadableStream({start(d){let m="";n.on("data",f=>{m+=f.toString();let a=m.split(`
140
- `);m=a.pop()??"";for(let p of a)p.trim()?.startsWith("{")&&d.enqueue(new TextEncoder().encode(p+`
141
- `));}),n.on("end",()=>{m.trim()&&m.startsWith("{")&&d.enqueue(new TextEncoder().encode(m+`
142
- `)),d.close();}),n.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,o){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(o);case "session.new":return this.connection.newSession(o);case "session.load":return this.connection.loadSession(o);case "session.list":return this.connection.listSessions(o);case "session.fork":return this.connection.unstable_forkSession(o);case "session.resume":return this.connection.resumeSession(o);case "session.close":return this.connection.closeSession(o);case "session.prompt":return this.connection.prompt(o);case "session.cancel":return this.connection.cancel(o);case "session.setMode":return this.connection.setSessionMode(o);case "session.setConfigOption":return this.connection.setSessionConfigOption(o);case "authenticate":return this.connection.authenticate(o);default:throw new Error(`Unsupported method: ${t}`)}}catch(n){throw n instanceof Error&&n.message.includes("stream")&&(He.error("STDIOConnection: stream error, marking as disconnected",{error:n.message,method:t}),this._state="disconnected",this.connection=null),n}}subscribe(t,o){return this.subscriptions.has(t)||this.subscriptions.set(t,new Set),this.subscriptions.get(t).add(o),()=>{let n=this.subscriptions.get(t);n&&(n.delete(o),n.size===0&&this.subscriptions.delete(t));}}isConnected(){return this._state==="connected"}};function zl(e){switch(e.type){case "websocket":return new Fl({url:e.url,token:e.token,reconnect:e.reconnect,timeout:e.timeout});case "http":return new Nl({url:e.url,token:e.token,timeout:e.timeout});case "stdio":return new Ul({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 Ro={includeThinking:false,includeToolDetails:false,includeToolOutput:false};var je=a.create({service:"acp-client"}),aI=300*1e3,Dn=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=zl(t),je.debug("ACPClient created",{type:t.type,url:t.url});}async initialize(t={protocolVersion:1}){if(this.initialized)return je.debug("ACPClient: already initialized"),{protocolVersion:t.protocolVersion,agentInfo:{name:"acp-client",version:"1.0.0"}};je.debug("ACPClient: initializing connection");try{await this.connection.connect();let o=await this.connection.send("initialize",t);return this.initialized=!0,je.debug("ACPClient: initialization complete"),o}catch(o){throw je.error("ACPClient: initialization failed",{error:o instanceof Error?o.message:String(o)}),o}}async authenticate(t){this.ensureInitialized(),je.debug("ACPClient: authenticate");try{return await this.connection.send("authenticate",t)}catch(o){throw je.error("ACPClient: authentication failed",{error:o instanceof Error?o.message:String(o)}),o}}async disconnect(){this.disconnected||(je.debug("ACPClient: disconnecting"),this.disconnected=true,await this.connection.disconnect(),je.debug("ACPClient: disconnected"));}async newSession(t){this.ensureInitialized(),je.debug("ACPClient: newSession",{cwd:t.cwd});let o=await this.connection.send("session.new",t);return je.debug("ACPClient: newSession complete",{sessionId:o.sessionId}),o}async loadSession(t){return this.ensureInitialized(),je.debug("ACPClient: loadSession",{sessionId:t.sessionId}),this.connection.send("session.load",t)}async listSessions(t){return this.ensureInitialized(),je.debug("ACPClient: listSessions",{cwd:t.cwd}),this.connection.send("session.list",t)}async unstable_forkSession(t){return this.ensureInitialized(),je.debug("ACPClient: forkSession",{sessionId:t.sessionId}),this.connection.send("session.fork",t)}async resumeSession(t){return this.ensureInitialized(),je.debug("ACPClient: resumeSession",{sessionId:t.sessionId}),this.connection.send("session.resume",t)}async closeSession(t){return this.ensureInitialized(),je.debug("ACPClient: closeSession",{sessionId:t.sessionId}),this.connection.send("session.close",t)}async prompt(t){this.ensureInitialized();let o=t.sessionId;je.debug("ACPClient: prompt",{sessionId:o,promptLength:t.prompt.length});let n=await this.connection.send("session.prompt",t);return je.debug("ACPClient: prompt complete",{sessionId:o,stopReason:n.stopReason}),n}async cancel(t){this.ensureInitialized(),je.debug("ACPClient: cancel",{sessionId:t.sessionId}),await this.connection.send("session.cancel",t),je.debug("ACPClient: cancel complete",{sessionId:t.sessionId});}async setSessionMode(t){return this.ensureInitialized(),je.debug("ACPClient: setSessionMode",{sessionId:t.sessionId,modeId:t.modeId}),this.connection.send("session.setMode",t)}async setSessionConfigOption(t){return this.ensureInitialized(),je.debug("ACPClient: setSessionConfigOption",{sessionId:t.sessionId,configId:t.configId}),this.connection.send("session.setConfigOption",t)}subscribeSessionEvents(t,o,n=Ro){return o.onMessage&&this.messageCallbacks.add(o.onMessage),this.connection.subscribe(t,s=>{let r=s.properties.messageId;if(s.type==="agent_thought_chunk"&&n.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:n,createdAt:Date.now()},this.messageCollectors.set(r,m)),m.thinkings.push(d.content.text);}}if(s.type==="agent_message_chunk")if(je.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:n,createdAt:Date.now()},this.messageCollectors.set(r,m),je.debug("agent_message_chunk: created new collector",{eventMessageId:r,collectorCount:this.messageCollectors.size})),m.text+=d.content.text,m.hasText=true,je.debug("agent_message_chunk: hasText=true",{eventMessageId:r,hasUsage:m.hasUsage}),m.hasUsage&&(je.debug("agent_message_chunk: triggering send",{eventMessageId:r}),this.checkAndSendMessage(r,m.tokens));}else je.debug("agent_message_chunk: skipped - no text content",{contentType:d.content?.type});}else je.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))je.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);}o.onSessionUpdate&&o.onSessionUpdate(s);})}dispatchNotification(t,o){let n=this.notificationCallbacks.get(t);if(n&&n.size>0){je.debug("ACPClient: dispatching notification",{method:t,callbackCount:n.size});for(let s of n)try{s(o);}catch(r){je.error("ACPClient: notification callback error",{method:t,error:String(r)});}}if(t==="session.status"){let s=o.status?.type??"idle";for(let r of this.sessionStatusCallbacks)try{r(s);}catch(i){je.error("ACPClient: sessionStatus callback error",{error:String(i)});}}}checkAndSendMessage(t,o){let n=this.messageCollectors.get(t);if(!n){je.debug("checkAndSendMessage: collector not found",{messageId:t});return}if(!n.hasText||!n.hasUsage){je.debug("checkAndSendMessage: conditions not met",{messageId:t,hasText:n.hasText,hasUsage:n.hasUsage});return}je.debug("checkAndSendMessage: sending message",{messageId:t,callbackCount:this.messageCallbacks.size}),this.messageCallbacks.size===0&&je.warn("checkAndSendMessage: no message callbacks registered",{messageId:t});try{let r={role:"assistant",text:n.text||void 0,thinking:n.filterConfig.includeThinking&&n.thinkings.join("")||void 0,tools:n.filterConfig.includeToolDetails&&(n.tools?.length??0)>0?n.tools:void 0,metadata:{sessionId:n.sessionId,messageId:t,timestamp:Date.now(),tokens:o?{input:o.input,output:o.output,total:o.input+o.output+(o.reasoning??0)}:void 0}};for(let i of this.messageCallbacks)i(r);}catch(r){je.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)),je.debug("checkAndSendMessage: message sent and collector cleaned",{messageId:t});}dispatchEvent(t){let{type:o,properties:n}=t;switch(o){case "tool_call_update":{let s=n.status==="running"?"in_progress":n.status??"pending",r={callId:n.toolCallId??"",tool:n.title??"",status:s,kind:n.kind,title:n.title,input:n.rawInput,output:n.rawOutput?.output,error:n.rawOutput?.error,content:n.content,locations:[]},c=n._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){je.error("ACPClient: tool callback error",{error:d instanceof Error?d.message:String(d)});}break}case "error":{n.error&&je.error("ACPClient: received error event",{name:n.error.name,data:n.error.data});break}case "usage_update":{let s=n,r=s._meta?.messageId;if(r){let i=this.messageCollectors.get(r);i||(i={sessionId:n.sessionId??"",text:"",thinkings:[],tools:[],hasText:false,hasUsage:true,tokens:void 0,filterConfig:s._meta?.filterConfig??Ro,createdAt:Date.now()},this.messageCollectors.set(r,i),je.debug("usage_update: created new collector",{messageId:r,collectorCount:this.messageCollectors.size})),i.hasUsage=true,i.tokens={input:0,output:0,reasoning:0,...n.tokens},je.debug("usage_update: hasUsage=true",{messageId:r,hasText:i.hasText}),i.hasText?(je.debug("usage_update: triggering send",{messageId:r}),this.checkAndSendMessage(r,i.tokens)):this.scheduleCollectorCleanup(r);}for(let i of this.usageCallbacks)try{i({used:n.used??0,size:n.size??0});}catch(c){je.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(n.availableCommands??[]);}catch(r){je.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(n.configOptions??[]);}catch(r){je.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(n.currentModeId??"");}catch(r){je.error("ACPClient: mode callback error",{error:r instanceof Error?r.message:String(r)});}break}}}onToolCall(t){return this.toolCallbacks.add(t),je.debug("ACPClient: tool callback registered",{callbackCount:this.toolCallbacks.size}),()=>{this.toolCallbacks.delete(t),je.debug("ACPClient: tool callback unregistered",{callbackCount:this.toolCallbacks.size});}}onQuestion(t){return this.questionCallbacks.add(t),je.debug("ACPClient: question callback registered",{callbackCount:this.questionCallbacks.size}),()=>{this.questionCallbacks.delete(t),je.debug("ACPClient: question callback unregistered",{callbackCount:this.questionCallbacks.size});}}onPermission(t){return this.permissionCallbacks.add(t),je.debug("ACPClient: permission callback registered",{callbackCount:this.permissionCallbacks.size}),()=>{this.permissionCallbacks.delete(t),je.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,o){return this.notificationCallbacks.has(t)||this.notificationCallbacks.set(t,new Set),this.notificationCallbacks.get(t).add(o),je.debug("ACPClient: notification callback registered",{method:t,callbackCount:this.notificationCallbacks.get(t)?.size}),()=>{let n=this.notificationCallbacks.get(t);n&&(n.delete(o),n.size===0&&this.notificationCallbacks.delete(t)),je.debug("ACPClient: notification callback unregistered",{method:t});}}registerQuestionHandler(t){return this.questionHandlers.push(t),je.debug("ACPClient: question handler registered",{handlerCount:this.questionHandlers.length}),()=>{let o=this.questionHandlers.indexOf(t);o>-1&&this.questionHandlers.splice(o,1),je.debug("ACPClient: question handler unregistered",{handlerCount:this.questionHandlers.length});}}async answerQuestion(t){this.ensureInitialized(),je.debug("ACPClient: answerQuestion",{sessionId:t.sessionId,requestId:t.requestId,answerCount:t.answers.length});let o=t.answers.map(n=>`[QUESTION_ANSWER:${t.requestId}] answer: "${n.join(", ")}"`).join(`
143
- `);await this.connection.send("session.prompt",{sessionId:t.sessionId,prompt:[{type:"text",text:o}]}),je.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 o=setTimeout(()=>{this.collectorCleanupTimers.delete(t);let n=this.messageCollectors.get(t);n&&(!n.hasText||!n.hasUsage)&&(je.debug("scheduleCollectorCleanup: cleaning orphaned collector",{messageId:t,hasText:n.hasText,hasUsage:n.hasUsage}),this.messageCollectors.delete(t));},aI);this.collectorCleanupTimers.set(t,o);}};var Mi=a.create({service:"websocket-subscriber"});function ql(e){return new mc(e)}var mc=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"websocket",url:""},Mi.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,o){let n=o??this._config,s=t||n.url||await this.getConfigWebSocketUrl();if(!s)throw new Error("No WebSocket URL provided and no config URL found");if(this._client){Mi.debug("WebSocket already connected, reusing");return}this._client=new Dn({...n,type:"websocket",url:s}),await this._client.initialize(),Mi.info("WebSocketSubscriber connected",{url:s});}async subscribe(t,o,n){if(!this._client)throw new Error("Not connected. Call connect() first.");Mi.debug("WebSocketSubscriber.subscribe",{sessionId:t});let s=this._client.subscribeSessionEvents(t,{onMessage:o,onError:n},Ro);return Mi.info("WebSocketSubscriber: subscribed to session",{sessionId:t}),s}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 Oi=a.create({service:"http-subscriber"});function Bl(e){return new Hl(e)}var Hl=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"http",url:""},Oi.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,o){let n=o??this._config,s=t||n.url;if(this._client){Oi.debug("HTTPSubscriber already connected, reusing");return}this._client=new Dn({...n,type:"http",url:s}),await this._client.initialize(),Oi.info("HTTPSubscriber connected",{baseUrl:s});}async subscribe(t,o,n){if(!this._client)throw new Error("Not connected. Call connect() first.");Oi.debug("HTTPSubscriber.subscribe",{sessionId:t});let s=this._client.subscribeSessionEvents(t,{onMessage:o,onError:n},Ro);return Oi.info("HTTPSubscriber: subscribed to session",{sessionId:t}),s}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}};var Er=a.create({service:"stdio-subscriber"});function Gl(e){return new fc(e)}var fc=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"stdio",url:""},Er.info("StdioSubscriber created",{config:this._config});}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,o){let n=o??this._config,s=t||n.url;if(this._client){Er.debug("StdioSubscriber: already connected, reusing");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()}`,Er.debug("StdioSubscriber: command",{command:r}),this._client=new Dn({...n,type:"stdio",url:r}),await this._client.initialize(),Er.info("StdioSubscriber: subprocess started");}async subscribe(t,o,n){if(!this._client)throw new Error("Not connected. Call connect() first.");Er.debug("StdioSubscriber.subscribe",{sessionId:t});let s=this._client.subscribeSessionEvents(t,{onMessage:o,onError:n},Ro);return Er.info("StdioSubscriber: subscribed to session",{sessionId:t}),s}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}};var Ut=a.create({service:"agent-service-registry"}),dI="agent-services.json",lI=3e5;function Wm(e){switch(e){case "healthy":return "online";case "offline":return "offline";default:return "unknown"}}var yc=class{constructor(t){b$1(this,"storagePath");b$1(this,"gatewayUrl");b$1(this,"cacheTtl");b$1(this,"services",new Map);b$1(this,"loaded",false);b$1(this,"gatewayClient",null);b$1(this,"gatewayCacheLastRefresh",0);b$1(this,"gatewayHeartbeatTimer",null);this.storagePath=t?.storagePath??Ce__default.join(R.directory,".easbot",dI),this.gatewayUrl=t?.gatewayUrl,this.cacheTtl=t?.cacheTtl??lI,Ut.info("Agent service registry created",{storagePath:this.storagePath,gatewayUrl:this.gatewayUrl,cacheTtl:this.cacheTtl});}async load(){this.loaded||(await this.loadFromLocalConfig(),await this.loadFromClientsConfig(),this.gatewayUrl&&await this.loadFromGateway(),this.loaded=true,Ut.debug("Agent services loaded",{count:this.services.size}));}async loadFromClientsConfig(){try{let t=await this.getClientsConfig();if(!t?.clients||t.clients.length===0){Ut.debug("No clients config found");return}for(let o of t.clients){let n=this.extractBaseUrl(o);if(!n){Ut.warn("Failed to extract baseUrl from client config",{clientId:o.id});continue}let s=`clients:${o.id}`;if(this.services.has(s)){Ut.debug("Service already exists from local config, skipping",{serviceId:s});continue}let r=o.agentId??o.id;this.services.set(s,{id:s,name:o.name,baseUrl:n,agentId:r,capabilities:o.channel?[o.channel]:[],status:"unknown",metadata:{type:o.type,channel:o.channel,autoConnect:o.autoConnect,priority:o.priority},updatedAt:Date.now()});}Ut.debug("Loaded services from clients config",{count:t.clients.length});}catch(t){Ut.warn("Failed to load clients config",{error:String(t)});}}extractBaseUrl(t){if(t.connection?.http?.baseUrl)return t.connection.http.baseUrl;if(t.connection?.ws?.url)return t.connection.ws.url;if(t.connection?.stdio)return "stdio://local"}async getClientsConfig(){let{getACPClientsConfig:t}=await import('./adapter-loader-SHO4LOSU.mjs');return t()}async loadFromLocalConfig(){try{if(!await Tt__default.access(this.storagePath).then(()=>!0,()=>!1)){Ut.debug("Local config file not found",{path:this.storagePath});return}let o=await Tt__default.readFile(this.storagePath,"utf-8"),n=JSON.parse(o);if(n.services)for(let s of n.services)this.services.set(s.id,{id:s.id,name:s.name,baseUrl:s.baseUrl,agentId:s.agentId,capabilities:s.capabilities??[],status:s.status??"unknown",metadata:s.metadata,updatedAt:Date.now()});Ut.debug("Loaded services from local config",{count:n.services?.length??0});}catch(t){Ut.warn("Failed to load local config",{error:String(t)});}}async loadFromGateway(){if(this.gatewayUrl)try{let t=this.getOrCreateGatewayClient();t.getState()!=="connected"&&await t.connect();let o=await t.fetchAgentList(),n=0,s=0;for(let r of o){let i=`gateway:${r.id}`,c=this.services.get(i),l={id:i,name:r.name,baseUrl:r.address,agentId:r.id,capabilities:r.capabilities??[],status:Wm(r.status),metadata:{sourceGatewayId:r.sourceGatewayId,...r.metadata},updatedAt:r.updatedAt};c?l.updatedAt>c.updatedAt&&(this.services.set(i,l),s++):(this.services.set(i,l),n++);}this.gatewayCacheLastRefresh=Date.now(),this.startGatewayHeartbeat(),Ut.debug("Loaded services from gateway",{total:o.length,added:n,updated:s});}catch{}}startGatewayHeartbeat(){this.gatewayHeartbeatTimer||(this.gatewayHeartbeatTimer=setInterval(async()=>{await this.loadFromGateway();},this.cacheTtl),Ut.debug("Gateway heartbeat started",{interval:this.cacheTtl}));}stopGatewayHeartbeat(){this.gatewayHeartbeatTimer&&(clearInterval(this.gatewayHeartbeatTimer),this.gatewayHeartbeatTimer=null,Ut.debug("Gateway heartbeat stopped"));}getOrCreateGatewayClient(){return this.gatewayClient?this.gatewayClient:(this.gatewayClient=new GatewayClient({url:this.gatewayUrl,type:"subagent",reconnect:{enabled:true,maxAttempts:3,delay:1e3},heartbeat:{enabled:true,interval:3e4}}),this.gatewayClient.onAgentListChange(t=>{Ut.debug("Gateway agent list changed",{count:t.length});for(let o of t){let n=`gateway:${o.id}`;this.services.set(n,{id:n,name:o.name,baseUrl:o.address,agentId:o.id,capabilities:o.capabilities??[],status:Wm(o.status),metadata:{sourceGatewayId:o.sourceGatewayId,...o.metadata},updatedAt:o.updatedAt});}}),this.gatewayClient)}isGatewayCacheExpired(){return !this.gatewayUrl||this.gatewayCacheLastRefresh===0?true:Date.now()-this.gatewayCacheLastRefresh>this.cacheTtl}async listServices(t,o){await this.load(),this.gatewayUrl&&(o?.refreshGateway??true)&&this.isGatewayCacheExpired()&&await this.loadFromGateway();let n=Array.from(this.services.values());return t?.status&&(n=n.filter(s=>s.status===t.status)),t?.capability&&(n=n.filter(s=>s.capabilities.includes(t.capability))),n}async getService(t){return await this.load(),this.services.get(t)}async getServiceByUrl(t){await this.load();for(let o of this.services.values())if(o.baseUrl===t)return o}async registerService(t){await this.load();let o={...t,updatedAt:Date.now()};this.services.set(t.id,o),await this.save(),Ut.debug("Service registered",{serviceId:t.id,name:t.name});}async unregisterService(t){await this.load(),this.services.delete(t)&&(await this.save(),Ut.debug("Service unregistered",{serviceId:t}));}async updateServiceStatus(t,o){await this.load();let n=this.services.get(t);n&&(n.status=o,n.updatedAt=Date.now(),await this.save(),Ut.debug("Service status updated",{serviceId:t,status:o}));}async save(){try{let t={version:1,services:Array.from(this.services.values()).map(o=>({id:o.id,name:o.name,baseUrl:o.baseUrl,agentId:o.agentId,capabilities:o.capabilities,status:o.status,metadata:o.metadata}))};await Tt__default.mkdir(Ce__default.dirname(this.storagePath),{recursive:!0}),await Tt__default.writeFile(this.storagePath,JSON.stringify(t,null,2),"utf-8"),Ut.debug("Services saved",{count:this.services.size});}catch(t){Ut.error("Failed to save services",{error:String(t)});}}async refresh(){this.loaded=false,this.services.clear(),this.gatewayCacheLastRefresh=0,await this.load(),Ut.debug("Services refreshed",{count:this.services.size});}async disconnect(){this.stopGatewayHeartbeat(),this.gatewayClient&&(await this.gatewayClient.disconnect(),this.gatewayClient=null,Ut.info("Gateway client disconnected"));}},hc=null;async function Ar(e){return hc||(hc=new yc(e),await hc.load()),hc}function uI(e,t){switch(t){case "websocket":return Ll(e);case "http":return Dl(e);case "stdio":return e;default:throw new Error(`Unsupported channel type: ${t}`)}}function pI(e){let t=e.type;switch(t){case "websocket":return ql(e);case "http":return Bl(e);case "stdio":return Gl(e);default:throw new Error(`Unsupported channel type: ${t}`)}}var en;(l=>{async function e(d){let{config:m,sessionId:f}=d,a=m.type,p=m.url,u=m.cwd??process.cwd(),h=pI(m);await h.connect(p);let g=f;if(g?(await h.client.listSessions({cwd:u})).sessions?.find(I=>I.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 o(d,m){await d.client.cancel({sessionId:m});}l.interrupt=o;async function n(d){let m=await d.client.initialize({protocolVersion:1});return {protocolVersion:m.protocolVersion,agentCapabilities:{modes:[],models:[],...m.agentInfo},authMethods:[]}}l.capabilities=n;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 uI(d,m)}l.getConnectionUrl=c;})(en||(en={}));function Vm(e,t){let o=btoa(String.fromCharCode(...e));return `data:${t??"application/octet-stream"};base64,${o}`}function Km(e,t){let o=[];if(t&&o.push(`<system-reminder>
144
- ${t}
145
- </system-reminder>`),e)for(let n of e)switch(n.type){case "text":n.text&&o.push(`<text>
146
- ${n.text}
147
- </text>`);break;case "image":{let s="";typeof n.image=="string"?s=n.image:n.image instanceof URL?s=n.image.toString():n.image instanceof Uint8Array&&(s=Vm(n.image,n.mime)),o.push(`<image mime="${n.mime??"image/png"}">
148
- ${s}
149
- </image>`);break}case "file":{let s="";typeof n.data=="string"?s=n.data:n.data instanceof URL?s=n.data.toString():n.data instanceof Uint8Array&&(s=Vm(n.data,n.mime)),o.push(`<file mime="${n.mime??"application/octet-stream"}">
150
- ${s}
151
- </file>`);break}case "command":o.push(n.arguments?`/${n.command} ${n.arguments}`:`/${n.command}`);break}return o.join(`
152
- `)}var po=a.create({service:"subagent.acp"}),bc=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){po.debug("ACPAgentHandler.start: already connected, reusing",{name:this.config.name});return}let t=this.config.transport==="websocket"?"websocket":this.config.transport==="http"?"http":"stdio",o=this.config.uri??this.buildUrl(this.config);po.debug("ACPAgentHandler.start",{type:t,url:o,cwd:this.config.cwd??R.directory??process.cwd(),name:this.config.name});try{let n=await en.connect({config:{type:t,url:o,cwd:this.config.cwd??R.directory??process.cwd(),timeout:this.config.timeout,env:this.config.env}});this.subscriber=n.subscriber,this.sessionId=n.sessionId,this._isRunning=!0,po.info("ACPAgentHandler started",{name:this.config.name,type:t,url:o});}catch(n){throw po.error("ACPAgentHandler.start failed",{name:this.config.name,error:String(n)}),n}}async stop(){if(po.debug("ACPAgentHandler.stop",{sessionId:this.sessionId,name:this.config?.name}),this.unsubscribeFn&&(this.unsubscribeFn(),this.unsubscribeFn=null),this.subscriber&&this.sessionId)try{await en.releaseSubscription(this.subscriber,this.sessionId);}catch(t){po.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");po.debug("ACPAgentHandler.execute",{title:t.title,agent:t.agent,partsCount:t.parts?.length??1});let o=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,po.debug("ACPAgentHandler.execute timeout",{timeout:o,messageCount:f}),i({title:t.title,output:l,metadata:{sessionId:this.sessionId??void 0,agent:t.agent,messageId:d,tokens:m}}));},o);(async()=>{try{let u=this.sessionId;if(!u)throw new Error("No session available. Call start() first.");po.debug("ACPAgentHandler: using existing session",{sessionId:u}),this.unsubscribeFn=s.subscribeSessionEvents(u,{onMessage:g=>{f++,po.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")){po.debug("ACPAgentHandler: ignored NotFoundError",{sessionId:u});return}po.error("ACPAgentHandler: subscription error",{error:g.message});}},{includeThinking:!1,includeToolDetails:!1,includeToolOutput:!1});let h=Km(t.parts,t.system);await s.prompt({sessionId:u,prompt:[{type:"text",text:h}]}),po.debug("ACPAgentHandler.execute prompt sent",{title:t.title,sessionId:u});}catch(u){a||(a=true,clearTimeout(p),c(u));}})();});return po.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&&(po.debug("ACPAgentHandler.interrupt",{sessionId:this.sessionId}),await en.interrupt(this.subscriber,this.sessionId));}isRunning(){return this._isRunning}async checkHealth(){if(!this._isRunning||!this.subscriber)return false;try{if(this.sessionId){let o=(await this.subscriber.client.listSessions({cwd:this.config?.cwd??process.cwd()}))?.sessions;return !o||!Array.isArray(o)?!1:o.some(n=>n.sessionId===this.sessionId)}return !0}catch(t){return po.debug("ACPAgentHandler.checkHealth failed",{error:String(t)}),false}}buildUrl(t){if(t.uri)return t.uri;let o=t.command??"easbot",n=t.args??["acp","--channel","stdio"];return `${o} ${n.join(" ")}`}};var tt;(c=>{let e;function t(){return e||(e=R.state(async()=>({...process.env}))),e}function o(){return t()()}async function n(l){return (await o())[l]}c.get=n;async function s(){return await o()}c.all=s;async function r(l,d){let m=await o();m[l]=d;}c.set=r;async function i(l){let d=await o();delete d[l];}c.remove=i;})(tt||(tt={}));var wc=a.create({service:"subagent.cli"}),xc=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,wc.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");wc.debug("CLIAgentHandler.execute",{title:t.title,command:this.config.command});let o=this.buildArgs(t),n=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,`${n} ${o.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:n,args:o,exitCode:a}};throw wc.error("CLI exited with error",{code:a,stderr:f}),new Error(`CLI exited with code ${a}: ${f}`)}catch(a){let p=a;throw wc.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 o=[...this.config?.args??[]],n=t.parts?.filter(s=>s.type==="text").map(s=>s.type==="text"&&"text"in s?s.text:"").filter(Boolean).join(`
153
- `)||t.title;return o.push("--prompt",n),o}};var xo=a.create({service:"subagent.registry"}),Ic=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,o=this.config.idleTimeout??1800*1e3;this.idleCleanupTimer=setInterval(()=>{this.cleanupIdleInstances(o);},t),xo.debug("Idle cleanup timer started",{interval:t,timeout:o});}stopIdleCleanup(){this.idleCleanupTimer&&(clearInterval(this.idleCleanupTimer),this.idleCleanupTimer=null,xo.debug("Idle cleanup timer stopped"));}async cleanupIdleInstances(t){let o=Date.now(),n=[];for(let[s,r]of this.instances){if(r.config.runMode!=="persistent"||r.status!=="idle"&&r.status!=="error")continue;o-r.lastActiveAt>t&&n.push(s);}if(n.length>0){xo.debug("Cleaning up idle instances",{count:n.length,maxIdleTime:t});for(let s of n)try{await this.terminate(s);}catch(r){xo.warn("Failed to cleanup idle instance",{id:s,error:String(r)});}}}async checkInstanceHealth(t){let o=this.handlers.get(t.id);if(!o)return false;try{return "checkHealth"in o&&typeof o.checkHealth=="function"?await o.checkHealth():o.isRunning()}catch{return false}}async spawn(t){let o=Identifier.ascending("subagent"),n={id:o,config:t,status:"starting",createdAt:Date.now(),lastActiveAt:Date.now()},s=this.createHandler(t);this.handlers.set(o,s),this.instances.set(o,n);try{return await s.start(t),n.status="idle",this.agentCounts.set(t.name,(this.agentCounts.get(t.name)??0)+1),xo.debug("Agent spawned",{id:o,name:t.name,status:n.status}),n}catch(r){throw n.status="error",n.error=String(r),this.handlers.delete(o),this.instances.delete(o),xo.error("Failed to spawn agent, cleaned up",{id:o,name:t.name,error:String(r)}),r}}createHandler(t){switch(t.transport){case "stdio":case "http":case "websocket":return new bc(t);case "cli":return new xc(t);default:throw new Error(`Unknown transport type: ${t.transport}`)}}async acquire(t){let o=await this.findIdleInstance(t.name);if(!o){let s=this.agentCounts.get(t.name)??0,r=t.maxConcurrent??this.config.maxConcurrent;s<r?o=await this.spawn(t):(xo.debug("Max concurrent reached, waiting for idle instance",{name:t.name,currentCount:s,maxConcurrent:r}),o=await this.waitForIdleInstance(t.name));}o.status="running",o.lastActiveAt=Date.now();let n=this.handlers.get(o.id);if(!n)throw new Error(`Handler not found for instance: ${o.id}`);return {instance:o,execute:async s=>{o.status="busy";try{let r=await n.execute(s);return o.status="idle",o.lastActiveAt=Date.now(),r}catch(r){throw o.status="error",r}},interrupt:()=>n.interrupt()}}async release(t,o){o==="ephemeral"?await this.terminate(t.id):(t.status="idle",xo.debug("Agent released to pool",{id:t.id,name:t.config.name}));}async terminate(t){let o=this.handlers.get(t),n=this.instances.get(t);if(this.handlers.delete(t),o)try{await o.stop();}catch(s){xo.warn("Error stopping agent",{id:t,error:String(s)});}if(n){let s=this.agentCounts.get(n.config.name)??0;s>0&&this.agentCounts.set(n.config.name,s-1),n.status="stopped",this.instances.delete(t);}xo.debug("Agent terminated",{id:t});}async interrupt(t){let o=this.handlers.get(t);if(o)try{await o.interrupt(),xo.debug("Agent interrupted",{id:t});}catch(n){xo.warn("Error interrupting agent",{id:t,error:String(n)});}}async shutdownAll(){this.stopIdleCleanup();let t=Array.from(this.instances.keys());await Promise.all(t.map(o=>this.terminate(o))),xo.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 o=[];for(let[n,s]of this.instances){if(s.config.name!==t||s.status!=="idle")continue;if(!await this.checkInstanceHealth(s)){xo.warn("Found unhealthy idle instance, marking for cleanup",{id:n,name:t,lastActiveAt:s.lastActiveAt}),o.push(n);continue}return s}for(let n of o)try{await this.terminate(n);}catch(s){xo.warn("Failed to terminate unhealthy instance",{id:n,error:String(s)});}}async waitForIdleInstance(t,o=6e4){let n=Date.now();for(;Date.now()-n<o;){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 jt=a.create({service:"subagent"});function Wl(e,t){return t?{...e,...t}:e}var As;(P=>{let e,t;function o(){return e||(e=R.state(async()=>{try{let I=await n();if(!I.enabled)return jt.debug("SubAgent system disabled"),{registry:null,config:I,initialized:!0};let A=new Ic(I),S=I.agents.filter(w=>w.runMode==="persistent");for(let w of S)try{await A.spawn(w),jt.info("Persistent agent spawned",{name:w.name});}catch(y){jt.error("Failed to spawn persistent agent",{name:w.name,error:String(y)});}return jt.info("SubAgent system initialized",{totalAgents:I.agents.length,persistentAgents:S.length}),{registry:A,config:I,initialized:!0}}catch(I){return t=I instanceof Error?I:new Error(String(I)),jt.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 I=>{I?.registry&&await I.registry.shutdownAll();})),e}async function n(){let I=await mr();if(!I.enabled)return {enabled:false,defaultRunMode:"ephemeral",timeout:3e5,maxConcurrent:5,idleTimeout:1800*1e3,idleCheckInterval:300*1e3,agents:[]};let S=I.defaultRunMode==="persistent"?"persistent":"ephemeral",w=I.timeout,y=I.maxConcurrent,b=I.idleTimeout??1800*1e3,C=I.idleCheckInterval??300*1e3,E=I.agents.map(O=>({...O,transport:O.transport,runMode:O.runMode}));return {enabled:true,defaultRunMode:S,timeout:w,maxConcurrent:y,idleTimeout:b,idleCheckInterval:C,agents:E}}function s(){return o()()}P.state=s;async function r(){return (await s()).config?.enabled??false}P.isEnabled=r;async function i(){return (await s()).initialized}P.isInitialized=i;function c(){return t}P.getInitError=c;async function l(I){let A=await s();if(!A.config?.enabled)throw new Error("SubAgent system is disabled");let S=A.config.agents.find(b=>b.name===I.agent);if(!S)throw new Error(`Unknown agent: ${I.agent}`);let w=Wl(S,I.config);if(jt.debug("SubAgent.run started",{title:I.title,agent:I.agent,runMode:w.runMode,transport:w.transport}),!A.registry)throw new Error("SubAgent registry not initialized");let y=await A.registry.acquire(w);try{let b=await y.execute(I);return jt.debug("SubAgent.run completed",{title:I.title,agent:I.agent,outputLength:b.output.length}),b}catch(b){if(jt.error("SubAgent.run failed",{title:I.title,agent:I.agent,runMode:w.runMode,error:String(b)}),w.runMode==="persistent"){jt.warn("Persistent agent failed, terminating instance",{id:y.instance.id,name:I.agent});try{await A.registry.terminate(y.instance.id);}catch(C){jt.warn("Failed to terminate persistent agent",{id:y.instance.id,error:String(C)});}}throw b}finally{if(w.runMode==="ephemeral")try{await A.registry.release(y.instance,"ephemeral");}catch(b){jt.warn("Failed to release ephemeral agent",{id:y.instance.id,error:String(b)});}}}P.run=l;async function d(I,A){let S=await s();if(!S.config?.enabled)throw new Error("SubAgent system is disabled");let w=S.config.agents.find(E=>E.name===I.agent);if(!w)throw new Error(`Unknown agent: ${I.agent}`);let y=Wl(w,I.config);if(jt.debug("SubAgent.runAsync started",{title:I.title,agent:I.agent,runMode:y.runMode,transport:y.transport}),!S.registry)throw new Error("SubAgent registry not initialized");let b=S.registry,C=await b.acquire(y);return (async()=>{try{let E=await C.execute(I);jt.debug("SubAgent.runAsync completed, triggering callback",{title:I.title,agent:I.agent,outputLength:E.output.length});try{await A(E);}finally{await b.release(C.instance,y.runMode);}}catch(E){jt.error("SubAgent.runAsync failed",{title:I.title,agent:I.agent,error:String(E)});try{await A({title:I.title,output:`Error: ${E}`,metadata:{error:String(E)}});}finally{await b.release(C.instance,y.runMode);}}})(),C.instance.id}P.runAsync=d;function m(I){return (async()=>{let A=await s();if(!A.config?.enabled)throw new Error("SubAgent system is disabled");let S=A.config.agents.find(C=>C.name===I.agent);if(!S)throw new Error(`Unknown agent: ${I.agent}`);let w=Wl(S,I.config);if(jt.debug("SubAgent.runPromise started",{title:I.title,agent:I.agent,runMode:w.runMode,transport:w.transport}),!A.registry)throw new Error("SubAgent registry not initialized");let y=A.registry,b=await y.acquire(w);try{let C=await b.execute(I);return jt.debug("SubAgent.runPromise completed",{title:I.title,agent:I.agent,outputLength:C.output.length}),{...C,instanceId:b.instance.id}}catch(C){throw jt.error("SubAgent.runPromise failed",{title:I.title,agent:I.agent,error:String(C)}),C}finally{await y.release(b.instance,w.runMode);}})()}P.runPromise=m;async function f(){return (await s()).registry?.list()??[]}P.list=f;async function a(I){return (await s()).registry?.get(I)}P.get=a;async function p(I){let A=await s();A.registry&&await A.registry.terminate(I);}P.close=p;async function u(){let I=await s();I.registry&&await I.registry.shutdownAll();}P.closeAll=u;async function h(I){let A=await s();A.registry&&A.registry.get(I)&&await A.registry.interrupt(I);}P.interrupt=h;async function g(I){let A=await s();if(A.config){if(A.config.agents.find(w=>w.name===I.name)){jt.warn("Agent already registered",{name:I.name});return}if(A.config.agents.push(I),I.runMode==="persistent"&&A.registry)try{await A.registry.spawn(I),jt.info("Persistent agent spawned after register",{name:I.name});}catch(w){jt.error("Failed to spawn persistent agent after register",{name:I.name,error:String(w)});}jt.info("Agent registered",{name:I.name});}}P.register=g;async function v(I){let A=await s();if(A.config){let S=A.config.agents.findIndex(w=>w.name===I);S!==-1&&(A.config.agents.splice(S,1),jt.info("Agent unregistered",{name:I}));}}P.unregister=v;})(As||(As={}));var Jm=a.create({service:"hook.executor.agent"}),Rs=class Rs{constructor(){b$1(this,"type","agent");}static getInstance(){return Rs._instance||(Rs._instance=new Rs),Rs._instance}canExecute(t){return !t||typeof t!="object"?false:t.type==="agent"}async execute(t,o,n){let s=Date.now();try{Jm.debug("Execute Agent Hook",{type:t.type,timeout:t.timeout,context:n?.sessionId});let r=await As.run({source:n?.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:o.modified,input:o.input,output:r.output,duration:Date.now()-s}}catch(r){return Jm.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 o=t.find(n=>typeof n=="object"&&n!==null&&n.type==="text");return o&&typeof o.text=="string"?o.text.slice(0,50):"Agent Task"}};b$1(Rs,"_instance");var ji=Rs;var ns=class ns{constructor(){b$1(this,"executors",[]);}static getInstance(){return ns._instance||(ns._instance=new ns,ns._instance.registerDefaultExecutors()),ns._instance}registerDefaultExecutors(){this.register(lc.getInstance()),this.register(uc.getInstance()),this.register(_i.getInstance()),this.register(pc.getInstance()),this.register(ji.getInstance());}register(t){this.executors.push(t);}getExecutor(t){return this.executors.find(o=>o.canExecute(t))}async execute(t,o,n){let s=this.getExecutor(t);return s?s.execute(t,o,n):{success:false,modified:false,error:`No executor found for hook type: ${t.type}`}}};b$1(ns,"_instance");var Li=ns;var Xm=a.create({service:"hook.builtin.scheduler"});var Vl=Jt("scheduler.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.ScheduledTaskTrigger,handler:async(e,t)=>{let o=e;return Xm.info("Scheduled task trigger event received",{taskID:o.taskID,taskName:o.taskName,timestamp:o.timestamp}),{modified:false,input:e}}},{name:HookEvent.ScheduledTaskComplete,handler:(e,t)=>{let o=e;return Xm.info("Scheduled task complete event received",{taskID:o.taskID,timestamp:o.timestamp,success:o.success}),{modified:false,input:e}}}]}}});var Zm=a.create({service:"hook.builtin.context"}),Kl=Jt("context.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.ContextBuildBefore,handler:(e,t)=>{let o=e;return Zm.debug("context.build.before hook triggered",{sessionId:o.sessionId,mode:o.mode}),{modified:false,input:e}}},{name:HookEvent.ContextBuildAfter,handler:(e,t)=>{let o=e;return Zm.debug("context.build.after hook triggered",{sessionId:o.context.metadata.sessionId}),{modified:false,input:e}}}]}}});var Jl=class extends Error{constructor(o,n){super(`Too many concurrent tasks: ${o} running, limit is ${n}`);b$1(this,"running");b$1(this,"limit");this.name="TaskConcurrencyError",this.running=o,this.limit=n;}},Lt;(A=>{let e=a.create({service:"task"});A.MAX_CONCURRENT_TASKS=5;async function o(S){let w=await n(S);if(w>=A.MAX_CONCURRENT_TASKS)throw new Jl(w,A.MAX_CONCURRENT_TASKS)}async function n(S){return (await g(S)).filter(y=>y.status==="running").length}A.getRunningCount=n;let s;async function r(){return Filesystem.normalize(Ce__default.join(a$1.Path.data,"task"))}async function i(S){let w=await r();return Filesystem.normalize(Ce__default.join(w,`${S}.json`))}async function c(S){let w=await i(S);try{let y=await Filesystem.readText(w);return y?JSON.parse(y):[]}catch{return []}}async function l(S,w){let y=await i(S);try{await Filesystem.write(y,JSON.stringify(w,null,2)),e.debug("Session tasks saved",{sessionId:S,count:w.length});}catch(b){e.error("Failed to save session tasks",{sessionId:S,error:String(b)});}}async function d(){let S=await r(),w=new Map;try{let y=await readdir(S);for(let b of y){if(!b.endsWith(".json"))continue;let C=b.replace(".json",""),E=await c(C);for(let O of E)w.set(O.taskId,O);}}catch(y){e.debug("Task directory not found or empty",{error:String(y)});}return w}function m(){return s||(s=R.state(async()=>{let S=await d();return e.debug("Task state initialized",{taskCount:S.size}),{tasks:S,initialized:true}},async()=>{})),s}function f(){return m()()}A.state=f;async function a$2(S){return (await f()).tasks.get(S)}A.get=a$2;async function p(S){await o(S.sessionId);let w=await f(),y=Date.now(),b={taskId:S.taskId,sessionId:S.sessionId,description:S.description,prompt:S.prompt,agentType:S.agentType,source:S.source||"tool",status:"pending",createdAt:y,updatedAt:y,metadata:S.metadata};w.tasks.set(S.taskId,b);let C=await c(S.sessionId);return C.push(b),await l(S.sessionId,C),e.debug("Task created",{taskId:S.taskId,sessionId:S.sessionId}),b}A.create=p;async function u(S,w){let y=await f(),b=y.tasks.get(S);if(!b){e.warn("Task not found for update",{taskId:S});return}w.status!==void 0&&(b.status=w.status),w.result!==void 0&&(b.result=w.result),w.error!==void 0&&(b.error=w.error),w.duration!==void 0&&(b.duration=w.duration),w.metadata!==void 0&&(b.metadata={...b.metadata,...w.metadata}),b.updatedAt=Date.now(),y.tasks.set(S,b);let C=await c(b.sessionId),E=C.findIndex(O=>O.taskId===S);E>=0?C[E]=b:C.push(b),await l(b.sessionId,C),e.debug("Task updated",{taskId:S,status:b.status});}A.update=u;async function h(S){let w=await f(),y=w.tasks.get(S);if(!y){e.warn("Task not found for remove",{taskId:S});return}let b=y.sessionId;w.tasks.delete(S);let E=(await c(b)).filter(O=>O.taskId!==S);await l(b,E),e.debug("Task removed",{taskId:S,sessionId:b});}A.remove=h;async function g(S){return c(S)}A.list=g;async function v(S){return (await g(S)).filter(y=>y.status==="running"||y.status==="pending")}A.active=v;async function P(S){let w=await g(S);return {total:w.length,pending:w.filter(y=>y.status==="pending").length,running:w.filter(y=>y.status==="running").length,completed:w.filter(y=>y.status==="completed").length,error:w.filter(y=>y.status==="error").length}}A.stats=P;async function I(S=10080*60*1e3){let w=await f(),y=Date.now(),b=0;for(let[C,E]of w.tasks)(E.status==="completed"||E.status==="error")&&y-E.updatedAt>S&&(w.tasks.delete(C),b++);if(b>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:b});}return b}A.cleanup=I;})(Lt||(Lt={}));var mo=a.create({service:"hook.builtin.task"});async function hI(e){try{return (await Mt.get(e)).type==="idle"}catch{return false}}async function yI(e){let{taskId:t,duration:o,error:n}=e;e.source==="scheduler"&&mo.debug("Scheduled task completed",{taskId:t,duration:o,success:!n});}async function bI(e){let{taskId:t,error:o}=e;e.source==="cli"&&(o?mo.error("CLI task error",{taskId:t,error:o}):mo.debug("CLI task completed",{taskId:t}));}async function wI(e){let{taskId:t,result:o,error:n}=e;e.source==="api"&&mo.debug("API task event",{taskId:t,hasError:!!n,hasResult:!!o});}var xI={tool:async()=>mo.debug("Tool task completed"),scheduler:yI,cli:bI,api:wI};async function II(e){try{await Lt.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){mo.error("Failed to create task",{taskId:e.taskId,error:String(t)});return}mo.debug("Task created (pending)",{taskId:e.taskId,sessionId:e.sessionId,source:e.source,agentType:e.agentType});}async function vI(e){await Lt.update(e.taskId,{status:"running"}),mo.debug("Task running",{taskId:e.taskId,sessionId:e.sessionId});}async function SI(e){if(!await Lt.get(e.taskId)){mo.warn("Task progress for unknown task",{taskId:e.taskId});return}mo.debug("Task progress",{taskId:e.taskId,step:e.step,totalSteps:e.totalSteps});}async function CI(e){let t=await Lt.get(e.taskId);if(!t){mo.warn("Task complete for unknown task",{taskId:e.taskId});return}await Lt.update(e.taskId,{status:e.error?"error":"completed",result:e.result,error:e.error,duration:e.duration,metadata:e.metadata}),mo.debug("Task completed (persisted)",{taskId:e.taskId,sessionId:t.sessionId,source:e.source,duration:e.duration,hasError:!!e.error}),await xI[e.source](e),t.sessionId&&e.source==="tool"&&(e.result||e.error?await kI(t,e):mo.debug("Task completed without result, skip injection",{taskId:e.taskId,sessionId:t.sessionId}));}async function kI(e,t){if(e?.sessionId)try{let o=await hI(e.sessionId);await Ke.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:!o}),o?mo.debug("Injected result to parent session (agent idle, will trigger LLM)",{taskId:e.taskId,sessionId:e.sessionId}):mo.debug("Injected result to parent session (agent busy, queued for next turn)",{taskId:e.taskId,sessionId:e.sessionId});}catch(o){mo.error("Failed to inject result to parent session",{taskId:e.taskId,sessionId:e.sessionId,error:o instanceof Error?o.message:String(o)});}}var Yl=Jt("task.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.TaskStart,handler:async e=>(await II(e),{modified:false,input:e})},{name:HookEvent.TaskRunning,handler:async e=>(await vI(e),{modified:false,input:e})},{name:HookEvent.TaskProgress,handler:async e=>(await SI(e),{modified:false,input:e})},{name:HookEvent.TaskComplete,handler:async e=>(await CI(e),{modified:false,input:e})}]}}});var Cc=a.create({service:"hook.builtin.loop"});async function PI(e,t){let o=await ve.getLastMessages(e);return !o.lastUser||o.lastUser.id===t?false:o.lastFinished?o.lastFinished.info.role==="assistant"&&o.lastFinished.info.parentId!==o.lastUser.id?(Cc.debug("Latest assistant message does not respond to latest user message, should continue loop",{lastUserId:o.lastUser.id,assistantParentId:o.lastFinished.info.parentId}),true):false:(Cc.debug("Found new user message without assistant response, should continue loop",{lastUserId:o.lastUser.id,expectedParentId:o.lastUser.id}),true)}var Xl=Jt("loop.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.LoopStart,handler:async e=>{let t=e;return Cc.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 PI(t.sessionId,t.lastUserId)?(Cc.debug("Loop should continue for pending messages"),{modified:true,input:{...t,result:"continue"}}):{modified:false,input:e}}}]}}});var of=a.create({service:"hook.matcher"}),_s=class _s{static getInstance(){return _s._instance||(_s._instance=new _s),_s._instance}match(t,o,n){return t.event!==o?{matched:false}:t.matcher&&!this.evaluateCondition(t.matcher,n)?(of.debug("Hook matcher condition not met",{matcher:t.matcher,context:n}),{matched:false}):{matched:true}}matchHook(t,o,n){return !("if"in t)||!t.if?true:this.evaluateCondition(t.if,n)}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,o){try{let n={...process.env,SESSION_ID:o?.sessionId,AGENT:o?.agent,MODEL:o?.model,CWD:o?.cwd};for(let[i,c]of Object.entries(o??{}))typeof c=="string"&&(n[i.toUpperCase()]=c);let s=t.replace(/\$\{(\w+)\}/g,(i,c)=>{let l=n[c];return typeof l=="string"?`"${l.replace(/"/g,'\\"')}"`:"undefined"});return !!new Function(`return ${s}`)()}catch(n){return of.error("Failed to evaluate condition",{condition:t,error:n?.message}),false}}};b$1(_s,"_instance");var Di=_s;var ln=a.create({service:"hook.registry"}),Ql=[Il,El,Rl,jl,Vl,Kl,Yl,Xl,Ml],Le;(m=>{let e;function t(){return e||(e=R.state(async()=>({matchers:[],executorRegistry:Li.getInstance(),hookMatcher:Di.getInstance()}),async()=>{ln.debug("hook registry cleanup");})),e}function o(){return t()()}m.state=o;function n(){return [...Ql]}m.all=n;async function s(){ln.debug("HookRegistry.init starting",{builtinCount:Ql.length});let f=await o(),a=[];for(let p of Ql){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),ln.debug("hook entry registered",{hook:p.name,hookName:h.name,scope:u.scope});}}return ln.debug("HookRegistry.init completed",{registeredCount:a.length,totalMatchers:f.matchers.length}),a}m.init=s;async function r(f){let a={...f,scope:f.scope,hookName:f.hookName};return (await o()).matchers.push(a),ln.debug("hook matcher registered",{event:f.event,hookCount:f.hooks.length,scope:f.scope,hookName:f.hookName}),()=>{o().then(u=>{let h=u.matchers.indexOf(a);h>-1&&(u.matchers.splice(h,1),ln.debug("hook matcher unregistered",{event:f.event}));});}}m.registerMatcher=r;async function i(f){try{let p=await Z.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 o(),h=Date.now(),g$1={success:true,output:a,modified:false,aborted:false,details:[],errors:[],duration:0},v=p?.sessionId,P=v?await i(v):g.General,I=u.matchers.filter(w=>{if(!u.hookMatcher.match(w,f,p).matched)return false;let y=w.scope??g.All;return y!==g.All&&y!==P?(ln.debug("hook scope filtered",{event:f,hookName:w.hookName,matcherScope:y,currentMode:P}),false):true}),A=[];for(let w of I)for(let y=0;y<w.hooks.length;y++){let b=w.hooks[y];b&&u.hookMatcher.matchHook(b,a,p)&&A.push({hook:b,hookIndex:y});}let S=a;for(let w=0;w<A.length;w++){if(p?.abort?.aborted){g$1.aborted=true,g$1.errors.push({index:w,hookName:"system",error:String(p.abort.reason??"Aborted")}),ln.debug("Hook chain aborted",{reason:p.abort.reason,stoppedAt:w});break}let y=A[w];if(!y)continue;let{hook:b}=y,C={index:w,hookType:b.type,hookName:`${f}:${u.hookMatcher.getHookName(b)}`,matched:true,skipped:false,success:false,modified:false,duration:0},E=Date.now();try{let O={modified:!1,input:S},D=await u.executorRegistry.execute(b,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")}),ln.debug("Hook triggered abort",{hook:C.hookName,reason:p.abort.reason});break}D.modified&&D.input!==void 0&&(S=D.input,C.modified=!0,g$1.modified=!0),C.success=D.success!==!1,C.output=D.output,C.duration=Date.now()-E,g$1.details.push(C);}catch(O){let D=O;if(D?.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:D?.message??String(O),stack:D?.stack}),ln.error("Hook execution error",{hook:C.hookName,error:D?.message,stack:D?.stack}),C.duration=Date.now()-E,g$1.details.push(C);}}return g$1.output=S,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,ln.debug("cleared all hooks");}m.clear=l;async function d(){return (await o()).matchers.length}m.matcherCount=d;})(Le||(Le={}));var kc;(s=>{let e=a.create({service:"skill-discovery"});function t(){return Ce__default.join(a$1.Path.cache,"skills")}s.dir=t;async function o(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 n(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=Ce__default.join(d,u.name);await Promise.all(u.files.map(async v=>{let P=new URL(v,`${m}/${u.name}/`).href,I=Ce__default.join(h,v);await mkdir(Ce__default.dirname(I),{recursive:!0}),await o(P,I);}));let g=Ce__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=n;})(kc||(kc={}));var Qt;(g=>{let e=a.create({service:"skill"});g.Info=U.object({name:U.string(),description:U.string(),location:U.string(),content:U.string(),scope:U.enum(h).optional().describe("Context mode scope")}),g.InvalidError=NamedError.create("SkillInvalidError",U.object({path:U.string(),message:U.string().optional(),issues:U.custom().optional()})),g.NameMismatchError=NamedError.create("SkillNameMismatchError",U.object({message:U.string(),path:U.string(),expected:U.string(),actual:U.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 v={},P=new Set,I=async w=>{let y=await a$9.parse(w).catch(C=>{let E=a$9.FrontmatterError.isInstance(C)?C.data.message:`Failed to parse skill ${w}`;ue.publish(Z.Event.Error,{error:new NamedError.Unknown({message:E}).toObject()}),e.error("failed to load skill",{skill:w,err:C});});if(!y)return;let b=g.Info.pick({name:true,description:true}).safeParse(y.data);b.success&&(v[b.data.name]&&e.warn("duplicate skill name",{name:b.data.name,existing:v[b.data.name]?.location,duplicate:w}),P.add(Ce__default.dirname(w)),v[b.data.name]={name:b.data.name,description:b.data.description,location:w,content:y.content,scope:y.data.scope});},A=async(w,y)=>glob(r,{cwd:w,absolute:true,nodir:true,follow:true,dot:true}).then(b=>Promise.all(b.map(I))).catch(b=>{e.error(`failed to scan ${y} skills`,{dir:w,error:b});});if(!a$2.EASBOT_DISABLE_EXTERNAL_SKILLS){for(let w of s){let y=Ce__default.join(a$1.Path.home,w);await Filesystem.isDir(y)&&await A(y,"global");}for await(let w of Filesystem.up({targets:s,start:R.directory,stop:R.worktree}))await A(w,"project");}for(let w of await he.directories()){let y=await glob(i$1,{cwd:w,absolute:true,nodir:true,follow:true});for(let b of y)await I(b);}let S=await he.get();for(let w of S.skills?.paths??[]){let y=w.startsWith("~/")?Ce__default.join(nc.homedir(),w.slice(2)):w,b=Ce__default.isAbsolute(y)?y:Ce__default.join(R.directory,y);if(!await Filesystem.isDir(b)){e.warn("skill path not found",{path:b});continue}let C=await glob(c,{cwd:b,absolute:true,nodir:true,follow:true});for(let E of C)await I(E);}for(let w of S.skills?.urls??[]){let y=await kc.pull(w);for(let b of y){P.add(b);let C=await glob(c,{cwd:b,absolute:true,nodir:true,follow:true});for(let E of C)await I(E);}}return {skills:v,dirs:Array.from(P)}})),l}function m(){return d()()}g.state=m;async function f(v){return m().then(P=>P.skills[v])}g.get=f;async function a$3(){return m().then(v=>Object.values(v.skills))}g.all=a$3;async function p(){return m().then(v=>v.dirs)}g.dirs=p;async function u(v,P=i){let I=await m();return Object.values(I.skills).toSorted((S,w)=>S.name.localeCompare(w.name)).filter(S=>{if(v&&Oe.evaluate("skill",S.name,v.permission).action==="deny")return false;if(P){let w=S.scope??i;if(w!=="all"&&w!==P)return false}return true})}g.available=u;function h$1(v,P){if(v.length===0)return "No skills are currently available.";let I=v.toSorted((A,S)=>A.name.localeCompare(S.name));return P.verbose?["<available_skills>",...I.flatMap(A=>[" <skill>",` <name>${A.name}</name>`,` <description>${A.description}</description>`,` <location>${pathToFileURL(A.location).href}</location>`," </skill>"]),"</available_skills>"].join(`
154
- `):["## 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.","",...I.map(A=>[`- **${A.name}**: ${A.description}`,` - Location: ${pathToFileURL(A.location).href}`].join(`
155
- `))].join(`
156
- `)}g.format=h$1;})(Qt||(Qt={}));var MI=loadTextFile("./generate.txt",import.meta.url),OI=MI(),jI=loadTextFile("./prompt/compaction.txt",import.meta.url),LI=jI(),DI=loadTextFile("./prompt/explore.txt",import.meta.url),$I=DI(),FI=loadTextFile("./prompt/summary.txt",import.meta.url),NI=FI(),UI=loadTextFile("./prompt/title.txt",import.meta.url),zI=UI(),qI=loadTextFile("./prompt/btw.txt",import.meta.url),HI=qI(),BI=loadTextFile("./prompt/memory.txt",import.meta.url),GI=BI(),Ne;(d=>{d.Info=U.object({name:U.string(),description:U.string().optional(),mode:U.enum(["subagent","primary","all"]),native:U.boolean().optional(),hidden:U.boolean().optional(),topP:U.number().optional(),temperature:U.number().optional(),color:U.string().optional(),permission:U.lazy(()=>Oe.Ruleset),scope:U.enum(h).optional(),model:U.object({modelId:U.string(),providerId:U.string()}).optional(),variant:U.string().optional(),prompt:U.string().optional(),options:U.record(U.string(),U.any()),steps:U.number().int().positive().optional()}).meta({ref:"Agent"});async function t(){let m=await he.get(),f=await Qt.dirs(),a=Oe.fromConfig({"*":"allow",doom_loop:"ask",external_directory:{"*":"ask",[Ve.GLOB]:"allow",...Object.fromEntries(f.map(h=>[Ce__default.join(h,"*"),"allow"]))},question:"deny",plan:"deny",read:{"*":"allow","*.env":"ask","*.env.*":"ask","*.env.example":"allow"}}),p=Oe.fromConfig(m.permission??{}),u={build:{name:"build",description:"The default agent. Executes tools based on configured permissions.",options:{},permission:Oe.merge(a,Oe.fromConfig({question:"allow",plan:"allow"}),p),mode:"primary",native:true},plan:{name:"plan",description:"Plan mode. Disallows all edit tools.",options:{},permission:Oe.merge(a,Oe.fromConfig({question:"allow",plan_exit:"allow",external_directory:{[Ce__default.join(a$1.Path.data,"plans","*")]:"allow"},edit:{"*":"deny",[Ce__default.posix.join(".easbot","plans","*.md")]:"allow",[Ce__default.posix.relative(R.worktree,Ce__default.posix.join(a$1.Path.data,Ce__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:Oe.merge(a,Oe.fromConfig({todo:"deny"}),p),options:{},mode:"subagent",native:true},explore:{name:"explore",permission:Oe.merge(a,Oe.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:$I,options:{},mode:"subagent",native:true},compaction:{name:"compaction",mode:"primary",native:true,hidden:true,prompt:LI,permission:Oe.merge(a,Oe.fromConfig({"*":"deny"}),p),options:{}},title:{name:"title",mode:"primary",options:{},native:true,hidden:true,temperature:.5,permission:Oe.merge(a,Oe.fromConfig({"*":"deny"}),p),prompt:zI},summary:{name:"summary",mode:"primary",options:{},native:true,hidden:true,permission:Oe.merge(a,Oe.fromConfig({"*":"deny"}),p),prompt:NI},btw:{name:"btw",description:"Act like a professional in the relevant domain",mode:"primary",options:{},native:true,permission:Oe.merge(a,Oe.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:HI},memory:{name:"memory",mode:"primary",options:{},native:true,hidden:true,permission:Oe.merge(a,Oe.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=>[Ce__default.join(h,"*"),"allow"]))}}),p),prompt:GI}};for(let[h,g]of Object.entries(m.agent??{})){if(g.disable){delete u[h];continue}let v=u[h];if(v||(v=u[h]={name:h,mode:"all",permission:Oe.merge(a,p),options:{},native:false}),g.model){let P=Se.parseModel(g.model);v.model={providerId:P.providerId,modelId:P.modelId};}v.variant=g.variant??v.variant,v.prompt=g.prompt??v.prompt,v.description=g.description??v.description,v.temperature=g.temperature??v.temperature,v.topP=g.top_p??v.topP,v.mode=g.mode??v.mode,v.color=g.color??v.color,v.hidden=g.hidden??v.hidden,v.name=g.name??v.name,v.steps=g.steps??v.steps,v.options=mergeDeep(v.options,g.options??{}),v.permission=Oe.merge(v.permission,Oe.fromConfig(g.permission??{}));}for(let h in u){if(!Object.hasOwn(u,h))continue;let g=u[h];!g||g.permission.some(P=>P.permission!=="external_directory"||P.action!=="deny"?false:P.pattern===Ve.GLOB)||!u[h]||(u[h].permission=Oe.merge(u[h].permission,Oe.fromConfig({external_directory:{[Ve.GLOB]:"allow"}})));}return u}let o;function n(){return o||(o=R.state(t)),o}function s(){return n()()}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 Se.defaultModel(),p=await Se.getModel(a.providerId,a.modelId),u=await Se.getLanguage(p),h=[OI];await Le.triggerEvent(HookEvent.SystemTransform,{model:p});let g=await i(),v={experimental_telemetry:{isEnabled:f.experimental?.openTelemetry,metadata:{userId:f.username??"unknown"}},temperature:.3,messages:[...h.map(I=>({role:"system",content:I})),{role:"user",content:`Create an agent configuration based on this request: "${m.description}".
157
-
158
- IMPORTANT: The following identifiers already exist and must NOT be used: ${g.map(I=>I.name).join(", ")}
159
- Return ONLY the JSON object, no other text, do not wrap in backticks`}],model:u,schema:U.object({identifier:U.string(),whenToUse:U.string(),systemPrompt:U.string()})};if(a.providerId==="openai"&&(await Qe.get(a.providerId))?.type==="oauth"){let I=streamObject({...v,providerOptions:bt.providerOptions(p,{instructions:h.join(`
160
- `),store:false}),onError:()=>{}});for await(let A of I.fullStream)if(A.type==="error")throw A.error;return I.object}return (await generateObject(v)).object}d.generate=l;})(Ne||(Ne={}));var Uo=a.create({service:"agent-cli-api-agent"});async function af(){try{Uo.debug("Get agent list");let t=(await Ne.list()).map(o=>{let n=o.model,s;if(n&&typeof n=="string"){let{provider:r,model:i}=parseModelId(n);r&&i&&(s={providerId:r,modelId:i});}return {...o,model:s}});return Uo.debug("Get agent list successful",{count:t.length}),t}catch(e){throw Uo.error("Failed to get agent list",{error:e}),e}}async function Tc(e){try{e=e?.trim()??await Ne.defaultAgent(),Uo.debug("Get agent details",{agentName:e});let t=await Ne.get(e);return t?(Uo.debug("Get agent details successful",{agentName:e}),t):(Uo.warn("Agent does not exist",{agentName:e}),null)}catch(t){throw Uo.error("Failed to get agent details",{agentName:e,error:t}),t}}async function XI(){try{Uo.debug("Get default agent");let e=await Ne.defaultAgent(),t=await Tc(e);if(!t)throw new Error(`Default agent "${e}" not found`);return Uo.debug("Get default agent successful",{agentName:e}),t}catch(e){throw Uo.error("Failed to get default agent",{error:e}),e}}var QI=af;async function cf(e){try{if(Uo.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"],o=e.mode||"primary";if(!t.includes(o))throw new Error(`Invalid agent mode: ${e.mode}. Valid modes are: ${t.join(", ")}`);if(await Tc(e.name))throw new Error(`Agent "${e.name}" already exists`);let s={mode:o};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-O5EE574O.mjs');await r.update({agent:{[e.name]:s}}),Uo.debug("Agent created successfully",{name:e.name});let i=await Tc(e.name);if(!i)throw new Error(`Failed to retrieve created agent "${e.name}"`);return i}catch(t){throw Uo.error("Failed to create agent",{name:e.name,error:t}),t}}var ZI=cf;var so={};a$7(so,{abort:()=>pv,abortSession:()=>mf,create:()=>lv,createSession:()=>uf,deleteSession:()=>ev,fork:()=>uv,forkSession:()=>pf,formatSessionJSON:()=>av,formatSessionTable:()=>iv,get:()=>dv,getSession:()=>lf,getSessionChildren:()=>ov,getSessionContextMode:()=>sv,getSessionStatus:()=>fv,initSession:()=>nv,list:()=>cv,listSessionStatuses:()=>gv,listSessions:()=>df,setSessionContextMode:()=>rv,summarize:()=>mv,summarizeSession:()=>Ec,updateSession:()=>tv});async function df(e){let t=[];for await(let n of Z.list())!n.parentId&&(!e?.directory||n.directory===e.directory)&&t.push(n);t.sort((n,s)=>s.time.updated-n.time.updated);let o=e?.limit;return !o||o<=0?t:t.slice(0,o)}async function lf(e){return Z.get(e)}async function uf(e){return Z.create(e)}async function pf(e,t,o){return Z.fork({sessionId:e,messageId:t,directory:o})}async function ev(e){await Z.remove(e);}async function mf(e){let{SessionPrompt:t}=await import('./prompt-JSZCNKQD.mjs');await t.cancel(e);}async function Ec(e){let[{SessionPrompt:t},{Compaction:o},{SessionRevert:n}]=await Promise.all([import('./prompt-JSZCNKQD.mjs'),import('./compaction-JR5FOLBX.mjs'),import('./revert-PDDRJVNK.mjs')]),s=e.sessionId,r=await Z.get(s);if(!r)throw new Error("session not found");await n.cleanup(r);let i;return e.providerId&&e.modelId&&(i={providerId:e.providerId,modelId:e.modelId}),await o.create({sessionId:s,model:i,agent:e.agent??"compaction",auto:e.auto??false}),await t.loop({sessionId:s}),true}async function tv(e,t){let o=await Z.get(e);if(!o)throw new Error("session not found");t.title&&(o.title=t.title),t.time?.archived&&(o.time.archived=t.time.archived);let{Storage:n}=await import('./storage-3T5H5KBY.mjs'),{Instance:s}=await import('./instance-S5GBRS3K.mjs');return await n.write(["session",s.project.id,e],o),o}async function ov(e){return Z.children(e)}async function nv(e){return true}async function sv(e){return Z.getContextMode(e)}async function rv(e,t){await Z.setContextMode(e,t);}function iv(e,t=20,o=25){let n=[],s=Math.max(t,...e.map(c=>c.id.length)),r=Math.max(o,...e.map(c=>c.title.length)),i=`Session ID${" ".repeat(s-10)} Title${" ".repeat(r-5)} Updated`;n.push(i),n.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}`;n.push(m);}return n.join(`
161
- `)}function av(e){let t=e.map(o=>({id:o.id,title:o.title,updated:o.time.updated,created:o.time.created,projectId:o.providerId,directory:o.directory}));return JSON.stringify(t,null,2)}var cv=df,dv=lf,lv=uf,uv=pf,pv=mf,mv=Ec;async function fv(e){return Mt.get(e)}async function gv(){return Mt.list()}var Ni={};a$7(Ni,{formatModels:()=>Iv,getDefaultModel:()=>hv,listModels:()=>bv,listProviders:()=>yv,parseModel:()=>xv,refreshModels:()=>wv});async function hv(){try{let e=await Se.defaultModel();return e?`${e.providerId}/${e.modelId}`:void 0}catch{return}}async function yv(){return Se.list()}async function bv(e){let t=await Se.list();if(e){let o=t[e];if(!o)throw new Error(`Provider not found: ${e}`);return {[e]:o}}return t}async function wv(){await a$3.refresh();}function xv(e){let t=Se.parseModel(e);if(t?.providerId)return {providerId:t.providerId,modelId:t.modelId}}function Iv(e,t=false){let o=[],n=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 n){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)o.push(`${s}/${c}`),t&&l&&o.push(JSON.stringify(l,null,2));}return o.join(`
162
- `)}var js={};a$7(js,{command:()=>Av,deleteMessage:()=>Cv,deletePart:()=>Pv,getMessage:()=>Sv,list:()=>vv,listMessages:()=>gf,send:()=>Ev,updateMessage:()=>kv,updatePart:()=>Tv});var Rr=a.create({service:"agent-cli-api-message"});async function gf(e,t){Rr.debug(i$1("message.history.start"),{sessionId:e});let o=await Z.messages({sessionId:e,limit:t});return Rr.debug(i$1("message.history.success"),{sessionId:e,count:o.length}),o}var vv=gf;async function Sv(e,t){return await ve.get({sessionId:e,messageId:t})}async function Cv(e,t){return Z.removeMessage({sessionId:e,messageId:t})}async function kv(e){return Z.updateMessage(e)}async function Pv(e,t,o){return Z.removePart({sessionId:e,messageId:t,partId:o})}async function Tv(e){return Z.updatePart(e)}async function Ev(e){Rr.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 n of e.files)t.push({type:"file",url:n.url,filename:n.filename,mime:n.mime});e.subAgent&&t.push({type:"agent",name:e.subAgent});let o=await Ke.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 Rr.debug(i$1("message.send.success"),{sessionId:e.sessionId,messageId:o.info.id}),o}async function Av(e){Rr.debug(i$1("message.command.start"),{sessionId:e.sessionId,command:e.command});let t=await Ke.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 Rr.debug(i$1("message.command.success"),{sessionId:e.sessionId,command:e.command,title:t.title}),t}var De;(t=>{function e(o,n){return {id:o,isEnabled:typeof n=="function"?void 0:n.isEnabled,scope:typeof n=="function"?void 0:n.scope,init:async s=>{let r=typeof n=="function"?await n(s):n,i=r.execute;return r.execute=async(c,l)=>{try{r.parameters.parse(c);}catch(f){throw f instanceof U.ZodError&&r.formatValidationError?new Error(r.formatValidationError(f),{cause:f}):new Error(`The ${o} tool was called with invalid arguments: ${f instanceof Error?f.message:String(f)}.
163
- 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 ou=new Set(["powershell","pwsh"]),nu=new Set(["cmd"]);function Mv(e){return e==="pwsh"?"pwsh":e==="powershell"?"powershell":e==="cmd"?"cmd":e==="bash"?"bash":e==="zsh"?"zsh":e}function tu(e){return ou.has(e)?`Brief description of this command (5-10 words). Examples:
164
- Input: Get-ChildItem -LiteralPath "."
165
- Output: Lists current directory
166
-
167
- Input: git status
168
- Output: Shows working tree status
169
-
170
- Input: npm install
171
- Output: Installs package dependencies
172
-
173
- Input: New-Item -ItemType Directory -Path "tmp"
174
- Output: Creates directory tmp`:nu.has(e)?`Brief description of this command (5-10 words). Examples:
175
- Input: dir
176
- Output: Lists current directory
177
-
178
- Input: if exist "package.json" type "package.json"
179
- Output: Prints package.json when it exists
180
-
181
- Input: mkdir tmp
182
- Output: Creates directory tmp`:`Brief description of this command (5-10 words). Examples:
183
- Input: ls
184
- Output: Lists files in current directory
185
-
186
- Input: git status
187
- Output: Shows working tree status
188
-
189
- Input: npm install
190
- Output: Installs package dependencies
191
-
192
- Input: mkdir foo
193
- Output: Creates directory 'foo'`}function Ov(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 jv(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.":ou.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.":nu.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 Lv(e,t){return `Before executing the command, please follow these steps:
194
-
195
- 1. Directory Verification:
196
- - If the command will create new directories or files, first use \`ls\` to verify the parent directory exists and is the correct location
197
- - For example, before running "mkdir foo/bar", first use \`ls foo\` to check that "foo" exists and is the intended parent directory
198
-
199
- 2. Command Execution:
200
- - Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
201
- - Examples of proper quoting:
202
- - mkdir "/Users/name/My Documents" (correct)
203
- - mkdir /Users/name/My Documents (incorrect - will fail)
204
- - python "/path/with spaces/script.py" (correct)
205
- - python /path/with spaces/script.py (incorrect - will fail)
206
- - After ensuring proper quoting, execute the command.
207
- - Capture the output of the command.
208
-
209
- Usage notes:
210
- - The command argument is required.
211
- - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
212
- - Provide a brief description of what this command does (5-10 words).
213
- - 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.
214
-
215
- - 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:
216
- - File search: Use Glob (NOT find or ls)
217
- - Content search: Use Grep (NOT grep or rg)
218
- - Read files: Use Read (NOT cat/head/tail)
219
- - Edit files: Use Edit (NOT sed/awk)
220
- - Write files: Use Write (NOT echo >/cat <<EOF)
221
- - Communication: Output text directly (NOT echo/printf)
222
- - When issuing multiple commands:
223
- - 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.
224
- - ${e}
225
- - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
226
- - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
227
- - AVOID using \`cd <directory> && <command>\`. Use the \`workdir\` parameter to change directories instead.
228
- <good-example>
229
- Use workdir="/foo/bar" with command: pytest tests
230
- </good-example>
231
- <bad-example>
232
- cd /foo/bar && pytest tests
233
- </bad-example>`}function Dv(e,t,o){let n=process.platform==="win32"?"\\":"/";return `${Ov(e)}
234
-
235
- Before executing the command, please follow these steps:
236
-
237
- 1. Directory Verification:
238
- - 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
239
- - For example, before creating \`foo${n}bar\`, first use \`Test-Path -LiteralPath "foo"\` to check that \`foo\` exists and is the intended parent directory
240
-
241
- 2. Command Execution:
242
- - Always quote file paths that contain spaces with double quotes (e.g., Remove-Item -LiteralPath "path with spaces${n}file.txt")
243
- - Examples of proper quoting:
244
- - New-Item -ItemType Directory -Path "My Documents" (correct)
245
- - New-Item -ItemType Directory -Path My Documents (incorrect - path is split)
246
- - & "path with spaces${n}script.ps1" (correct)
247
- - path with spaces${n}script.ps1 (incorrect - path is split and not invoked)
248
- - After ensuring proper quoting, execute the command.
249
- - Capture the output of the command.
250
-
251
- Usage notes:
252
- - The command argument is required.
253
- - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
254
- - Provide a brief description of what this command does (5-10 words).
255
- - If the output exceeds ${o.maxLines} lines or ${o.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.
256
-
257
- - 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:
258
- - File search: Use Glob (NOT Get-ChildItem)
259
- - Content search: Use Grep (NOT Select-String)
260
- - Read files: Use Read (NOT Get-Content)
261
- - Edit files: Use Edit (NOT Set-Content)
262
- - Write files: Use Write (NOT Set-Content/Out-File or here-strings)
263
- - Communication: Output text directly (NOT Write-Output/Write-Host)
264
- - When issuing multiple commands:
265
- - 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.
266
- - ${t}
267
- - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
268
- - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
269
- - AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
270
- <good-example>
271
- Use workdir="project${n}subdir" with command: pytest tests
272
- </good-example>
273
- <bad-example>
274
- ${e==="powershell"?`Set-Location -LiteralPath "project${n}subdir"; if ($?) { pytest tests }`:`Set-Location -LiteralPath "project${n}subdir" && pytest tests`}
275
- </bad-example>`}function $v(e,t){return `# cmd.exe shell notes
276
- - Use double quotes for paths with spaces.
277
- - Use %VAR% for environment variables.
278
- - Use \`if exist\` for existence checks.
279
- - Use \`call\` when invoking batch files from another batch-style command.
280
-
281
- Before executing the command, please follow these steps:
282
-
283
- 1. Directory Verification:
284
- - If the command will create new directories or files, first use \`if exist\` to verify the parent directory exists and is the correct location
285
- - For example, before creating \`foo\\bar\`, first use \`if exist "foo\\" dir "foo"\` to check that \`foo\` exists and is the intended parent directory
286
-
287
- 2. Command Execution:
288
- - Always quote file paths that contain spaces with double quotes (e.g., del "path with spaces\\file.txt")
289
- - Examples of proper quoting:
290
- - mkdir "My Documents" (correct)
291
- - mkdir My Documents (incorrect - path is split)
292
- - call "path with spaces\\script.bat" (correct)
293
- - path with spaces\\script.bat (incorrect - path is split and not invoked correctly)
294
- - After ensuring proper quoting, execute the command.
295
- - Capture the output of the command.
296
-
297
- Usage notes:
298
- - The command argument is required.
299
- - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
300
- - Provide a brief description of what this command does (5-10 words).
301
- - 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.
302
-
303
- - 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:
304
- - File search: Use Glob (NOT dir /s)
305
- - Content search: Use Grep (NOT findstr)
306
- - Read files: Use Read (NOT type)
307
- - Edit files: Use Edit (NOT copy)
308
- - Write files: Use Write (NOT echo > file)
309
- - Communication: Output text directly (NOT echo)
310
- - When issuing multiple commands:
311
- - 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.
312
- - ${e}
313
- - Use '&' only when you need to run commands sequentially but don't care if earlier commands fail
314
- - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
315
- - AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
316
- <good-example>
317
- Use workdir="project\\subdir" with command: dir
318
- </good-example>
319
- <bad-example>
320
- cd /d "project\\subdir" && dir
321
- </bad-example>`}function Fv(e,t){let o=ou.has(e),n=nu.has(e),s=Mv(e),r=jv(e);return 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:$v(r,t),gitSection:`# Committing changes with git
322
-
323
- 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:
324
-
325
- Git Safety Protocol:
326
- - NEVER update the git config
327
- - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
328
- - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
329
- - NEVER run force push to main/master, warn the user if they request it
330
- - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
331
- (1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
332
- (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
333
- (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
334
- - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
335
- - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
336
- - 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.
337
-
338
- 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:
339
- - Run \`git status\` to see all untracked files
340
- - Run \`git diff\` to see both staged and unstaged changes that will be committed
341
- - Run \`git log --oneline -10\` to see recent commit messages
342
-
343
- 2. Analyze all staged changes and draft a commit message:
344
- - Summarize the nature of the changes
345
- - Draft a concise (1-2 sentences) commit message
346
- - Do not commit files that likely contain secrets (.env, etc.)
347
-
348
- 3. Create the commit using a temporary body file so cmd.exe quoting stays simple:
349
- \`(
350
- echo ## Summary
351
- echo ^<1-3 bullet points^>
352
- ) ^> pr-body.txt
353
- gh pr create --title "the pr title" --body-file pr-body.txt\`
354
-
355
- 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
356
-
357
- # Creating pull requests
358
-
359
- 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:
360
- \`(
361
- echo ## Summary
362
- echo - ^<1-3 bullet points^>
363
- ) ^> pr-body.txt
364
- gh pr create --title "the pr title" --body-file pr-body.txt\``,parameterDescription:tu(e)}: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:Dv(e,r,t),gitSection:`# Committing changes with git
365
-
366
- 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:
367
-
368
- Git Safety Protocol:
369
- - NEVER update the git config
370
- - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
371
- - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
372
- - NEVER run force push to main/master, warn the user if they request it
373
- - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
374
- (1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
375
- (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
376
- (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
377
- - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
378
- - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
379
- - 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.
380
-
381
- 1. Run these commands in parallel:
382
- - Run \`git status\` to see all untracked files
383
- - Run \`git diff\` to see both staged and unstaged changes
384
- - Run \`git log --oneline -10\` to see recent commit messages
385
-
386
- 2. Analyze all staged changes and draft a commit message
387
-
388
- 3. Create the commit:
389
- - Add relevant untracked files to the staging area
390
- - Create the commit with a message
391
- - Run git status after the commit completes
392
-
393
- 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
394
-
395
- # Creating pull requests
396
-
397
- 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:
398
- \`\`\`powershell
399
- gh pr create --title "the pr title" --body @'
400
- ## Summary
401
- - <1-3 bullet points>
402
- '@
403
- \`\`\``,createPrSection:`IMPORTANT: When creating a PR with gh, use a PowerShell here-string for correct body formatting:
404
- \`gh pr create --title "the pr title" --body @'
405
- ## Summary
406
- - <1-3 bullet points>
407
- '@`,parameterDescription:tu(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:Lv(r,t),gitSection:`# Committing changes with git
408
-
409
- 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:
410
-
411
- Git Safety Protocol:
412
- - NEVER update the git config
413
- - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
414
- - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
415
- - NEVER run force push to main/master, warn the user if they request it
416
- - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
417
- (1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
418
- (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
419
- (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
420
- - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
421
- - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
422
- - 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.
423
-
424
- 1. Run these commands in parallel:
425
- - Run \`git status\` to see all untracked files
426
- - Run \`git diff\` to see both staged and unstaged changes
427
- - Run \`git log --oneline -10\` to see recent commit messages
428
-
429
- 2. Analyze all staged changes and draft a commit message
430
-
431
- 3. Create the commit:
432
- - Add relevant untracked files to the staging area
433
- - Create the commit with a message
434
- - Run git status after the commit completes
435
-
436
- 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
437
-
438
- # Creating pull requests
439
-
440
- 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:
441
- \`\`\`bash
442
- gh pr create --title "the pr title" --body "$(cat <<'EOF'
443
- ## Summary
444
- <1-3 bullet points>
445
- EOF
446
- )"
447
- \`\`\``,createPrSection:`IMPORTANT: When creating a PR with gh, use a HEREDOC to pass the body:
448
- \`gh pr create --title "the pr title" --body "$(cat <<'EOF'
449
- ## Summary
450
- <1-3 bullet points>
451
- EOF
452
- )"\``,parameterDescription:tu(e)}}function hf(e){let t={maxLines:Ve.MAX_LINES,maxBytes:Ve.MAX_BYTES},o=Shell.name(e),n=Fv(o,t);return {description:`${n.intro}
453
-
454
- ${n.workdirSection}
455
-
456
- ${n.commandSection}
457
-
458
- ${n.gitSection}
459
-
460
- ${n.createPrSection}`,parameterDescription:n.parameterDescription}}var Ac=3e4,qv=a$2.EASBOT_BASH_DEFAULT_TIMEOUT_MS||120*1e3,Rc=a.create({service:"tool.bash"});function Hv(e){let t=[];function o(n){if(n){if(n.type==="Command"){let s=n.name?.text||"",r=[],i=n.text||"";if(n.suffix)for(let c of n.suffix)c.text&&r.push(c.text);s&&t.push({command:s,args:r,fullText:i});}if(n.commands)for(let s of n.commands)o(s);n.left&&o(n.left),n.right&&o(n.right),n.then&&o(n.then),n.else&&o(n.else);}}return o(e),t}var bf=De.define("bash",async()=>{let e=Shell.acceptable()??"/bin/bash";Rc.debug("bash tool using shell",{shell:e});let{description:t,parameterDescription:o}=hf(e);return {description:t.replaceAll("{{directory}}",R.directory).replaceAll("{{maxLines}}",String(Ve.MAX_LINES)).replaceAll("{{maxBytes}}",String(Ve.MAX_BYTES)),parameters:U.object({command:U.string().describe("The command to execute"),timeout:U.number().describe("Optional timeout in milliseconds").optional(),workdir:U.string().describe(`The working directory to run the command in. Defaults to ${R.directory}. Use this instead of 'cd' commands.`).optional(),description:U.string().describe(o)}),async execute(n,s){let r=n.workdir||R.directory;if(n.timeout!==void 0&&n.timeout<0)throw new Error(`Invalid timeout value: ${n.timeout}. Timeout must be a positive number.`);let i=n.timeout??qv,c;try{c=Uv(n.command);}catch(g){Rc.warn("Failed to parse command, requesting full bash permission",{command:n.command,error:g instanceof Error?g.message:String(g)}),await s.ask({permission:"bash",patterns:[n.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 v=new Set,P=new Set,I=Hv(c);for(let{command:A,args:S,fullText:w}of I){if(["cd","rm","cp","mv","mkdir","touch","chmod","chown","cat"].includes(A))for(let y of S){if(y.startsWith("-")||A==="chmod"&&y.startsWith("+"))continue;let b=await realpath(Ce__default.resolve(r,y)).catch(()=>null);if(Rc.debug("resolved path",{arg:y,resolved:b}),b){let C=process.platform==="win32"&&b.match(/^\/[a-z]\//)?b.replace(/^\/([a-z])\//,(E,O)=>`${O.toUpperCase()}:\\`).replace(/\//g,"\\"):b;if(!R.containsPath(C)){let E=await Filesystem.isDir(C)?C:Filesystem.dirname(C);g.add(E);}}}A&&A!=="cd"&&(v.add(w),P.add(`${A} *`));}if(g.size>0){let A=Array.from(g).map(S=>Filesystem.join(S,"*"));await s.ask({permission:"external_directory",patterns:A,always:A,metadata:{}});}v.size>0&&await s.ask({permission:"bash",patterns:Array.from(v),always:Array.from(P),metadata:{}});}Rc.debug("Executing bash command",{command:n.command,cwd:r,shell:e});let d=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:r})).output?.env??{},m=Shell.spawn(e,n.command,{cwd:r,env:{...process.env,...d},stdin:"null",stdout:"pipe",stderr:"pipe",signal:s.abort}),f="";s.metadata({metadata:{output:"",description:n.description}});let a=g=>{f+=g.toString("utf-8"),s.metadata({metadata:{output:f.length>Ac?f.slice(0,Ac)+`
461
-
462
- ...`:f,description:n.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 v=[];return p&&v.push(`bash tool terminated command after exceeding timeout ${i} ms`),u&&v.push("User aborted the command"),v.length>0&&(f+=`
463
-
464
- <bash_metadata>
465
- `+v.join(`
466
- `)+`
467
- </bash_metadata>`),{title:n.description,metadata:{output:f.length>Ac?f.slice(0,Ac)+`
468
-
469
- ...`:f,exit:g,description:n.description},output:f}}catch(g){throw clearTimeout(h),g}}}});var _c;(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/**"],o=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 [...o,...d])if(m.match(i))return true;return false}r.match=s;})(_c||(_c={}));createRequire(import.meta.url);var If=1e4,zo;(f=>{let e=a.create({service:"file.watcher"});f.Event={Updated:a$5.define("file.watcher.updated",U.object({file:U.string(),event:U.union([U.literal("add"),U.literal("change"),U.literal("unlink")])}))};function o(){let a=process.platform==="linux"?`-${EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${a}`}async function n(a){try{let p=process.env.EASBOT_CACHE_PATH||Ce__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||Ce__default.join(".easbot","cache");return await Shell.install(a,p,u)}let r=lazyAsync(async()=>{try{let a=o(),p=await n(a),u;if(p){let P=process.env.EASBOT_CACHE_PATH||Ce__default.join(".easbot","cache");u=Ce__default.join(P,"node_modules",a);}else {let P="latest";e.info("Parcel watcher binding not found, attempting to install",{binding:a}),u=await s(a,P);}e.info("Loading Parcel watcher binding",{binding:a,modulePath:u});let{createWrapper:h}=await import('@parcel/watcher/wrapper.js'),v=createRequire(Ce__default.join(u,"package.json"))(a);return h(v)}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=(S,w)=>{R.provide({directory:h,init:void 0,fn:()=>ue.publish(f.Event.Updated,{file:S,event:w})});},v=(S,w)=>{if(!S)for(let y of w){let b=y;b.type==="create"&&g(b.path,"add"),b.type==="update"&&g(b.path,"change"),b.type==="delete"&&g(b.path,"unlink");}},P=[],I=a.watcher?.ignore??[];if(a$2.EASBOT_FILEWATCHER){let S=u.subscribe(R.directory,v,{ignore:[..._c.PATTERNS,...I],backend:p}),w=await withTimeout(S,If).catch(y=>{e.error("failed to subscribe to Instance.directory",{error:y}),S.then(b=>b.unsubscribe()).catch(()=>{});});w&&P.push(w);}let A=await $`git rev-parse --git-dir`.quiet().nothrow().cwd(R.worktree).text().then(S=>Filesystem.resolve(Filesystem.join(R.worktree,S.trim()))).catch(()=>{});if(A&&!I.includes(".git")&&!I.includes(A)){let w=(await readdir(A).catch(()=>[])).filter(C=>C!=="HEAD"),y=u.subscribe(A,v,{ignore:w,backend:p}),b=await withTimeout(y,If).catch(C=>{e.error("failed to subscribe to vcsDir",{error:C}),y.then(E=>E.unsubscribe()).catch(()=>{});});b&&P.push(b);}return {subs:P}}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;})(zo||(zo={}));var _o;(l=>{let e=a.create({service:"file.time"}),t;function o(){return t||(t=R.state(()=>({read:{},locks:new Map}))),t}function n(){return o()()}l.state=n;function s(d,m){e.info("read",{sessionId:d,file:m});let{read:f}=n();f[d]=f[d]||{},f[d][m]=new Date;}l.read=s;function r(d,m){return n().read[d]?.[m]}l.get=r;async function i(d,m){let f=n(),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.
470
- Last modification: ${a.mtime.toISOString()}
471
- Last read: ${f.toISOString()}
472
-
473
- Please read the file again before modifying it.`)}l.assert=c;})(_o||(_o={}));async function Zt(e,t,o){if(!t||o?.bypass)return;let n=Filesystem.normalize(Ce__default.isAbsolute(t)?t:Ce__default.resolve(R.directory,t)),s=await Qv(n),r=s??n;if(R.containsPath(r))return;let c=(o?.kind??"file")==="directory"?n:Ce__default.posix.dirname(n),l=Ce__default.posix.join(c,"*");await e.ask({permission:"external_directory",patterns:[l],always:[l],metadata:{filepath:n,realPath:s??void 0,parentDir:c,tool:o?.tool??"read"}});}async function Qv(e){try{let t=await Tt.realpath(e);return Filesystem.normalize(t)}catch{return}}var Mr=class e extends Error{constructor(o,n,s){let r=n||`Operation '${o}' was aborted`;super(r);b$1(this,"name","AbortError");b$1(this,"operation");b$1(this,"cause");this.operation=o,this.cause=s,Object.setPrototypeOf(this,e.prototype);}static isAbortError(o){return o instanceof e}};var At;(n=>{function e(s,r){if(s?.aborted)throw new Mr(r,`Operation '${r}' was aborted`)}n.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}}n.withTimeout=t;async function o(s,r,i){if(e(r,s),!r)return await i(void 0);let c=new Promise((l,d)=>{if(r.aborted)d(new Mr(s,`Operation '${s}' was aborted`,r.reason));else {let m=()=>{d(new Mr(s,`Operation '${s}' was aborted`,r.reason));};r.addEventListener("abort",m,{once:true});}});return await Promise.race([i(r),c])}n.wrap=o;})(At||(At={}));var tS=loadTextFile("./edit.txt",import.meta.url),oS=tS(),au=20;function Oc(e){return e.replaceAll(`\r
474
- `,`
475
- `)}var jc=De.define("edit",{description:oS,parameters:U.object({filePath:U.string().describe("The absolute path to the file to modify"),oldString:U.string().describe("The text to replace"),newString:U.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:U.boolean().optional().describe("Replace all occurrences of oldString (default false)")}),async execute(e,t){if(At.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 o=Filesystem.normalize(Ce.isAbsolute(e.filePath)?e.filePath:Filesystem.join(R.directory,e.filePath));await Zt(t,o,{tool:"edit"});let n="",s="",r="";await _o.withLock(o,async()=>{if(e.oldString===""){let m=await PKG.file(o).exists();r=e.newString,n=$n(createTwoFilesPatch(o,o,s,r)),await t.ask({permission:"edit",patterns:[Ce.posix.relative(R.worktree,o)],always:["*"],metadata:{filepath:o,diff:n}}),At.check(t.abort,"edit"),await PKG.write(o,e.newString),await ue.publish(yt.Event.Edited,{file:o}),await ue.publish(zo.Event.Updated,{file:o,event:m?"change":"add"}),_o.read(t.sessionId,o);return}let d=await Tt.stat(o).catch(()=>null);if(!d)throw new Error(`File ${o} not found`);if(d.isDirectory())throw new Error(`Path is a directory, not a file: ${o}`);await _o.assert(t.sessionId,o),s=await Tt.readFile(o,"utf-8"),r=mS(s,e.oldString,e.newString,e.replaceAll),n=$n(createTwoFilesPatch(o,o,Oc(s),Oc(r))),await t.ask({permission:"edit",patterns:[Ce.posix.relative(R.worktree,o)],always:["*"],metadata:{filepath:o,diff:n}}),At.check(t.abort,"edit"),await Tt.writeFile(o,r),await ue.publish(yt.Event.Edited,{file:o}),await ue.publish(zo.Event.Updated,{file:o,event:"change"}),r=await Tt.readFile(o,"utf-8"),n=$n(createTwoFilesPatch(o,o,Oc(s),Oc(r))),_o.read(t.sessionId,o);});let i={file:o,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:n,filediff:i,diagnostics:{}}});let c="Edit applied successfully.";At.check(t.abort,"edit");let l=[];if(await We.isAvailable(t.sessionId)){await We.touchFile(o,true);let d=await We.getFileDiagnostics(o);l.push(...d);let m=d.filter(f=>f.severity===1);if(m.length>0){let f=m.slice(0,au),a=m.length>au?`
476
- ... and ${m.length-au} more`:"",p=f.map(u=>We.Diagnostic.pretty(u));c+=`
477
-
478
- LSP errors detected in this file, please fix:
479
- <diagnostics file="${o}">
480
- ${p.join(`
481
- `)}${a}
482
- </diagnostics>`;}}return {metadata:{filepath:o,diagnostics:{[Filesystem.normalize(o)]:l},diff:n,filediff:i},title:`${Ce.posix.relative(R.worktree,o)}`,output:c}}}),Pf=0,nS=.3;function Tf(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let o=Array.from({length:e.length+1},(n,s)=>Array.from({length:t.length+1},(r,i)=>s===0?i:i===0?s:0));for(let n=1;n<=e.length;n++)for(let s=1;s<=t.length;s++){let r=e[n-1]===t[s-1]?0:1,i=o[n],c=o[n-1];i[s]=Math.min((c[s]??0)+1,(i[s-1]??0)+1,(c[s-1]??0)+r);}return o[e.length]?.[t.length]??0}var sS=function*(e,t){yield t;},rS=function*(e,t){let o=e.split(`
483
- `),n=t.split(`
484
- `);n[n.length-1]===""&&n.pop();for(let s=0;s<=o.length-n.length;s++){let r=true;for(let i=0;i<n.length;i++){let c=o[s+i],l=n[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=o[l];d!==void 0&&(i+=d.length+1);}let c=i;for(let l=0;l<n.length;l++){let d=o[s+l];d!==void 0&&(c+=d.length,l<n.length-1&&(c+=1));}yield e.substring(i,c);}}},iS=function*(e,t){let o=e.split(`
485
- `),n=t.split(`
486
- `);if(n.length<3)return;n[n.length-1]===""&&n.pop();let s=n[0]?.trim()??"",r=n[n.length-1]?.trim()??"",i=n.length,c=[];for(let m=0;m<o.length;m++){let f=o[m];if(f!==void 0&&f.trim()===s)for(let a=m+2;a<o.length;a++){let p=o[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=o[m+h],v=n[h];if(!g||!v)continue;let P=g.trim(),I=v.trim(),A=Math.max(P.length,I.length);if(A===0)continue;let S=Tf(P,I);if(p+=(1-S/A)/u,p>=Pf)break}else p=1;if(p>=Pf){let h=0;for(let v=0;v<m;v++){let P=o[v];P!==void 0&&(h+=P.length+1);}let g=h;for(let v=m;v<=f;v++){let P=o[v];P!==void 0&&(g+=P.length,v<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 v=o[f+g],P=n[g];if(!v||!P)continue;let I=v.trim(),A=P.trim(),S=Math.max(I.length,A.length);if(S===0)continue;let w=Tf(I,A);u+=1-w/S;}u/=h;}else u=1;u>d&&(d=u,l=m);}if(d>=nS&&l){let{startLine:m,endLine:f}=l,a=0;for(let u=0;u<m;u++){let h=o[u];h&&(a+=h.length+1);}let p=a;for(let u=m;u<=f;u++){let h=o[u];h&&(p+=h.length,u<f&&(p+=1));}yield e.substring(a,p);}},aS=function*(e,t){let o=i=>i.replace(/\s+/g," ").trim(),n=o(t),s=e.split(`
487
- `);for(let i=0;i<s.length;i++){let c=s[i];if(o(c)===n)yield c;else if(o(c).includes(n)){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(`
488
- `);if(r.length>1)for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length);o(c.join(`
489
- `))===n&&(yield c.join(`
490
- `));}},cS=function*(e,t){let o=i=>{let c=i.split(`
491
- `),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(`
492
- `)},n=o(t),s=e.split(`
493
- `),r=t.split(`
494
- `);for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length).join(`
495
- `);o(c)===n&&(yield c);}},dS=function*(e,t){let o=i=>i.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(c,l)=>{switch(l){case "n":return `
496
- `;case "t":return " ";case "r":return "\r";case "'":return "'";case '"':return '"';case "`":return "`";case "\\":return "\\";case `
497
- `:return `
498
- `;case "$":return "$";default:return c}}),n=o(t);e.includes(n)&&(yield n);let s=e.split(`
499
- `),r=n.split(`
500
- `);for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length).join(`
501
- `);o(c)===n&&(yield c);}},lS=function*(e,t){let o=0;for(;;){let n=e.indexOf(t,o);if(n===-1)break;yield t,o=n+t.length;}},uS=function*(e,t){let o=t.trim();if(o===t)return;e.includes(o)&&(yield o);let n=e.split(`
502
- `),s=t.split(`
503
- `);for(let r=0;r<=n.length-s.length;r++){let i=n.slice(r,r+s.length).join(`
504
- `);i.trim()===o&&(yield i);}},pS=function*(e,t){let o=t.split(`
505
- `);if(o.length<3)return;o[o.length-1]===""&&o.pop();let n=e.split(`
506
- `),s=o[0]?.trim(),r=o[o.length-1]?.trim();if(!(!s||!r))for(let i=0;i<n.length;i++){let c=n[i];if(!(!c||c.trim()!==s))for(let l=i+2;l<n.length;l++){let d=n[l];if(!d||d.trim()!==r)continue;let m=n.slice(i,l+1),f=m.join(`
507
- `);if(m.length===o.length){let a=0,p=0;for(let u=1;u<m.length-1;u++){let h=m[u],g=o[u];if(!h||!g)continue;let v=h.trim(),P=g.trim();(v.length>0||P.length>0)&&(p++,v===P&&a++);}if(p===0||a/p>=.5){yield f;break}}break}}};function $n(e){let t=e.split(`
508
- `),o=t.filter(r=>(r.startsWith("+")||r.startsWith("-")||r.startsWith(" "))&&!r.startsWith("---")&&!r.startsWith("+++"));if(o.length===0)return e;let n=1/0;for(let r of o){let i=r.slice(1);if(i.trim().length>0){let c=i.match(/^(\s*)/);c?.[1]&&(n=Math.min(n,c[1].length));}}return n===1/0||n===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(n)}return r}).join(`
509
- `)}function mS(e,t,o,n=false){if(t===o)throw new Error("No changes to apply: oldString and newString are identical.");let s=true;for(let r of [sS,rS,iS,aS,cS,dS,uS,pS,lS])for(let i of r(e,t)){let c=e.indexOf(i);if(c===-1)continue;if(s=false,n)return e.replaceAll(i,o);let l=e.lastIndexOf(i);if(c===l)return e.substring(0,c)+o+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 hS=loadTextFile("./glob.txt",import.meta.url),yS=hS(),Af=De.define("glob",{description:yS,parameters:U.object({pattern:U.string().describe("The glob pattern to match files against"),path:U.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:U.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 o=e.path??R.directory;o=Filesystem.normalize(Ce__default.isAbsolute(o)?o:Ce__default.resolve(R.directory,o)),await Zt(t,o,{kind:"directory",tool:"glob"});let n=e.limit??100,s=[],r=false;for await(let c of a$8.files({cwd:o,glob:[e.pattern],signal:t.abort})){if(s.length>=n){r=true;break}let l=Filesystem.join(o,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(`[${n} results limit reached. Use limit=${n*2} for more, or refine pattern]`))),{title:Ce__default.posix.relative(R.worktree,o),metadata:{pattern:e.pattern,path:o,count:s.length,truncated:r,resultLimitReached:r?n:void 0},output:i.join(`
510
- `)}}});var IS=loadTextFile("./grep.txt",import.meta.url),vS=IS(),Mf=2e3,jf=De.define("grep",{description:vS,parameters:U.object({pattern:U.string().describe("The regex pattern to search for in file contents"),path:U.string().optional().describe("The directory to search in. Defaults to the current working directory."),include:U.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 o=e.path??R.directory;o=Filesystem.normalize(Ce__default.isAbsolute(o)?o:Ce__default.resolve(R.directory,o)),await Zt(t,o,{kind:"directory",tool:"grep"});let n=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(o);let i=PKG.spawn([n,...r],{stdin:"null",stdout:"pipe",stderr:"pipe"}),c=createInterface({input:i.stdout}),l="",d=0,m=false,f=[];i.stderr?.on("data",v=>{l+=v.toString("utf-8");}),c.on("line",v=>{if(!v.trim()||d>=s)return;let P;try{P=JSON.parse(v);}catch{return}if(P.type==="match"){let I=Filesystem.toUnixPath(P.data?.path?.text),A=P.data?.line_number,S=P.data?.lines?.text;I&&typeof A=="number"&&S&&Tt.stat(I).then(w=>{d++,f.push({path:I,lineNum:A,lineText:S.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 v=l.trim()||`ripgrep exited with code ${a}`;throw new Error(v)}return {title:e.pattern,metadata:{matches:0,truncated:false},output:"No files found"}}f.sort((v,P)=>P.modTime-v.modTime);let p=m,u=[`Found ${f.length} matches`],h="";for(let v of f){h!==v.path&&(h!==""&&u.push(""),h=v.path,u.push(`${v.path}:`));let P=v.lineText.length>Mf?v.lineText.substring(0,Mf)+"...":v.lineText;u.push(` Line ${v.lineNum}: ${P}`);}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:o,matches:f.length,truncated:p},output:u.join(`
511
- `)}}});var CS=loadTextFile("./batch.txt",import.meta.url),kS=CS(),du=new Set(["batch"]),PS=new Set(["invalid","patch",...du]),Lf=De.define("batch",async()=>{let e=await he.get();return {isEnabled:async()=>e.experimental?.batch_tool===true,description:kS,parameters:U.object({tool_calls:U.array(U.object({tool:U.string().describe("The name of the tool to execute"),parameters:U.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':
512
- ${t.issues.map(n=>` - ${n.path.length>0?n.path.join("."):"root"}: ${n.message}`).join(`
513
- `)}
514
-
515
- Expected payload format:
516
- [{"tool": "tool_name", "parameters": {...}}, {...}]`},async execute(t,o){let{Session:n}=await import('./session-TXC5Z4O2.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-NITFPORZ.mjs'),l=await c.tools({modelId:"",providerId:""}),d=new Map(l.map(g=>[g.id,g])),m=async g=>{let v=Date.now(),P=s.ascending("part");try{if(du.has(g.tool))throw new Error(`Tool '${g.tool}' is not allowed in batch. Disallowed tools: ${Array.from(du).join(", ")}`);let I=d.get(g.tool);if(!I){let y=Array.from(d.keys()).filter(b=>!PS.has(b));throw new Error(`Tool '${g.tool}' not in registry. External tools (MCP, environment) cannot be batched - call them directly. Available tools: ${y.join(", ")}`)}let A=I.parameters.parse(g.parameters);await n.updatePart({id:P,messageId:o.messageId,sessionId:o.sessionId,type:"tool",tool:g.tool,callId:P,state:{status:"running",input:g.parameters,time:{start:v}}});let S=await I.execute(A,{...o,callId:P}),w;return S.attachments&&S.attachments.length>0&&(w=S.attachments.map(y=>({...y,id:y.id??s.ascending("part"),sessionId:y.sessionId??o.sessionId,messageId:y.messageId??o.messageId}))),await n.updatePart({id:P,messageId:o.messageId,sessionId:o.sessionId,type:"tool",tool:g.tool,callId:P,state:{status:"completed",input:g.parameters,output:S.output,title:S.title,metadata:S.metadata,attachments:w,time:{start:v,end:Date.now()}}}),{success:!0,tool:g.tool,result:S}}catch(I){return await n.updatePart({id:P,messageId:o.messageId,sessionId:o.sessionId,type:"tool",tool:g.tool,callId:P,state:{status:"error",input:g.parameters,error:I instanceof Error?I.message:String(I),time:{start:v,end:Date.now()}}}),{success:false,tool:g.tool,error:I}}},f=await Promise.all(r.map(g=>m(g))),a=Date.now();for(let g of i){let v=s.ascending("part");await n.updatePart({id:v,messageId:o.messageId,sessionId:o.sessionId,type:"tool",tool:g.tool,callId:v,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.
517
-
518
- 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 AS=a.create({service:"instruction"}),Df=["AGENTS.md"];function RS(){let e=[];return a$2.EASBOT_CONFIG_DIR&&e.push(Ce__default.join(a$2.EASBOT_CONFIG_DIR,"AGENTS.md")),e.push(Ce__default.join(a$1.Path.config,"AGENTS.md")),e}async function _S(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(()=>[]):(AS.warn(`Skipping relative instruction "${e}" - no EASBOT_CONFIG_DIR set while project config is disabled`),[]):Filesystem.globUp(e,R.directory,R.worktree).catch(()=>[])}var Ds;(f=>{let e;function t(){return e||(e=R.state(async()=>({claims:new Map}))),e}function o(){return t()()}async function n(a,p){let h=(await o()).claims.get(a);return h?h.has(p):false}async function s(a,p){let u=await o(),h=u.claims.get(a);h||(h=new Set,u.claims.set(a,h)),h.add(p);}async function r(a){(await o()).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 Df){let h=await Filesystem.findUp(u,R.directory,R.worktree);if(h.length>0){h.forEach(g=>{p.add(Ce__default.resolve(g));});break}}for(let u of RS())try{await Tt__default.access(u),p.add(Ce__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=Ce__default.join(nc.homedir(),u.slice(2))),(Ce__default.isAbsolute(u)?await glob(Ce__default.basename(u),{cwd:Ce__default.dirname(u),absolute:true,nodir:true,follow:false,dot:false}):await _S(u)).forEach(g=>{p.add(Ce__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 v=>{let P=await Tt__default.readFile(v,"utf-8").catch(()=>"");return {path:v,content:P}}),h=[];if(a.instructions)for(let v of a.instructions)(v.startsWith("https://")||v.startsWith("http://"))&&h.push(v);let g=h.map(v=>fetch(v,{signal:AbortSignal.timeout(5e3)}).then(P=>P.ok?P.text():"").catch(()=>"").then(P=>P?"Instructions from: "+v+`
519
- `+P:""));return Promise.all([...u,...g]).then(v=>v.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 v of g)typeof v=="string"&&p.add(v);}return p}f.loaded=l;async function d(a){for(let p of Df){let u=Ce__default.resolve(Ce__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),v=[],P=Ce__default.resolve(p),I=Ce__default.dirname(P),A=Ce__default.resolve(R.directory);for(;I.startsWith(A)&&I!==A;){let S=await d(I);if(S&&S!==P&&!h.has(S)&&!g.has(S)&&!n(u,S)){await s(u,S);let w=await Tt__default.readFile(S,"utf-8").catch(()=>{});w&&v.push({filepath:S,content:"Instructions from: "+S+`
520
- `+w});}I=Ce__default.dirname(I);}return v}f.resolve=m;})(Ds||(Ds={}));var LS=loadTextFile("./read.txt",import.meta.url),DS=LS(),$f=2e3,uu=2e3,$S=`... (line truncated to ${uu} chars)`,Ff=50*1024,FS=`${Ff/1024} KB`,Nc=De.define("read",{description:DS,parameters:U.object({filePath:U.string().describe("The absolute path to the file or directory to read"),offset:U.coerce.number().describe("The line number to start reading from (1-indexed)").optional(),limit:U.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 o=Filesystem.normalize(Ce.isAbsolute(e.filePath)?e.filePath:Ce.resolve(R.directory,e.filePath)),n=Ce.posix.relative(R.worktree,o),s=Filesystem.stat(o);if(await Zt(t,o,{bypass:!!t.extra?.bypassCwdCheck,kind:s?.isDirectory()?"directory":"file",tool:"read"}),await t.ask({permission:"read",patterns:[Ce.posix.relative(R.worktree,o)],always:["*"],metadata:{}}),!s){let O=Filesystem.dirname(o),D=Filesystem.basename(o),$=await Tt.readdir(O).then(K=>K.filter(ee=>ee.toLowerCase().includes(D.toLowerCase())||D.toLowerCase().includes(ee.toLowerCase())).map(ee=>Filesystem.join(O,ee)).slice(0,3)).catch(()=>[]);throw $.length>0?new Error(`File not found: ${o}
521
-
522
- Did you mean one of these?
523
- ${$.join(`
524
- `)}`):new Error(`File not found: ${o}`)}if(s.isDirectory()){let O=await Tt.readdir(o,{withFileTypes:true}),D=await Promise.all(O.map(async j=>j.isDirectory()||j.isSymbolicLink()&&(await Tt.stat(Filesystem.join(o,j.name)).catch(()=>{}))?.isDirectory()?j.name+"/":j.name));D.sort((j,x)=>j.localeCompare(x));let $=e.limit??$f,K=e.offset??1,ee=K-1,N=D.slice(ee,ee+$),M=ee+N.length<D.length,T=[`<path>${o}</path>`,"<type>directory</type>","<entries>",N.join(`
525
- `),M?`
526
- (Showing ${N.length} of ${D.length} entries. Use 'offset' parameter to read beyond entry ${K+N.length})`:`
527
- (${D.length} entries)`,"</entries>"].join(`
528
- `);return {title:n,output:T,metadata:{preview:N.slice(0,20).join(`
529
- `),truncated:M,loaded:[]}}}let r=await Ds.resolve(t.messages,o,t.messageId),i=Filesystem.mimeType(o),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:n,output:O,metadata:{preview:O,truncated:false,loaded:r.map(D=>D.filepath)},attachments:[{type:"file",mime:i??"application/octet-stream",url:`data:${i??"application/octet-stream"};base64,${Buffer.from(await Filesystem.readBytes(o)).toString("base64")}`}]}}if(await NS(o,Number(s.size)))throw new Error(`Cannot read binary file: ${o}`);let m=createReadStream(o,{encoding:"utf8"}),f=createInterface({input:m,crlfDelay:1/0}),a=e.limit??$f,p=e.offset??1,u=p-1,h=[],g=0,v=0,P=false,I=false;try{for await(let O of f){if(v+=1,v<=u)continue;if(h.length>=a){I=!0;continue}let D=O.length>uu?O.substring(0,uu)+$S:O,$=Buffer.byteLength(D,"utf-8")+(h.length>0?1:0);if(g+$>Ff){P=!0,I=!0;break}h.push(D),g+=$;}}finally{f.close(),m.destroy();}if(v<p&&!(v===0&&p===1))throw new Error(`Offset ${p} is out of range for this file (${v} lines)`);let A=h.map((O,D)=>`${D+p}: ${O}`),S=h.slice(0,20).join(`
530
- `),w=[`<path>${o}</path>`,"<type>file</type>","<content>"].join(`
531
- `);w+=A.join(`
532
- `);let y=v,b=p+h.length-1,C=b+1,E=I||P;return P?w+=`
533
-
534
- (Output capped at ${FS}. Showing lines ${p}-${b}. Use offset=${C} to continue.)`:I?w+=`
535
-
536
- (Showing lines ${p}-${b} of ${y}. Use offset=${C} to continue.)`:w+=`
537
-
538
- (End of file - total ${y} lines)`,w+=`
539
- </content>`,await We.isAvailable(t.sessionId)&&await We.touchFile(o,false),_o.read(t.sessionId,o),r.length>0&&(w+=`
540
-
541
- <system-reminder>
542
- ${r.map(O=>O.content).join(`
543
-
544
- `)}
545
- </system-reminder>`),{title:n,output:w,metadata:{filepath:o,preview:S,truncated:E,loaded:r.map(O=>O.filepath)}}}});async function NS(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 n=await Tt.open(e,"r");try{let s=Math.min(4096,t),r=Buffer.alloc(s),i=await n.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 n.close();}}a.create({service:"tool.task"});var qS=loadTextFile("./task.txt",import.meta.url),HS=qS(),Bi={create:U.object({operation:U.literal("create").describe("Create a new async subtask"),description:U.string().describe("Task description, brief summary of task goal"),prompt:U.string().describe("Task prompt, detailed description of work to execute"),subagent_type:U.string().describe("Agent type, specifies the Agent role for executing the task")}),query:U.object({operation:U.literal("query").describe("Query task status or list"),taskId:U.string().optional().describe("Task ID, omit to list all tasks")}),continue:U.object({operation:U.literal("continue").describe("Continue executing a task"),taskId:U.string().describe("Task ID, the task to continue executing")}),delete:U.object({operation:U.literal("delete").describe("Delete task record"),taskId:U.string().describe("Task ID, the task to delete")}),agents:U.object({operation:U.literal("agents").describe("Get list of available Agent types")})},BS=U.discriminatedUnion("operation",[Bi.create,Bi.query,Bi.continue,Bi.delete,Bi.agents]),Gi=De.define("task",{description:HS,parameters:BS,formatValidationError(e){return `Task tool validation error: ${e.issues.map(o=>o.message).join("; ")}`},async execute(e,t){if(e.operation==="create")return GS(e,t);if(e.operation==="query")return WS(e,t);if(e.operation==="continue")return VS(e,t);if(e.operation==="delete")return KS(e);if(e.operation==="agents")return YS();throw new Error(`Unknown operation: ${e.operation}`)}});async function GS(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 n=await Lt.getRunningCount(t.sessionId);if(n>=Lt.MAX_CONCURRENT_TASKS)throw new Error(`Too many concurrent tasks: ${n} running, max is ${Lt.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 Ne.get(e.subagent_type);return As.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}
546
-
547
- Task started, results will be injected when complete`,title:e.description,metadata:{operation:"create",taskId:s}}}async function WS(e,t){if(e.taskId){let s=await Lt.get(e.taskId);if(!s)return {output:`<task>
548
- Task not found: ${e.taskId}
549
- </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(`
550
- `),title:`Task: ${s.description}`,metadata:{operation:"query",found:true,taskId:e.taskId,status:s.status}}}let o=await Lt.list(t.sessionId);if(o.length===0)return {output:`<tasks>
551
- No tasks found
552
- </tasks>`,title:"Task Query",metadata:{operation:"query",total:0}};let n=[`<tasks total="${o.length}">`];for(let s of o)n.push(`[task_id="${s.taskId}"]`),n.push(` status: ${s.status}`),s.description&&n.push(` description: ${s.description}`),s.agentType&&n.push(` agent: ${s.agentType}`),n.push("");return n.push("</tasks>"),{output:n.join(`
553
- `),title:`Tasks: ${o.length}`,metadata:{operation:"query",total:o.length}}}async function VS(e,t){let o=await Lt.get(e.taskId);if(!o)return {output:`<task>
554
- Task not found: ${e.taskId}
555
- </task>`,title:"Task Continue",metadata:{operation:"continue",found:false,taskId:e.taskId}};if(o.status==="completed"||o.status==="running")return {output:`<task>
556
- Task ${e.taskId} is already ${o.status}. Cannot restart.
557
- </task>`,title:"Task Continue",metadata:{operation:"continue",taskId:e.taskId,status:o.status}};await Lt.update(e.taskId,{status:"running"});let n=Date.now();t.metadata({title:o.description,metadata:{taskId:e.taskId}});let s=[{type:"text",text:o.prompt}],r=await Ne.get(o.agentType);return As.runAsync({source:t.sessionId,title:o.description,agent:"task_general",system:r?.prompt??"",parts:s,config:{runMode:"ephemeral",transport:"stdio"}},async i=>{let c=Date.now()-n;await Lt.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:o.agentType});}),{output:`taskId: ${e.taskId}
558
-
559
- Task continued, results will be injected when complete`,title:o.description,metadata:{operation:"continue",taskId:e.taskId}}}async function KS(e,t){return await Lt.get(e.taskId)?(await Lt.remove(e.taskId),{output:`<task>
560
- Task ${e.taskId} deleted successfully.
561
- </task>`,title:"Task Delete",metadata:{operation:"delete",found:true,taskId:e.taskId}}):{output:`<task>
562
- Task not found: ${e.taskId}
563
- </task>`,title:"Task Delete",metadata:{operation:"delete",found:false,taskId:e.taskId}}}async function JS(){return (await Ne.list()).filter(t=>t.hidden!==true).map(t=>({name:t.name,description:t.description}))}async function YS(){let e=await JS(),t=[`<agents total="${e.length}">`];for(let o of e)t.push(`- ${o.name}: ${o.description??"No description"}`);return t.push("</agents>"),{output:t.join(`
564
- `),title:`Agents: ${e.length}`,metadata:{operation:"agents",total:e.length}}}var un;(s=>{s.Info=U.object({content:U.string().describe("Brief description of the task"),status:U.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),priority:U.string().describe("Priority level of the task: high, medium, low"),id:U.string().describe("Unique identifier for the todo item")}).meta({ref:"Todo"}),s.Event={Updated:a$5.define("todo.updated",U.object({sessionId:U.string(),todos:U.array(s.Info)}))};async function o(r){await a$6.write(["todo",r.sessionId],r.todos),await ue.publish(s.Event.Updated,r);}s.update=o;async function n(r){return a$6.read(["todo",r]).then(i=>i||[]).catch(()=>[])}s.get=n;})(un||(un={}));var QS=loadTextFile("./todo.txt",import.meta.url),ZS=QS(),Nf={write:U.object({operation:U.literal("write").describe("Write or update TODO list"),todos:U.union([U.array(un.Info),U.string()]).describe("The updated todo list")}),read:U.object({operation:U.literal("read").describe("Read current TODO list")})},eC=U.discriminatedUnion("operation",[Nf.write,Nf.read]),Uf=De.define("todo",{description:ZS,parameters:eC,formatValidationError(e){return `Todo tool validation error: ${e.issues.map(o=>o.message).join("; ")}`},async execute(e,t){if(At.check(t.abort,"todo"),e.operation==="write")return tC(e,t);if(e.operation==="read")return oC(e,t);throw new Error(`Unknown operation: ${e.operation}`)}});async function tC(e,t){await t.ask({permission:"todo",patterns:["*"],always:["*"],metadata:{}});let o=[];if(typeof e.todos=="string")try{o=JSON.parse(e.todos);}catch{throw new Error("Invalid todos format: expected JSON array or array")}else o=e.todos;await un.update({sessionId:t.sessionId,todos:o});let n=o.filter(s=>s.status!=="completed").length;return {title:`${n} todos`,output:JSON.stringify(o,null,2),metadata:{operation:"write",total:o.length,active:n,todos:o}}}async function oC(e,t){await t.ask({permission:"todo",patterns:["*"],always:["*"],metadata:{}});let o=await un.get(t.sessionId),n=o.filter(s=>s.status!=="completed").length;return {title:`${n} todos`,metadata:{operation:"read",total:o.length,active:n,todos:o},output:JSON.stringify(o,null,2)}}var aC=loadTextFile("./webfetch.txt",import.meta.url),cC=aC(),qf=5*1024*1024,Hf=2*1024*1024,dC=30*1e3,lC=120*1e3,Bf=De.define("webfetch",{description:cC,parameters:U.object({url:U.string().describe("The URL to fetch content from"),format:U.enum(["text","markdown","html"]).default("markdown").describe("The format to return the content in (text, markdown, or html). Defaults to markdown."),timeout:U.number().describe("Optional timeout in seconds (max 120)").optional()}),formatValidationError(e){return `WebFetch tool validation error:
565
- ${e.issues.map(o=>o.path.includes("format")?`Invalid format parameter: "${"received"in o?o.received:"unknown"}". Must be one of: "text", "markdown", or "html". Defaults to "markdown" if not specified.`:o.path.includes("url")?`Invalid URL: ${o.message}. URL must start with http:// or https://.`:o.path.includes("timeout")?`Invalid timeout: ${o.message}. Timeout must be a number (max 120 seconds).`:o.message).join(`
566
- `)}`},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 o=Math.min((e.timeout??dC/1e3)*1e3,lC),{signal:n,clearTimeout:s}=abortAfterAny(o,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 v=await Fetch.get(e.url,{signal:n,headers:i,responseType:"arrayBuffer"});c={ok:v.ok,status:v.status,statusText:v.statusText,headers:v.headers,arrayBuffer:async()=>Promise.resolve(v.data)};}catch(v){if(s(),v instanceof Error){if(v.name==="AbortError")throw new Error(`Request timed out after ${o/1e3} seconds. Try increasing the timeout parameter.`);if(v.message.includes("fetch failed"))throw new Error(`Failed to fetch URL: ${e.url}. The server may be unreachable or blocking requests. Original error: ${v.message}`)}throw v}let l=c.status===403&&c.headers.get("cf-mitigated")==="challenge"?await(async()=>{let v=await Fetch.get(e.url,{signal:n,headers:{...i,"User-Agent":"easbot"},responseType:"arrayBuffer"});return {ok:v.ok,status:v.status,statusText:v.statusText,headers:v.headers,arrayBuffer:async()=>Promise.resolve(v.data)}})():c;if(s(),!l.ok){let v=l.statusText||"Unknown error";throw new Error(`Request failed with status ${l.status} (${v}). The server may be blocking requests or the URL may be incorrect.`)}let d=l.headers.get("content-length");if(d&&parseInt(d,10)>qf)throw new Error("Response too large (exceeds 5MB limit)");let m=await l.arrayBuffer();if(m.byteLength>qf)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>Hf)return {title:p,output:`Image fetched successfully but too large to display (${(m.byteLength/1024/1024).toFixed(2)}MB, max ${Hf/1024/1024}MB). Image URL: ${e.url}`,metadata:{size:m.byteLength,mime:a,url:e.url}};try{let v=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,${v}`}]}}catch(v){return {title:p,output:`Image fetched but failed to convert to base64: ${v instanceof Error?v.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:pC(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 uC(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 uC(e){try{let t=parse(e),o=["script","style","noscript","iframe","object","embed","svg","head"];for(let r of o){let i=t.querySelectorAll(r);for(let c of i)c.remove();}let n=t.querySelector("body"),s=n?n.textContent||n.text||"":t.textContent||t.text||"";return s=s.replace(/<[^>]+>/g," "),s=s.replace(/\s+/g," ").trim(),s}catch{let o=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 o=o.replace(/<[^>]+>/g," "),o=o.replace(/\s+/g," ").trim(),o}}function pC(e){let t=new rC({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}var gC=loadTextFile("./write.txt",import.meta.url),hC=gC(),fu=20;var Wf=De.define("write",{description:hC,parameters:U.object({content:U.string().describe("The content to write to the file"),filePath:U.string().describe("The absolute path to the file to write (must be absolute, not relative)")}),async execute(e,t){At.check(t.abort,"write");let o=Filesystem.normalize(Ce.isAbsolute(e.filePath)?e.filePath:Filesystem.join(R.directory,e.filePath));await Zt(t,o,{tool:"write"});let n=PKG.file(o),s=await n.exists(),r=s?await n.text():"";s&&await _o.assert(t.sessionId,o);let i=$n(createTwoFilesPatch(o,o,r,e.content));await t.ask({permission:"edit",patterns:[Ce.posix.relative(R.worktree,o)],always:["*"],metadata:{filepath:o,diff:i}}),At.check(t.abort,"write"),await PKG.write(o,e.content),await ue.publish(yt.Event.Edited,{file:o}),await ue.publish(zo.Event.Updated,{file:o,event:s?"change":"add"}),_o.read(t.sessionId,o);let c="Wrote file successfully.";At.check(t.abort,"write");let l=[];if(await We.isAvailable(t.sessionId)){await We.touchFile(o,true);let d=await We.getFileDiagnostics(o);l.push(...d);let m=d.filter(f=>f.severity===1);if(m.length>0){let f=m.slice(0,fu),a=m.length>fu?`
567
- ... and ${m.length-fu} more`:"",p=f.map(u=>We.Diagnostic.pretty(u));c+=`
568
-
569
- LSP errors detected in this file, please fix:
570
- <diagnostics file="${o}">
571
- ${p.join(`
572
- `)}${a}
573
- </diagnostics>`;}}return {title:Ce.posix.relative(R.worktree,o),metadata:{diagnostics:{[Filesystem.normalize(o)]:l},filepath:o,exists:s},output:c}}});var Vf=De.define("invalid",{description:"Do not use",parameters:U.object({tool:U.string(),error:U.string()}),async execute(e){return {title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}}});var Yf=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(`
574
- `),t=U.object({name:U.string().describe("The name of the skill to load")});return {description:e,parameters:t,async execute(o,n){let s=await Z.getContextMode(n.sessionId),r=await Ne.get(n.agent),i=await Qt.available(r,s),c=await Qt.get(o.name);if(!c){let p=i.length>0?i.map(u=>u.name).join(", "):"none";throw new Error(`Skill "${o.name}" not found. Available skills: ${p}`)}if(!i.some(p=>p.name===o.name)){let p=i.length>0?i.map(u=>u.name).join(", "):"none";throw new Error(`Skill "${o.name}" is not available. Available skills: ${p}`)}await n.ask({permission:"skill",patterns:[o.name],always:[o.name],metadata:{}});let d=Ce__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:n.abort}))if(!u.includes("SKILL.md")&&(p.push(Ce__default.posix.join(d,u)),p.length>=f))break;return p}).then(p=>p.map(u=>`<file>${u}</file>`).join(`
575
- `));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(`
576
- `),metadata:{name:c.name,dir:d}}}}});var nt;(b=>{let e=a.create({service:"pty"}),t=1024*1024*2,o=64*1024,n=new TextEncoder,s=C=>{let E=JSON.stringify({cursor:C}),O=n.encode(E),D=new Uint8Array(O.length+1);return D[0]=0,D.set(O,1),D},r=lazy(async()=>wC);b.Info=U.object({id:Identifier.schema("pty"),title:U.string(),command:U.string(),args:U.array(U.string()),cwd:U.string(),status:U.enum(["running","exited"]),pid:U.number()}).meta({ref:"Pty"}),b.CreateInput=U.object({command:U.string().optional(),args:U.array(U.string()).optional(),cwd:U.string().optional(),title:U.string().optional(),env:U.record(U.string(),U.string()).optional(),persistent:U.boolean().optional().default(true)}),b.UpdateInput=U.object({title:U.string().optional(),size:U.object({rows:U.number(),cols:U.number()}).optional()}),b.Event={Created:a$5.define("pty.created",U.object({info:b.Info})),Updated:a$5.define("pty.updated",U.object({info:b.Info})),Exited:a$5.define("pty.exited",U.object({id:Identifier.schema("pty"),exitCode:U.number()})),Deleted:a$5.define("pty.deleted",U.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)}b.list=u;async function h(C){return a$1().get(C)?.info}b.get=h;async function g(C){let E=Identifier.create("pty",false),O=C.persistent??true,D=process.platform==="win32"?"cmd":Shell.acceptable(),$=C.command||D,K=C.args||[],ee=C.cwd||R.directory,M=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:ee})).output?.env??{},T={...process.env,...C.env,...M,TERM:"xterm-256color",EASBOT_TERMINAL:"1"};process.platform==="win32"&&(T.LANG="en_US.UTF-8",T.LC_ALL="en_US.UTF-8",T.LC_CTYPE="en_US.UTF-8");let j=$;if(process.platform==="win32"){let{PKG:ae}=await import('@easbot/utils'),le=await ae.which(j);if(le)e.debug("resolved command path",{original:j,resolved:le});else {e.warn("command not found in PATH, trying PKG.which() fallback",{command:j});let be=j?.toLowerCase(),se=null;if(be==="cmd.exe"||be==="cmd"?se="cmd":be==="powershell.exe"||be==="powershell"?se="powershell":be==="pwsh.exe"||be==="pwsh"?se="pwsh":be==="wsl.exe"||be==="wsl"?se="wsl":se=Shell.acceptable(be)??"",se){let Q=await ae.which(se);Q?(e.debug("found command via PKG.which()",{original:j,resolved:Q})):(e.warn("command not found, using original",{command:j}),j);}else e.warn("unknown command type, using original",{command:j});}}let k=$??"",_=[...K];k.endsWith("sh")&&_.push("-l"),e.debug("creating PTY session",{id:E,cmd:k,args:_,cwd:ee,platform:process.platform});let L=await r(),H;try{H=L.spawn(k,_,{name:"xterm-256color",cwd:ee,env:T}),e.debug("PTY process spawned successfully",{id:E,pid:H.pid});}catch(ae){let le=ae instanceof Error?ae.message:String(ae);e.error("Failed to spawn PTY process",{command:k,args:_,cwd:ee,platform:process.platform,error:le,stack:ae instanceof Error?ae.stack:void 0});let be="";throw le.includes("ENOENT")||le.includes("not found")?be=`
577
-
578
- \u{1F4A1} Hint: The command "${k}" was not found. Please ensure:
579
- - The command is installed and available in PATH
580
- - On Windows, use full path like "cmd.exe" or "powershell.exe"
581
- - On Unix, use full path like "/bin/bash" or "/usr/bin/ssh"`:le.includes("permission")&&(be=`
582
-
583
- \u{1F4A1} Hint: Permission denied. Please check file permissions.`),new Error(`Failed to create PTY session: ${le}${be}`)}let Y={id:E,title:C.title||`Terminal ${E.slice(-4)}`,command:$,args:_,cwd:ee,status:"running",pid:H.pid},X={info:Y,process:H,buffer:"",bufferCursor:0,cursor:0,subscribers:new Set};return a$1().set(E,X),H.onData(ae=>{X.cursor+=ae.length;for(let be of X.subscribers){if(be.readyState!==1){X.subscribers.delete(be);continue}be.send(ae);}if(X.buffer+=ae,X.buffer.length<=t)return;let le=X.buffer.length-t;X.buffer=X.buffer.slice(le),X.bufferCursor+=le;}),H.onExit(async({exitCode:ae})=>{e.debug("session exited",{id:E,exitCode:ae,persistent:O}),X.info.status="exited";for(let le of X.subscribers)le.close();X.subscribers.clear(),await ue.publish(b.Event.Exited,{id:E,exitCode:ae}),O?e.debug("persistent session, keeping for reconnection",{id:E,exitCode:ae}):(e.debug("non-persistent session, deleting",{id:E,exitCode:ae}),p.set(E,ae),a$1().delete(E));}),await ue.publish(b.Event.Created,{info:Y}),Y}b.create=g;async function v(C,E){let D=a$1().get(C);if(!D)throw new Error(`Session ${C} not found`);if(E.title&&(D.info.title=E.title),(E?.size?.cols??0)>0&&(E?.size?.rows??0)>0){if(D.info.status==="exited")throw new Error(`Session ${C} has exited (PID: ${D.info.pid}). Cannot resize. Use 'remove' to delete and create a new session.`);D.process.resize(E?.size?.cols??0,E?.size?.rows??0);}return await ue.publish(b.Event.Updated,{info:D.info}),D.info}b.update=v;async function P(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 D of O.subscribers)D.close();E.delete(C),p.delete(C),await ue.publish(b.Event.Deleted,{id:C});}b.remove=P;async function I(C,E,O){let $=a$1().get(C);if(!$)throw new Error(`Session ${C} not found`);if($.info.status==="exited")throw e.warn("cannot resize exited session",{id:C}),new Error(`Session ${C} has exited (PID: ${$.info.pid}). Use 'remove' to delete it and create a new session.`);$.process.resize(E,O);}b.resize=I;async function A(C,E){let D=a$1().get(C);if(!D)throw new Error(`Session ${C} not found`);if(D.info.status==="exited")throw e.warn("cannot write to 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.write(E);}b.write=A;async function S(C,E,O){let $=a$1().get(C);if(!$)return e.warn("cannot connect to non-existent session",{id:C}),E.close(),{onMessage:()=>{},onClose:()=>{}};e.debug("client connected to session",{id:C,status:$.info.status});let K=$.bufferCursor,ee=$.cursor,N=O===-1?ee:typeof O=="number"&&Number.isSafeInteger(O)?Math.max(0,O):0,M=(()=>{if(!$.buffer||N>=ee)return "";let T=Math.max(0,N-K);return T>=$.buffer.length?"":$.buffer.slice(T)})();if(M)try{for(let T=0;T<M.length;T+=o)E.send(M.slice(T,T+o));}catch{E.close();return}try{E.send(s(ee));}catch{E.close();return}return $.subscribers.add(E),{onMessage:T=>{$.process.write(String(T));},onClose:()=>{e.debug("client disconnected from session",{id:C}),$.subscribers.delete(E);}}}b.connect=S;async function w(C){let O=a$1().get(C);if(O)return {buffer:O.buffer,cursor:O.cursor,bufferCursor:O.bufferCursor}}b.getBuffer=w;async function y(C,E){let D=a$1().get(C);if(!D){let ee=p.get(C);if(ee!==void 0)return e.debug("subscribing to exited session",{id:C,exitCode:ee}),E.onExit&&E.onExit(ee),()=>{};throw e.warn("session not found for subscription",{id:C}),new Error(`Session ${C} not found`)}let $={readyState:1,send:ee=>{typeof ee=="string"&&E.onData&&E.onData(ee);},close:()=>{}};D.subscribers.add($);let K;return E.onExit&&(K=ue.subscribe(b.Event.Exited,ee=>{ee.properties.id===C&&E.onExit&&E.onExit(ee.properties.exitCode);})),()=>{D.subscribers.delete($),K&&K();}}b.subscribe=y;})(nt||(nt={}));var IC=loadTextFile("./pty_session.txt",import.meta.url),vC=loadTextFile("./pty_manage.txt",import.meta.url),SC=IC(),CC=vC(),Qf=a.create({service:"tool.pty"}),jr={BUFFER_SIZE_LIMIT:8*1024,MAX_LINES:200,DEFAULT_COLS:120,DEFAULT_ROWS:30},kC=U.object({action:U.enum(["list","get","resize","write","close"]).describe("Management action to perform"),sessionId:U.string().optional().describe("Session ID for get/resize/write/close actions"),cols:U.number().optional().describe("New columns for resize action"),rows:U.number().optional().describe("New rows for resize action"),data:U.string().optional().describe("Data to write to session")}),eg=De.define("pty_manage",{description:CC,parameters:kC,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 o=await nt.list(),n=o.length===0?"No active PTY sessions":`Active PTY Sessions (${o.length}):
584
- ${o.map(s=>`- ${s.id}: ${s.title} (PID: ${s.pid}, Status: ${s.status})`).join(`
585
- `)}`;return {title:"PTY Sessions",metadata:{action:"list",sessionCount:o.length,sessions:o.map(s=>({id:s.id,title:s.title,command:s.command,pid:s.pid,status:s.status}))},output:n}}case "get":{if(!e.sessionId)throw new Error("sessionId is required for get action");let o=await nt.get(e.sessionId);if(!o)return {title:"Session Not Found",metadata:{action:"get",found:false,sessionCount:0,sessions:[]},output:`No session found with ID: ${e.sessionId}`};let n=await nt.getBuffer(e.sessionId),s=n?.buffer||"";return {title:`Session ${e.sessionId}`,metadata:{action:"get",found:true,sessionCount:1,sessions:[{id:o.id,title:o.title,command:o.command,pid:o.pid,status:o.status}],session:{id:o.id,title:o.title,command:o.command,cwd:o.cwd,pid:o.pid,status:o.status},bufferSize:s.length,cursor:n?.cursor,bufferCursor:n?.bufferCursor},output:`Session Details:
586
- ID: ${o.id}
587
- Title: ${o.title}
588
- Command: ${o.command}
589
- PID: ${o.pid}
590
- Status: ${o.status}
591
- CWD: ${o.cwd}
592
-
593
- Output Buffer (${s.length} characters):
594
- ${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 nt.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 o=process.platform==="win32"?e.data.replace(/\n/g,`\r
595
- `):e.data;return await nt.write(e.sessionId,o),{title:"Data Written",metadata:{action:"write",sessionId:e.sessionId,dataLength:o.length,sessionCount:1,sessions:[]},output:`Wrote ${o.length} characters to session ${e.sessionId}`}}case "close":{if(!e.sessionId)throw new Error("sessionId is required for close action");return await nt.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}`)}}}),tg=De.define("pty_session",{description:SC,parameters:U.object({command:U.string().describe("Initial command to run in session"),args:U.array(U.string()).optional().describe("Command arguments"),cwd:U.string().optional().describe("Working directory (defaults to project directory)"),env:U.record(U.string(),U.string()).optional().describe("Environment variables"),sessionName:U.string().optional().describe("Session name for identification"),cols:U.number().min(10).max(500).optional().default(jr.DEFAULT_COLS).describe("Terminal columns (default: 120)"),rows:U.number().min(5).max(200).optional().default(jr.DEFAULT_ROWS).describe("Terminal rows (default: 30)"),truncateMode:U.enum(["head","tail"]).optional().default("tail").describe("Truncation mode: head (keep beginning) or tail (keep end, default for PTY sessions)"),persistent:U.boolean().optional().default(true).describe("Keep session running after initial command completes (default: true, for SSH/long-running connections)")}),async execute(e,t){let o=e.command,n=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??jr.DEFAULT_COLS,i=e.rows??jr.DEFAULT_ROWS;try{if(t.abort.aborted)throw new Error("Operation aborted");let c=await nt.create({command:o,args:n,cwd:s,env:e.env,title:e.sessionName||`Interactive Session: ${e.command}`,persistent:e.persistent??!0});return r&&i&&await nt.resize(c.id,r,i),Qf.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.
596
-
597
- Session ID: ${c.id}
598
- Session Name: ${e.sessionName||c.title}
599
- Command: ${c.command}
600
- PID: ${c.pid}
601
- Status: ${c.status}
602
- Output Limit: ${jr.BUFFER_SIZE_LIMIT/1024}KB / ${jr.MAX_LINES} lines
603
- Truncate Mode: ${e.truncateMode||"tail"} (${e.truncateMode==="head"?"keeps beginning of output":"keeps latest output for interactive use"})
604
-
605
- \u26A0\uFE0F IMPORTANT: This session will run in the background until explicitly closed.
606
- Use pty_manage tool to interact with this session:
607
- - Send input: pty_manage { "action": "write", "sessionId": "${c.id}", "data": "your command\\n" }
608
- - Check status: pty_manage { "action": "get", "sessionId": "${c.id}" }
609
- - Close session: pty_manage { "action": "close", "sessionId": "${c.id}" }
610
-
611
- \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 Qf.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 AC=loadTextFile("./websearch.txt",import.meta.url),RC=AC(),hu={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{SEARCH:"/mcp"},DEFAULT_NUM_RESULTS:8},og=De.define("websearch",async()=>({get description(){return RC.replace("{{year}}",new Date().getFullYear().toString())},parameters:U.object({query:U.string().describe("Websearch query"),numResults:U.number().optional().describe("Number of search results to return (default: 8)"),livecrawl:U.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:U.enum(["auto","fast","deep"]).optional().describe("Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"),contextMaxCharacters:U.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 o={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||hu.DEFAULT_NUM_RESULTS,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}},{signal:n,clearTimeout:s}=abortAfterAny(25e3,t.abort);try{let r={accept:"application/json, text/event-stream","content-type":"application/json"},i=await Fetch.post(`${hu.BASE_URL}${hu.ENDPOINTS.SEARCH}`,o,{headers:r,responseType:"text",signal:n});if(s(),!i.ok)throw new Error(`Search error (${i.status}): ${i.data||"Unknown error"}`);let l=i.data.split(`
612
- `);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 jC=loadTextFile("./codesearch.txt",import.meta.url),LC=jC(),ng={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{CONTEXT:"/mcp"}},sg=De.define("codesearch",{scope:g.Coder,description:LC,parameters:U.object({query:U.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:U.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 o={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"get_code_context_exa",arguments:{query:e.query,tokensNum:e.tokensNum||5e3}}},{signal:n,clearTimeout:s}=abortAfterAny(3e4,t.abort);try{let r={accept:"application/json, text/event-stream","content-type":"application/json"},i=await Fetch.post(`${ng.BASE_URL}${ng.ENDPOINTS.CONTEXT}`,o,{headers:r,responseType:"text",signal:n});if(s(),!i.ok)throw new Error(`Code search error (${i.status}): ${i.data||"Unknown error"}`);let l=i.data.split(`
613
- `);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 bu=a.create({service:"tool.note"}),$C=loadTextFile("./note.txt",import.meta.url),FC=$C(),NC=10,UC=800,rg=30,ig=1500,zC=10,qC=500,HC=U.discriminatedUnion("operation",[U.object({operation:U.literal("search"),query:U.string().optional().describe("Search query for note content"),maxResults:U.number().optional().default(10).describe("Maximum number of results to return"),minScore:U.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)")}),U.object({operation:U.literal("queryEdges"),nodeId:U.number().describe("Node ID to query relations"),maxDepth:U.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")})]);async function BC(e,t){if(e.length===0)return `<note_context>
614
- No note context found.
615
- </note_context>`;let o=[];o.push(`<note_context total="${e.length}">`);for(let n=0;n<e.length;n++){let s=e[n],r=await Ve.output(s.snippet,{maxLines:NC,maxBytes:UC,contentType:"list",toolName:"note_snippet"},t);if(o.push(`[${n+1}]`),o.push(` document: ${s.document.path}`),o.push(` lines: ${s.chunk.startLine}-${s.chunk.endLine}`),o.push(` score: ${s.score.toFixed(4)}`),o.push(` source: ${s.source}`),o.push(` snippet: ${r.content}`),r.truncated&&o.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(`
616
- `)}).join(`
617
- `),c=await Ve.output(i,{maxLines:rg,maxBytes:ig,contentType:"list",toolName:"note_nodes"},t);o.push(` nodes (${s.nodes.length}):`),o.push(c.content),c.truncated&&o.push(` (nodes: ${c.outputPath})`);}o.push("");}return o.push("</note_context>"),o.join(`
618
- `)}var ag=De.define("note",{description:FC,parameters:HC,async execute(e,t){if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");let o={directory:t.extra.directory},n=await Yt.config(),s=o.directory;bu.debug("note tool execute",{operation:e.operation,...e.operation==="search"&&{query:e.query},directory:s,noteConfigLoaded:!!n,noteConfig:n?{search:n.search,sync:n.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:!!n}});let r=await Yt.get();if(!r)return bu.warn("note kb not available"),{output:`<note_context>
619
- Note knowledge base is not enabled or not properly configured.
620
- </note_context>`,title:`Note: ${e.operation}`,metadata:{available:false,count:0,enabled:false}};if(e.operation==="search"){let i=n?.search?.minScore??.3,c=e.minScore!==void 0&&e.minScore!==null?Number(e.minScore):i,l=n?.search?.maxResults??10;bu.debug("note search params",{query:e.query,minScore:c,defaultMinScore:i,maxResults:e.maxResults??l,noteMinScore:n?.search?.minScore}),n?.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 BC(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>
621
- Node with id ${e.nodeId} not found.
622
- </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(I=>`[id=${I.id}] type=${I.type} name=${I.name}`).join(`
623
- `),h=await Ve.output(u,{maxLines:rg,maxBytes:ig,contentType:"list",toolName:"note_neighbors"},t.extra?.agent),g=p.map(I=>{let A=I.source===i?"out":"in";return I.targetNode?` \u2192 [${A}] ${I.relation} \u2192 ${I.targetNode.type}:${I.targetNode.name} (id=${I.target})`:` \u2192 [${A}] ${I.relation} \u2192 id=${I.target} (node not found)`}).join(`
624
- `);if(f.edges.length>a){let I=f.edges.length-a,A=p.length>0?`
625
- `:"";g=g+A+` ... and ${I} more relations`;}let v=await Ve.output(g,{maxLines:zC,maxBytes:qC,contentType:"list",toolName:"note_edges"},t.extra?.agent),P=[];return P.push(`<note_queryEdges node_id="${e.nodeId}" name="${l.name}" type="${l.type}">`),P.push(`neighbors (${f.nodes.length}):`),P.push(h.content),h.truncated&&P.push(` (neighbors: ${h.outputPath})`),P.push(""),P.push(`relations (${f.edges.length}):`),P.push(v.content),v.truncated&&P.push(` (relations: ${v.outputPath})`),P.push("</note_queryEdges>"),{output:P.join(`
626
- `),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 VC=loadTextFile("./memory.txt",import.meta.url),KC=VC()||"Access and manage memory system for agent operations",JC=10,YC=800,XC=30,QC=1500;async function ZC(e,t){if(e.length===0)return `<memory_context>
627
- No memories found.
628
- </memory_context>`;let o=[];o.push(`<memory_context total="${e.length}">`);for(let n=0;n<e.length;n++){let s=e[n],r=new Date(s.createdAt),i=formatLocalISOCompact(r),c=Intl.DateTimeFormat().resolvedOptions().timeZone,l=await Ve.output(s.snippet,{maxLines:JC,maxBytes:YC,contentType:"list",toolName:"memory_snippet"},t);if(o.push(`[${n+1}]`),o.push(` id: ${s.memoryId}`),o.push(` [${s.category}] importance=${s.importance}`),o.push(` score: ${s.score.toFixed(4)}`),o.push(` created: ${i} (${c})`),o.push(` agent: ${s.agentId}`),o.push(` source: ${s.source}`),o.push(` snippet: ${l.content}`),l.truncated&&o.push(` (snippet: ${l.outputPath})`),s.filePath){let d=Filesystem.normalize(s.filePath);o.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(`
629
- `)}).join(`
630
- `),m=await Ve.output(d,{maxLines:XC,maxBytes:QC,contentType:"list",toolName:"memory_nodes"},t);o.push(` nodes (${s.nodes.length}):`),o.push(m.content),m.truncated&&o.push(` (nodes: ${m.outputPath})`);}o.push("");}return o.push("</memory_context>"),o.join(`
631
- `)}function cg(e){if(e?.trim())return e.split(",").map(t=>t.trim()).filter(Boolean)}function dg(e){if(e)try{let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}catch{return}}var wu=U.enum(["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"]),ek=U.discriminatedUnion("operation",[U.object({operation:U.literal("remember"),content:U.string().describe("Memory content to store"),category:wu.describe("Memory category"),importance:U.coerce.number().min(1).max(10).describe("Importance score 1-10"),tags:U.string().optional().describe('Optional tags, comma-separated (e.g. "typescript, testing, api")')}),U.object({operation:U.literal("recall"),query:U.string().describe("Search query"),maxResults:U.coerce.number().optional().default(10).describe("Maximum number of results to return (default 10)"),minScore:U.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)"),category:wu.optional().describe("Filter by memory category"),fromTime:U.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:U.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')}),U.object({operation:U.literal("queryEdges"),nodeId:U.coerce.number().describe("Node ID to query relations"),maxDepth:U.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")}),U.object({operation:U.literal("forget"),memoryId:U.string().describe("Memory ID to delete")}),U.object({operation:U.literal("update"),memoryId:U.string().describe("Memory ID to update"),content:U.string().optional().describe("Updated memory content"),importance:U.coerce.number().min(1).max(10).optional().describe("Updated importance score 1-10"),tags:U.string().optional().describe('Updated tags, comma-separated (e.g. "typescript, testing, api")')}),U.object({operation:U.literal("list"),maxResults:U.coerce.number().min(1).max(100).optional().default(20).describe("Maximum number of memories to list (default 20, max 100)"),category:wu.optional().describe("Filter by memory category"),fromTime:U.string().optional().describe('Start time filter in local time (e.g. "2024-01-01 00:00:00")'),toTime:U.string().optional().describe('End time filter in local time (e.g. "2024-12-31 23:59:59")')})]),ug=De.define("memory",{description:KC,parameters:ek,formatValidationError(e){return `Memory tool validation error: ${e.issues.map(o=>o.message).join("; ")}`},async execute(e,t){let o=t.extra?.directory??"unknown";await t.ask({permission:"memory",patterns:e.operation==="recall"?[e.query]:["*"],always:["*"],metadata:{operation:e.operation,workspaceDir:o}});let n=await wo.get();if(!n)return {output:`<memory_context>
632
- Memory system is not enabled or not properly configured.
633
- </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 n.remember({agentId:s,content:e.content,category:e.category,importance:e.importance,source:"session_self_write",tags:cg(e.tags),sessionId:t.sessionId,msgId:t.messageId,parentMsgId:r});return {output:`<memory_result>
634
- Memory saved successfully.
635
- id: ${i.id}
636
- category: ${i.category}
637
- importance: ${i.importance}
638
- </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 wo.config())?.search?.minScore??.3,c=await n.query(e.query,{agentId:s,maxResults:e.maxResults??10,minScore:e.minScore??i,category:e.category,fromTime:dg(e.fromTime),toTime:dg(e.toTime)}),l=t.extra?.agent;return {output:await ZC(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 n.queryEdgesByNodeId(r,{maxDepth:c});if(!l.node)return {output:`<memory_queryEdges node_id="${e.nodeId}">
639
- Node ${e.nodeId} not found.
640
- </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(`
641
- `),title:`Memory queryEdges: ${e.nodeId}`,metadata:{operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:l.edges.length}}}if(e.operation==="forget")try{return await n.forget(s,e.memoryId),{output:`<memory_result>
642
- Memory ${e.memoryId} deleted successfully.
643
- </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>
644
- Memory ${e.memoryId} not found or already deleted.
645
- </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 n.update(s,e.memoryId,{content:e.content,importance:e.importance,tags:cg(e.tags)});return {output:`<memory_result>
646
- Memory ${r.id} updated successfully.
647
- category: ${r.category}
648
- importance: ${r.importance}
649
- </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>
650
- Memory ${e.memoryId} not found. Please use 'list' to see available memory IDs.
651
- </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 n.queryForSummary(s,{limit:e.maxResults??20,category:e.category,fromTime:e.fromTime,toTime:e.toTime});if(r.length===0)return {output:`<memory_context>
652
- No memories found${e.category||e.fromTime||e.toTime?" with given filters":""}.
653
- </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(`
654
- `),title:`Memory list (${r.length})`,metadata:{operation:"list",enabled:true,total:r.length,truncated:false}}}throw new Error(`Unknown operation: ${e.operation}`)}});var ok=loadTextFile("./codebase.txt",import.meta.url),nk=ok()||"Access and analyze codebase knowledge graph for agent operations",sk=10,rk=1e3,Hc=20,Bc=2e3,ik=U.discriminatedUnion("operation",[U.object({operation:U.literal("search"),query:U.string().optional().describe("Search query for codebase content"),maxResults:U.number().optional().default(10).describe("Maximum number of results to return"),astType:U.string().optional().describe("Filter by AST type (e.g., class_declaration, function_declaration)"),language:U.string().optional().describe("Filter by programming language"),minScore:U.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)")}),U.object({operation:U.literal("queryEdges"),nodeId:U.string().describe("Node ID to query relations"),direction:U.enum(["in","out","both"]).optional().default("both").describe("Edge direction: in (incoming), out (outgoing), both"),maxDepth:U.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")})]);async function ak(e,t){if(e.length===0)return `<codebase_context>
655
- No codebase results found.
656
- </codebase_context>`;let o=[];o.push(`<codebase_context total="${e.length}">`);for(let n=0;n<e.length;n++){let s=e[n],r=await Ve.output(s.text,{maxLines:sk,maxBytes:rk,contentType:"output",toolName:"codebase_code"},t),i=s.edges?.map(l=>` \u2192 ${l.relation} \u2192 node:${l.target}`).join(`
657
- `)||"";s.edges&&s.edges.length>0?await Ve.output(i,{maxLines:Hc,maxBytes:Bc,contentType:"list",toolName:"codebase_edges"},t):null;if(o.push(`[${n+1}]`),o.push(` node id=${s.id}`),o.push(` type: ${s.ast_type}`),o.push(` language: ${s.language}`),o.push(` name: ${s.name}`),o.push(` location: ${s.file_path}:${s.start_line}`),o.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(`
658
- `),m=await Ve.output(d,{maxLines:Hc,maxBytes:Bc,contentType:"list",toolName:"codebase_edges"},t);o.push(` edges (${s.edges.length}):`),o.push(m.content);}o.push("");}return o.push("</codebase_context>"),o.join(`
659
- `)}var pg=De.define("codebase",{scope:g.Coder,description:nk,parameters:ik,formatValidationError(e){return `Codebase tool validation error: ${e.issues.map(o=>o.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 o=await jn.get();if(!o)return {output:`<codebase_context>
660
- Codebase knowledge base is not enabled or not properly configured.
661
- </codebase_context>`,title:`Codebase ${e.operation}`,metadata:{count:0,enabled:false,operation:e.operation}};if(e.operation==="search"){let s=(await jn.config())?.search?.minScore??.3,r=await o.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 ak(r,t.extra?.agent);return r.length===0&&e.astType&&(i+=`
662
-
663
- <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 n={in:"incoming",out:"outgoing",both:"both"},s=String(e.nodeId),r=await o.getNode(s),i=Math.min(e.maxDepth??2,3),{nodes:c,edges:l}=await o.queryNeighbors(s,{limit:50,maxDepth:i,direction:n[e.direction??"both"]});if((!l||l.length===0)&&!r)return {output:`<codebase_queryEdges node_id="${e.nodeId}">
664
- Node ${e.nodeId} not found or has no relations.
665
- </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(`
666
- `),p=await Ve.output(a,{maxLines:Hc,maxBytes:Bc,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 v=g.source===s?"out":"in",P=a.get(g.target),I=P?.ast_type||"unknown",A=P?.name||String(g.target);p.push(` \u2192 [${v}] ${g.relation} \u2192 target=${I}:${A} (id=${g.target})`);}l.length>m&&p.push(` ... and ${l.length-m} more relations`);let u=p.join(`
667
- `),h=await Ve.output(u,{maxLines:Hc,maxBytes:Bc,contentType:"list",toolName:"codebase_edges"},t.extra?.agent);d.push(h.content);}return d.push("</codebase_queryEdges>"),{output:d.join(`
668
- `),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 uk=loadTextFile("./lsp.txt",import.meta.url),pk=uk(),mk=200,fk=5*1024,gk=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],mg=De.define("lsp",{scope:g.Coder,isEnabled:()=>a$2.EASBOT_LSP_TOOL,description:pk,parameters:U.object({operation:U.enum(gk).describe("The LSP operation to perform"),filePath:U.string().describe("The absolute or relative path to the file"),line:U.number().int().min(1).describe("The line number (1-based, as shown in editors)"),character:U.number().int().min(1).describe("The character offset (1-based, as shown in editors)"),query:U.string().optional().describe("Search query for workspaceSymbol. Empty string requests all symbols.")}),formatValidationError(e){return `LSP tool validation error: ${e.issues.map(o=>o.message).join("; ")}`},execute:async(e,t)=>{At.check(t.abort,"lsp");let o=Filesystem.normalize(Ce__default.isAbsolute(e.filePath)?e.filePath:Ce__default.join(R.directory,e.filePath));await Zt(t,o,{tool:"lsp"});let n=e.operation==="workspaceSymbol"?{operation:e.operation}:e.operation==="documentSymbol"?{operation:e.operation,filePath:o}:{operation:e.operation,filePath:o,line:e.line,character:e.character};await t.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:n});let s={file:o,line:e.line-1,character:e.character-1},r=Ce__default.posix.relative(R.worktree,o),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(o).then(()=>true).catch(()=>false))throw new Error(`File not found: ${o}`);if(!await We.hasClients(o))throw new Error("No LSP server available for this file type.");await We.touchFile(o,true);let m=await At.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:o});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:mk,maxBytes:fk,contentType:"output",toolName:"lsp"});return {title:c,metadata:{filepath:o,truncated:a.truncated,...a.truncated&&{outputPath:a.outputPath}},output:a.content}}});var yk=loadTextFile("./plan.txt",import.meta.url),bk=yk();async function hg(e){for await(let t of ve.stream(e))if(t.info.role==="user"&&t.info.model)return t.info.model;return Se.defaultModel()}var fg={enter:U.object({operation:U.literal("enter").describe("Enter plan mode for research and planning")}),exit:U.object({operation:U.literal("exit").describe("Exit plan mode and switch to build mode")})},wk=U.discriminatedUnion("operation",[fg.enter,fg.exit]),yg=De.define("plan",{description:bk,parameters:wk,formatValidationError(e){return `Plan tool validation error: ${e.issues.map(o=>o.message).join("; ")}`},async execute(e,t){if(e.operation==="enter")return xk(t);if(e.operation==="exit")return Ik(t);throw new Error(`Unknown operation: ${e.operation}`)}});async function xk(e){let t=await Z.get(e.sessionId),o=Ce__default.posix.relative(R.worktree,Z.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 ${o}?`,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 hg(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 Z.updateMessage(c),await Z.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 ${o}. Begin planning.`,metadata:{operation:"enter"}}}async function Ik(e){let t=await Z.get(e.sessionId),o=Ce__default.posix.relative(R.worktree,Z.plan(t));if((await Ot.ask({sessionId:e.sessionId,questions:[{question:`Plan at ${o} 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 hg(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 Z.updateMessage(c),await Z.updatePart({id:Identifier.ascending("part"),messageId:c.id,sessionId:e.sessionId,type:"text",text:`The plan at ${o} 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 Ki;(S=>{let e=a.create({service:"patch"});S.PatchSchema=U.object({patchText:U.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"))(S.ApplyPatchError||(S.ApplyPatchError={}));(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.PatchParseError="PatchParseError",E.NotApplyPatch="NotApplyPatch"))(S.MaybeApplyPatch||(S.MaybeApplyPatch={}));(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.CorrectnessError="CorrectnessError",E.NotApplyPatch="NotApplyPatch"))(S.MaybeApplyPatchVerified||(S.MaybeApplyPatchVerified={}));function r(w,y){let b=w[y];if(!b)return null;let C=E=>{let O=E.indexOf(":");if(O!==-1)return E.substring(O+1).trim()||void 0};if(b.startsWith("*** Add File:")){let E=C(b);return E?{filePath:E,nextIdx:y+1}:null}if(b.startsWith("*** Delete File:")){let E=C(b);return E?{filePath:E,nextIdx:y+1}:null}if(b.startsWith("*** Update File:")){let E=C(b),O,D=y+1;if(D<w.length&&w[D]?.startsWith("*** Move to:")){let $=w[D];$&&(O=C($)),D++;}return E?{filePath:E,movePath:O,nextIdx:D}:null}return null}function i(w,y){let b=[],C=y;for(;C<w.length&&!w[C]?.startsWith("***");){let E=w[C];if(!E){C++;continue}if(E.startsWith("@@")){let O=E.indexOf("@@",2),D=O!==-1?E.substring(O+2).trim():"";C++;let $=[],K=[],ee=false;for(;C<w.length&&!w[C]?.startsWith("@@")&&!w[C]?.startsWith("***");){let N=w[C];if(!N){C++;continue}if(N==="*** End of File"){ee=true,C++;break}if(N.startsWith(" ")){let M=N.substring(1);$.push(M),K.push(M);}else N.startsWith("-")?$.push(N.substring(1)):N.startsWith("+")&&K.push(N.substring(1));C++;}b.push({old_lines:$,new_lines:K,change_context:D||void 0,is_end_of_file:ee||void 0});}else C++;}return {chunks:b,nextIdx:C}}function c(w,y){let b="",C=y;for(;C<w.length&&!w[C]?.startsWith("***");){let E=w[C];if(!E){C++;continue}E.startsWith("+")&&(b+=E.substring(1)+`
669
- `),C++;}return b.endsWith(`
670
- `)&&(b=b.slice(0,-1)),{content:b,nextIdx:C}}function l(w){let y=w.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return y?.[2]?y[2]:w}function d(w){let b=l(w.trim()).split(`
671
- `),C=[],E=0,O="*** Begin Patch",D="*** End Patch",$=b.findIndex(ee=>ee.trim()===O),K=b.findIndex(ee=>ee.trim()===D);if($===-1||K===-1||$>=K)throw new Error("Invalid patch format: missing Begin/End markers");for(E=$+1;E<K;){let ee=r(b,E);if(!ee){E++;continue}if(b[E]?.startsWith("*** Add File:")){let{content:N,nextIdx:M}=c(b,ee.nextIdx);C.push({type:"add",path:ee.filePath,contents:N}),E=M;}else if(b[E]?.startsWith("*** Delete File:"))C.push({type:"delete",path:ee.filePath}),E=ee.nextIdx;else if(b[E]?.startsWith("*** Update File:")){let{chunks:N,nextIdx:M}=i(b,ee.nextIdx);C.push({type:"update",path:ee.filePath,move_path:ee.movePath,chunks:N}),E=M;}else E++;}return {hunks:C}}S.parsePatch=d;function m(w){let y=["apply_patch","applypatch"];if(w.length===2&&y.includes(w[0]))try{let b=w[1];if(!b)return {type:"PatchParseError",error:new Error("Missing patch argument")};let{hunks:C}=d(b);return {type:"Body",args:{patch:b,hunks:C}}}catch(b){return {type:"PatchParseError",error:b}}if(w.length===3&&w[0]==="bash"&&w[1]==="-lc"){let b=w[2];if(!b)return {type:"NotApplyPatch"};let C=b.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"}}S.maybeParseApplyPatch=m;function f(w,y){let b;try{b=readFileSync(w,"utf-8");}catch(K){throw new Error(`Failed to read file ${w}: ${K}`)}let C=b.split(`
672
- `);C.length>0&&C[C.length-1]===""&&C.pop();let E=a$1(C,w,y),O=p(C,E);(O.length===0||O[O.length-1]!=="")&&O.push("");let D=O.join(`
673
- `);return {unified_diff:v(b,D),content:D}}S.deriveNewContentsFromChunks=f;function a$1(w,y,b){let C=[],E=0;for(let O of b){if(O.change_context){let ee=g(w,[O.change_context],E);if(ee===-1)throw new Error(`Failed to find context '${O.change_context}' in ${y}`);E=ee+1;}if(O.old_lines.length===0){let ee=w.length>0&&w[w.length-1]===""?w.length-1:w.length;C.push([ee,0,O.new_lines]);continue}let D=O.old_lines,$=O.new_lines,K=g(w,D,E,O.is_end_of_file);if(K===-1&&D.length>0&&D[D.length-1]===""&&(D=D.slice(0,-1),$.length>0&&$[$.length-1]===""&&($=$.slice(0,-1)),K=g(w,D,E,O.is_end_of_file)),K!==-1){let ee=[K,D.length,$];C.push(ee),E=K+D.length;}else throw new Error(`Failed to find expected lines in ${y}:
674
- ${O.old_lines.join(`
675
- `)}`)}return C.sort((O,D)=>O[0]-D[0]),C}function p(w,y){let b=[...w];for(let C=y.length-1;C>=0;C--){let E=y[C];if(!E)continue;let[O,D,$]=E;b.splice(O,D);for(let K=0;K<$.length;K++){let ee=$[K];ee!==void 0&&b.splice(O+K,0,ee);}}return b}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,y,b,C,E){if(E){let O=w.length-y.length;if(O>=b){let D=true;for(let $=0;$<y.length;$++){let K=w[O+$],ee=y[$];if(!K||!ee||!C(K,ee)){D=false;break}}if(D)return O}}for(let O=b;O<=w.length-y.length;O++){let D=true;for(let $=0;$<y.length;$++){let K=w[O+$],ee=y[$];if(!K||!ee||!C(K,ee)){D=false;break}}if(D)return O}return -1}function g(w,y,b,C=false){if(y.length===0)return -1;let E=h(w,y,b,(K,ee)=>K===ee,C);if(E!==-1)return E;let O=h(w,y,b,(K,ee)=>K.trimEnd()===ee.trimEnd(),C);if(O!==-1)return O;let D=h(w,y,b,(K,ee)=>K.trim()===ee.trim(),C);return D!==-1?D:h(w,y,b,(K,ee)=>u(K.trim())===u(ee.trim()),C)}function v(w,y){let b=w.split(`
676
- `),C=y.split(`
677
- `),E=`@@ -1 +1 @@
678
- `,O=Math.max(b.length,C.length),D=false;for(let $=0;$<O;$++){let K=b[$]||"",ee=C[$]||"";K!==ee?(K&&(E+=`-${K}
679
- `),ee&&(E+=`+${ee}
680
- `),D=true):K&&(E+=` ${K}
681
- `);}return D?E:""}async function P(w){if(w.length===0)throw new Error("No files were modified.");let y=[],b=[],C=[];for(let E of w)switch(E.type){case "add":{let O=Ce.dirname(E.path);O!=="."&&O!=="/"&&await Tt.mkdir(O,{recursive:true}),await Tt.writeFile(E.path,E.contents,"utf-8"),y.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 D=Ce.dirname(E.move_path);D!=="."&&D!=="/"&&await Tt.mkdir(D,{recursive:true}),await Tt.writeFile(E.move_path,O.content,"utf-8"),await Tt.unlink(E.path),b.push(E.move_path),e.info(`Moved file: ${E.path} -> ${E.move_path}`);}else await Tt.writeFile(E.path,O.content,"utf-8"),b.push(E.path),e.info(`Updated file: ${E.path}`);break}}return {added:y,modified:b,deleted:C}}S.applyHunksToFiles=P;async function I(w){let{hunks:y}=d(w);return P(y)}S.applyPatch=I;async function A(w,y){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 b=m(w);switch(b.type){case "Body":{let{args:C}=b,E=C.workdir?Ce.resolve(y,C.workdir):y,O=new Map;for(let D of C.hunks){let $=Ce.resolve(E,D.type==="update"&&D.move_path?D.move_path:D.path);switch(D.type){case "add":O.set($,{type:"add",content:D.contents});break;case "delete":{let K=Ce.resolve(E,D.path);try{let ee=await Tt.readFile(K,"utf-8");O.set($,{type:"delete",content:ee});}catch{return {type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${K}`)}}break}case "update":{let K=Ce.resolve(E,D.path);try{let ee=f(K,D.chunks);O.set($,{type:"update",unified_diff:ee.unified_diff,move_path:D.move_path?Ce.resolve(E,D.move_path):void 0,new_content:ee.content});}catch(ee){return {type:"CorrectnessError",error:ee}}break}}}return {type:"Body",action:{changes:O,patch:C.patch,cwd:E}}}case "PatchParseError":return {type:"CorrectnessError",error:b.error};case "NotApplyPatch":return {type:"NotApplyPatch"}}}S.maybeParseApplyPatchVerified=A;})(Ki||(Ki={}));var Ck=loadTextFile("./apply_patch.txt",import.meta.url),kk=Ck(),Pk=U.object({patchText:U.string().describe("The full patch text that describes all changes to be made")}),Ig=De.define("apply_patch",{scope:g.Coder,description:kk,parameters:Pk,async execute(e,t){if(At.check(t.abort,"apply_patch"),!e.patchText)throw new Error("patchText is required");let o;try{o=Ki.parsePatch(e.patchText).hunks;}catch(a){throw new Error(`apply_patch verification failed: ${a}`)}if(o.length===0)throw e.patchText.replace(/\r\n/g,`
682
- `).replace(/\r/g,`
683
- `).trim()===`*** Begin Patch
684
- *** End Patch`?new Error("patch rejected: empty patch"):new Error("apply_patch verification failed: no hunks found");let n=[],s="";for(let a of o){let p=Filesystem.normalize(Ce.resolve(R.directory,a.path));switch(await Zt(t,p,{tool:"patch"}),a.type){case "add":{let h=a.contents.length===0||a.contents.endsWith(`
685
- `)?a.contents:`${a.contents}
686
- `,g=$n(createTwoFilesPatch(p,p,"",h)),v=0,P=0;for(let I of diffLines("",h))I.added&&(v+=I.count||0),I.removed&&(P+=I.count||0);n.push({filePath:p,oldContent:"",newContent:h,type:"add",diff:g,additions:v,deletions:P}),s+=g+`
687
- `;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=Ki.deriveNewContentsFromChunks(p,a.chunks).content;}catch(S){throw new Error(`apply_patch verification failed: ${S}`)}let v=$n(createTwoFilesPatch(p,p,h,g)),P=0,I=0;for(let S of diffLines(h,g))S.added&&(P+=S.count||0),S.removed&&(I+=S.count||0);let A=a.move_path?Filesystem.normalize(Ce.resolve(R.directory,a.move_path)):void 0;await Zt(t,A,{tool:"patch"}),n.push({filePath:p,oldContent:h,newContent:g,type:a.move_path?"move":"update",movePath:A,diff:v,additions:P,deletions:I}),s+=v+`
688
- `;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=$n(createTwoFilesPatch(p,p,h,"")),v=h.split(`
689
- `).length;n.push({filePath:p,oldContent:h,newContent:"",type:"delete",diff:g,additions:0,deletions:v}),s+=g+`
690
- `;break}}}let r=n.map(a=>({filePath:a.filePath,relativePath:Ce.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=n.map(a=>Ce.posix.relative(R.worktree,a.filePath));await t.ask({permission:"edit",patterns:i,always:["*"],metadata:{filepath:i.join(", "),diff:s,files:r}}),At.check(t.abort,"apply_patch");let c=[];for(let a of n){let p=a.type==="delete"?void 0:a.movePath??a.filePath;switch(a.type){case "add":await Tt.mkdir(Ce.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(Ce.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 ue.publish(yt.Event.Edited,{file:p});}for(let a of c)await ue.publish(zo.Event.Updated,a);At.check(t.abort,"apply_patch");for(let a of n){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:
691
- ${n.map(a=>{if(a.type==="add")return `A ${Ce.posix.relative(R.worktree,a.filePath)}`;if(a.type==="delete")return `D ${Ce.posix.relative(R.worktree,a.filePath)}`;let p=a.movePath??a.filePath;return `M ${Ce.posix.relative(R.worktree,p)}`}).join(`
692
- `)}`,f=20;for(let a of n){if(a.type==="delete")continue;let p=a.movePath??a.filePath,u=Filesystem.normalize(p),g=(l[u]??[]).filter(v=>v.severity===1);if(g.length>0){let v=g.slice(0,f),P=g.length>f?`
693
- ... and ${g.length-f} more`:"";m+=`
694
-
695
- LSP errors detected in ${Ce.posix.relative(R.worktree,p)}, please fix:
696
- <diagnostics file="${p}">
697
- ${v.map(We.Diagnostic.pretty).join(`
698
- `)}${P}
699
- </diagnostics>`;}}return {title:m,metadata:{diff:s,files:r,diagnostics:l},output:m}}});var Ek=loadTextFile("./multiedit.txt",import.meta.url),Ak=Ek(),_k=U.object({edits:U.array(U.object({filePath:U.string().describe("The absolute path to the file to modify"),oldString:U.string().describe("The text to replace"),newString:U.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:U.boolean().optional().describe("Replace all occurrences of oldString (default false)")})).min(1).describe("Array of edit operations to perform sequentially"),continueOnError:U.boolean().optional().default(false).describe("Continue processing remaining edits if one fails (default false)")});function Mk(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(o=>({filePath:o.filePath||e.filePath,oldString:o.oldString,newString:o.newString,replaceAll:o.replaceAll})),continueOnError:e.continueOnError??false}):e}var vg=De.define("multiedit",{description:Ak,parameters:_k,async execute(e,t){let o=Mk(e);At.check(t.abort,"multiedit");let n=await jc.init(),s=[],r=[],i=new Map;for(let a of o.edits)i.has(a.filePath)||i.set(a.filePath,[]),i.get(a.filePath).push(a);for(let[a,p]of i.entries()){At.check(t.abort,"multiedit");try{for(let u of p){let h=await n.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}),!o.continueOnError)throw u}}let c=s.filter(a=>a.success).length,l=s.filter(a=>!a.success).length,d=o.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+=`
700
-
701
- Errors:
702
- `;for(let{filePath:a,error:p}of r)f+=`- ${Ce__default.posix.relative(R.worktree,a)}: ${p.message}
703
- `;}return m?.result&&(f+=`
704
-
705
- Last successful edit:
706
- `,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 jk=loadTextFile("./ls.txt",import.meta.url),Lk=jk(),Dk=["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/"],$k=100,Wc=De.define("list",{description:Lk,parameters:U.object({path:U.string().default(".").optional().describe("The directory to list (default: current directory"),ignore:U.array(U.string()).default([]).optional().describe("List of glob patterns to ignore"),limit:U.number().default(100).optional().describe("Maximum number of entries to return (default: 100")}),execute:async(e,t)=>{let o=Filesystem.normalize(Ce.isAbsolute(e.path||".")?e.path||".":Ce.resolve(R.directory,e.path||"."));await Zt(t,o,{kind:"directory",tool:"list"}),await t.ask({permission:"list",patterns:[Ce.posix.relative(R.worktree,o)],always:["*"],metadata:{path:o}});let n=e.limit??$k,s="/",r=Dk.map(a=>`!${a}*`).concat(e.ignore?.map(a=>`!${a}`)||[]),i=[],c=false;for await(let a of a$8.files({cwd:o,glob:r,signal:t.abort})){if(i.length>=n){c=true;break}i.push(Filesystem.toUnixPath(a));}let l=new Set,d=new Map;for(let a of i){let p=Ce.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(Ce.posix.basename(a));}let m=(a,p)=>{let u=" ".repeat(p),h="";p>0&&(h+=`${u}${Ce.posix.basename(a)}/
707
- `);let g=" ".repeat(p+1),v=Array.from(l).filter(I=>Ce.posix.dirname(I)===a&&I!==a).sort();for(let I of v)h+=m(I,p+1);let P=d.get(a)||[];for(let I of P.sort())h+=`${g}${I}
708
- `;return h},f=`${o}/
709
- `+m(".",0);return c&&(f+=`
710
- [${n} entries limit reached, Use limit=${n*2} for more]`),{title:Ce.posix.relative(R.worktree,o),metadata:{path:o,count:i.length,truncated:c},output:f}}});var Ns=a.create({service:"connection-registry"}),go;(a=>{let e=null;async function t(){return e||(e=await Vc.create()),e}async function o(p){e=await Vc.create(p),Ns.info("AcpConnectionRegistry initialized");}a.init=o;async function n(p){return (await t()).connect(p.baseUrl,p.localAgentId,p.remoteAgentId,p.remoteSessionId,p.localSessionId)}a.connect=n;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;})(go||(go={}));var Vc=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",Ns.info("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(t){return new e(t)}connect(t,o,n,s,r){let i=this.agentIndex.get(o);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(),Ns.debug("reused existing connection",{connectionId:m,localAgentId:o,baseUrl:t}),{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:o,remoteAgentId:n,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(o)||this.agentIndex.set(o,new Set),this.agentIndex.get(o).add(c),this.serviceIndex.has(t)||this.serviceIndex.set(t,new Set),this.serviceIndex.get(t).add(c),Ns.debug("new connection created",{connectionId:c,localAgentId:o,remoteAgentId:n,baseUrl:t}),{connectionId:c,sessionId:l,localAgentId:o,remoteAgentId:n,baseUrl:t}}resolve(t,o=false){let n=this.connections.get(t);if(n)return n;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(o){let c=this.connect("http://localhost","system-local","system-remote",t);return this.connections.get(c.connectionId)}}closeConnection(t){let o=this.connections.get(t);if(!o)return;this.connections.delete(t);let n=this.agentIndex.get(o.localAgentId);n&&(n.delete(t),n.size===0&&this.agentIndex.delete(o.localAgentId));let s=this.serviceIndex.get(o.baseUrl);s&&(s.delete(t),s.size===0&&this.serviceIndex.delete(o.baseUrl)),Ns.info("connection closed and removed",{connectionId:t,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId});}markDegraded(t,o){let n=this.connections.get(t);n&&(n.status="degraded",n.updatedAt=Date.now(),Ns.debug("connection marked degraded",{connectionId:t,reason:o}));}getConnectionsByAgent(t){let o=this.agentIndex.get(t);return o?Array.from(o).map(n=>this.connections.get(n)).filter(n=>n!==void 0&&n.status!=="closed"):[]}getConnectionsByService(t){let o=this.serviceIndex.get(t);return o?Array.from(o).map(n=>this.connections.get(n)).filter(n=>n!==void 0&&n.status!=="closed"):[]}getAllActiveConnections(){return Array.from(this.connections.values()).filter(t=>t.status!=="closed")}updateLastSeenMessageId(t,o){let n=this.connections.get(t);n&&(n.lastSeenMessageId=o,n.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(),Ns.info("connection registry closed");}};var Un=a.create({service:"session-router"});var $r=class extends Error{constructor(o,n,s){super(n);b$1(this,"code",o);b$1(this,"context",s);this.name="RoutingError";}},Su=class e{static create(){return new e}constructor(){Un.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(o){let n=o instanceof Error?o.message:String(o);return Un.error("routing failed",{context:t,error:n}),{success:false,error:n}}}routeOrThrow(t){let o=this.route(t);if(!o.success)throw new $r(this.getErrorCode(o.error),o.error??"routing failed",t);if(!o.connectionId)throw new $r("NOT_FOUND","connection not found",t);let n=this.getConnectionState(o.connectionId);if(!n)throw new $r("NOT_FOUND","connection state not found",t);if(n.status==="closed")throw new $r("CONNECTION_CLOSED","connection is closed",t);return n}registerConnection(t){return !t.connectionId||!t.localAgentId||!t.remoteAgentId||!t.baseUrl||!t.sessionId?{success:false,error:"invalid connection state: missing required fields"}:(Un.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 o=this.getConnectionState(t);return o?(Un.debug("connection unregistered",{connectionId:t,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}),true):(Un.debug("connection not found for unregister",{connectionId:t}),false)}isValidContext(t){return !!(t.connectionId||t.remoteAgentId||t.baseUrl||t.sessionId)}routeByConnectionId(t){let o=this.getConnectionState(t);return o?o.status==="closed"?{success:false,error:`connection is closed: ${t}`}:{success:true,connectionId:o.connectionId,sessionId:o.sessionId,localAgentId:o.localAgentId,remoteAgentId:o.remoteAgentId,baseUrl:o.baseUrl}:{success:false,error:`connection not found: ${t}`}}routeByPeerAndBaseUrl(t,o){let s=this.getConnectionsByPeer(t).filter(i=>i.baseUrl===o&&i.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for localAgentId=${t}, baseUrl=${o}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${t}, baseUrl=${o}`};let r=s[0];return {success:true,connectionId:r.connectionId,sessionId:r.sessionId,localAgentId:r.localAgentId,remoteAgentId:r.remoteAgentId,baseUrl:r.baseUrl}}routeByBaseUrlAndSessionId(t,o){let s=this.getConnectionsByService(t).filter(i=>i.sessionId===o&&i.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for baseUrl=${t}, sessionId=${o}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${t}, sessionId=${o}`};let r=s[0];return {success:true,connectionId:r.connectionId,sessionId:r.sessionId,localAgentId:r.localAgentId,remoteAgentId:r.remoteAgentId,baseUrl:r.baseUrl}}getConnectionState(t){Un.warn("getConnectionState not implemented, returning undefined",{connectionId:t});}getConnectionsByPeer(t){return Un.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:t}),[]}getConnectionsByService(t){return Un.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"}},Cg=class e extends Su{constructor(o){super();b$1(this,"registry");this.registry=o,Un.info("registry session router created");}static fromRegistry(o){return new e(o)}getConnectionState(o){return this.registry.resolve(o)}getConnectionsByPeer(o){return this.registry.getConnectionsByPeer(o)}getConnectionsByService(o){return this.registry.getConnectionsByService(o)}};var mn=a.create({service:"agent-client-api"});function Nk(e){return e==="stdio"||e==="http"||e==="websocket"?e:"http"}async function Uk(e){return (await Pe(()=>Cn.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",e||{directory:R.directory}).catch(()=>{}))?.acp?.server?.agentId??""}var to;(v=>{async function e(P,I){mn.debug("connect called",{args:P,context:I});let A=await Pe(()=>Cn.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",I||{directory:R.directory}).catch(()=>{}),S=A?.acp?.server?.agentId,w=P.agentId;w||(w=(await(await Ar()).getServiceByUrl(P.baseUrl))?.agentId);let y;if(P.baseUrl.startsWith("ws://")||P.baseUrl.startsWith("wss://")?y="websocket":P.baseUrl.startsWith("http://")||P.baseUrl.startsWith("https://")?y="http":y=Nk(A?.acp?.server?.channel),mn.debug("connect resolved",{baseUrl:P.baseUrl,resolvedChannel:y,localAgentId:S,remoteAgentId:w}),S){let ee=(await go.getConnectionsByLocalAgent(S)).find(N=>N.baseUrl===P.baseUrl);if(ee){if(mn.debug("connect: found existing connection by agent"),ee.channel&&ee.channel!==y)throw new Error(`Channel mismatch for agent ${S}: ${ee.channel} != ${y}`);return {reused:true,...ee,channel:ee.channel??y}}}let b=await go.getConnectionsByService(P.baseUrl);if(b.length>0){let K=b[0];if(mn.debug("connect: found existing connection by service",{existing:K}),K.channel&&K.channel!==y)throw new Error(`Channel mismatch for service ${P.baseUrl}: ${K.channel} != ${y}`);return {reused:true,connectionId:K.connectionId,sessionId:K.sessionId,remoteAgentId:K.remoteAgentId,baseUrl:K.baseUrl,channel:K.channel??y}}let C=S??"local-unknown",E=w??`remote-${Buffer.from(P.baseUrl).toString("base64").slice(0,16)}`;mn.debug("connect: using effective agent IDs",{effectiveLocalAgentId:C,effectiveRemoteAgentId:E}),mn.debug("connect: calling AgentClientService.connect",{baseUrl:P.baseUrl,channel:y});let O;try{O=await en.connect({config:{type:y,url:P.baseUrl,cwd:I.directory}}),mn.debug("connect: AgentClientService.connect succeeded",{remote:O});}catch(K){throw mn.error("connect: AgentClientService.connect failed",{error:K.message,stack:K.stack}),K}mn.debug("connect: creating connection in registry",{baseUrl:O.baseUrl,localAgentId:C,remoteAgentId:E,sessionId:O.sessionId});let D=await go.connect({baseUrl:O.baseUrl,localAgentId:C,remoteAgentId:E,remoteSessionId:O.sessionId}),$=await go.resolve(D.connectionId);return $&&($.channel=O.channel??y,$.subscriber=O.subscriber),mn.debug("connect: completed",{result:D}),{created:true,connectionId:D.connectionId,sessionId:D.sessionId,remoteAgentId:D.remoteAgentId,baseUrl:D.baseUrl,channel:O.channel??y}}v.connect=e;async function t(P,I){let A=P.agentId??await Uk(I);return (await go.getConnectionsByLocalAgent(A)).filter(w=>!P.baseUrl||w.baseUrl===P.baseUrl)}v.list=t;async function o(P,I,A){let S=await go.resolve(P);if(!S)throw new Error("Connection not found");let w=S.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");await en.send(w,S.sessionId,I.parts),S.updatedAt=Date.now();}v.send=o;async function n(P,I){let A=await go.resolve(P);if(!A)throw new Error("Connection not found");let S=A.subscriber;if(!S)throw new Error("Connection not initialized with subscriber");return en.capabilities(S)}v.capabilities=n;async function s(P,I){await go.close(P);}v.close=s;async function r(P,I){let A=await go.resolve(P);return A?{connectionId:A.connectionId,remoteAgentId:A.remoteAgentId,baseUrl:A.baseUrl,sessionId:A.sessionId,status:A.status,updatedAt:A.updatedAt}:{connectionId:P,status:"unknown"}}v.status=r;async function i(P){let I=await Pe(()=>Cn.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",P).catch(()=>{}),A=await go.getAllActiveConnections();return {config:I?.acp,managedConnections:A.length}}v.config=i;async function c(P){return (await Ar()).listServices(P)}v.listServices=c;async function l(P){return (await Ar()).getService(P)}v.getService=l;async function d(P){return (await Ar()).registerService(P)}v.registerService=d;async function m(P,I,A,S){let w=await go.resolve(P);if(!w)throw new Error("Connection not found");let y={...Ro,...S},b=w.channel??"http";switch(b){case "websocket":return f(w,y,I);case "http":return a(w,y,I);case "stdio":return p(w,y,I);default:throw new Error(`Unsupported channel type: ${b}`)}}v.subscribe=m;async function f(P,I,A){let S=P.subscriber;if(!S)throw new Error("Connection not initialized with subscriber");return S.subscribe(P.sessionId,A)}async function a(P,I,A,S){let w=P.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");return w.subscribe(P.sessionId,A,S)}async function p(P,I,A,S){let w=P.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");return w.subscribe(P.sessionId,A,S)}async function u(P,I){let A=await go.resolve(P);if(!A)throw new Error("Connection not found");let S=A.subscriber;if(!S)throw new Error("Connection not initialized with subscriber");await en.interrupt(S,A.sessionId);}v.interrupt=u;async function h(P,I,A,S,w){return await o(P,I),m(P,A,S,w)}v.exchangeSubscribe=h;async function g(P,I){let A=await go.resolve(P);if(!A){mn.warn("Connection not found for releaseSubscription",{connectionId:P});return}let S=A.subscriber;if(!S)throw new Error("Connection not initialized with subscriber");await en.releaseSubscription(S,A.sessionId);}v.releaseSubscription=g;})(to||(to={}));var Cu=a.create({service:"api"}),Kc=class extends Error{constructor(o,n,s){super(o);b$1(this,"code",n);b$1(this,"details",s);this.name="ApiError";}};async function Pe(e,t,o){try{o&&Cu.debug(`API call started: ${JSON.stringify(o)}`,{errorCode:t});let n=await R.provide({directory:o?.directory??R.directory,init:void 0,fn:e});return o&&Cu.debug(`API call completed: ${JSON.stringify(o)}`,{errorCode:t}),n}catch(n){let s=n instanceof Error?n.message:String(n),r=n instanceof Error?n.name:"Error",i=n instanceof Error?n.stack:void 0;throw Cu.error(`API call failed: ${o||t}`,{errorCode:t,errorName:r,error:s,stack:i}),n instanceof Kc?n:new Kc(s,t,n)}}var kn=a.create({service:"tool.agent-client"}),qk=loadTextFile("./agent-client.txt",import.meta.url),Hk=10,Us=new Map,kg=De.define("agent_client",{description:qk(),parameters:U.object({operation:U.enum(["connect","list","discover","capabilities","send","close","status","config","interrupt"]).default("connect").describe("Operation: connect | list | discover | capabilities | send | status | config | interrupt | close"),baseUrl:U.string().optional().describe("Target easbot service base URL (required for connect operation, e.g. http://127.0.0.1:3000)"),connectionId:U.string().optional().describe("Connection ID from a previous connect operation (auto-resolved if not provided)"),prompt:U.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(o=>o.message).join("; ")}`},async execute(e,t){let o=e.operation??"connect",n=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(n.has(o)&&e.baseUrl&&await t.ask({permission:"agent_client",patterns:[e.baseUrl],always:["*"],metadata:{operation:o,baseUrl:e.baseUrl}}),o==="config"){let[r,i]=await Promise.all([to.config(s),to.list({},s)]),c=r.config,l=["<config>"];if(l.push(` managedConnections: ${i.length}`),c?.server&&(l.push(" server:"),l.push(` channel: ${c.server.channel??"unknown"}`),l.push(` port: ${c.server.port??"unknown"}`),l.push(` hostname: ${c.server.hostname??"unknown"}`)),i.length>0){let d=[...new Set(i.map(m=>m.channel).filter(Boolean))];l.push(" connections:"),l.push(` channels: ${d.join(", ")||"none"}`),l.push(` total: ${i.length}`);}return l.push("</config>"),{title:"Agent client config",metadata:{count:0},output:l.join(`
711
- `)}}if(o==="list"){let r=await to.list({baseUrl:e.baseUrl},s);if(r.length===0)return {title:"Connection List",metadata:{count:0},output:`<connections>
712
- No active connections
713
- </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(`
714
- `)}}if(o==="connect"){if(!e.baseUrl)throw new Error("baseUrl required for connect");let r=await to.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(`
715
- `)}}if(o==="discover"){let r=await to.listServices();if(r.length===0)return {title:"Discoverable Services",metadata:{count:0},output:`<services>
716
- No services discovered
717
- </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(`
718
- `)}}if(!e.connectionId){let i=(await to.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(o==="close"){await to.interrupt(e.connectionId,s).catch(i=>{kn.warn("interrupt during close failed (connection may already be closed)",{error:i});});let r=Us.get(e.connectionId);return r&&(r.unsubscribe?.(),Us.delete(e.connectionId)),await to.close(e.connectionId,s),{title:"Connection closed",metadata:{count:0},output:`<connection>
719
- connectionId: ${e.connectionId}
720
- status: closed
721
- </connection>`}}if(o==="interrupt"){await to.interrupt(e.connectionId,s);let r=Us.get(e.connectionId);return r&&(r.unsubscribe?.(),Us.delete(e.connectionId)),{title:"Session Interrupted",metadata:{count:0},output:`<connection>
722
- connectionId: ${e.connectionId}
723
- status: interrupted
724
- </connection>`}}if(o==="capabilities"){let r=await to.capabilities(e.connectionId,s);return {title:"Remote Agent Capabilities",metadata:{count:1},output:JSON.stringify(r,null,2)}}if(o==="status"){let r=await to.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(`
725
- `)}}if(o==="send"){if(!e.prompt)throw new Error("prompt required");let r=e.connectionId,i=Us.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 to.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:Hk,hasPendingResponse:false,startedAt:Date.now()},kn.debug("Establishing subscription for Agent-to-Agent interaction",{connectionId:r,sessionId:t.sessionId,remoteSessionId:l.sessionId});let d=await to.subscribe(r,async m=>{if(kn.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,kn.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 Ke.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}),kn.debug("Round completed, keeping connection alive for next round",{connectionId:r,currentRound:i.currentRound,remainingRounds:i.maxRounds-i.currentRound}),i.currentRound>=i.maxRounds){kn.debug("Max rounds reached, closing connection",{connectionId:r,currentRound:i.currentRound,maxRounds:i.maxRounds});try{await to.releaseSubscription(r,s);}catch(a){kn.warn("Failed to release server subscription",{connectionId:r,error:a instanceof Error?a.message:String(a)});}Us.delete(r);}}},s,{includeThinking:false,includeToolDetails:false,includeToolOutput:false});i.unsubscribe=d,Us.set(r,i);}kn.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 to.send(r,{sessionId:i.sessionId,parts:[{type:"text",text:`${e.prompt}
726
-
727
- [async] Agent Client message`}]},s);}catch(l){throw i.hasPendingResponse=false,l}kn.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 kn.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>
728
- connectionId: ${r}
729
- round: ${i.currentRound}/${i.maxRounds}
730
- status: Remote agent is processing, response will be injected automatically
731
- </agent_message>`}}throw new Error(`Unknown operation: ${o}`)}});var Pn=a.create({service:"tool.gateway"}),Vk=loadTextFile("./gateway.txt",import.meta.url),Kk=Vk(),Xi=null;async function Jk(){if(Xi)return Xi;try{let e=await c$1(),t=e.path||"",o=t.endsWith("/")?t.slice(0,-1):t,n=`ws://${e.hostname}:${e.port}${o}`;return Xi=new GatewayClient({url:n,type:"api"}),await Xi.connect(),Pn.debug("gateway client connected",{url:n}),Xi}catch(e){return Pn.error("failed to connect to gateway",{error:String(e)}),null}}var Yk=U.discriminatedUnion("operation",[U.object({operation:U.literal("status")}),U.object({operation:U.literal("channels")}),U.object({operation:U.literal("sessions"),limit:U.number().optional(),offset:U.number().optional(),type:U.enum(["private","group","all"]).optional().default("all").describe("Filter by chat type: private, group, or all")}),U.object({operation:U.literal("contacts"),platform:U.string().describe("Platform to list contacts (e.g., telegram, discord)"),limit:U.number().optional(),offset:U.number().optional()}),U.object({operation:U.literal("send"),contactUid:U.string().optional().describe('Full Contact UID like "telegram:123456789" (recommended)'),sessionId:U.string().optional().describe("Session ID to use"),content:U.string(),messageType:U.enum(["text","image","file"]).default("text")})]),Eg=De.define("gateway",async()=>({description:Kk,parameters:Yk,async execute(e,t){let o=await Jk();if(!o)return {title:"Gateway Not Available",metadata:{available:false},output:"**Error**: Cannot connect to Gateway server"};if(e.operation==="status"){let n=await o.getStatus();return {title:"Gateway Status",metadata:{connections:n.connections,sessions:n.sessions,subscriptions:n.subscriptions},output:`## Gateway Status
732
-
733
- - **Status**: ${n.status}
734
- - **Connections**: ${n.connections}
735
- - **Sessions**: ${n.sessions}
736
- - **Subscriptions**: ${n.subscriptions}
737
- - **Uptime**: ${Xk(n.uptime)}
738
- - **Version**: ${n.version}`}}if(e.operation==="channels"){let n=await o.listChannels();if(n.channels.length===0)return {title:"Channels",metadata:{count:0},output:"**No channels connected**"};let s=["## Connected Channels"];for(let r of n.channels)s.push(`### ${r.name} (${r.platform})`),s.push(`- ID: ${r.id}`),r.version&&s.push(`- Version: ${r.version}`);return {title:"Channels",metadata:{count:n.channels.length},output:s.join(`
739
- `)}}if(e.operation==="sessions"){let n=e.limit??50,s=e.offset??0,r=e.type??"all",i=await o.listSessions({limit:n,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**: ${Pg(d.lastActiveAt)}`);return i.hasMore&&l.push(`
740
- *Showing ${c.length} of ${i.total}*`),{title:"Sessions",metadata:{count:i.sessions.length,total:i.total},output:l.join(`
741
- `)}}if(e.operation==="contacts"){let n=e.platform,s=e.limit??50,r=e.offset??0,i=await o.listContacts(n,{limit:s,offset:r});if(i.contacts.length===0)return {title:"Contacts",metadata:{count:0},output:`**No contacts found on ${n}**`};let c=[`## Contacts on ${n} (${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**: ${Pg(l.lastSeenAt)}`);}return i.hasMore&&c.push(`
742
- *Showing ${i.contacts.length} of ${i.total}*`),{title:"Contacts",metadata:{count:i.contacts.length,total:i.total,platform:n},output:c.join(`
743
- `)}}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 Zk(t,e.content,e.messageType);if(!l.valid)return {title:"Send Failed",metadata:{success:false},output:`**Error**: ${l.error}`}}let n,s,r,i,c;if(e.contactUid){let[l,d]=e.contactUid.split(":");l&&d&&(r=l,n=d,s=d,i=`${r}-main`,c=`${r}_${i}_${s}_${n}`,Pn.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],n=l.length>=4?l[3]:s,Pn.debug("extracted params from sessionId",{sessionId:c,platform:r,channelId:i,chatId:s,userId:n}));}if(!c||!s)return {title:"Send Failed",metadata:{success:false},output:"**Error**: sessionId or contactUid is required"};if(!i)try{let l=await o.listChannels();l.channels.length>0&&(i=l.channels[0]?.id,r=l.channels[0]?.platform,Pn.debug("using first available channel",{channelId:i,platform:r}));}catch(l){Pn.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 o.getOrCreateSession({sessionId:c,platform:r,channel:i,userId:n,chatId:s});c=l.sessionId,Pn.debug("session ensured",{sessionId:c,created:l.created});}catch(l){return Pn.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=Ce__default.isAbsolute(f)?f:Ce__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 o.sendMessage(c,{content:d,channel:i,userId:n,chatId:s,processorId:"gateway",agent:t?.agent??"gateway"});return Pn.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
744
-
745
- - **Message ID**: ${m.messageId}
746
- - **Session ID**: ${c}
747
- ${r&&n?`- **Contact UID**: ${r}:${n}`:""}
748
- - **Content**: ${l(e.content).length>100?l(e.content).slice(0,100)+"...":l(e.content)}`}}catch(l){return Pn.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 Xk(e){let t=Math.floor(e/1e3),o=Math.floor(t/60),n=Math.floor(o/60),s=Math.floor(n/24);return s>0?`${s}d ${n%24}h ${o%60}m`:n>0?`${n}h ${o%60}m`:o>0?`${o}m ${t%60}s`:`${t}s`}function Pg(e){let t=new Date(e),n=new Date().getTime()-t.getTime();return n<6e4?"just now":n<36e5?`${Math.floor(n/6e4)}m ago`:n<864e5?`${Math.floor(n/36e5)}h ago`:t.toISOString().replace("T"," ").slice(0,19)}function Qk(e){let t=e.trim();if(t.startsWith("file://")&&(t=t.slice(7)),Filesystem.isAbsolute(t))return Filesystem.normalize(t);let o=Ce__default.resolve(R.directory,t);return Filesystem.normalize(o)}async function Zk(e,t,o){let n=Qk(t),s=Filesystem.stat(n);if(!s){let i=Filesystem.dirname(n),c=Filesystem.basename(n),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: ${n}
749
-
750
- Did you mean one of these?
751
- ${l.join(`
752
- `)}`}:{valid:false,error:`File not found: ${n}`}}if(s.isDirectory())return {valid:false,error:`Path is a directory, not a file: ${n}`};await Zt(e,n,{bypass:!!e.extra?.bypassCwdCheck,kind:"file",tool:"gateway"});let r=Ce__default.posix.relative(R.worktree,n);return await e.ask({permission:"read",patterns:[r],always:["*"],metadata:{}}),{valid:true,filePath:n}}var tP=loadTextFile("./question.txt",import.meta.url),oP=tP(),Rg=De.define("question",{isEnabled:()=>["app","cli","desktop"].includes(a$2.EASBOT_CLIENT)||a$2.EASBOT_ENABLE_QUESTION_TOOL,description:oP,parameters:U.object({questions:U.array(Ot.Info).describe("Questions to ask")}),async execute(e,t){let o=await Ot.ask({sessionId:t.sessionId,questions:e.questions,tool:t.callId?{messageId:t.messageId,callId:t.callId}:void 0});function n(r){return !r||r.length===0?"Unanswered":r.join(", ")}let s=e.questions.map((r,i)=>`"${r.question}"="${n(o[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:o}}}});var _g=a.create({service:"tool.registry"}),nP=[Vf,Rg,bf,tg,eg,Nc,Af,Wc,jf,jc,Wf,vg,Gi,Bf,Uf,og,sg,ag,ug,pg,kg,Eg,Yf,Ig,mg,Lf,yg],Ho;(p=>{let e,t;async function o(){let u={},{Filesystem:h}=await import('@easbot/utils'),{glob:g}=await import('glob');for await(let v of h.up({targets:[".easbot/tools"],start:R.directory,stop:R.worktree})){if(!await h.isDir(v))continue;let P=await g("*.{ts,js}",{cwd:v,absolute:true,nodir:true,follow:false,dot:false});for(let I of P)try{let A=h.extname(I),S=h.basename(I,A),{pathToFileURL:w}=await import('url'),y=await import(w(I).href);for(let[b,C]of Object.entries(y)){let E=b==="default"?S:`${S}_${b}`;u[E]={...C,id:E,source:"custom"};}}catch(A){_g.error("Failed to load tool file",{file:I,error:A});}}return u}function n(){return e||(e=R.state(async()=>{let u={};for(let g of nP)g.isEnabled&&!await g.isEnabled()||(u[g.id]={...g,source:"builtin"});let h=await o();for(let[g,v]of Object.entries(h))u[g]||(u[g]=v);if(t)for(let[g,v]of Object.entries(t))u[g]=v;return u})),e}async function s(){return n()()}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 P=>{let A=(await Le.triggerEvent(HookEvent.ToolDefinition,P)).output;if(A.isEnabled&&!await A.isEnabled())return null;let S=await A.init({agent:h});return {id:A.id,init:A.init,scope:A.scope,isEnabled:A.isEnabled,...S}}))).filter(P=>P!==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(),_g.debug("tool registry initialized");}p.init=a;})(Ho||(Ho={}));a.create({service:"agent-cli-api-tool"});var Cn={};a$7(Cn,{getConfig:()=>rP,getConfigDirectories:()=>dP,getGlobalConfig:()=>iP,updateConfig:()=>aP,updateGlobalConfig:()=>cP,waitForConfigDependencies:()=>lP});async function rP(){return he.get()}async function iP(){return he.getGlobal()}async function aP(e){return await he.update(e),he.get()}async function cP(e){return await he.updateGlobal(e),he.getGlobal()}async function dP(){return he.directories()}async function lP(){await he.waitForDependencies();}var Yc={};a$7(Yc,{getProvider:()=>pP,listAllProviders:()=>uP,listProviders:()=>Mg});var Tn=a.create({service:"agent-cli-api-provider"});async function Mg(){try{Tn.debug("List providers");let e=await Se.list(),t=Object.values(e);return Tn.debug("List providers success",{count:t.length}),t}catch(e){throw Tn.error("List providers failed",{error:e}),e}}async function uP(){try{Tn.debug("List all available providers");let e=await a$3.get(),t=Object.values(e).map(o=>Se.fromModelsDevProvider(o));return Tn.debug("List all available providers success",{count:t.length}),t}catch(e){throw Tn.error("List all available providers failed",{error:e}),e}}async function pP(e){try{Tn.debug("Get provider details",{providerId:e});let o=(await Mg()).find(n=>n.id===e);return o?(Tn.debug("Get provider details success",{providerId:e}),o):(Tn.warn("Provider not found",{providerId:e}),null)}catch(t){throw Tn.error("Get provider details failed",{providerId:e,error:t}),t}}var nd={};a$7(nd,{list:()=>tT,listCommands:()=>th});var fP=loadTextFile("./init.txt",import.meta.url),ku=f("init",{description:"create/update AGENTS.md",source:"command",commandType:"prompt",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let o=fP(),n=e$1(o,e);return {title:"Initialize",metadata:{sessionId:t.sessionId},output:n,parts:[{type:"text",text:n}],success:true}},init:async()=>({})});var hP=loadTextFile("./review.txt",import.meta.url),Pu=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 o=hP(),n=e$1(o,e);return {title:"Code Review",metadata:{sessionId:t.sessionId},output:n,parts:[{type:"text",text:n}],success:true}},init:async()=>({})});var bP=loadTextFile("./vuln.txt",import.meta.url),Tu=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 o=bP(),n=e$1(o,e);return {title:"Security Vulnerability Analysis",metadata:{sessionId:t.sessionId},output:n,parts:[{type:"text",text:n}],success:true}},init:async()=>({})});var xP=loadTextFile("./arch.txt",import.meta.url),Eu=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 o=xP(),n=e$1(o,e);return {title:"Architecture Review",metadata:{sessionId:t.sessionId},output:n,parts:[{type:"text",text:n}],success:true}},init:async()=>({})});var IP="Never use question tool (question)",Au=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:o}=await import('./provider-TU4AF2GP.mjs');if(!t.model)throw new Error("BTW command requires model");let n=o.parseModel(t.model),s=typeof e=="string"?e:JSON.stringify(e),r=await wr.run({source:t.sessionId,title:"BTW Response",agent:t.agent,model:{providerId:n.providerId,modelId:n.modelId},parts:[{type:"text",text:s}],system:IP,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 SP(e){return typeof e=="string"?e:JSON.stringify(e)}var Ru=f("shell",{description:"execute shell command locally",source:"command",commandType:"local",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let o=SP(e).trim();if(!o)return {title:"Shell Command",metadata:{sessionId:t.sessionId},output:"No command provided",success:true};try{let n=await Shell.run(void 0,o,{cwd:R.directory});if(n.code!==0){let r=n.stderr||n.stdout||`Exit code: ${n.code}`;throw new Error(`Command failed (${n.code}): ${r}`)}let s=n.stdout||n.stderr;return {title:"Shell Command",metadata:{sessionId:t.sessionId,command:o},output:s||"(empty output)",success:!0}}catch(n){return {title:"Shell Command",metadata:{sessionId:t.sessionId,command:o,error:n instanceof Error?n.message:String(n)},output:`Error: ${n instanceof Error?n.message:String(n)}`,success:false}}},init:async()=>({})});var Qi=a.create({service:"scheduler.task-store"}),kP="scheduler",PP="tasks.json",jg=1,Be;(y=>{let e={heartbeats:[],scheduled:[],commands:[],version:jg},t=false;function o(){return Ce__default.join(a$1.Path.data,kP)}function n(){let b=o();return Ce__default.join(b,PP)}async function s(){let b=o();await Filesystem.exists(b)||await mkdir(b,{recursive:true});}async function r(){let b=n();if(!await Filesystem.exists(b)){Qi.debug("Task store file not found, using empty store");return}try{let C=await Filesystem.readText(b),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:jg,Qi.info("Task store loaded",{heartbeats:e.heartbeats.length,scheduled:e.scheduled.length,commands:e.commands.length});}catch(C){Qi.error("Failed to load task store",{error:C});}}async function i(){if(!t)return;await s();let b=n();try{let C=JSON.stringify(e,null,2);await Filesystem.write(b,C),t=!1,Qi.debug("Task store saved");}catch(C){throw Qi.error("Failed to save task store",{error:C}),C}}async function c(){await r();}y.init=c;async function l(){return [...e.heartbeats]}y.getHeartbeats=l;async function d(){return [...e.scheduled]}y.getScheduled=d;async function m(b){return e.heartbeats.find(C=>C.id===b)}y.getHeartbeat=m;async function f(b){return e.scheduled.find(C=>C.id===b)}y.getScheduledTask=f;async function a(b){let C=e.heartbeats.findIndex(E=>E.id===b.id);C>=0?e.heartbeats[C]=b:e.heartbeats.push(b),t=true,await i();}y.saveHeartbeat=a;async function p(b){let C=e.scheduled.findIndex(E=>E.id===b.id);C>=0?e.scheduled[C]=b:e.scheduled.push(b),t=true,await i();}y.saveScheduled=p;async function u(b){e.heartbeats=e.heartbeats.filter(C=>C.id!==b),t=true,await i();}y.deleteHeartbeat=u;async function h(b){e.scheduled=e.scheduled.filter(C=>C.id!==b),t=true,await i();}y.deleteScheduled=h;async function g(b,C){let E=e.heartbeats.findIndex($=>$.id===b);if(E<0)throw new Error(`Heartbeat task not found: ${b}`);let O=e.heartbeats[E],D={id:b,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]=D,t=true,await i();}y.updateHeartbeat=g;async function v(b,C){let E=e.scheduled.findIndex($=>$.id===b);if(E<0)throw new Error(`Scheduled task not found: ${b}`);let O=e.scheduled[E],D={id:b,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]=D,t=true,await i();}y.updateScheduled=v;async function P(){return [...e.commands]}y.getCommands=P;async function I(b){return e.commands.find(C=>C.id===b)}y.getCommand=I;async function A(b){let C=e.commands.findIndex(E=>E.id===b.id);C>=0?e.commands[C]=b:e.commands.push(b),t=true,await i();}y.saveCommand=A;async function S(b){e.commands=e.commands.filter(C=>C.id!==b),t=true,await i();}y.deleteCommand=S;async function w(b,C){let E=e.commands.findIndex($=>$.id===b);if(E<0)throw new Error(`Command task not found: ${b}`);let O=e.commands[E],D={id:b,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]=D,t=true,await i();}y.updateCommand=w;})(Be||(Be={}));var _u;(h=>{async function e(){return Be.getHeartbeats()}h.getHeartbeats=e;async function t(){return Be.getScheduled()}h.getScheduled=t;async function o(g){return Be.getHeartbeat(g)}h.getHeartbeat=o;async function n(g){return Be.getScheduledTask(g)}h.getScheduledTask=n;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,v){return Be.updateHeartbeat(g,v)}h.updateHeartbeat=l;async function d(g,v){return Be.updateScheduled(g,v)}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,v){return Be.updateCommand(g,v)}h.updateCommand=u;})(_u||(_u={}));function Zi(e,t,o){if(e==="*"){let r=[];for(let i=t;i<=o;i++)r.push(i);return r}let n=new Set,s=e.split(",");for(let r of s)if(r.includes("/")){let[i,c]=r.split("/"),l=Lg(i??"*",t,o),d=parseInt(c??"1",10);for(let m=0;m<l.length;m+=d)m<l.length&&n.add(l[m]);}else if(r.includes("-")){let i=Lg(r,t,o);for(let c of i)n.add(c);}else {let i=parseInt(r,10);!Number.isNaN(i)&&i>=t&&i<=o&&n.add(i);}return Array.from(n).sort((r,i)=>r-i)}function Lg(e,t,o){if(e==="*"){let l=[];for(let d=t;d<=o;d++)l.push(d);return l}let[n,s]=e.split("-"),r=n?parseInt(n,10):t,i=s?parseInt(s,10):o,c=[];for(let l=r;l<=i;l++)l>=t&&l<=o&&c.push(l);return c}function Fr(e){if(!e||typeof e!="string")return null;let o=e.trim().split(/\s+/);if(o.length!==5)return null;try{let[n,s,r,i,c]=o;return {minutes:Zi(n??"*",0,59),hours:Zi(s??"*",0,23),days:Zi(r??"*",1,31),months:Zi(i??"*",1,12),weekdays:Zi(c??"*",0,6)}}catch{return null}}function cs(e){return Fr(e)!==null}function Qc(e,t=new Date){let o=new Date(t);o.setSeconds(0,0);for(let n=0;n<366*24*60;n++){o.setMinutes(o.getMinutes()+1);let s=o.getMinutes(),r=o.getHours(),i=o.getDate(),c=o.getMonth()+1,l=o.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(o)}return new Date(o.getTime()+1440*60*1e3*366)}function TP(e){let t=(o,n,s)=>{if(o.length===s-n+1)return "*";if(o.length===1)return o[0].toString();let r=[...o],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 EP(e){if(!Fr(e))return null;let o=e.trim().split(/\s+/);return o.length!==5?null:{minute:o[0]??"",hour:o[1]??"",day:o[2]??"",month:o[3]??"",weekday:o[4]??""}}function Dg(e){let t=EP(e);if(!t)return "Invalid cron expression";let o=[];if(t.minute==="*")o.push("every minute");else if(t.minute.startsWith("*/")){let n=t.minute.slice(2);o.push(`every ${n} minutes`);}else o.push(`at minute ${t.minute}`);if(t.hour!=="*")if(t.hour.startsWith("*/")){let n=t.hour.slice(2);o.push(`every ${n} hours`);}else o.push(`at hour ${t.hour}`);if(t.day!=="*"&&o.push(`on day ${t.day}`),t.month!=="*"){let n=["","Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],s=parseInt(t.month,10);!Number.isNaN(s)&&s>=1&&s<=12&&o.push(`in ${n[s]}`);}if(t.weekday!=="*"){let n=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],s=parseInt(t.weekday,10);!Number.isNaN(s)&&s>=0&&s<=6&&o.push(`on ${n[s]}`);}return o.join(" ")}var _P=loadTextFile("./heartbeat.txt",import.meta.url),MP=loadTextFile("./scheduled.txt",import.meta.url),Hg=_P(),Bg=MP(),Ug=a.create({service:"scheduler.history"}),OP=/\{\{([A-Z_]+)\}/g,Ou;(s=>{function e(r,i){return r.replace(OP,(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 o(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(Hg,i)}s.buildHeartbeatPrompt=o;function n(r,i){let c={taskId:r.id,taskName:r.name,taskType:"scheduled",agent:r.agentType,model:r.model,timestamp:Date.now()};return `${s.render(Bg,c)}
753
-
754
- ## User Request
755
-
756
- ${i}`}s.buildScheduledPrompt=n;})(Ou||(Ou={}));var jP="scheduler/history",zg=100;function td(){return Ce__default.join(a$1.Path.data,jP)}function Mu(e){let t=td(),o=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Ce__default.join(t,`${o}.json`)}async function Nr(e){try{return await access(e),!0}catch{return false}}async function LP(){let e=td();await Nr(e)||await mkdir(e,{recursive:true});}var od;(i=>{async function e(c){await LP();let l=Mu(c.taskId),d=[];if(await Nr(l))try{let f=await readFile(l,"utf-8");d=JSON.parse(f);}catch{d=[];}d.unshift(c),d.length>zg&&(d=d.slice(0,zg)),await writeFile(l,JSON.stringify(d,null,2)),Ug.debug("Task history record added",{taskId:c.taskId,success:c.success});}i.add=e;async function t(c,l){let d=Mu(c);if(!await Nr(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 o(c){let l=Mu(c);await Nr(l)&&await unlink(l);}i.clear=o;async function n(c){let l=td(),d=0,m=c?Date.now()-c:Date.now()-720*60*60*1e3;if(!await Nr(l))return 0;let a=await readdir(l);for(let p of a){if(!p.endsWith(".json"))continue;let u=Ce__default.join(l,p);try{let h=await readFile(u,"utf-8"),g=JSON.parse(h),v=g.filter(P=>P.endTime>m);v.length!==g.length&&(v.length===0?await unlink(u):await writeFile(u,JSON.stringify(v,null,2)),d+=g.length-v.length);}catch{}}return Ug.info("Task history pruned",{prunedCount:d}),d}i.prune=n;async function s(){let c=td(),l=0,d=0;if(!await Nr(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=Ce__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;})(od||(od={}));function DP(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return `hist_${e}_${t}`}async function ds(e,t,o,n){let s={id:DP(),taskId:e,taskType:t,startTime:o,endTime:Date.now(),success:n.success,output:n.output,error:n.error};await od.add(s);}var at=a.create({service:"scheduler"});function zn(e,t){let o=Fr(e);return o?Qc(o,new Date(t??Date.now())).getTime():0}var ho;(ee=>{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 T of M.timers.values())clearTimeout(T);M.timers.clear(),M.listeners.clear();}})),e}function o(){return t()()}ee.state=o;async function n(){return (await o()).status}ee.getStatus=n;async function s(){return (await o()).initialized}ee.isInitialized=s;async function r(){let N=await o();if(N.status==="running"){at.warn("Scheduler already running");return}at.info("Starting scheduler"),N.status="running";let M=await Be.getHeartbeats();for(let x of M)x.enabled&&C(N,x);let T=await Be.getScheduled();for(let x of T)x.enabled&&E(N,x);let j=await Be.getCommands();for(let x of j)x.enabled&&$(N,x);at.info("Scheduler started",{heartbeats:M.length,scheduled:T.length,commands:j.length});}ee.start=r;async function i(){let N=await o();if(N.status==="running"){at.info("Stopping scheduler");for(let M of N.timers.values())clearTimeout(M);N.timers.clear(),N.status="stopped",at.info("Scheduler stopped");}}ee.stop=i;function c(N,M){return o().then(T=>{T.listeners.has(N)||T.listeners.set(N,new Set),T.listeners.get(N).add(M);}),()=>{o().then(T=>{T.listeners.get(N)?.delete(M);});}}ee.onTaskComplete=c;async function l(N){if(!cs(N.cron))throw new Error(`Invalid cron expression: ${N.cron}`);let T={id:N.id??Identifier.ascending("heartbeat"),name:N.name,cron:N.cron,type:"heartbeat",enabled:true,parts:N.parts,config:{session:N.session,mode:N.mode??"session",agentId:N.agentId,transport:N.transport,agentConfig:N.agentConfig},recurring:true,createdAt:Date.now(),updatedAt:Date.now(),nextFireAt:zn(N.cron,Date.now())};await Be.saveHeartbeat(T);let j=await o();return j.status==="running"&&T.enabled&&C(j,T),at.info("Heartbeat task created",{id:T.id,name:T.name}),T}ee.createHeartbeat=l;async function d(N){if(!cs(N.cron))throw new Error(`Invalid cron expression: ${N.cron}`);let M=N.id??Identifier.ascending("task"),T=Date.now(),j={id:M,name:N.name,cron:N.cron,type:"scheduled",enabled:true,parts:N.parts,agentType:N.agentType??"default",transport:N.transport??"stdio",agentConfig:N.agentConfig,recurring:N.recurring??true,durable:N.durable??true,createdAt:T,updatedAt:T,nextFireAt:zn(N.cron,T)};await Be.saveScheduled(j);let x=await o();return x.status==="running"&&j.enabled&&E(x,j),at.info("Scheduled task created",{id:j.id,name:j.name}),j}ee.createScheduled=d;async function m(N){if(!cs(N.cron))throw new Error(`Invalid cron expression: ${N.cron}`);let M=N.id??Identifier.ascending("command"),T=Date.now(),j={id:M,name:N.name,cron:N.cron,type:"command",enabled:true,config:{command:N.command,arguments:N.arguments,session:N.session,durable:N.durable},recurring:N.recurring??true,durable:N.durable??true,createdAt:T,updatedAt:T,nextFireAt:zn(N.cron,T)};await Be.saveCommand(j);let x=await o();return x.status==="running"&&j.enabled&&$(x,j),at.info("Command task created",{id:j.id,name:j.name,command:j.config.command}),j}ee.createCommand=m;async function f(){return Be.getHeartbeats()}ee.listHeartbeats=f;async function a(){return Be.getScheduled()}ee.listScheduled=a;async function p(){return Be.getCommands()}ee.listCommands=p;async function u(N){return Be.getHeartbeat(N)}ee.getHeartbeat=u;async function h(N){return Be.getScheduledTask(N)}ee.getScheduled=h;async function g(N){let M=await o();b(M,N),await Be.deleteHeartbeat(N),at.info("Heartbeat task deleted",{id:N});}ee.deleteHeartbeat=g;async function v(N){let M=await o();b(M,N),await Be.deleteScheduled(N),at.info("Scheduled task deleted",{id:N});}ee.deleteScheduled=v;async function P(N){let M=await Be.getHeartbeat(N);if(!M)throw new Error(`Heartbeat task not found: ${N}`);await Be.updateHeartbeat(N,{enabled:true});let T=await o();C(T,{...M,enabled:true}),at.info("Heartbeat task enabled",{id:N});}ee.enableHeartbeat=P;async function I(N){let M=await o();b(M,N),await Be.updateHeartbeat(N,{enabled:false}),at.info("Heartbeat task disabled",{id:N});}ee.disableHeartbeat=I;async function A(N){let M=await Be.getScheduledTask(N);if(!M)throw new Error(`Scheduled task not found: ${N}`);await Be.updateScheduled(N,{enabled:true});let T=await o();E(T,{...M,enabled:true}),at.info("Scheduled task enabled",{id:N});}ee.enableScheduled=A;async function S(N){let M=await o();b(M,N),await Be.updateScheduled(N,{enabled:false}),at.info("Scheduled task disabled",{id:N});}ee.disableScheduled=S;async function w(N){let M=await Be.getHeartbeat(N);if(!M)throw new Error(`Heartbeat task not found: ${N}`);return O(M)}ee.triggerHeartbeat=w;async function y(N){let M=await Be.getScheduledTask(N);if(!M)throw new Error(`Scheduled task not found: ${N}`);return D(M)}ee.triggerScheduled=y;function b(N,M){let T=N.timers.get(M);T&&(clearTimeout(T),N.timers.delete(M));}function C(N,M){b(N,M.id);let T=(M.nextFireAt??zn(M.cron))-Date.now(),j=Math.max(0,T);at.info("Scheduling heartbeat",{id:M.id,nextFireAt:M.nextFireAt,delay:j});let x=setTimeout(async()=>{try{let k=await O(M),_=N.listeners.get(M.id);if(_)for(let L of _)try{L(k);}catch(H){at.error("Task listener error",{taskId:M.id,error:H});}if(M.enabled&&M.recurring){let L=zn(M.cron);await Be.updateHeartbeat(M.id,{lastFiredAt:Date.now(),nextFireAt:L});let H=await Be.getHeartbeat(M.id);H&&C(N,{...H,nextFireAt:L});}}catch(k){at.error("Heartbeat execution failed",{id:M.id,error:k});}},j);x.unref(),N.timers.set(M.id,x);}function E(N,M){b(N,M.id);let T=(M.nextFireAt??zn(M.cron))-Date.now(),j=Math.max(0,T);at.info("Scheduling task",{id:M.id,nextFireAt:M.nextFireAt,delay:j});let x=setTimeout(async()=>{try{let k=await D(M),_=N.listeners.get(M.id);if(_)for(let L of _)try{L(k);}catch(H){at.error("Task listener error",{taskId:M.id,error:H});}if(M.enabled&&(M.recurring??!0)){let L=zn(M.cron);await Be.updateScheduled(M.id,{lastFiredAt:Date.now(),nextFireAt:L});let H=await Be.getScheduledTask(M.id);H&&E(N,{...H,nextFireAt:L});}}catch(k){at.error("Scheduled task execution failed",{id:M.id,error:k});}},j);x.unref(),N.timers.set(M.id,x);}async function O(N){let M=Date.now(),T={type:"heartbeat",parts:N.parts,system:N.config.agentConfig?.system,config:{session:N.config.session,mode:N.config.mode,agent:N.config.agentId,model:N.config.agentConfig?.model,tools:N.config.agentConfig?.tools}},j={sessionId:N.config.session,agent:N.config.agentId,model:N.config.agentConfig?.model},x={taskId:N.id,taskName:N.name,sessionId:N.config.session,mode:N.config.mode,definition:T,context:j};try{at.info("Executing heartbeat",{id:N.id,mode:N.config.mode});let L=(await Le.triggerEvent(HookEvent.HeartbeatTrigger,x,j)).output?.execution;if(!L)throw new Error(`No heartbeat hook handled event: ${HookEvent.HeartbeatTrigger}`);return await ds(N.id,"heartbeat",M,L),await Le.triggerEvent(HookEvent.HeartbeatComplete,{taskId:N.id,taskName:N.name,success:L.success,output:L.output,error:L.error,duration:Date.now()-M},j),{taskId:N.id,success:L.success,output:L.output,error:L.error,executedAt:M,duration:Date.now()-M}}catch(k){at.error("Heartbeat execution error",{id:N.id,error:k});let _={success:false,error:k instanceof Error?k.message:String(k)};return await ds(N.id,"heartbeat",M,_),await Le.triggerEvent(HookEvent.HeartbeatComplete,{taskId:N.id,taskName:N.name,success:false,error:k instanceof Error?k.message:String(k),duration:Date.now()-M},j),{taskId:N.id,success:false,error:k instanceof Error?k.message:String(k),executedAt:M,duration:Date.now()-M}}}async function D(N){let M=Date.now(),T={type:"scheduler",parts:N.parts,system:N.agentConfig?.system,config:{agentType:N.agentType,transport:N.transport,model:N.agentConfig?.model,tools:N.agentConfig?.tools}},j={agent:N.agentType,model:N.agentConfig?.model},x={taskId:N.id,taskName:N.name,agentType:N.agentType,transport:N.transport,definition:T,context:j};try{at.info("Executing scheduled task",{id:N.id,agentType:N.agentType});let L=(await Le.triggerEvent(HookEvent.ScheduledTaskTrigger,x,j)).output?.execution;if(!L)throw new Error(`No scheduler hook handled event: ${HookEvent.ScheduledTaskTrigger}`);return await ds(N.id,"scheduled",M,L),await Le.triggerEvent(HookEvent.ScheduledTaskComplete,{taskId:N.id,taskName:N.name,success:L.success,output:L.output,error:L.error,duration:Date.now()-M},j),{taskId:N.id,success:L.success,output:L.output,error:L.error,executedAt:M,duration:Date.now()-M}}catch(k){at.error("Scheduled task execution error",{id:N.id,error:k});let _={success:false,error:k instanceof Error?k.message:String(k)};return await ds(N.id,"scheduled",M,_),await Le.triggerEvent(HookEvent.ScheduledTaskComplete,{taskId:N.id,taskName:N.name,success:false,error:k instanceof Error?k.message:String(k),duration:Date.now()-M},j),{taskId:N.id,success:false,error:k instanceof Error?k.message:String(k),executedAt:M,duration:Date.now()-M}}}function $(N,M){b(N,M.id);let T=(M.nextFireAt??zn(M.cron))-Date.now(),j=Math.max(0,T);at.info("Scheduling command task",{id:M.id,nextFireAt:M.nextFireAt,delay:j});let x=setTimeout(async()=>{try{let k=await K(M),_=N.listeners.get(M.id);if(_)for(let L of _)try{L(k);}catch(H){at.error("Task listener error",{taskId:M.id,error:H});}if(M.enabled&&(M.recurring??!0)){let L=zn(M.cron);await Be.updateCommand(M.id,{lastFiredAt:Date.now(),nextFireAt:L});let H=await Be.getCommand(M.id);H&&$(N,{...H,nextFireAt:L});}}catch(k){at.error("Command task execution failed",{id:M.id,error:k});}},j);x.unref(),N.timers.set(M.id,x);}async function K(N){let M=Date.now();at.info("Executing command task",{id:N.id,command:N.config.command});try{let T=await Ke.command({sessionId:N.config.session??"scheduler",command:N.config.command,arguments:N.config.arguments??""}),j={success:!T.error,output:T.output,error:T.error};return await ds(N.id,"command",M,j),{taskId:N.id,success:j.success,output:j.output,error:j.error,executedAt:M,duration:Date.now()-M}}catch(T){at.error("Command task execution error",{id:N.id,error:T});let j={success:false,error:T instanceof Error?T.message:String(T)};return await ds(N.id,"command",M,j),{taskId:N.id,success:false,error:T instanceof Error?T.message:String(T),executedAt:M,duration:Date.now()-M}}}})(ho||(ho={}));function $P(e){let t={};if(typeof e=="string"){let o=e.trim().split(/\s+/);o.length>0&&(t.subcommand=o[0],t.name=o[1]);for(let n=2;n<o.length;n++){let s=o[n];s==="--cron"&&n+1<o.length?t.cron=o[++n]:s==="--type"&&n+1<o.length?t.type=o[++n]:s==="--session"&&n+1<o.length?t.session=o[++n]:s==="--mode"&&n+1<o.length?t.mode=o[++n]:s==="--prompt"&&n+1<o.length?t.prompt=o[++n]:s==="--agent-type"&&n+1<o.length?t.agentType=o[++n]:s==="--transport"&&n+1<o.length?t.transport=o[++n]:s==="--recurring"?t.recurring=true:s==="--durable"&&(t.durable=true);}}return t}function Gg(e,t){let o=["Tasks:"];if(e.length>0){o.push(`
757
- Heartbeats:`),o.push("ID | Name | Cron | Session | Mode | Enabled"),o.push("------------------|---------------|---------------|---------|---------|--------");for(let n of e)o.push(`${n.id.padEnd(17)}| ${n.name.padEnd(12)}| ${n.cron.padEnd(12)}| ${n.config.session.padEnd(7)}| ${n.config.mode.padEnd(7)}| ${n.enabled}`);}else o.push(`
758
- Heartbeats: (none)`);if(t.length>0){o.push(`
759
- Scheduled:`),o.push("ID | Name | Cron | Agent Type | Recurring | Durable"),o.push("------------------|---------------|---------------|------------|-----------|--------");for(let n of t)o.push(`${n.id.padEnd(17)}| ${n.name.padEnd(12)}| ${n.cron.padEnd(12)}| ${(n.agentType||"default").padEnd(11)}| ${(n.recurring?"yes":"no").padEnd(7)}| ${n.durable?"yes":"no"}`);}else o.push(`
760
- Scheduled: (none)`);return o.join(`
761
- `)}var Lu=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 o=$P(e);if(!o.subcommand)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:Ur(),success:true,parts:[{type:"text",text:Ur()}]};switch(o.subcommand){case "create":return FP(o,t);case "list":return NP(t);case "delete":return UP(o,t);case "enable":return zP(o,t);case "disable":return qP(o,t);case "trigger":return HP(o,t);case "help":return {title:"Loop Command Help",metadata:{sessionId:t.sessionId},output:Ur(),success:true,parts:[{type:"text",text:Ur()}]};default:return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Unknown subcommand: ${o.subcommand}
762
-
763
- ${Ur()}`,success:true,parts:[{type:"text",text:Ur()}]}}},init:async()=>({})});async function FP(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task name is required
764
-
765
- 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
766
-
767
- Usage: /loop create <name> --cron <expression> [options]`,success:false,parts:[{type:"text",text:"Error: Cron expression is required"}]};if(!cs(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
768
-
769
- 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 n=await ho.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!
770
-
771
- ID: ${n.id}
772
- Name: ${n.name}
773
- Cron: ${n.cron}
774
- Session: ${n.config.session}
775
- Mode: ${n.config.mode}
776
- Next Fire: ${new Date(n.nextFireAt).toLocaleString()}`,success:!0,parts:[{type:"text",text:`Heartbeat task created: ${n.id}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error creating heartbeat: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}if(!e.prompt)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Prompt is required for scheduled tasks
777
-
778
- 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 n=await ho.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!
779
-
780
- ID: ${n.id}
781
- Name: ${n.name}
782
- Cron: ${n.cron}
783
- Agent Type: ${n.agentType}
784
- Recurring: ${n.recurring}
785
- Next Fire: ${new Date(n.nextFireAt).toLocaleString()}`,success:!0,parts:[{type:"text",text:`Scheduled task created: ${n.id}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error creating scheduled task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function NP(e){try{let t=await ho.listHeartbeats(),o=await ho.listScheduled();return {title:"Task List",metadata:{sessionId:e.sessionId},output:Gg(t,o),success:!0,parts:[{type:"text",text:Gg(t,o)}]}}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 UP(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
786
-
787
- Usage: /loop delete <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await ho.deleteHeartbeat(e.name).catch(()=>ho.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(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error deleting task: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}async function zP(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
788
-
789
- Usage: /loop enable <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await ho.enableHeartbeat(e.name).catch(()=>ho.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(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error enabling task: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}async function qP(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
790
-
791
- Usage: /loop disable <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await ho.disableHeartbeat(e.name).catch(()=>ho.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(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error disabling task: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}async function HP(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
792
-
793
- Usage: /loop trigger <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{let o=await ho.triggerHeartbeat(e.name).catch(()=>ho.triggerScheduled(e.name));return {title:"Task Triggered",metadata:{sessionId:t.sessionId},output:o.success?`Task triggered successfully!
794
-
795
- Output: ${o.output||"(no output)"}`:`Task failed: ${o.error}`,success:o.success,parts:[{type:"text",text:o.success?`Task executed: ${o.output||"(no output)"}`:`Task failed: ${o.error}`}]}}catch(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error triggering task: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}function Ur(){return `Loop Command - Create and manage scheduled tasks and heartbeats
796
-
797
- Usage:
798
- /loop <subcommand> [options]
799
-
800
- Subcommands:
801
- create <name> --cron <expression> [options]
802
- Create a scheduled task or heartbeat
803
-
804
- list
805
- List all tasks
806
-
807
- delete <id>
808
- Delete a task
809
-
810
- enable <id>
811
- Enable a task
812
-
813
- disable <id>
814
- Disable a task
815
-
816
- trigger <id>
817
- Manually trigger a task
818
-
819
- help
820
- Show this help message
821
-
822
- Options:
823
- --cron <expr> Cron expression (required)
824
- --type <type> Task type: heartbeat (default) | scheduled
825
- --session <name> Session name (heartbeat required)
826
- --mode <mode> Mode: session (default) | fork
827
- --prompt <text> Prompt (scheduled required)
828
- --agent-type <type> Agent type (default: default)
829
- --transport <type> Transport: stdio (default) | http | websocket | cli
830
- --recurring Recurring execution
831
- --durable Persistent storage
832
-
833
- Cron Expression Format:
834
- \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0-59)
835
- \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0-23)
836
- \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day (1-31)
837
- \u2502 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 month (1-12)
838
- \u2502 \u2502 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 weekday (0-6, 0=Sun)
839
- \u2502 \u2502 \u2502 \u2502 \u2502
840
- * * * * *
841
-
842
- Examples:
843
- /loop create main-heartbeat --cron "*/5 * * * *" --session main --type heartbeat
844
- /loop create hourly-sync --cron "0 * * * *" --prompt "Sync data" --type scheduled
845
- /loop list
846
- /loop delete hb_xxx
847
- /loop enable st_xxx
848
- /loop trigger hb_xxx
849
- `}var Du=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 o=[],n=[];if(typeof e=="string"&&e.includes("truncation"))try{await Ve.cleanup(),o.push("Truncation cleanup completed");}catch(r){n.push(`Truncation cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("snapshot"))try{await ht.cleanup(),o.push("Snapshot cleanup completed");}catch(r){n.push(`Snapshot cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("all")){try{await Ve.cleanup(),o.push("Truncation cleanup completed");}catch(r){n.push(`Truncation cleanup failed: ${r instanceof Error?r.message:String(r)}`);}try{await ht.cleanup(),o.push("Snapshot cleanup completed");}catch(r){n.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(),o.push("Truncation cleanup completed");}catch(i){n.push(`Truncation cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(r.type==="snapshot"||r.target==="snapshot")try{await ht.cleanup(),o.push("Snapshot cleanup completed");}catch(i){n.push(`Snapshot cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(!r.type&&!r.target){try{await Ve.cleanup(),o.push("Truncation cleanup completed");}catch(i){n.push(`Truncation cleanup failed: ${i instanceof Error?i.message:String(i)}`);}try{await ht.cleanup(),o.push("Snapshot cleanup completed");}catch(i){n.push(`Snapshot cleanup failed: ${i instanceof Error?i.message:String(i)}`);}}}let s=[...o,...n].join(`
850
- `);return {title:"Cleanup Command",metadata:{sessionId:t.sessionId,success:n.length===0,cleaned:o.length,errors:n.length},output:s,success:n.length===0,parts:[{type:"text",text:s}]}},init:async()=>({})});async function BP(e){let t,o;switch(e){case "note":t=await Yt.isEnabled(),o=()=>Yt.sync();break;case "codebase":t=await jn.isEnabled(),o=()=>jn.sync();break;case "memory":t=await wo.isEnabled(),o=()=>wo.sync();break}return t?(o().catch(n=>{console.error(`${e} sync failed:`,n);}),{target:e,started:true,message:`${e} sync started`}):{target:e,started:false,message:`${e} not enabled`}}function GP(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>["note","codebase","memory"].includes(t))}var $u=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 o=GP(e),n=o.length>0?o:["note","codebase","memory"],s=await Promise.all(n.map(d=>BP(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(`
851
- `);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 ZP=["BOOT.md","IDENTITY.md","SOUL.md","USER.md","AGENTS.md","TOOLS.md","CONTEXT.md","CODER.md"];function Wg(){let e=new Date,t=e.getFullYear(),o=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return `${t}-${o}-${n}`}async function Vg(e){try{return await access(e,constants.F_OK),!0}catch{return false}}async function eT(e,t,o){let n={backedUpFiles:[],cleanedOldBackups:0},s=Wg(),r=join(t,s);await mkdir(r,{recursive:true});for(let i of ZP){let c=join(e,i),l=join(r,i);await Vg(c)&&(await copyFile(c,l),n.backedUpFiles.push(i));}if(o>0){let i=new Date;i.setDate(i.getDate()-o);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}),n.cleanedOldBackups++);}}catch{}}return n}var Fu=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 o=[],n=[],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 Vg(s))o.push(`Config directory not found: ${s}`);else {let d=await eT(s,c,r);o.push(`Backup completed to: ${join(c,Wg())}`),o.push(`Backed up files: ${d.backedUpFiles.length}`),d.backedUpFiles.length>0&&o.push(`Files: ${d.backedUpFiles.join(", ")}`),d.cleanedOldBackups>0&&o.push(`Cleaned old backups: ${d.cleanedOldBackups}`);}}catch(c){n.push(`Backup failed: ${c instanceof Error?c.message:String(c)}`);}let i=[...o,...n].join(`
852
- `);return {title:"Backup Command",metadata:{sessionId:t.sessionId,success:n.length===0,backedUpFiles:o.filter(c=>c.includes("Backed up files:")).length,errors:n.length},output:i,success:n.length===0,parts:[{type:"text",text:i}]}},init:async()=>({})});var Kg=a.create({service:"command-abort"});function Nu(e,t,o,n={}){let s={title:"Abort",metadata:{sessionId:e,...n},output:o,parts:[{type:"text",text:o}],success:t};return t?s:{...s,error:o}}var Uu=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:o}=t;Kg.debug("Abort command executed",{sessionId:o});try{return (await Mt.get(o))?.type!=="busy"?Nu(o,!0,"\u2298 No active task to abort",{aborted:!1,reason:"no_active_task"}):(await so.abortSession(o),Nu(o,!0,`\u2713 Abort signal sent
853
-
854
- The agent will stop after completing its current action.`,{aborted:!0}))}catch(n){let s=n instanceof Error?n.message:String(n);return Kg.error("Failed to abort session",{sessionId:o,error:s}),Nu(o,false,`\u2298 Failed to abort: ${s}`,{error:s})}},init:async()=>({})});var Jg=a.create({service:"command-compact"});function Yg(e,t,o,n={}){let s={title:"Compact",metadata:{sessionId:e,...n},output:o,parts:[{type:"text",text:o}],success:t};return t?s:{...s,error:o}}var zu=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:o}=t;Jg.debug("Compact command executed",{sessionId:o});try{return await Ec({sessionId:o,agent:"compaction"}),Yg(o,!0,`\u2713 Context compaction started
855
-
856
- Summarization is running in the background.`)}catch(n){let s=n instanceof Error?n.message:String(n);return Jg.error("Failed to start compact",{sessionId:o,error:s}),Yg(o,false,`\u2298 Failed to start compaction: ${s}`,{error:s})}},init:async()=>({})});var Xg=[ku,Pu,Tu,Eu,Au,Ru,Lu,Du,$u,Fu,Uu,zu];var eh=a.create({service:"command.registry"}),So;(P=>{P.Info=U.object({name:U.string(),description:U.string().optional(),agent:U.string().optional(),model:U.string().optional(),source:U.enum(["command","mcp","skill"]).optional(),subtask:U.boolean().optional(),hints:U.array(U.string()).optional(),commandType:U.enum(["prompt","local"]).optional(),isHidden:U.boolean().optional(),isEnabled:U.any().optional(),execute:U.any()}).meta({ref:"Command"}),P.Default={INIT:"init",REVIEW:"review",BTW:"btw"},P.Event={Executed:a$5.define("command.executed",U.object({name:U.string(),sessionId:Identifier.schema("session"),arguments:U.union([U.string(),U.record(U.string(),U.unknown())]),messageId:Identifier.schema("message")}))},P.define=f;let s,r;async function i(I){let A={};return I.init&&await I.init(A),{name:I.name,description:I.description,agent:I.agent,model:I.model,source:I.source,subtask:I.subtask,hints:I.hints,commandType:I.commandType,isEnabled:I.isEnabled,scope:I.scope??"all",execute:I.execute}}async function c(I){let{glob:A}=await import('glob'),S={};if(!await Filesystem.isDir(I))return S;let w=await A("*.md",{cwd:I,absolute:true,nodir:true,follow:false,dot:false});for(let y of w)try{let{ConfigMarkdown:b}=await import('./markdown-Z6UXVBNP.mjs'),C=await b.parse(y),{CommandMetadataSchema:E}=await import('@easbot/plugin'),O=E.parse(C.data),D=c$3(O,C.content,"command");S[D.name]=D;}catch(b){eh.error("Failed to load command file",{file:y,error:b});}return S}function l(){return s||(s=R.state(async()=>{let I=await he.get(),A={};for(let S of Xg){let w=await i(S);A[S.name]=w;}for(let[S,w]of Object.entries(I.command??{})){let y=typeof w.template=="string"?w.template:"";A[S]={name:S,agent:w.agent,model:w.model,scope:w.scope??"all",description:w.description,source:"command",subtask:w.subtask,hints:/\{\{ARGUMENTS\}\}/i.test(y)?["{{ARGUMENTS}}"]:[],commandType:"prompt",isEnabled:()=>true,execute:async(b,C)=>{let{replaceTemplateVars:E}=await import('./command-CPT2YSIR.mjs'),O=E(y,b);return {title:S,metadata:{sessionId:C.sessionId},output:O,success:true,parts:[{type:"text",text:O}]}}};}for(let[S,w]of Object.entries(await Ue.prompts()))A[S]={name:S,source:"mcp",scope:w.scope??"all",description:w.description,commandType:"prompt",hints:w.arguments?.map((y,b)=>`$${b+1}`)??[],isEnabled:()=>true,execute:async y=>{if(typeof y=="string"){let O=(y.match(/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi)??[]).map(ee=>ee.replace(/^["']|["']$/g,"")),D=w.arguments?Object.fromEntries(w.arguments.map((ee,N)=>[ee.name,O[N]??""])):{},K=(await Ue.getPrompt(w.client,w.name,D))?.messages.map(ee=>ee.content.type==="text"?ee.content.text:"").join(`
857
- `)||"";return {title:S,metadata:{},output:K,success:true,parts:[{type:"text",text:K}]}}let C=(await Ue.getPrompt(w.client,w.name,y))?.messages.map(E=>E.content.type==="text"?E.content.text:"").join(`
858
- `)||"";return {title:S,metadata:{},output:C,success:true,parts:[{type:"text",text:C}]}}};for(let S of await Qt.all())A[S.name]={name:S.name,description:S.description,source:"skill",commandType:"prompt",hints:[],scope:S.scope??"all",isEnabled:()=>true,execute:async(w,y)=>({title:S.name,metadata:{sessionId:y.sessionId},output:S.content,success:true,parts:[{type:"text",text:S.content}]})};if(r)for(let[S,w]of Object.entries(r))A[S]=w;for await(let S of Filesystem.up({targets:[".easbot/commands"],start:R.directory,stop:R.worktree})){let w=await c(S);for(let[y,b]of Object.entries(w))A[y]||(A[y]=b);}return A})),s}async function d(){return l()()}P.state=d;async function m(){return d()}P.all=m;async function f$1(I){return d().then(A=>A[I])}P.get=f$1;async function a(I){let A=await d(),S=I??"general",w=[];for(let y of Object.values(A)){let b=y.scope??"all";b!=="all"&&b!==S||y.isEnabled&&!await y.isEnabled()||w.push(y);}return w}P.list=a;async function p(I,A){r||(r=await d()),r[I]=A,h();}P.register=p;async function u(I){return r?.[I]?(delete r[I],h(),true):false}P.unregister=u;function h(){s=void 0;}async function g(){r=void 0,h(),await d();}P.refresh=g;async function v(){await d(),eh.debug("command registry initialized");}P.init=v;})(So||(So={}));var qu=So;async function th(e){return (await So.list(e)).map(n=>({name:n.name,description:n.description,source:n.source,subtask:n.subtask,hints:n.hints??[],agent:n.agent,model:n.model,commandType:n.commandType}))}var tT=th;var Bo={};a$7(Bo,{add:()=>sT,addMcpServer:()=>vT,authCallback:()=>wT,authenticate:()=>mT,clients:()=>xT,connect:()=>rT,disconnect:()=>iT,finishAuth:()=>fT,getAuthStatus:()=>bT,getMcpServerInfo:()=>CT,getPrompt:()=>lT,hasStoredTokens:()=>yT,list:()=>nT,listMcpServers:()=>IT,prompts:()=>cT,readResource:()=>uT,removeAuth:()=>gT,removeMcpServer:()=>ST,resources:()=>dT,startAuth:()=>pT,status:()=>oT,supportsOAuth:()=>hT,tools:()=>aT});async function oT(){return Ue.status()}async function nT(){return Ue.status()}async function sT(e,t){await Ue.add(e,t);return Ue.status()}async function rT(e){await Ue.connect(e);return Ue.status()}async function iT(e){await Ue.disconnect(e);return Ue.status()}async function aT(){return Ue.tools()}async function cT(){return Ue.prompts()}async function dT(){return Ue.resources()}async function lT(e,t,o){return Ue.getPrompt(e,t,o)}async function uT(e,t){return Ue.readResource(e,t)}async function pT(e){return Ue.startAuth(e)}async function mT(e){return Ue.authenticate(e)}async function fT(e,t){return Ue.finishAuth(e,t)}async function gT(e){return Ue.removeAuth(e)}async function hT(e){return Ue.supportsOAuth(e)}async function yT(e){return Ue.hasStoredTokens(e)}async function bT(e){return Ue.getAuthStatus(e)}async function wT(e,t){return Ue.finishAuth(e,t)}async function xT(){return Ue.clients()}async function IT(){let t=(await he.get()).mcp??{};return Object.entries(t).map(([o,n])=>({name:o,...n}))}async function vT(e){let{name:t,...o}=e;return await he.update({mcp:{[t]:o}}),{name:t,...o}}async function ST(e){await he.update({mcp:{[e]:void 0}});}async function CT(e){let o=(await he.get()).mcp?.[e];return o?{name:e,...o}:null}var sd={};a$7(sd,{getLspStatus:()=>oh,status:()=>kT});var Hu=a.create({service:"agent-cli-api-lsp"});async function oh(){try{Hu.debug("Get LSP status");let e=await We.status();return Hu.debug("Get LSP status successful",{count:e.length}),e}catch(e){throw Hu.error("Failed to get LSP status",{error:e}),e}}var kT=oh;var qn={};a$7(qn,{publish:()=>PT,subscribe:()=>RT,subscribeAll:()=>AT,subscribeMessage:()=>MT,subscribeSession:()=>_T});var Mo=a.create({service:"agent-cli-api-events"});async function PT(e){try{Mo.debug("Publish event",{eventType:e.type});let t=a$5.define(e.type,U.record(U.string(),U.any()));await ue.publish(t,e.properties??{});}catch(t){throw Mo.error("Publish event failed",{eventType:e.type,error:t}),t}}function nh(e){return typeof e!="object"||e===null?false:typeof e.sessionId=="string"}function TT(e){return nh(e)?typeof e.messageId=="string":false}function sh(e){if(nh(e))return e.sessionId}function ET(e){if(TT(e))return e.messageId}async function AT(e){try{Mo.debug("Subscribe all events");let t=await ue.subscribeAll(e);return Mo.debug("Subscribe all events success"),t}catch(t){throw Mo.error("Subscribe all events failed",{error:t}),t}}async function RT(e,t){try{Mo.debug("Subscribe event",{eventType:e});let o=await ue.subscribeAll(n=>{n.type===e&&t(n);});return Mo.debug("Subscribe event success",{eventType:e}),o}catch(o){throw Mo.error("Subscribe event failed",{eventType:e,error:o}),o}}async function _T(e,t){try{Mo.debug("Subscribe session events",{sessionId:e});let o=await ue.subscribeAll(n=>{sh(n.properties)===e&&t(n);});return Mo.debug("Subscribe session events success",{sessionId:e}),o}catch(o){throw Mo.error("Subscribe session events failed",{sessionId:e,error:o}),o}}async function MT(e,t,o){try{Mo.debug("Subscribe message events",{sessionId:e,messageId:t});let n=await ue.subscribeAll(s=>{let r=sh(s.properties),i=ET(s.properties);r===e&&(t===void 0||i===t)&&o(s);});return Mo.debug("Subscribe message events success",{sessionId:e,messageId:t}),n}catch(n){throw Mo.error("Subscribe message events failed",{sessionId:e,messageId:t,error:n}),n}}var rd={};a$7(rd,{all:()=>OT});function OT(){return Qt.all()}var ea={};a$7(ea,{remove:()=>LT,set:()=>jT});async function jT(e,t){return Qe.set(e,t)}async function LT(e){return Qe.remove(e)}var qs={};a$7(qs,{current:()=>FT,initGit:()=>NT,list:()=>$T,update:()=>UT});async function $T(){return qt.list()}async function FT(){return R.project}async function NT(e){let t=e.directory||R.directory,o=await git(["init"],{cwd:t});if(o.exitCode!==0)throw new Error(`Git init failed: ${await o.text()}`);return R.project}async function UT(e,t){return R.project}var Hn={};a$7(Hn,{connect:()=>VT,create:()=>HT,get:()=>qT,list:()=>zT,remove:()=>GT,resize:()=>WT,update:()=>BT});async function zT(){return nt.list()}async function qT(e){return nt.get(e)}async function HT(e){return nt.create(e)}async function BT(e,t){return nt.update(e,t)}async function GT(e){return nt.remove(e)}async function WT(e,t,o){return nt.resize(e,t,o)}async function VT(e){return nt.get(e)}var rh;(t=>{async function e(){return []}t.list=e;})(rh||(rh={}));var qr={};a$7(qr,{list:()=>JT,listQuestions:()=>ih,reject:()=>XT,rejectQuestion:()=>ch,reply:()=>YT,replyQuestion:()=>ah});async function ih(){return Ot.list()}async function ah(e){return await Ot.reply(e),true}async function ch(e){return await Ot.reject(e.requestId),true}var JT=ih,YT=ah,XT=ch;var Hs={};a$7(Hs,{list:()=>QT,read:()=>ZT,search:()=>tE,status:()=>eE});async function QT(e){return yt.list(e.path)}async function ZT(e){return yt.read(e.path)}async function eE(){return yt.status()}async function tE(e){return yt.search(e)}var id={};a$7(id,{dispose:()=>oE});async function oE(){return R.dispose()}var Hr={};a$7(Hr,{list:()=>nE,listPermissions:()=>dh,reply:()=>sE,replyPermission:()=>lh,respond:()=>rE,respondPermission:()=>uh});async function dh(){return Oe.list()}async function lh(e){return await Oe.reply(e),true}async function uh(e){return await Oe.reply({requestId:e.permissionId,reply:e.response}),true}var nE=dh,sE=lh,rE=uh;var fd={};a$7(fd,{getContext:()=>WE,getProtocolMetadata:()=>VE});var ph=a.create({service:"context-workspace"}),Wu=".easbot",aE="protocol.json",mh=1;function cE(e){return Ce__default.join(e,aE)}async function Vu(e){try{let t=await Tt__default.readFile(e,"utf-8"),o=JSON.parse(t);return {version:mh,bootstrapSeededAt:o.bootstrapSeededAt,setupCompletedAt:o.setupCompletedAt,metadata:o.metadata}}catch{return {version:mh}}}async function ta(e){return e?Ce__default.join(e,Wu):Ce__default.join(R.directory,Wu)}async function ad(e){let t=e?await ta(e):await ta(),o=cE(t);ph.debug("isSetupCompleted checking",{workspace:e,easbotDir:t,statePath:o});let n=await Vu(o),s=typeof n.setupCompletedAt=="string"&&n.setupCompletedAt.trim().length>0;return ph.debug("isSetupCompleted result",{statePath:o,setupCompletedAt:n.setupCompletedAt,completed:s}),s}var ro=a.create({service:"context-instructions"});async function lE(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()=>wo.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()}],o=["| Tool | Description |","|------|-------------|"];for(let n of t)await n.condition()&&o.push(`| \`${n.name}\` | ${n.description} |`);return o.join(`
859
- `)}async function uE(e){let t=["| Directory | Description |","|-------------|-------------|"],o=[{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 n of o)if(n.condition?await n.condition():true){let r=await n.path();t.push(`| \`${r}/\` | ${n.description} |`);}return t.join(`
860
- `)}async function Ku(e,t){let o=e;if(o.includes("{{tools}}"))try{o=o.replace("{{tools}}",await lE(t));}catch(s){ro.warn("failed to render {{tools}} placeholder",{error:String(s)}),o=o.replace("{{tools}}","");}if(o.includes("{{directories}}"))try{o=o.replace("{{directories}}",await uE(t));}catch(s){ro.warn("failed to render {{directories}} placeholder",{error:String(s)}),o=o.replace("{{directories}}","");}o=o.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(s,r,i)=>{let c=t[r];return c!=null&&c!==0&&c!==""?i:""}),o=o.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 n={};return t.metadata&&Object.entries(t.metadata).forEach(([s,r])=>{n[s]=r;}),Object.entries(t).forEach(([s,r])=>{s==="metadata"||s==="tools"||s==="directories"||s==="files"||(n[s]=r);}),Object.keys(n).length>0&&(o=a$9.replaceVariables(o,n)),o}function pE(e){let t=`| File | Priority | Description | Scope | Type | Permission | Location | Status |
861
- |------|----------|-------------|-------|------|------------|----------|--------|`,o=e.map(n=>`| ${n.name} | ${n.priority} | ${n.description} | ${n.scope} | ${n.type} | ${n.permission} | ${n.location} | ${n.status} |`).join(`
862
- `);return `${t}
863
- ${o}`}function fn(e){if(e)return typeof e=="string"?e:String(e)}function Ju(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 gh(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true"}}function dd(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(o=>String(o))}catch{return e.split(",").map(t=>t.trim())}}}function hh(e,t){return e.scope===i?true:e.scope===t}function mE(e,t){return !e.owner||e.owner.length===0?true:t?!!(e.owner.includes(t)||e.share?.includes(t)):false}async function fE(e,t,o){if(await Filesystem.isDir(e))try{let n=await Tt__default.readdir(e,{withFileTypes:!0});for(let s of n){if(!s.isFile()||!s.name.endsWith(".md"))continue;let r=s.name;if(!l.includes(r)||t.has(r))continue;let i=Ce__default.join(e,r),c=await ld(i,o);c&&t.set(r,c);}}catch(n){ro.warn("failed to scan builtin system files",{dir:e,error:String(n)});}}async function gE(e,t,o){for(let[n$1,s]of Object.entries(n))if(!o.has(n$1))for await(let r of Filesystem.up({targets:[s],start:e,stop:R.worktree})){let i=await ld(r,t);if(i){o.set(n$1,i);break}}}async function hE(e,t,o){let n=Ce__default.join(e,"rules"),s=new Map;if(!await Filesystem.isDir(n))return s;try{let r=await Tt__default.readdir(n,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(".md")||t.has(i.name))continue;let c=Ce__default.join(n,i.name),l=await ld(c,o);l&&s.set(i.name,l);}}catch(r){ro.warn("failed to scan rules directory",{dir:n,error:String(r)});}return s}async function yE(e,t,o,n){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=Ce__default.join(e,f.name),p=await ld(a,n);if(!p)continue;let u=yh(m,i$1,p.frontmatter);hh(u,t)&&mE(u,o)&&s.set(m,{...p,config:u});}}catch(d){ro.warn("failed to load context files",{root:e,error:String(d)});}return s}function yh(e,t,o){let n=p[e],s=t?.[e];return {name:e,type:fn(o?.type)??s?.type??n?.type??"system",scope:fn(o?.scope)??s?.scope??n?.scope??"all",priority:Ju(o?.priority)??s?.priority??n?.priority??q,owner:dd(o?.owner)??s?.owner??n?.owner,share:dd(o?.share)??s?.share??n?.share,permission:fn(o?.permission)??s?.permission??n?.permission??"read",description:fn(o?.description)??s?.description??n?.description,dynamic:gh(o?.dynamic)??s?.dynamic??n?.dynamic}}function cd(e,t,o,n,s,r=false){let i=o.permission==="write"?"writable":"readonly",c=`<file path="${n}" priority="${s}" mode="${i}">
864
- ${t}
865
- </file>`;return {name:e,content:c,priority:s,dynamic:r,location:n,permission:o.permission,owner:o.owner,share:o.share}}async function bE(e,t){try{if(await ad(e))return ro.debug("workspace already initialized, skipping builtin bootstrap"),null;let n=null,s="",r=await Qt.get("eas-agent-evolution");if(r){let l=Ce__default.join(Ce__default.dirname(r.location),"assets","BOOTSTRAP.md");try{n=await Tt__default.readFile(l,"utf-8"),s=l;}catch{}}if(!n){let l=m.replace(".md","");n=await loadTextFileAsync(`./template/${l}.txt`,import.meta.url)(),n&&(s=`context/template/${l}.txt`);}if(!n)return ro.debug("builtin bootstrap template not found"),null;let i=await Ku(n,t).catch(l=>(ro.warn("renderTemplate failed for bootstrap, using raw content",{error:String(l)}),n)),c=p[m]??{name:m,type:"system",scope:"all",priority:20};return ro.debug("loaded builtin bootstrap template",{location:s}),cd(m,i,c,`<builtin:${s}>`,c.priority??20,!1)}catch(o){return ro.warn("failed to load builtin bootstrap",{error:String(o)}),null}}function wE(e,t,o$1=false){let n$1=[],s=(r,i$1)=>{let c=i$1?.frontmatter||{},l=p[r],d=fn(c.scope)||l?.scope||i;d!==i&&d!==t||o$1&&!o.includes(r)||n$1.push({name:r,priority:Ju(c.priority)||l?.priority||q,description:fn(c.description)||l?.description||"",scope:d,type:fn(c.type)||l?.type||"system",permission:fn(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 n$1.sort((r,i)=>r.priority-i.priority),n$1}async function xE(e,t){let o={};try{let s=`${await ta(e)}/protocol.json`,r=await Vu(s);o.metadata=r.metadata;}catch(n){ro.debug("failed to read protocol for render context",{error:String(n)});}return o}async function ld(e,t){let o=t??{};try{let n=await a$9.parse(e);return {content:await Ku(n.content,o).catch(r=>(ro.warn("renderTemplate failed on parsed content, using raw",{filePath:e,error:String(r)}),n.content)),frontmatter:n.data,location:e}}catch(n){if(n.code==="ENOENT")return null;try{let s=await Tt__default.readFile(e,"utf-8");return ro.warn("failed to parse frontmatter, using raw content",{filePath:e,error:String(n)}),{content:await Ku(s,o).catch(i=>(ro.warn("renderTemplate failed on raw content, using as-is",{filePath:e,error:String(i)}),s)),frontmatter:{},location:e}}catch(s){return ro.warn("failed to load template file",{filePath:e,error:String(s)}),null}}}async function IE(e){let t=e.mode??f$1,o$1=e.workspaceDir??R.directory,n=e.agent?.mode==="subagent",s=e.agent?.name,r$1=[],i=new Set,c=new Map,l=await xE(o$1),d=e.protocolInitialized??await ad(o$1);if(ro.debug("loadTemplatesForMode: initialization status",{workspaceDir:o$1,isInitialized:d,protocolInitializedProvided:e.protocolInitialized!==void 0}),d){for await(let m of Filesystem.up({targets:[".easbot"],start:o$1,stop:R.worktree}))await fE(m,c,l);await gE(o$1,l,c);for(let[m,f]of c){if(i.has(m)||n&&!o.includes(m))continue;let a=yh(m,void 0,f.frontmatter);if(!hh(a,t))continue;let p=a.priority??q,u=m==="HEARTBEAT.md"||a.dynamic===true;r$1.push(cd(m,f.content,a,f.location,p,u)),i.add(m);}}else {let m$1=await bE(o$1,l);m$1&&(r$1.push(m$1),i.add(m));}for await(let m of Filesystem.up({targets:[".easbot"],start:o$1,stop:R.worktree})){let f=await hE(m,i,l);for(let[p,u]of f){if(i.has(p))continue;let h={scope:fn(u.frontmatter?.scope)??"all",priority:Ju(u.frontmatter?.priority)??r,permission:fn(u.frontmatter?.permission)??"read",dynamic:gh(u.frontmatter?.dynamic)??true,owner:dd(u.frontmatter?.owner),share:dd(u.frontmatter?.share),description:fn(u.frontmatter?.description)};r$1.push(cd(p,u.content,h,u.location,h.priority,h.dynamic)),i.add(p);}let a=await yE(m,t,s,l);for(let[p,u]of a)i.has(p)||(r$1.push(cd(p,u.content,u.config,u.location,u.config.priority??q)),i.add(p));}if(l.files=wE(c,t,n),l.files&&l.files.length>0)try{let m=pE(l.files);for(let f of r$1)f.content.includes("{{files}}")&&(f.content=f.content.replace("{{files}}",m));}catch(m){ro.warn("failed to render {{files}} placeholder",{error:String(m)});}return r$1.sort((m,f)=>m.priority-f.priority),ro.debug("templates loaded from filesystem",{mode:t,workspaceDir:o$1,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 fh=new Map;async function bh(e){let t=e.mode??f$1,o=e.workspaceDir??R.directory,s=e.agent?.mode==="subagent"?e.agent.name:"primary",r=o?`template:${t}:${s}:${o}`:`template:${t}:${s}`,i=fh.get(r);if(i)return i;let l={sections:await IE(e),mode:t,loadedAt:Date.now()};return fh.set(r,l),l}async function Yu(e){return (await bh(e)).sections}var us=a.create({service:"file-cache"}),wh=25*1024*1024,xh=100,Qu=class{constructor(t=xh,o=wh){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=o,this.currentSizeBytes=0;}get(t){let o=this.cache.get(t);return o!==void 0&&(this.cache.delete(t),this.cache.set(t,o)),o}set(t,o){for(this.cache.has(t)&&(this.cache.delete(t),this.currentSizeBytes-=this.estimateSize(o));this.cache.size>=this.maxEntries||this.currentSizeBytes>=this.maxSizeBytes;){let n=this.cache.keys().next().value;if(n!==void 0){let s=this.cache.get(n);s!==void 0&&(this.currentSizeBytes-=this.estimateSize(s)),this.cache.delete(n),us.debug("cache entry evicted",{key:n});}else break}this.cache.set(t,o),this.currentSizeBytes+=this.estimateSize(o);}has(t){return this.cache.has(t)}delete(t){let o=this.cache.get(t);return o!==void 0&&(this.currentSizeBytes-=this.estimateSize(o)),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()}},ud=class{constructor(t=xh,o=wh){b$1(this,"maxEntries",t);b$1(this,"maxSizeBytes",o);b$1(this,"cache");this.cache=new Qu(this.maxEntries,this.maxSizeBytes),us.debug("file state cache created",{maxEntries:this.maxEntries,maxSizeBytes:this.maxSizeBytes});}async readFile(t,o){try{let n=await Tt__default.stat(t),s=n.mtimeMs,r=this.cache.get(t);if(r&&r.timestamp===s&&r.offset===o?.offset&&r.limit===o?.limit)return us.debug("cache hit",{filePath:t}),r.content;let i;if(o?.offset!==void 0||o?.limit!==void 0){let d=(await Tt__default.readFile(t,"utf-8")).split(`
866
- `),m=o.offset??0,f=o.limit?m+o.limit:d.length;i=d.slice(m,f).join(`
867
- `);}else i=await Tt__default.readFile(t,"utf-8");let c={content:i,timestamp:s,lineCount:i.split(`
868
- `).length,size:n.size,offset:o?.offset,limit:o?.limit};return this.cache.set(t,c),us.debug("cache miss, file read",{filePath:t,size:n.size}),i}catch(n){if(n.code==="ENOENT"){this.cache.delete(t);return}throw n}}getState(t){return this.cache.get(t)}async detectChanges(){let t=[];for(let[o,n]of this.cache.entries())try{let s=await Tt__default.stat(o);if(s.mtimeMs!==n.timestamp){let r=await Tt__default.readFile(o,"utf-8");t.push({path:o,oldContent:n.content,newContent:r,oldMtime:n.timestamp,newMtime:s.mtimeMs}),this.cache.set(o,{...n,content:r,timestamp:s.mtimeMs});}}catch(s){s.code==="ENOENT"&&(t.push({path:o,oldContent:n.content,newContent:"",oldMtime:n.timestamp,newMtime:0}),this.cache.delete(o));}return t.length>0&&us.info("file changes detected",{count:t.length}),t}invalidate(t){this.cache.delete(t),us.debug("cache invalidated",{filePath:t});}invalidateAll(){this.cache.clear(),us.info("all cache invalidated");}has(t){return this.cache.has(t)}clear(){this.cache.clear(),us.info("cache cleared");}get size(){return this.cache.size}get sizeBytes(){return this.cache.sizeBytes}getFilePaths(){return Array.from(this.cache.keys())}},Xu=null;function Wr(e,t){return Xu||(Xu=new ud(e,t)),Xu}var Vr=a.create({service:"static-prompt"}),Bs;(f=>{let e$1;function t(){return e$1||(e$1=R.state(()=>({promptCache:new Map,fileCache:Wr()}))),e$1}function o(){return t()()}function n(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=o(),g=u?.mode,v=s(a,p,g),P=h.promptCache.get(v);return P&&P.configHash===n(a,p,g)?(Vr.debug("static prompt cache hit",{cacheKey:v}),P.sections):null}f.getCached=r;function i(a,p,u,h){let g=o(),v=h?.mode,P=s(a,p,v),I={sections:u,configHash:n(a,p,v),builtAt:Date.now()};g.promptCache.set(P,I),Vr.debug("static prompt cached",{cacheKey:P,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;Vr.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 Yu(a);return i(a,p,h,a.agent),Vr.debug("static prompt built",{length:h.length}),h}f.buildStaticPrompt=c;function l(a,p){let u=o();if(a&&p){for(let h of e){let g=`${a}/${p}/${h}`;u.promptCache.delete(g);}Vr.debug("static prompt cache entries invalidated",{agentName:a,modelId:p});}else u.promptCache.clear(),Vr.debug("all static prompt cache invalidated");}f.invalidateCache=l;function d(){let a=o(),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 o().fileCache}f.getFileCache=m;})(Bs||(Bs={}));var sa;(m=>{let e=a.create({service:"summary"}),t=loadTextFile("./memory-summary.txt",import.meta.url),o=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 Se.defaultModel(),p=f??await Se.getModel(a.providerId??"default",a.modelId??"default");return Se.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(`
869
- `)}).join(`
870
- `)}async function l(f,a){let{query:p,chunks:u,model:h,maxLength:g}=f;if(u.length===0)return "";let v=await i(h),P=o()??"Synthesize the following document chunks into a concise summary relevant to the query. Order by Priority descending.",I=u.map((w,y)=>{let b=w.startLine!=null?`#L${w.startLine}-L${w.endLine??w.startLine}`:"",C=w.score??0,E=`[Chunk ${y+1}] Priority: ${C.toFixed(3)}
871
- Source: [${w.path}](./${w.path}${b})
872
- ${w.content}`;return !w.nodes||w.nodes.length===0?E:`${E}
873
- Graph Nodes:
874
- ${c(w.nodes)}`}).join(`
875
-
876
- `),A=`[Query]
877
- ${p}
878
-
879
- [Knowledge Chunks]
880
- ${I}`;e.debug("note summary started",{query:p,chunkCount:u.length});let S=await r(v,P,A,g??1e3,a);return e.debug("note summary completed",{summaryLength:S.length}),S.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 v=await i(h),P=t()??"Synthesize the following memory facts into a concise summary relevant to the query. Order by Priority descending.",I=u.map((w,y)=>{let b=w.score??0,C=`[Fact ${y+1}] Priority: ${b.toFixed(3)}
881
- Category: ${w.category} | Importance: ${w.importance} | Source: ${w.source}
882
- ${w.content}`;if(!w.nodes||w.nodes.length===0)return C;let E=w.nodes.map(O=>{let D=[` - node: id=${O.id} type=${O.type} name=${O.name}`];if(O.edges&&O.edges.length>0)for(let $ of O.edges){let K=$.direction??($.source===O.id?"out":"in");D.push(` \u2192 [${K}] ${$.relation} \u2192 target=${$.targetNode?.type??"node"}:${$.targetNode?.name??`id=${$.target}`} (id=${$.target})`);}return D.join(`
883
- `)}).join(`
884
- `);return `${C}
885
- Graph Nodes:
886
- ${E}`}).join(`
887
-
888
- `),A=`[Query]
889
- ${p}
890
-
891
- [Memory Facts]
892
- ${I}`;e.debug("memory summary started",{query:p,factCount:u.length});let S=await r(v,P,A,g??1e3,a);return e.debug("memory summary completed",{summaryLength:S.length}),S.trim()}m.summarizeMemoryFacts=d;})(sa||(sa={}));a.create({service:"context-token"});function ps(e){return e?Token.estimate(e):0}var Zu=800,ra=a.create({service:"dynamic-prompt"}),ia;(l=>{async function e(d){let m=[],{mode:f}=d,a=d.useLLMSummary??true,p=d.maxTokens??Zu;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 o(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 un.get(d.sessionId),h=n(u);m.push(h);}catch(u){ra.warn("failed to load todos for dynamic prompt",{error:String(u)});}if((d.includeTaskAgents??true)&&d.sessionId)try{let u=await Lt.list(d.sessionId),h=s(u);h&&m.push(h);}catch(u){ra.warn("failed to load task agents for dynamic prompt",{error:String(u)});}if(f==="coder"&&d.includeCoderContext){let u=i();m.push(...u);}return ra.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=Zu){if(m.length===0)return `<memory>
893
- ## Memory Summary
894
-
895
- No memory found.
896
- </memory>`;if(f)try{return `<memory>
897
- ## Memory Summary
898
-
899
- ${await sa.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(v=>({id:v.id,name:v.name,type:v.type,edges:v.edges?.map(P=>({source:P.source,target:P.target,relation:P.relation,direction:P.source===v.id?"out":"in",targetNode:P.targetNode?{name:P.targetNode.name,type:P.targetNode.type}:void 0}))}))})),maxLength:a})}
900
- </memory>`}catch(h){ra.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],v=new Date(g.createdAt).getTime(),P=(Date.now()-v)/864e5,I=Math.exp(-0.1*P),A=(g.importance-1)/9,S=.35*g.score+.35*I+.3*A;if(p.push(`[${h+1}] Priority: ${S.toFixed(3)}`),p.push(`Category: ${g.category} | Importance: ${g.importance} | Source: ${g.source}`),g.nodes&&g.nodes.length>0){let y=[];for(let O of g.nodes){let D=O.edges&&O.edges.length>0?O.edges.map($=>` --[${$.source===O.id?"out":"in"}] ${$.relation}--> ${$.targetNode?.name??`node:${$.target}`} (${$.targetNode?.type??"node"})`).join(`
901
- `):" (no relations)";y.push(` Node: ${O.name} (${O.type})
902
- ${D}`);}let b=y.join(`
903
- `),C=Math.floor(u*4*.5),E=c(b,C);p.push(`Graph Nodes:
904
- ${E}`);}let w=Math.max(0,u-ps(p.join(`
905
- `)));if(w>30){let y=Math.floor(w*4),b=c(g.snippet,y);p.push(b);}p.push("");}return p.push("</memory>"),p.join(`
906
- `)}l.buildMemorySummary=t;async function o(d,m,f,a=Zu){if(m.length===0)return `<note>
907
- ## Knowledge Summary
908
-
909
- No knowledge found.
910
- </note>`;if(f)try{return `<note>
911
- ## Knowledge Summary
912
-
913
- ${await sa.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(v=>({id:v.id,name:v.name,type:v.type,properties:v.properties,edges:v.edges?.map(P=>{let I=P.source===v.id?"out":"in",A=g.nodes?.find(S=>S.id===P.target);return {direction:I,relation:P.relation,targetId:P.target,targetName:A?.name??String(P.target),targetType:A?.type??"node"}})}))})),maxLength:a})}
914
- </note>`}catch(h){ra.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],v=g.chunk.startLine!=null?`#L${g.chunk.startLine}-L${g.chunk.endLine??g.chunk.startLine}`:"",P=.7*(g.score??0);if(p.push(`[${h+1}] Priority: ${P.toFixed(3)}`),p.push(`Source: [${g.chunk.path}](./${g.chunk.path}${v})`),g.nodes&&g.nodes.length>0){let A=[];for(let b of g.nodes){let C=b.edges&&b.edges.length>0?b.edges.map(E=>` --[${E.source===b.id?"out":"in"}] ${E.relation}--> node:${E.target} (node)`).join(`
915
- `):" (no relations)";A.push(` Node: ${b.name} (${b.type})
916
- ${C}`);}let S=A.join(`
917
- `),w=Math.floor(u*4*.5),y=c(S,w);p.push(`Graph Nodes:
918
- ${y}`);}let I=Math.max(0,u-ps(p.join(`
919
- `)));if(I>20){let A=Math.floor(I*4),S=c(g.chunk.content,A);p.push(S);}p.push("");}return p.push("</note>"),p.join(`
920
- `)}l.buildKnowledgeSummary=o;function n(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(`
921
- `);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(`
922
- `)}l.buildTodosSummary=n;function s(d){let m=["<tasks>","## Agent Tasks",""];if(!d||d.length===0)return m.push("No running tasks."),m.push("</tasks>"),m.join(`
923
- `);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(`
924
- `);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(`
925
- `)}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(`
926
- `)}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(`
927
- `),p=a>m*.8?a:m;return d.slice(0,p).trimEnd()+`
928
- [...truncated...]`}})(ia||(ia={}));var kE=loadTextFile("./prompt/anthropic.txt",import.meta.url)(),PE=loadTextFile("./prompt/default.txt",import.meta.url)(),TE=loadTextFile("./prompt/beast.txt",import.meta.url)(),EE=loadTextFile("./prompt/gemini.txt",import.meta.url)(),AE=loadTextFile("./prompt/codex.txt",import.meta.url)(),RE=loadTextFile("./prompt/gpt.txt",import.meta.url)(),_E=loadTextFile("./prompt/trinity.txt",import.meta.url)(),ME=loadTextFile("./prompt/kimi.txt",import.meta.url)(),OE=loadTextFile("./prompt/qwen.txt",import.meta.url)(),jE=loadTextFile("./prompt/glm.txt",import.meta.url)(),LE=loadTextFile("./prompt/minimax.txt",import.meta.url)();function ep(e){let t=e.model.id.toLowerCase(),o=e.protocolMetadata;return t.includes("gpt-4")||t.includes("o1")||t.includes("o3")?[a$9.replaceVariables(TE,o)]:t.includes("gpt")?t.includes("codex")?[a$9.replaceVariables(AE,o)]:[RE]:t.includes("gemini-")?[a$9.replaceVariables(EE,o)]:t.includes("claude")?[a$9.replaceVariables(kE,o)]:t.includes("trinity")?[a$9.replaceVariables(_E,o)]:t.includes("kimi")?[a$9.replaceVariables(ME,o)]:t.includes("qwen")?[a$9.replaceVariables(OE,o)]:t.includes("glm")?[a$9.replaceVariables(jE,o)]:t.includes("minimax")?[a$9.replaceVariables(LE,o)]:[a$9.replaceVariables(PE,o)]}function DE(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 $E(e,t){if(Oe.disabled(["skill"],e.permission).has("skill"))return [];let o=await Qt.available(e,t);return ["<skills>",Qt.format(o,{verbose:false}),"</skills>"]}async function tp(e){let{Instance:t}=await import('./instance-S5GBRS3K.mjs'),o=t.project,n=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: ${o.vcs==="git"?"yes":"no"}`),r.push(` Platform: ${process.platform}`),r.push(` Local time: ${formatLocalISOCompact(n)} (${s})`),r.push(` UTC time: ${n.toISOString()}`),r.push("</env>"),r.push(...DE(e.mode)),r.push(...await $E(e.agent,e.mode)),[r.join(`
929
- `)]}var aa=a.create({service:"context-search"});async function op(e,t,o){try{let n=await wo.get();return !n||!t?[]:await n.query(t,{agentId:e.agent.name,maxResults:o,minScore:.2})}catch(n){return aa.warn("memory search error",{error:String(n)}),[]}}async function np(e,t,o){try{let n=await Yt.get();if(!n||!t)return aa.debug("searchKnowledge: kb or query not available",{kb:!!n,query:!!t}),[];aa.debug("searchKnowledge: calling kb.search",{query:t,maxResults:o,minScore:.3});let s=await n.search(t,{maxResults:o,minScore:.3});return aa.debug("searchKnowledge: kb.search returned",{query:t,resultsCount:s.length,results:s.map(r=>({score:r.score,path:r.document.path}))}),s}catch(n){return aa.warn("knowledge search error",{error:String(n)}),[]}}var Bn=a.create({service:"context-engine"}),NE=loadTextFile("./prompt/max-steps.txt",import.meta.url),UE=NE(),zE=loadTextFile("./prompt/plan.txt",import.meta.url),qE=zE(),HE=loadTextFile("./prompt/coder-plan.txt",import.meta.url),BE=HE(),GE=loadTextFile("./prompt/build-switch.txt",import.meta.url),Sh=GE();function ip(e,t,o){let n=o?`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}}",n)}var hn;(A=>{let e,t;async function o(){return t||(t=bi().then(S=>({mode:S.mode??f$1,fileCacheMaxEntries:S.fileCache?.maxEntries??100,fileCacheMaxBytes:S.fileCache?.maxBytes??25*1024*1024,maxTokens:S.maxTokens??2e3,searchMaxResults:S.searchMaxResults??3}))),t}function n(){return e||(e=R.state(async()=>{let S=await o(),w=R.directory,y={workspace:w,name:"EasBot",userName:"",mission:""},b=false;try{let C=Ce__default.join(w,".easbot"),E=Ce__default.join(C,"protocol.json"),O=await Tt__default.readFile(E,"utf-8"),D=JSON.parse(O);D.metadata&&(y={agentId:D.metadata.agentId,workspace:D.metadata.workspace||w,name:D.metadata.name||"EasBot",userName:D.metadata.userName||"",mission:D.metadata.mission||""}),b=typeof D.setupCompletedAt=="string"&&D.setupCompletedAt.trim().length>0;}catch{Bn.debug("protocol.json not found, using default metadata");}return {config:S,initialized:true,protocolInitialized:b,fileCache:Wr(),protocolMetadata:y}})),e}async function s(){return n()()}function r(S){t=Promise.resolve({mode:S.mode??f$1,fileCacheMaxEntries:S.fileCacheMaxEntries??100,fileCacheMaxBytes:S.fileCacheMaxBytes??25*1024*1024,maxTokens:S.maxTokens??2e3,searchMaxResults:S.searchMaxResults??3}),Bn.info("context engine configured",{mode:S.mode,maxTokens:S.maxTokens,searchMaxResults:S.searchMaxResults});}A.configure=r;async function i(){return (await s()).config}A.getConfig=i;async function c(S){let w=await s();return !w.protocolInitialized&&!w.protocolMetadata.agentId&&S&&(w.protocolMetadata.agentId=S.name),w.protocolMetadata}A.getProtocolMetadata=c;async function l(){let S=await s();return {protocolMetadata:S.protocolMetadata,protocolInitialized:S.protocolInitialized}}A.getContext=l;function d(){return Wr()}A.getFileCache=d;function m(S){let w=[];for(let y of S.parts)y.type==="text"&&y.text&&w.push(y.text);return w.join(" ").trim()}A.extractQuery=m;async function f(S){let w=await Le.triggerEvent(HookEvent.ContextBuildBefore,S,{sessionId:S.sessionId});w.modified&&w.output&&(S=w.output);let y=await s();y.protocolMetadata.agentId||(y.protocolMetadata.agentId=S.agent.name);let b=S.mode??y.config.mode??f$1,C=S.maxTokens??y.config.maxTokens??2e3,E=S.searchMaxResults??y.config.searchMaxResults??3,O=m(S.userMessage);Bn.debug("context build started",{sessionId:S.sessionId,mode:b,hasQuery:!!O,messageCount:S.messages.length});let[D,$]=[op(S,O,E).catch(G=>(Bn.warn("memory search failed",{error:String(G)}),[])),np(S,O,E).catch(G=>(Bn.warn("knowledge search failed",{error:String(G)}),[]))],K=Bs.buildStaticPrompt({mode:b,workspaceDir:S.session.directory,agent:S.agent,model:S.model,protocolMetadata:y.protocolMetadata,protocolInitialized:y.protocolInitialized});Bn.debug("ContextEngine.build: static prompt promise created",{sessionDirectory:S.session.directory,agent:S.agent.name,protocolInitialized:y.protocolInitialized});let[ee,N,M]=await Promise.all([K,D,$]),T=y.protocolMetadata,j=ee.map(G=>G.name),x=ee.map(G=>G.content),k=await ia.build({query:O,mode:b,sessionId:S.sessionId,memoryResults:N,knowledgeResults:M,includeTodos:true,includeCoderContext:b==="coder",useLLMSummary:true,maxTokens:C}),_=await a({sessionId:S.sessionId,model:S.model,agent:S.agent,user:S.user,workspace:S.session.directory,staticPrompt:x,staticPromptSources:j,dynamicParts:k,maxChars:C*4,protocolMetadata:y.protocolMetadata,mode:b}),{messages:L,lastUserMessage:H,lastAssistantMessage:Y}=await p(S),X=h(L,_),ne=S.model.limit?.context??0,ae=ne>0?ne:Se.DEFAULT_CONTEXT_LIMIT,be=Math.max(ae-2e4,5e4)-X,se=io.calculateTokenUsageState(X,S.model),Q=se.isAboveAutoCompactThreshold||se.isAtBlockingLimit;se.isAboveWarningThreshold&&Bn.warn("context window running low",{remaining:be,tokenEstimate:X,percentLeft:se.percentLeft,needsCompaction:Q});let q={sessionId:S.sessionId,isLastStep:S.isLastStep??false,mode:b,messageCount:L.length,tokenEstimate:X,remaining:be,sources:g(b,N.length>0,M.length>0),memoryResults:N.length,knowledgeResults:M.length,lastUserMessage:H,lastAssistantMessage:Y,needsCompaction:Q,protocolMetadata:T};Bn.debug("context build completed",{...q,lastUserMessage:H?.info.id,lastAssistantMessage:Y?.info.id});let F={system:_,messages:L,tools:S.tools,model:S.model,agent:S.agent,session:S.session,metadata:q},te=await Le.triggerEvent(HookEvent.ContextBuildAfter,{context:F},{sessionId:S.sessionId});return te.modified&&te.output?te.output.context:F}A.build=f;async function a(S){let {sessionId:w,model:y,agent:b,user:C,staticPrompt:O,staticPromptSources:D,dynamicParts:$,maxChars:K,protocolMetadata:ee,mode:N}=S;await Se.getProvider(y.providerId);await Qe.get(y.providerId);let j=[];b.prompt&&b.prompt.trim().length>0?j.push(a$9.replaceVariables(b.prompt,ee)):j.push(...ep({model:y,protocolMetadata:ee}));for(let x=0;x<O.length;x++){let k=D?.[x]??`template-${x}`,_=await TruncateContent.truncate(O[x],{label:"static prompt",sourcePath:k,maxChars:K});j.push(_.content);}if(j.push(...await tp({model:y,mode:N,agent:b,protocolMetadata:ee})),j.push(...$),C.system){let x=await TruncateContent.truncate(C.system,{label:"user system prompt",maxChars:K});j.push(x.content);}return await Le.triggerEvent(HookEvent.SystemTransform,{sessionId:w,model:y}),j}async function p(S){let w=clone(S.messages),y=S.mode??f$1;for(let K=w.length-1;K>=0;K--){let ee=w[K];if(ee&&ee.info.role==="assistant"&&ee.info.finish){break}}(S.includeReminders??true)&&await u(w,{agent:S.agent,session:S.session,userMessageId:S.userMessage.info.id,lastFinished:S.lastFinished,step:S.step??1,isLastStep:S.isLastStep??false,mode:y});let E=w;S.maxMessages&&S.maxMessages>0&&(E=w.slice(-S.maxMessages));let O=await ve.toModelMessages(E,S.model);S.isLastStep&&O.push({role:"assistant",content:[{type:"text",text:UE}]});let D=w.findLast(K=>K.info.role==="user"),$=w.findLast(K=>K.info.role==="assistant");return {messages:O,lastUserMessage:D,lastAssistantMessage:$}}async function u(S,w){let{agent:y,session:b,lastFinished:C,step:E,isLastStep:O,mode:D}=w,$=S.findLast(T=>T.info.role==="user");if(!$)return;let K=D==="coder"?BE:qE,ee=Z.plan(b),N=false;try{await Tt__default.access(ee),N=!0;}catch{N=false;}let M=ip(K,ee,N);if(!a$2.EASBOT_PLAN_MODE)y.name==="plan"&&$.parts.push({id:Identifier.ascending("part"),messageId:$.info.id,sessionId:$.info.sessionId,type:"text",text:M,synthetic:true}),S.some(j=>j.info.role==="assistant"&&j.info.agent==="plan")&&y.name==="build"&&$.parts.push({id:Identifier.ascending("part"),messageId:$.info.id,sessionId:$.info.sessionId,type:"text",text:ip(Sh,ee,N),synthetic:true});else {let T=S.findLast(j=>j.info.role==="assistant");if(y.name!=="plan"&&T?.info.agent==="plan"){if(N){let j=await Z.updatePart({id:Identifier.ascending("part"),messageId:$.info.id,sessionId:$.info.sessionId,type:"text",text:ip(Sh,ee,N),synthetic:true});$.parts.push(j);}return}if(y.name==="plan"&&T?.info.agent!=="plan"){N||await Tt__default.mkdir(Ce__default.dirname(ee),{recursive:true});let j=await Z.updatePart({id:Identifier.ascending("part"),messageId:$.info.id,sessionId:$.info.sessionId,type:"text",text:M,synthetic:true});$.parts.push(j);return}}if(E>1&&C&&!O){for(let T of S)if(!(T.info.role!=="user"||T.info.id<=C.info.id))for(let j of T.parts)j.type!=="text"||j.ignored||j.synthetic||j.text?.trim()&&(j.text=`<system-reminder>
930
- The user sent the following message:
931
- `+j.text+`
932
-
933
- Please address this message and continue with your tasks.
934
- </system-reminder>`);}await Le.triggerEvent(HookEvent.MessageTransform,{sessionId:w.session.id,userMessageId:w.userMessageId});}function h(S,w){let y=0;if(w)for(let b of w)y+=ps(b);for(let b of S)if(b.content){if(typeof b.content=="string")y+=ps(b.content);else if(Array.isArray(b.content)){for(let C of b.content)if(typeof C=="object"&&C!==null){let E=C;typeof E.text=="string"&&(y+=ps(E.text));}}}return y}A.tokenCountWithEstimation=h;function g(S,w,y){let b=["system","history","tools","templates"];return w&&b.push("memory"),y&&b.push("knowledge"),S==="coder"&&b.push("coder-context"),b}function v(S,w){Bs.invalidateCache(S,w);}A.invalidateCache=v;function P(){return Bs.getCacheStats()}A.getCacheStats=P;async function I(){(await s()).fileCache.clear(),Bn.debug("file cache reset");}A.resetFileCache=I;})(hn||(hn={}));async function WE(){return hn.getContext()}async function VE(){return hn.getProtocolMetadata()}function ca(){let e=null,t=false,o=[];return {stream:{[Symbol.asyncIterator](){return {next(){return t?Promise.resolve({value:void 0,done:true}):o.length>0?Promise.resolve({value:o.shift(),done:false}):new Promise(i=>{e=i;})}}}},push:i=>{t||(e?(e({value:i,done:false}),e=null):o.push(i));},close:()=>{t=true,e&&(e({value:void 0,done:true}),e=null);}}}function Ch(e){let t={directory:e.directory};return {config:{get:async(o,n)=>({data:await Pe(()=>Cn.getConfig(),"CONFIG_GET_ERROR",t)}),providers:async(o,n)=>({data:{providers:await Pe(()=>Yc.listProviders(),"CONFIG_PROVIDERS_ERROR",t)}})},model:{default:async(o,n)=>{let s=await Pe(()=>Ni.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(o,n)=>({data:await Pe(()=>Promise.resolve(Ni.parseModel(o.model)),"MODEL_PARSE_ERROR",t)})},command:{list:async(o,n)=>({data:await Pe(()=>nd.listCommands(o.contextMode),"COMMAND_LIST_ERROR",t)})},permission:{list:async(o,n)=>({data:await Pe(()=>Hr.listPermissions(),"PERMISSION_LIST_ERROR",t)}),respond:async(o,n)=>(await Pe(()=>Hr.respondPermission({sessionId:o.sessionId,permissionId:o.permissionId,response:o.response}),"PERMISSION_RESPOND_ERROR",t),{data:true}),reply:async(o,n)=>(await Pe(()=>Hr.replyPermission({requestId:o.requestId,reply:o.reply,message:o.message}),"PERMISSION_REPLY_ERROR",t),{data:true})},question:{list:async(o,n)=>({data:await Pe(()=>qr.listQuestions(),"QUESTION_LIST_ERROR",t)}),reply:async(o,n)=>(await Pe(()=>qr.replyQuestion({requestId:o.requestId,answers:o.answers}),"QUESTION_REPLY_ERROR",t),{data:true}),reject:async(o,n)=>(await Pe(()=>qr.rejectQuestion({requestId:o.requestId}),"QUESTION_REJECT_ERROR",t),{data:true})},session:{create:async(o,n)=>({data:await Pe(()=>so.createSession({title:o?.title,directory:o?.directory??t.directory}),"SESSION_CREATE_ERROR",t)}),get:async(o,n)=>({data:await Pe(()=>so.getSession(o.sessionId),"SESSION_GET_ERROR",t)}),list:async(o,n)=>({data:await Pe(()=>so.listSessions({limit:o?.limit,directory:o?.directory??t.directory}),"SESSION_LIST_ERROR",t)}),fork:async(o,n)=>{let s=o?.directory??t.directory;return {data:await Pe(()=>so.forkSession(o.sessionId,o.messageId,s),"SESSION_FORK_ERROR",t)}},delete:async(o,n)=>(await Pe(()=>so.deleteSession(o.sessionId),"SESSION_DELETE_ERROR",t),{data:true}),abort:async(o,n)=>(await Pe(()=>so.abortSession(o.sessionId),"SESSION_ABORT_ERROR",t),{data:true}),summarize:async(o,n)=>({data:await Pe(()=>so.summarizeSession({sessionId:o.sessionId,providerId:o.providerId,modelId:o.modelId,auto:o.auto}),"SESSION_SUMMARIZE_ERROR",t)}),contextMode:{get:async(o,n)=>({data:await Pe(()=>so.getSessionContextMode(o.sessionId),"SESSION_CONTEXT_MODE_ERROR",t)}),set:async(o,n)=>(await Pe(()=>so.setSessionContextMode(o.sessionId,o.mode),"SESSION_CONTEXT_MODE_ERROR",t),{data:o.mode})},messages:async(o,n)=>({data:await Pe(()=>js.listMessages(o.sessionId,o.limit),"SESSION_MESSAGES_ERROR",t)}),message:async(o,n)=>({data:await Pe(()=>js.getMessage(o.sessionId,o.messageId),"SESSION_MESSAGE_ERROR",t)}),prompt:async(o,n)=>{let s=(o.parts??[]).filter(l=>l.type==="text").map(l=>l.text).join(`
935
- `),r=(o.parts??[]).filter(l=>l.type==="file").map(l=>({url:l.url,filename:l.filename,mime:l.mime})),i=(o.parts??[]).find(l=>l.type==="agent")?.name;return {data:await Pe(()=>js.send({sessionId:o.sessionId,text:s,agent:o.agent,subAgent:i,model:o.model,variant:o.variant,files:r.length>0?r:void 0,noReply:o.noReply,contextMode:o.contextMode,system:o.system}),"SESSION_PROMPT_ERROR",t)}},command:async(o,n)=>({data:await Pe(()=>js.command({sessionId:o.sessionId,command:o.command,arguments:o.arguments,agent:o.agent,model:o.model,variant:o.variant,messageId:o.messageId,contextMode:o.contextMode,parts:o.parts}),"SESSION_COMMAND_ERROR",t)}),event:async(o,n)=>{let{stream:s,push:r,close:i}=ca(),c;try{c=await Pe(()=>qn.subscribeSession(o.sessionId,d=>{r({sessionId:o.sessionId,payload:d});}),"SESSION_EVENT_ERROR",t);}catch(d){throw i(),d}let l=o?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},update:async(o,n)=>({data:await Pe(()=>so.updateSession(o.sessionId,o),"SESSION_UPDATE_ERROR",t)}),children:async(o,n)=>({data:await Pe(()=>so.getSessionChildren(o.sessionId),"SESSION_CHILDREN_ERROR",t)}),init:async(o,n)=>({data:await Pe(()=>so.initSession(o),"SESSION_INIT_ERROR",t)}),status:async(o,n)=>({data:await Pe(()=>so.listSessionStatuses(),"SESSION_STATUS_ERROR",t)})},message:{event:async(o,n)=>{let{stream:s,push:r,close:i}=ca(),c;try{c=await Pe(()=>qn.subscribeMessage(o.sessionId,o.messageId,d=>{r({sessionId:o.sessionId,messageId:o.messageId,payload:d});}),"MESSAGE_EVENT_ERROR",t);}catch(d){throw i(),d}let l=o?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}}},event:{subscribe:async(o,n)=>{let{stream:s,push:r,close:i}=ca(),c;try{c=await Pe(()=>qn.subscribeAll(d=>{r({payload:d});}),"EVENT_SUBSCRIBE_ERROR",t);}catch(d){throw i(),d}let l=o?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},publish:async(o,n)=>(await Pe(()=>qn.publish(o),"EVENT_PUBLISH_ERROR",t),{data:true})},agent:{list:async(o,n)=>({data:await Pe(()=>ss.listAgents(),"AGENT_LIST_ERROR",t)}),get:async(o,n)=>({data:await Pe(()=>ss.getAgent(o.agentId),"AGENT_GET_ERROR",t)}),default:async(o,n)=>({data:await Pe(()=>ss.getDefaultAgent(),"AGENT_DEFAULT_ERROR",t)}),create:async(o,n)=>({data:await Pe(()=>ss.createAgent({name:o.name,mode:o.mode,permission:o.permission}),"AGENT_CREATE_ERROR",t)}),event:async(o,n)=>{let{stream:s,push:r,close:i}=ca(),c;try{c=await Pe(()=>qn.subscribeAll(d=>{d.properties?.agentId===o.agentId&&r({agentId:o.agentId,payload:d});}),"AGENT_EVENT_ERROR",t);}catch(d){throw i(),d}let l=o?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}}},global:{event:async(o,n)=>{let{stream:s,push:r,close:i}=ca(),c;try{c=await Pe(()=>qn.subscribeAll(d=>{r({payload:d});}),"GLOBAL_EVENT_ERROR",t);}catch(d){throw i(),d}let l=o?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},config:{get:async(o,n)=>({data:await Pe(()=>Cn.getGlobalConfig(),"CONFIG_GET_ERROR",t)}),update:async(o,n)=>({data:await Pe(()=>Cn.updateGlobalConfig(o),"CONFIG_UPDATE_ERROR",t)})},dispose:async(o,n)=>(await Pe(()=>id.dispose(),"GLOBAL_DISPOSE_ERROR",t),{data:true})},app:{agents:async(o,n)=>({data:await Pe(()=>ss.listAgents(),"APP_AGENTS_ERROR",t)}),skills:async(o,n)=>({data:(await Pe(()=>rd.all(),"APP_SKILLS_ERROR",t)).map(r=>({name:r.name,description:r.description??"",location:r.location}))}),log:async(o,n)=>({data:[]}),context:async(o,n)=>({data:await Pe(()=>fd.getContext(),"APP_CONTEXT_ERROR",t)})},auth:{set:async(o,n)=>(await Pe(()=>ea.set(o.providerId,o.info),"AUTH_SET_ERROR",t),{data:true}),remove:async(o,n)=>(await Pe(()=>ea.remove(o.providerId),"AUTH_REMOVE_ERROR",t),{data:true})},project:{list:async(o,n)=>({data:await Pe(()=>qs.list(),"PROJECT_LIST_ERROR",t)}),current:async(o,n)=>({data:await Pe(()=>qs.current(),"PROJECT_CURRENT_ERROR",t)}),initGit:async(o,n)=>({data:await Pe(()=>qs.initGit(o),"PROJECT_INIT_GIT_ERROR",t)}),update:async(o,n)=>({data:await Pe(()=>qs.update(o.providerId,o),"PROJECT_UPDATE_ERROR",t)})},pty:{list:async(o,n)=>({data:await Pe(()=>Hn.list(),"PTY_LIST_ERROR",t)}),get:async(o,n)=>({data:await Pe(()=>Hn.get(o.id),"PTY_GET_ERROR",t)}),create:async(o,n)=>({data:await Pe(()=>Hn.create(o),"PTY_CREATE_ERROR",t)}),update:async(o,n)=>({data:await Pe(()=>Hn.update(o.id,o),"PTY_UPDATE_ERROR",t)}),remove:async(o,n)=>(await Pe(()=>Hn.remove(o.id),"PTY_REMOVE_ERROR",t),{data:true}),connect:async(o,n)=>({data:await Pe(()=>Hn.connect(o.id),"PTY_CONNECT_ERROR",t)})},file:{list:async(o,n)=>({data:await Pe(()=>Hs.list({directory:o?.directory,path:o?.path}),"FILE_LIST_ERROR",t)}),read:async(o,n)=>({data:await Pe(()=>Hs.read({directory:o?.directory,path:o?.path}),"FILE_READ_ERROR",t)}),status:async(o,n)=>({data:await Pe(()=>Hs.status(),"FILE_STATUS_ERROR",t)}),search:async(o,n)=>({data:await Pe(()=>Hs.search(o),"FILE_SEARCH_ERROR",t)})},mcp:{status:async(o,n)=>({data:await Pe(()=>Bo.status(),"MCP_STATUS_ERROR",t)}),add:async(o,n)=>{let{name:s,config:r}=o;return {data:await Pe(()=>Bo.add(s,r),"MCP_ADD_ERROR",t)}},connect:async(o,n)=>{let{name:s}=o;return {data:await Pe(()=>Bo.connect(s),"MCP_CONNECT_ERROR",t)}},disconnect:async(o,n)=>{let{name:s}=o;return {data:await Pe(()=>Bo.disconnect(s),"MCP_DISCONNECT_ERROR",t)}},tools:async(o,n)=>{let s=await Pe(()=>Bo.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(o,n)=>{let{name:s}=o;return {data:await Pe(()=>Bo.startAuth(s),"MCP_AUTH_START_ERROR",t)}},authenticate:async(o,n)=>{let{name:s}=o;return {data:await Pe(()=>Bo.authenticate(s),"MCP_AUTH_AUTHENTICATE_ERROR",t)}},finish:async(o,n)=>{let{name:s,authorizationCode:r}=o;return {data:await Pe(()=>Bo.finishAuth(s,r),"MCP_AUTH_FINISH_ERROR",t)}},callback:async(o,n)=>{let{name:s,callbackUrl:r}=o;return {data:await Pe(()=>Bo.authCallback(s,r),"MCP_AUTH_CALLBACK_ERROR",t)}},remove:async(o,n)=>{let{name:s}=o;return await Pe(()=>Bo.removeAuth(s),"MCP_AUTH_REMOVE_ERROR",t),{data:true}}}},lsp:{status:async(o,n)=>({data:await Pe(()=>sd.getLspStatus(),"LSP_STATUS_ERROR",t)})}}}async function KE(){let{Server:e}=await import('./server-3RDX4X3L.mjs');return e.openapi()}var Fe=a.create({service:"cli-tui-state"});async function QE(e,t,o){let n=t.options,s=m=>{if(!m)return SessionTitle.createDefault(false);let f=m.trim();return f.slice(0,50)+(f.length>50?"...":"")};if(n?.new){let m=s(n.prompt),{data:f}=await e.session.create({title:m,directory:R.directory,contextMode:o.contextMode});return Fe.debug("New session created via --new",{sessionId:f?.id,contextMode:o.contextMode}),f?.id??null}let{data:r}=await e.session.list({limit:1}),i=r?.find(m=>!m.parentId)?.id,c=t.sessionId||o.sessionId||i;if(c&&n?.fork){let{data:m}=await e.session.fork({sessionId:c,contextMode:o.contextMode});return Fe.debug("Session forked",{baseID:c,forkedID:m?.id,contextMode:o.contextMode}),m?.id??null}if(c)return Fe.debug("Using existing session",{sessionId:c}),c;let l=s(n?.prompt),{data:d}=await e.session.create({title:l,directory:R.directory,contextMode:o.contextMode});return Fe.debug("New session created (fallback)",{sessionId:d?.id,contextMode:o.contextMode}),d?.id??null}async function ZE(e={}){Fe.debug("Creating TUI state",{options:e});let t={directory:R.directory,projectId:R.project.id},o={toolsExpanded:true,showThinking:true,thinkingLevel:"low",verboseLevel:"off",messageLimit:50,localShellPermission:"ask",contextMode:void 0,model:void 0,agent:void 0,sessionId:void 0},n=e.sessionId||e.options?.sessionId;if(n)try{o=await a$b(n),Fe.debug("Loaded TUI state from session",{sessionId:n,persistedState:o});}catch{Fe.debug("No persisted state found for session",{sessionId:n});}let s=Ch({directory:t.directory}),r=await QE(s,{...e,sessionId:n},o),i=r||"new";if(r)try{let m=(await s.session.get({sessionId:r})).data;m?.title&&(i=m.title);}catch(d){Fe.debug("Failed to load session title",{sessionId:r,error:d});}if(r&&r!==n)try{o=await a$b(r),Fe.debug("Loaded TUI state from resolved session",{sessionId:r,persistedState:o});}catch{Fe.debug("No persisted state found for resolved session",{sessionId:r});}let c=e.model||o.model;if(!c)try{let d=await s.model.default({});d.data&&(c=`${d.data.providerId}/${d.data.modelId}`,Fe.debug("Got default model from backend",{model:c}));}catch(d){Fe.warn("Failed to get default model",{error:d});}let l=e.agent||o.agent;if(!l)try{let f=((await s.app.agents({})).data||[]).filter(a=>a.mode!=="subagent");f.length>0?(l=f[0].name,Fe.debug("Got default agent from backend",{agent:l})):(l="",Fe.warn("No agents available"));}catch(d){l="",Fe.warn("Failed to get default agent",{error:d});}return r||Fe.warn("No session ID provided, TUI may not function correctly"),Fe.debug("TUI state resolved",{agent:{provided:e.agent,persisted:o.agent,final:l},model:{provided:e.model,persisted:o.model,final:c},sessionId:{provided:e.sessionId,persisted:o.sessionId,final:r},contextMode:o.contextMode}),{agent:l,currentSessionKey:i,currentSessionId:r,activeChatRunId:null,historyLoaded:false,toolsExpanded:o.toolsExpanded,showThinking:o.showThinking,thinkingLevel:o.thinkingLevel,verboseLevel:o.verboseLevel,messageLimit:o.messageLimit,localShellPermission:o.localShellPermission,contextMode:o.contextMode,pendingShellCommand:null,sessionInfo:{model:c,modelProvider:void 0,totalTokens:null,contextTokens:null},pendingPermission:null,pendingQuestion:null,questionDisplayTimer:null,instanceContext:t,sdk:s}}var ap;function eA(){if(!ap){let e=R.state(()=>new Map,async t=>{Fe.debug("Disposing TUI state",{count:t.size}),t.clear();});ap=async t=>{let o=e(),n=JSON.stringify(t);if(!o.has(n)){let s=await ZE(t);o.set(n,s);}return o.get(n)};}return ap}async function cp(e={}){return eA()(e)}async function RX(e,t,o,n){Fe.debug("Initializing TUI state with health check and event subscription");let s=await cp(e);if(s.currentSessionId&&!s.contextMode)try{let c=await s.sdk.session.contextMode.get({sessionId:s.currentSessionId});c.data&&(s.contextMode=c.data,Fe.debug("Got contextMode from session API",{sessionId:s.currentSessionId,contextMode:s.contextMode}));}catch(c){Fe.debug("Failed to get contextMode from session API",{sessionId:s.currentSessionId,error:c});}s.currentSessionId?(Fe.debug("Saving initial TUI state to storage",{sessionId:s.currentSessionId}),await b$4(s)):Fe.warn("No session ID, skipping initial state save"),await tA(s,o),Fe.debug("Running TUI state health check");let r=await Eh(s);if(r.healthy)Fe.debug("TUI state health check passed");else {Fe.warn("TUI state health check failed",{report:r}),Fe.debug("Attempting to auto-heal TUI state");let c=await nA(s);c.success?(Fe.debug("TUI state auto-heal successful",{report:c}),o.addSystem(i$1("tui.state.healed")),await b$4(s)):(Fe.error("TUI state auto-heal failed",{report:c}),o.addSystem(i$1("tui.state.heal_failed")));}Fe.debug("Subscribing to backend state events");let i=await oA(s,t,o,n);return Fe.debug("Backend state events subscribed"),{state:s,unsubscribe:i}}async function tA(e,t){Fe.debug("Validating local preferences",{localModel:e.sessionInfo.model,localAgent:e.agent,sessionId:e.currentSessionId});try{let o=[];if(e.sessionInfo.model)try{let n=await e.sdk.model.parse({model:e.sessionInfo.model});n.data&&(((await e.sdk.config.providers({})).data?.providers||[]).find(l=>l.id===n.data.providerId)?.models?.[n.data.modelId]?(o.push(`model: ${e.sessionInfo.model}`),Fe.debug("Model validated successfully",{model:e.sessionInfo.model})):(Fe.warn("Local model does not exist",{model:e.sessionInfo.model,providerId:n.data.providerId,modelId:n.data.modelId}),t.addSystem(i$1("tui.state.model_not_found",{vars:{model:e.sessionInfo.model}})),e.sessionInfo.model=void 0));}catch(n){Fe.error("Failed to validate model",{model:e.sessionInfo.model,error:n});}if(e.agent)try{((await e.sdk.app.agents({})).data||[]).find(i=>i.name===e.agent)?(o.push(`agent: ${e.agent}`),Fe.debug("Agent validated successfully",{agent:e.agent})):(Fe.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(n){Fe.error("Failed to validate agent",{agent:e.agent,error:n});}o.length>0&&(Fe.debug("Local preferences validated",{validationResults:o}),t.addSystem(i$1("tui.state.preferences_validated",{vars:{items:o.join(", ")}}))),Fe.debug("Local preferences validation completed");}catch(o){Fe.error("Failed to validate local preferences",{error:o});}}async function kh(e,t){return R.provide({directory:e.instanceContext.directory,init:void 0,fn:t})}async function yn(e,t,o){await kh(e,async()=>{await ue.publish(t,o);});}async function gd(e,t,o){let n=()=>{};return await kh(e,async()=>{n=ue.subscribe(t,o),await ue.waitForSubscription();}),n}async function _X(e,t){await e.sdk.permission.reply({requestId:t.requestId,reply:t.reply});}async function MX(e,t){await e.sdk.question.reply({requestId:t.requestId,answers:t.answers});}var nn={async appendPrompt(e,t){await yn(e,c$2.PromptAppend,t);},async openHelp(e){await yn(e,c$2.CommandExecute,{command:"help.show"});},async openSessions(e){await yn(e,c$2.CommandExecute,{command:"session.list"});},async openThemes(e){await yn(e,c$2.CommandExecute,{command:"session.list"});},async openModels(e){await yn(e,c$2.CommandExecute,{command:"model.list"});},async submitPrompt(e){await yn(e,c$2.CommandExecute,{command:"prompt.submit"});},async clearPrompt(e){await yn(e,c$2.CommandExecute,{command:"prompt.clear"});},async executeCommand(e,t){let o={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 yn(e,c$2.CommandExecute,{command:o[t.command]||t.command});},async showToast(e,t){await yn(e,c$2.ToastShow,t);},async selectSession(e,t){await yn(e,c$2.SessionSelect,t);},async publish(e,t){let o=Object.values(c$2).find(n=>n.type===t.type);o&&await yn(e,o,t.properties);}};async function Ph(e){return (await e.sdk.app.agents({})).data||[]}async function OX(e){return (await e.sdk.session.list({limit:50})).data||[]}async function Th(e){let o=(await e.sdk.config.providers({})).data?.providers||[];return Object.fromEntries(o.filter(n=>typeof n.id=="string"&&n.id.length>0).map(n=>[n.id,{name:n.name,models:n.models}]))}async function oA(e,t,o,n){let s=[];Fe.debug("Subscribing to backend events");let r=await gd(e,Z.Event.Created,async d=>{Fe.debug("Session created",{sessionId:d.properties.info.id}),o.addSystem(i$1("tui.state.session.created",{vars:{title:d.properties.info.title||d.properties.info.id}}));});s.push(r);let i=await gd(e,Z.Event.Updated,async d=>{Fe.debug("Session updated",{sessionId:d.properties.info.id}),e.currentSessionId===d.properties.info.id&&n();});s.push(i);let c=await gd(e,Z.Event.Deleted,async d=>{let m=d.properties.info.id,f=d.properties.info.title||m;Fe.debug("Session deleted",{sessionId:m,sessionTitle:f}),o.addSystem(i$1("tui.state.session.deleted",{vars:{title:f}})),e.currentSessionId===m&&(e.currentSessionId=null,e.currentSessionKey="new",n());});s.push(c);let l=await gd(e,Ue.ToolsChanged,async d=>{Fe.debug("MCP tools changed",{server:d.properties.server});});return s.push(l),Fe.debug("Backend events subscribed",{count:s.length}),()=>{Fe.debug("Unsubscribing from backend events");for(let d of s)d();}}async function Eh(e){let t={checks:[],healthy:true};Fe.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 o=await Ph(e);Fe.debug("Agent list retrieved for health check",{agent:e.agent,availableAgents:o.map(s=>s.name),agentCount:o.length}),o.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"}),Fe.warn("Current agent not found in available agents",{agent:e.agent,availableAgents:o.map(s=>s.name)}));}catch(o){t.healthy=false,t.checks.push({name:"Current Agent",status:"fail",message:`Failed to check agent: ${String(o)}`,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(o){t.healthy=false,t.checks.push({name:"Current Session",status:"fail",message:`Failed to check session: ${String(o)}`,suggestion:"Clear invalid session ID"});}if(e.sessionInfo.model)try{let o=await Th(e),{provider:n,model:s}=parseModelId(e.sessionInfo.model);o[n]?.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(o){t.healthy=false,t.checks.push({name:"Current Model",status:"fail",message:`Failed to check model: ${String(o)}`,suggestion:"Check Instance context and API layer"});}return Fe.debug("TUI state diagnostics completed",{healthy:t.healthy,checks:t.checks.length}),t}async function nA(e){let t={actions:[],success:true};Fe.debug("Running TUI state auto-heal");let o=await Eh(e);for(let n of o.checks)if(n.status==="fail")try{switch(n.name){case "Current Agent":{let s=await Ph(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 Th(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 ${n.name}`,status:"fail",message:`Failed to fix: ${String(s)}`});}return Fe.debug("TUI state auto-heal completed",{success:t.success,actions:t.actions.length}),t}var sA={400:{description:"Bad request",content:{"application/json":{schema:resolver(U.object({data:U.any(),errors:U.array(U.record(U.string(),U.any())),success:U.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,sA[t]]))}var bn=()=>cp(),iA=U.object({path:U.string(),body:U.any()}),aA=new AsyncQueue,cA=new AsyncQueue;var dA=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(iA)}}}}}),async e=>{let t=await aA.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(U.boolean())}}}}}),validator("json",U.any()),async e=>{let t=e.req.valid("json");return cA.push(t),e.json(true)}),Mh=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(U.boolean())}}},...Te(400)}}),validator("json",b$2.PromptAppend.properties),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),async e=>{let t=await bn();return await nn.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(U.boolean())}}},...Te(400)}}),validator("json",U.object({command:U.string()})),async e=>{let t=await bn();return await nn.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(U.boolean())}}}}}),validator("json",b$2.ToastShow.properties),async e=>{let t=await bn();return await nn.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(U.boolean())}}},...Te(400)}}),validator("json",U.union(Object.values(b$2).map(e=>U.object({type:U.literal(e.type),properties:e.properties}).meta({ref:"Event."+e.type})))),async e=>{let t=await bn();return await nn.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(U.boolean())}}},...Te(400,404)}}),validator("json",b$2.SessionSelect.properties),async e=>{let t=await bn();return await nn.selectSession(t,e.req.valid("json")),e.json(true)}).route("/control",dA));var Oh=a.create({service:"vcs"}),Ws;(l=>{l.Event={BranchUpdated:a$5.define("vcs.branch.updated",U.object({branch:U.string().optional()}))},l.Info=U.object({branch:U.string()}).meta({ref:"VcsInfo"});async function o(){return $`git rev-parse --abbrev-ref HEAD`.quiet().nothrow().cwd(R.worktree).text().then(d=>d.trim()).catch(()=>{})}let n;function s(){return n||(n=R.state(async()=>{if(R.project.vcs!=="git")return {branch:async()=>{},unsubscribe:void 0};let d=await o();Oh.info("initialized",{branch:d});let m=ue.subscribe(zo.Event.Updated,async f=>{if(f.properties.file.endsWith("HEAD"))return;let a=await o();a!==d&&(Oh.info("branch changed",{from:d,to:a}),d=a,await ue.publish(l.Event.BranchUpdated,{branch:a}));});return {branch:async()=>d,unsubscribe:m}},async d=>{d.unsubscribe?.();})),n}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;})(Ws||(Ws={}));var Dh=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(qt.Info.array())}}}}}),async e=>{let t=await qt.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(qt.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(qt.Info)}}},...Te(400,404)}}),validator("param",U.object({providerId:U.string()})),validator("json",qt.update.schema.omit({providerId:true})),async e=>{let t=e.req.valid("param").providerId,o=e.req.valid("json"),n=await qt.update({...o,providerId:t});return e.json(n)}));var Jr=a.create({service:"server"}),Nh=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(Z.Info.array())}}}}}),validator("query",U.object({directory:U.string().optional().meta({description:"Filter sessions by project directory"}),roots:U.coerce.boolean().optional().meta({description:"Only return root sessions (no parentId)"}),start:U.coerce.number().optional().meta({description:"Filter sessions updated on or after this timestamp (milliseconds since epoch)"}),search:U.string().optional().meta({description:"Filter sessions by title (case-insensitive)"}),limit:U.coerce.number().optional().meta({description:"Maximum number of sessions to return"})})),async e=>{let t=e.req.valid("query"),o=t.search?.toLowerCase(),n=[];for await(let s of Z.list())if(!(t.directory!==void 0&&s.directory!==t.directory)&&!(t.roots&&s.parentId)&&!(t.start!==void 0&&s.time.updated<t.start)&&!(o!==void 0&&!s.title.toLowerCase().includes(o))&&(n.push(s),t.limit!==void 0&&n.length>=t.limit))break;return e.json(n)}).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(U.record(U.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(Z.Info)}}},...Te(400,404)}}),validator("param",U.object({sessionId:Z.get.schema})),async e=>{let t=e.req.valid("param").sessionId;Jr.info("SEARCH",{url:e.req.url});let o=await Z.get(t);return e.json(o)}).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(Z.Info.array())}}},...Te(400,404)}}),validator("param",U.object({sessionId:Z.children.schema})),async e=>{let t=e.req.valid("param").sessionId,o=await Z.children(t);return e.json(o)}).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(un.Info.array())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),async e=>{let t=e.req.valid("param").sessionId,o=await un.get(t);return e.json(o)}).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(Z.Info)}}}}}),validator("json",Z.create.schema.optional()),async e=>{let t=e.req.valid("json")??{},o=await Z.create(t);return e.json(o)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:Z.remove.schema})),async e=>{let t=e.req.valid("param").sessionId;return await Z.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(Z.Info)}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string()})),validator("json",U.object({title:U.string().optional(),time:U.object({archived:U.number().optional()}).optional()})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json"),n=await Z.update(t,s=>{o.title!==void 0&&(s.title=o.title),o.time?.archived!==void 0&&(s.time.archived=o.time.archived);},{touch:false});return e.json(n)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",Z.initialize.schema.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json");return await Z.initialize({...o,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(Z.Info)}}}}}),validator("param",U.object({sessionId:Z.fork.schema.shape.sessionId})),validator("json",Z.fork.schema.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json"),n=await Z.fork({...o,sessionId:t});return e.json(n)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string()})),async e=>(await Ke.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(Z.Info)}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string()})),async e=>{let t=e.req.valid("param").sessionId;await Z.share(t);let o=await Z.get(t);return e.json(o)}).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(ht.FileDiff.array())}}}}}),validator("param",U.object({sessionId:ms.diff.schema.shape.sessionId})),validator("query",U.object({messageId:ms.diff.schema.shape.messageId})),async e=>{let t=e.req.valid("query"),o=e.req.valid("param"),n=await ms.diff({sessionId:o.sessionId,messageId:t.messageId});return e.json(n)}).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(Z.Info)}}},...Te(400,404)}}),validator("param",U.object({sessionId:Z.unshare.schema})),async e=>{let t=e.req.valid("param").sessionId;await Z.unshare(t);let o=await Z.get(t);return e.json(o)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",U.object({providerId:U.string(),modelId:U.string(),auto:U.boolean().optional().default(false)})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json"),n=await Z.get(t);return await wn.cleanup(n),await io.create({sessionId:t,agent:"compaction",model:{providerId:o.providerId,modelId:o.modelId},auto:o.auto}),await Ke.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(U.enum(["general","coder"]))}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),async e=>{let t=e.req.valid("param").sessionId,o=await Z.getContextMode(t);return e.json(o)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",U.object({mode:U.enum(["general","coder"]).meta({description:"Context mode to set"})})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json");return await Z.setContextMode(t,o.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",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("query",U.object({limit:U.coerce.number().optional()})),async e=>{let t=e.req.valid("query"),o=await Z.messages({sessionId:e.req.valid("param").sessionId,limit:t.limit});return e.json(o)}).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(U.object({info:ve.Info,parts:ve.Part.array()}))}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"}),messageId:U.string().meta({description:"Message ID"})})),async e=>{let t=e.req.valid("param"),o=await ve.get({sessionId:t.sessionId,messageId:t.messageId});return e.json(o)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"}),messageId:U.string().meta({description:"Message ID"}),partId:U.string().meta({description:"Part ID"})})),async e=>{let t=e.req.valid("param");return await Z.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",U.object({sessionId:U.string().meta({description:"Session ID"}),messageId:U.string().meta({description:"Message ID"}),partId:U.string().meta({description:"Part ID"})})),validator("json",ve.Part),async e=>{let t=e.req.valid("param"),o=e.req.valid("json");if(o.id!==t.partId||o.messageId!==t.messageId||o.sessionId!==t.sessionId)throw new Error(`Part mismatch: body.id='${o.id}' vs partId='${t.partId}', body.messageId='${o.messageId}' vs messageId='${t.messageId}', body.sessionId='${o.sessionId}' vs sessionId='${t.sessionId}'`);let n=await Z.updatePart(o);return e.json(n)}).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(U.object({info:ve.Assistant,parts:ve.Part.array()}))}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",Ke.PromptInput.omit({sessionId:true})),async e=>(e.status(200),e.header("Content-Type","application/json"),stream(e,async t=>{let o=e.req.valid("param").sessionId,n=e.req.valid("json"),s=await Ke.prompt({...n,sessionId:o});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",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",Ke.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,o=e.req.valid("json");Ke.prompt({...o,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(U.object({info:ve.Assistant.optional(),parts:ve.Part.array().optional(),title:U.string(),metadata:U.record(U.string(),U.unknown()),output:U.string(),success:U.boolean(),error:U.string().optional()}))}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",Ke.CommandInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json"),n=await Ke.command({...o,sessionId:t});return e.json(n)}).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",U.object({sessionId:U.string().meta({description:"Session ID"})})),validator("json",Ke.ShellInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,o=e.req.valid("json"),n=await Ke.shell({...o,sessionId:t});return e.json(n)}).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(Z.Info)}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string()})),validator("json",wn.RevertInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId;Jr.info("revert",e.req.valid("json"));let o=await wn.revert({sessionId:t,...e.req.valid("json")});return e.json(o)}).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(Z.Info)}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string()})),async e=>{let t=e.req.valid("param").sessionId,o=await wn.unrevert({sessionId:t});return e.json(o)}).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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({sessionId:U.string(),permissionId:U.string()})),validator("json",U.object({response:Oe.Reply})),async e=>{let t=e.req.valid("param");return Oe.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(U.object({sessionId:U.string(),directory:U.string(),payload:a$5.payloads()}))}}}}}),validator("param",U.object({sessionId:U.string()})),async e=>{let{sessionId:t}=e.req.valid("param");return Jr.info("session event connected",{sessionId:t}),streamSSE(e,async o=>{await o.writeSSE({data:JSON.stringify({sessionId:t,payload:{type:"session.connected",properties:{}}})});async function n(r){(r.properties?.sessionId??r.properties?.sessionId)===t&&await o.writeSSE({data:JSON.stringify({sessionId:t,payload:r})});}mt.on("event",n);let s=setInterval(()=>{o.writeSSE({data:JSON.stringify({sessionId:t,payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(r=>{o.onAbort(()=>{clearInterval(s),mt.off("event",n),Jr.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(U.object({sessionId:U.string(),messageId:U.string(),directory:U.string(),payload:a$5.payloads()}))}}}}}),validator("param",U.object({sessionId:U.string(),messageId:U.string()})),async e=>{let{sessionId:t,messageId:o}=e.req.valid("param");return Jr.info("message event connected",{sessionId:t,messageId:o}),streamSSE(e,async n=>{await n.writeSSE({data:JSON.stringify({sessionId:t,messageId:o,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===o&&await n.writeSSE({data:JSON.stringify({sessionId:t,messageId:o,payload:i})});}mt.on("event",s);let r=setInterval(()=>{n.writeSSE({data:JSON.stringify({sessionId:t,messageId:o,payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(i=>{n.onAbort(()=>{clearInterval(r),mt.off("event",s),Jr.info("message event disconnected",{sessionId:t,messageId:o}),i();});});})}));var Uh=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(nt.Info.array())}}}}}),async e=>e.json(nt.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(nt.Info)}}},...Te(400)}}),validator("json",nt.CreateInput),async e=>{let t=await nt.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(nt.Info)}}},...Te(404)}}),validator("param",U.object({ptyId:U.string()})),async e=>{let t=nt.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(nt.Info)}}},...Te(400)}}),validator("param",U.object({ptyId:U.string()})),validator("json",nt.UpdateInput),async e=>{let t=await nt.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(U.boolean())}}},...Te(404)}}),validator("param",U.object({ptyId:U.string()})),async e=>(await nt.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(U.boolean())}}},...Te(404)}}),validator("param",U.object({ptyId:U.string()})),async e=>e.json({error:"WebSocket not implemented in Node.js mode yet"},501)));var zh=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(U.record(U.string(),Status))}}}}}),async e=>e.json(await Ue.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(U.record(U.string(),Status))}}},...Te(400)}}),validator("json",U.object({name:U.string(),config:he.Mcp})),async e=>{let{name:t,config:o}=e.req.valid("json"),n=await Ue.add(t,o);return e.json(n.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(U.object({authorizationUrl:U.string().describe("URL to open in browser for authorization")}))}}},...Te(400,404)}}),async e=>{let t=e.req.param("name");if(!await Ue.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let n=await Ue.startAuth(t);return e.json(n)}).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",U.object({code:U.string().describe("Authorization code from OAuth callback")})),async e=>{let t=e.req.param("name"),{code:o}=e.req.valid("json"),n=await Ue.finishAuth(t,o);return e.json(n)}).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 Ue.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let n=await Ue.authenticate(t);return e.json(n)}).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(U.object({success:U.literal(true)}))}}},...Te(404)}}),async e=>{let t=e.req.param("name");return await Ue.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(U.boolean())}}}}}),validator("param",U.object({name:U.string()})),async e=>{let{name:t}=e.req.valid("param");return await Ue.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(U.boolean())}}}}}),validator("param",U.object({name:U.string()})),async e=>{let{name:t}=e.req.valid("param");return await Ue.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(U.record(U.string(),U.array(U.string())))}}}}}),async e=>{let t=await Ue.tools(),o={};for(let n of Object.keys(t)){let s=n.split("_"),r=s[0];if(!r)continue;let i=s.slice(1).join("_");o[r]||(o[r]=[]),o[r].push(i);}return e.json(o)}));var qh=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",U.object({pattern:U.string()})),async e=>{let t=e.req.valid("query").pattern,o=await a$8.search({cwd:R.directory,pattern:t,limit:10});return e.json(o)}).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(U.string().array())}}}}}),validator("query",U.object({query:U.string(),dirs:U.enum(["true","false"]).optional(),type:U.enum(["file","directory"]).optional(),limit:U.coerce.number().int().min(1).max(200).optional()})),async e=>{let t=e.req.valid("query").query,o=e.req.valid("query").dirs,n=e.req.valid("query").type,s=e.req.valid("query").limit,r=await yt.search({query:t,limit:s??10,dirs:o!=="false",type:n});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",U.object({query:U.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(yt.Node.array())}}}}}),validator("query",U.object({path:U.string()})),async e=>{let t=e.req.valid("query").path,o=await yt.list(t);return e.json(o)}).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(yt.Content)}}}}}),validator("query",U.object({path:U.string()})),async e=>{let t=e.req.valid("query").path,o=await yt.read(t);return e.json(o)}).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(yt.Info.array())}}}}}),async e=>{let t=await yt.status();return e.json(t)}));var CA=a.create({service:"server"}),Bh=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(U.object({providers:Se.Info.array(),default:U.record(U.string(),U.string())}))}}}}}),async e=>{var n=[];try{let t=c(n,CA.time("providers"));let o=await Se.list().then(c=>mapValues(c,l=>l));return e.json({providers:Object.values(o),default:mapValues(o,c=>Se.sort(Object.values(c.models))[0]?.id??"")})}catch(s){var r=s,i=true;}finally{d(n,r,i);}}));var xd;(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 o=process.env.EASBOT_DISABLE_SHARE==="true"||process.env.EASBOT_DISABLE_SHARE==="1";async function n(){o||(ue.subscribe(Z.Event.Updated,async f=>{await c(f.properties.info.id,[{type:"session",data:f.properties.info}]);}),ue.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 Se.getModel(f.properties.info.model.providerId,f.properties.info.model.modelId).then(a=>a)]}]);}),ue.subscribe(ve.Event.PartUpdated,async f=>{await c(f.properties.part.sessionId,[{type:"part",data:f.properties.part}]);}),ue.subscribe(Z.Event.Diff,async f=>{await c(f.properties.sessionId,[{type:"session_diff",data:f.properties.diff}]);}));}m.init=n;async function s(f){if(o)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(o)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 v=await r(f).catch(()=>{});v&&await Fetch.post(`${await t()}/api/share/${v.id}/sync`,{secret:v.secret,data:Array.from(g.data.values())});},1e3);i.set(f,{timeout:h,data:u});}async function l(f){if(o)return;e.info("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 Z.get(f),p=await Z.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=>Se.getModel(g.providerId,g.modelId).then(v=>v)));await c(f,[{type:"session",data:a},...u.map(g=>({type:"message",data:g.info})),...u.flatMap(g=>g.parts.map(v=>({type:"part",data:v}))),{type:"session_diff",data:p},{type:"model",data:h}]);}})(xd||(xd={}));var kA=a$5.define("command.executed",U.object({name:U.string(),sessionId:U.string(),arguments:U.union([U.string(),U.record(U.string(),U.unknown())]),messageId:U.string().optional()})),Wh=false;async function la(){if(Wh){a.Default.debug("InstanceBootstrap already executed, skipping");return}Wh=true,a.Default.info("bootstrapping",{directory:R.directory}),await fs.init(),await xd.init(),vs.init(),await We.init(),zo.init(),yt.init(),await Ws.init(),await ht.init(),await Ve.init(),ue.subscribe(kA,async e=>{e.properties.name===qu.Default.INIT&&await qt.setInitialized(R.project.id);});}var An;(T=>{let e=a.create({service:"worktree"});T.Event={Ready:a$5.define("worktree.ready",U.object({name:U.string(),branch:U.string()})),Failed:a$5.define("worktree.failed",U.object({message:U.string()}))},T.Info=U.object({name:U.string(),branch:U.string(),directory:U.string()}).meta({ref:"Worktree"}),T.CreateInput=U.object({name:U.string().optional(),startCommand:U.string().optional().describe("Additional startup script to run after the project's start command")}).meta({ref:"WorktreeCreateInput"}),T.RemoveInput=U.object({directory:U.string()}).meta({ref:"WorktreeRemoveInput"}),T.ResetInput=U.object({directory:U.string()}).meta({ref:"WorktreeResetInput"}),T.NotGitError=NamedError.create("WorktreeNotGitError",U.object({message:U.string()})),T.NameGenerationFailedError=NamedError.create("WorktreeNameGenerationFailedError",U.object({message:U.string()})),T.CreateFailedError=NamedError.create("WorktreeCreateFailedError",U.object({message:U.string()})),T.StartCommandFailedError=NamedError.create("WorktreeStartCommandFailedError",U.object({message:U.string()})),T.RemoveFailedError=NamedError.create("WorktreeRemoveFailedError",U.object({message:U.string()})),T.ResetFailedError=NamedError.create("WorktreeResetFailedError",U.object({message:U.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(j){return j[Math.floor(Math.random()*j.length)]}function h(j){return j.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function g(){return `${u(a$2)}-${u(p)}`}async function v(j){return Tt__default.stat(j).then(()=>true).catch(()=>false)}function P(j){return j?.length===0?"":new TextDecoder().decode(j).trim()}function I(j){return [P(j.stderr),P(j.stdout)].filter(Boolean).join(`
936
- `)}function A(j){return [P(j.stderr),P(j.stdout)].filter(Boolean).flatMap(x=>x.split(`
937
- `).map(k=>k.trim()).flatMap(k=>{let _=k.match(/^warning:\s+failed to remove\s+(.+):\s+/i);if(!_)return [];let L=_[1]?.trim().replace(/^['"]|['"]$/g,"");return L?[L]:[]}))}async function S(j,x){let k=await y(j);await Promise.all(x.map(async _=>{let L=await y(Ce__default.resolve(j,_));L!==k&&L.startsWith(`${k}${Ce__default.sep}`)&&await Tt__default.rm(L,{recursive:true,force:true}).catch(()=>{});}));}async function w(j){let x=await $`git clean -ffdx`.quiet().nothrow().cwd(j);if(x.exitCode===0)return x;let k=A(x);return k.length===0?x:(await S(j,k),$`git clean -ffdx`.quiet().nothrow().cwd(j))}async function y(j){let x=Ce__default.resolve(j),k=await Tt__default.realpath(x).catch(()=>x),_=Ce__default.normalize(k);return process.platform==="win32"?_.toLowerCase():_}async function b(j,x){for(let k of Array.from({length:26},(_,L)=>L)){let _=x?k===0?x:`${x}-${g()}`:g(),L=`easbot/${_}`,H=Ce__default.join(j,_);if(await v(H))continue;let Y=`refs/heads/${L}`;if((await $`git show-ref --verify --quiet ${Y}`.quiet().nothrow().cwd(R.worktree)).exitCode!==0)return T.Info.parse({name:_,branch:L,directory:H})}throw new T.NameGenerationFailedError({message:"Failed to generate a unique worktree name"})}async function C(j,x){return process.platform==="win32"?$`cmd /c ${x}`.nothrow().cwd(j):$`bash -lc ${x}`.nothrow().cwd(j)}async function E(j,x,k){let _=x.trim();if(!_)return true;let L=await C(j,_);return L.exitCode===0?true:(e.error("worktree start command failed",{kind:k,directory:j,message:I(L)}),false)}async function O(j,x){let _=(await a$6.read(["project",x.providerId]).catch(()=>{}))?.commands?.start?.trim()??"";if(!await E(j,_,"project"))return false;let H=x.extra??"";return await E(j,H,"worktree"),true}function D(j,x){setTimeout(()=>{(async()=>{await O(j,x);})().catch(_=>{e.error("worktree start task failed",{directory:j,error:_});});},0);}async function $$1(j){if(R.project.vcs!=="git")throw new T.NotGitError({message:"Worktrees are only supported for git projects"});let x=Ce__default.join(a$1.Path.data,"worktree",R.project.id);await Tt__default.mkdir(x,{recursive:true});let k=j?h(j):"";return b(x,k||void 0)}T.makeWorktreeInfo=$$1;async function K(j){if(R.project.vcs!=="git")throw new T.NotGitError({message:"Worktrees are only supported for git projects"});let x=await $`git worktree add --no-checkout -b ${j.branch} ${j.directory}`.quiet().nothrow().cwd(R.worktree);if(x.exitCode!==0)throw new T.CreateFailedError({message:I(x)||"Failed to create git worktree"});await qt.addSandbox(R.project.id,j.directory).catch(()=>{});let k=R.project.id;setTimeout(()=>{(async()=>{let L=await $`git reset --hard`.quiet().nothrow().cwd(j.directory);if(L.exitCode!==0){let Y=I(L)||"Failed to populate worktree";e.error("worktree checkout failed",{directory:j.directory,message:Y}),mt.emit("event",{directory:j.directory,payload:{type:T.Event.Failed.type,properties:{message:Y}}});return}await R.provide({directory:j.directory,init:la,fn:()=>{}}).then(()=>true).catch(Y=>{let X=Y instanceof Error?Y.message:String(Y);return e.error("worktree bootstrap failed",{directory:j.directory,message:X}),mt.emit("event",{directory:j.directory,payload:{type:T.Event.Failed.type,properties:{message:X}}}),false})&&(mt.emit("event",{directory:j.directory,payload:{type:T.Event.Ready.type,properties:{name:j.name,branch:j.branch}}}),await O(j.directory,{providerId:k}));})().catch(L=>{e.error("worktree start task failed",{directory:j.directory,error:L});});},0);}T.createFromInfo=K,T.create=fn$1(T.CreateInput.optional(),async j=>{if(R.project.vcs!=="git")throw new T.NotGitError({message:"Worktrees are only supported for git projects"});let x=Ce__default.join(a$1.Path.data,"worktree",R.project.id);await Tt__default.mkdir(x,{recursive:true});let k=j?.name?h(j.name):"",_=await b(x,k||void 0),L=await $`git worktree add --no-checkout -b ${_.branch} ${_.directory}`.quiet().nothrow().cwd(R.worktree);if(L.exitCode!==0)throw new T.CreateFailedError({message:I(L)||"Failed to create git worktree"});await qt.addSandbox(R.project.id,_.directory).catch(()=>{});let H=R.project.id,Y=j?.startCommand?.trim();return setTimeout(()=>{(async()=>{let ne=await $`git reset --hard`.quiet().nothrow().cwd(_.directory);if(ne.exitCode!==0){let le=I(ne)||"Failed to populate worktree";e.error("worktree checkout failed",{directory:_.directory,message:le}),mt.emit("event",{directory:_.directory,payload:{type:T.Event.Failed.type,properties:{message:le}}});return}await R.provide({directory:_.directory,init:la,fn:()=>{}}).then(()=>true).catch(le=>{let be=le instanceof Error?le.message:String(le);return e.error("worktree bootstrap failed",{directory:_.directory,message:be}),mt.emit("event",{directory:_.directory,payload:{type:T.Event.Failed.type,properties:{message:be}}}),false})&&(mt.emit("event",{directory:_.directory,payload:{type:T.Event.Ready.type,properties:{name:_.name,branch:_.branch}}}),await O(_.directory,{providerId:H,extra:Y}));})().catch(ne=>{e.error("worktree start task failed",{directory:_.directory,error:ne});});},0),_}),T.remove=fn$1(T.RemoveInput,async j=>{if(R.project.vcs!=="git")throw new T.NotGitError({message:"Worktrees are only supported for git projects"});let x=await y(j.directory),k=await $`git worktree list --porcelain`.quiet().nothrow().cwd(R.worktree);if(k.exitCode!==0)throw new T.RemoveFailedError({message:I(k)||"Failed to read git worktrees"});let L=P(k.stdout).split(`
938
- `).map(ne=>ne.trim()).reduce((ne,ae)=>{if(!ae)return ne;if(ae.startsWith("worktree "))return ne.push({path:ae.slice(9).trim()}),ne;let le=ne[ne.length-1];return le&&ae.startsWith("branch ")&&(le.branch=ae.slice(7).trim()),ne},[]),H=await(async()=>{for(let ne of L){if(!ne.path)continue;if(await y(ne.path)===x)return ne}})();if(!H?.path)return await v(x)&&await Tt__default.rm(x,{recursive:true,force:true}),true;let Y=await $`git worktree remove --force ${H.path}`.quiet().nothrow().cwd(R.worktree);if(Y.exitCode!==0)throw new T.RemoveFailedError({message:I(Y)||"Failed to remove git worktree"});let X=H.branch?.replace(/^refs\/heads\//,"");if(X){let ne=await $`git branch -D ${X}`.quiet().nothrow().cwd(R.worktree);if(ne.exitCode!==0)throw new T.RemoveFailedError({message:I(ne)||"Failed to delete worktree branch"})}return true}),T.reset=fn$1(T.ResetInput,async j=>{if(R.project.vcs!=="git")throw new T.NotGitError({message:"Worktrees are only supported for git projects"});let x=await y(j.directory),k=await y(R.worktree);if(x===k)throw new T.ResetFailedError({message:"Cannot reset the primary workspace"});let _=await $`git worktree list --porcelain`.quiet().nothrow().cwd(R.worktree);if(_.exitCode!==0)throw new T.ResetFailedError({message:I(_)||"Failed to read git worktrees"});let H=P(_.stdout).split(`
939
- `).map(re=>re.trim()).reduce((re,Ee)=>{if(!Ee)return re;if(Ee.startsWith("worktree "))return re.push({path:Ee.slice(9).trim()}),re;let Ae=re[re.length-1];return Ae&&Ee.startsWith("branch ")&&(Ae.branch=Ee.slice(7).trim()),re},[]),Y=await(async()=>{for(let re of H){if(!re.path)continue;if(await y(re.path)===x)return re}})();if(!Y?.path)throw new T.ResetFailedError({message:"Worktree not found"});let X=await $`git remote`.quiet().nothrow().cwd(R.worktree);if(X.exitCode!==0)throw new T.ResetFailedError({message:I(X)||"Failed to list git remotes"});let ne=P(X.stdout).split(`
940
- `).map(re=>re.trim()).filter(Boolean),ae=ne.includes("origin")?"origin":ne.length===1?ne[0]:ne.includes("upstream")?"upstream":"",le=ae?await $`git symbolic-ref refs/remotes/${ae}/HEAD`.quiet().nothrow().cwd(R.worktree):{exitCode:1,stdout:void 0},be=le.exitCode===0?P(le.stdout):"",se=be?be.replace(/^refs\/remotes\//,""):"",Q=ae&&se.startsWith(`${ae}/`)?se.slice(`${ae}/`.length):"",q=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=q.exitCode===0?"main":F.exitCode===0?"master":"",G=Q?`${ae}/${Q}`:te;if(!G)throw new T.ResetFailedError({message:"Default branch not found"});if(Q){let re=await $`git fetch ${ae} ${Q}`.quiet().nothrow().cwd(R.worktree);if(re.exitCode!==0)throw new T.ResetFailedError({message:I(re)||`Failed to fetch ${G}`})}if(!Y.path)throw new T.ResetFailedError({message:"Worktree path not found"});let J=Y.path,oe=await $`git reset --hard ${G}`.quiet().nothrow().cwd(J);if(oe.exitCode!==0)throw new T.ResetFailedError({message:I(oe)||"Failed to reset worktree to target"});let ce=await w(J);if(ce.exitCode!==0)throw new T.ResetFailedError({message:I(ce)||"Failed to clean worktree"});let me=await $`git submodule update --init --recursive --force`.quiet().nothrow().cwd(J);if(me.exitCode!==0)throw new T.ResetFailedError({message:I(me)||"Failed to update submodules"});let pe=await $`git submodule foreach --recursive git reset --hard`.quiet().nothrow().cwd(J);if(pe.exitCode!==0)throw new T.ResetFailedError({message:I(pe)||"Failed to reset submodules"});let xe=await $`git submodule foreach --recursive git clean -fdx`.quiet().nothrow().cwd(J);if(xe.exitCode!==0)throw new T.ResetFailedError({message:I(xe)||"Failed to clean submodules"});let qe=await $`git status --porcelain=v1`.quiet().nothrow().cwd(J);if(qe.exitCode!==0)throw new T.ResetFailedError({message:I(qe)||"Failed to read git status"});let Ie=P(qe.stdout);if(Ie)throw new T.ResetFailedError({message:`Worktree reset left local changes:
941
- ${Ie}`});let we=R.project.id;return D(J,{providerId:we}),true});})(An||(An={}));var Vh=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(U.array(U.string()).meta({ref:"ToolIDs"}))}}},...Te(400)}}),async e=>e.json(await Ho.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(U.array(U.object({id:U.string(),description:U.string(),parameters:U.any()}).meta({ref:"ToolListItem"})).meta({ref:"ToolList"}))}}},...Te(400)}}),validator("query",U.object({provider:U.string(),model:U.string()})),async e=>{let{provider:t,model:o}=e.req.valid("query"),n=await Ho.tools({providerId:t,modelId:o});return e.json(n.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(An.Info)}}},...Te(400)}}),validator("json",An.create.schema),async e=>{let t=e.req.valid("json"),o=await An.create(t);return e.json(o)}).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(U.array(U.string()))}}}}}),async e=>{let t=await qt.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(U.boolean())}}},...Te(400)}}),validator("json",An.remove.schema),async e=>{let t=e.req.valid("json");return await An.remove(t),await qt.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(U.boolean())}}},...Te(400)}}),validator("json",An.reset.schema),async e=>{let t=e.req.valid("json");return await An.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(U.record(U.string(),U.unknown()))}}}}}),async e=>e.json(await Ue.resources())));var gs;(a=>{let e;function t(){return e||(e=R.state(async()=>({methods:pipe(await fs.list(),filter(u=>u.auth?.provider!==void 0),map(u=>[u.auth.provider,u.auth]),fromEntries()),pending:{}}))),e}function o(){return t()()}a.Method=U.object({type:U.union([U.literal("oauth"),U.literal("api")]),label:U.string()}).meta({ref:"ProviderAuthMethod"});async function s(){let p=await o().then(u=>u.methods);return mapValues(p,u=>u.methods.map(h=>({type:h.type,label:h.label})))}a.methods=s,a.Authorization=U.object({url:U.string(),method:U.union([U.literal("auto"),U.literal("code")]),instructions:U.string()}).meta({ref:"ProviderAuthAuthorization"}),a.authorize=fn$1(U.object({providerId:U.string(),method:U.number()}),async p=>{let u=await o().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 o().then(v=>v.pending[p.providerId]=g),{url:g.url??"",method:g.method??"",instructions:g.instructions??""}):void 0}}),a.callback=fn$1(U.object({providerId:U.string(),method:U.number(),code:U.string().optional()}),async p=>{let u=await o().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(U.object({providerId:U.string(),key:U.string()}),async p=>{await Qe.set(p.providerId,{type:"api",key:p.key});}),a.OauthMissing=NamedError.create("ProviderAuthOauthMissing",U.object({providerId:U.string()})),a.OauthCodeMissing=NamedError.create("ProviderAuthOauthCodeMissing",U.object({providerId:U.string()})),a.OauthCallbackFailed=NamedError.create("ProviderAuthOauthCallbackFailed",U.object({}));})(gs||(gs={}));var Jh=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(U.object({all:a$3.Provider.array(),default:U.record(U.string(),U.string()),connected:U.array(U.string())}))}}}}}),async e=>{let t=await he.get(),o=new Set(t.disabled_providers??[]),n=t.enabled_providers?new Set(t.enabled_providers):void 0,s=await a$3.get(),r={};for(let[l,d]of Object.entries(s))(!n||n.has(l))&&!o.has(l)&&(r[l]=d);let i=await Se.list(),c=Object.assign(mapValues(r,l=>Se.fromModelsDevProvider(l)),i);return e.json({all:Object.values(c),default:mapValues(c,l=>Se.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(U.record(U.string(),U.array(gs.Method)))}}}}}),async e=>e.json(await gs.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(gs.Authorization.optional())}}},...Te(400)}}),validator("param",U.object({providerId:U.string().meta({description:"Provider ID"})})),validator("json",U.object({method:U.number().meta({description:"Auth method index"})})),async e=>{let t=e.req.valid("param").providerId,{method:o}=e.req.valid("json"),n=await gs.authorize({providerId:t,method:o});return e.json(n)}).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(U.boolean())}}},...Te(400)}}),validator("param",U.object({providerId:U.string().meta({description:"Provider ID"})})),validator("json",U.object({method:U.number().meta({description:"Auth method index"}),code:U.string().optional().meta({description:"OAuth authorization code"})})),async e=>{let t=e.req.valid("param").providerId,{method:o,code:n}=e.req.valid("json");return await gs.callback({providerId:t,method:o,code:n}),e.json(true)}));var Qh=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(U.object({providerId:U.string(),modelId:U.string()}).optional())}}},...Te(400)}}),async e=>{let t=await Se.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(U.object({providerId:U.string(),modelId:U.string()}).optional())}}},...Te(400)}}),async e=>{let t=e.req.query("model");if(!t)return e.json(void 0);let o=Se.parseModel(t);return o?.providerId?e.json({providerId:o.providerId,modelId:o.modelId}):e.json(void 0)}));var Zh=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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({requestId:U.string()})),validator("json",Ot.Reply),async e=>{let t=e.req.valid("param"),o=e.req.valid("json");return await Ot.reply({requestId:t.requestId,answers:o.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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({requestId:U.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(U.boolean())}}},...Te(400,404)}}),validator("param",U.object({requestId:U.string()})),validator("json",U.object({reply:Oe.Reply,message:U.string().optional()})),async e=>{let t=e.req.valid("param"),o=e.req.valid("json");return await Oe.reply({requestId:t.requestId,reply:o.reply,message:o.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(Oe.Request.array())}}}}}),async e=>{let t=await Oe.list();return e.json(t)}));var sy=a.create({service:"server"}),WA=a$5.define("global.disposed",U.object({})),ry=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(U.object({healthy:U.literal(true),version:U.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(U.object({directory:U.string(),payload:a$5.payloads()}).meta({ref:"GlobalEvent"}))}}}}}),async e=>(sy.info("global event connected"),streamSSE(e,async t=>{t.writeSSE({data:JSON.stringify({payload:{type:"server.connected",properties:{}}})});async function o(s){await t.writeSSE({data:JSON.stringify(s)});}mt.on("event",o);let n=setInterval(()=>{t.writeSSE({data:JSON.stringify({payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(s=>{t.onAbort(()=>{clearInterval(n),mt.off("event",o),s(),sy.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"),o=await he.updateGlobal(t);return e.json(o)}).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(U.boolean())}}}}}),async e=>(await R.disposeAll(),mt.emit("event",{directory:"global",payload:{type:WA.type,properties:{}}}),e.json(true))));var iy=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(U.array(Ne.Info))}}}}}),async e=>{let t=await Ne.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(Ne.Info)}}},...Te(404)}}),async e=>{let t=e.req.param("agentId"),o=await Ne.get(t);return o?e.json(o):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 o=>{await o.writeSSE({data:JSON.stringify({type:"agent.connected",properties:{agentId:t}})});let n=ue.subscribeAll(async s=>{s.properties?.agentId===t&&await o.writeSSE({data:JSON.stringify(s)});});await new Promise(s=>{o.onAbort(()=>{n(),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(Ne.Info)}}},...Te(404)}}),async e=>{let t=await Ne.defaultAgent(),o=await Ne.get(t);return o?e.json(o):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(Ne.Info)}}},...Te(400),...Te(404)}}),validator("json",U.object({name:U.string(),mode:U.enum(["subagent","primary","all"]).optional(),permission:U.record(U.string(),U.any()).optional(),description:U.string().optional(),prompt:U.string().optional(),model:U.object({providerId:U.string(),modelId:U.string()}).optional(),temperature:U.number().optional(),topP:U.number().optional(),color:U.string().optional(),hidden:U.boolean().optional(),variant:U.string().optional(),steps:U.number().int().positive().optional(),options:U.record(U.string(),U.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 Ne.get(t.name))return e.json({error:`Agent "${t.name}" already exists`},400);let n={mode:t.mode||"primary"};t.description&&(n.description=t.description),t.prompt&&(n.prompt=t.prompt),t.model&&(n.model=`${t.model.providerId}/${t.model.modelId}`),t.temperature!==void 0&&(n.temperature=t.temperature),t.topP!==void 0&&(n.topP=t.topP),t.color&&(n.color=t.color),t.hidden!==void 0&&(n.hidden=t.hidden),t.variant&&(n.variant=t.variant),t.steps!==void 0&&(n.steps=t.steps),t.permission&&(n.permission=t.permission),t.options&&(n.options=t.options),await he.update({agent:{[t.name]:n}});let s=await Ne.get(t.name);return s?e.json(s,201):e.json({error:`Failed to retrieve created agent "${t.name}"`},500)}catch(o){let n=o instanceof Error?o.message:"Agent creation failed";return e.json({error:n},400)}}));var ga=a.create({service:"mdns"}),ha;(s=>{let e,t;function o(r,i){if(t!==r){e&&n();try{let c=i??"easbot.local",l=`easbot-${r}`;e=new XA;let d=e.publish({name:l,type:"http",host:c,port:r,txt:{path:"/"}});d.on("up",()=>{ga.info("mDNS service published",{name:l,port:r});}),d.on("error",m=>{ga.error("mDNS service error",{error:m});}),t=r;}catch(c){if(ga.error("mDNS publish failed",{error:c}),e)try{e.destroy();}catch{}e=void 0,t=void 0;}}}s.publish=o;function n(){if(e){try{e.unpublishAll(),e.destroy();}catch(r){ga.error("mDNS unpublish failed",{error:r});}e=void 0,t=void 0,ga.info("mDNS service unpublished");}}s.unpublish=n;})(ha||(ha={}));globalThis.AI_SDK_LOG_WARNINGS=false;var ya;(f=>{let e=a.create({service:"server"}),t=compress(),o=(a,p)=>!!(a==="/event"||a==="/global/event"||a==="/global/sync-event"||p==="POST"&&/\/session\/[^/]+\/(message|prompt_async)$/.test(a)),n,s=[];function r(){return n??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 Se.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)=>o(a.req.path,a.req.method)?p():t(a,p)).route("/global",ry()).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(U.boolean())}}},...Te(400)}}),validator("param",U.object({providerId:U.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(U.boolean())}}},...Te(400)}}),validator("param",U.object({providerId:U.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:la,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",U.object({directory:U.string().optional(),workspace:U.string().optional()}))).route("/project",Dh()).route("/pty",Uh()).route("/config",Bh()).route("/experimental",Vh()).route("/session",Nh()).route("/permission",ny()).route("/question",Zh()).route("/provider",Jh()).route("/model",Qh()).route("/",qh()).route("/mcp",zh()).route("/agent",iy()).route("/tui",Mh()).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(U.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(U.object({home:U.string(),state:U.string(),config:U.string(),worktree:U.string(),directory:U.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(Ws.Info)}}}}}),async a=>{let p=await Ws.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(So.Info.array())}}}}}),validator("query",U.object({contextMode:U.string().optional()})),async a=>{let{contextMode:p}=a.req.valid("query"),u=await So.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(U.boolean())}}},...Te(400)}}),validator("json",U.object({service:U.string().meta({description:"Service name for the log entry"}),level:U.enum(["debug","info","error","warn"]).meta({description:"Log level"}),message:U.string().meta({description:"Log message"}),extra:U.record(U.string(),U.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"),v=a.create({service:p});switch(u){case "debug":v.debug(h,g);break;case "info":v.info(h,g);break;case "error":v.error(h,g);break;case "warn":v.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(Ne.Info.array())}}}}}),async a=>{let p=await Ne.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(Qt.Info.array())}}}}}),async a=>{let p=await Qt.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(vs.Status.array())}}}}}),async a=>a.json(await vs.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=ue.subscribeAll(async g=>{await p.writeSSE({data:JSON.stringify(g)}),g.type===ue.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(U.boolean())}}}}}),validator("json",U.object({type:U.string(),properties:U.record(U.string(),U.any()).optional()})),async a=>{let p=a.req.valid("json"),u=a$5.define(p.type,U.record(U.string(),U.any()));return await ue.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(U.object({protocolMetadata:U.object({agentId:U.string().optional(),workspace:U.string(),name:U.string(),userName:U.string(),mission:U.string(),preferredName:U.string().optional(),coreRelationship:U.string().optional(),coreValues:U.array(U.string()).optional(),behaviorStyle:U.string().optional(),decisionPrinciples:U.array(U.string()).optional()}),protocolInitialized:U.boolean()}))}}}}}),async a=>{let p=await hn.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((S,w)=>{(0, f.App)().fetch;let b=new URL(S.url??"/",`http://${S.headers.host}`),C=new Headers;for(let[$,K]of Object.entries(S.headers))K&&C.set($,Array.isArray(K)?K.join(", "):K);let E=new AbortController;S.on("close",()=>E.abort());let O=new Request(b,{method:S.method,headers:C,body:S.method!=="GET"&&S.method!=="HEAD"?S:void 0,signal:E.signal,duplex:"half"}),D=(0, f.App)().fetch(O);Promise.resolve(D).then($=>{w.statusCode=$.status,w.statusMessage=$.statusText;for(let[K,ee]of $.headers.entries())w.setHeader(K,ee);$.body?$.body.pipeTo(new WritableStream({write(K){w.write(K);},close(){w.end();}})):w.end();}).catch($=>{e.error("Server error",{error:$.message}),w.statusCode=500,w.end("Internal Server Error");});}),u=S=>{try{return p.listen(S,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(),v=typeof g=="object"&&g?g.port:h,P=a.hostname==="0.0.0.0"?"localhost":a.hostname;n=new URL(`http://${P}:${v}`);let I=a.mdns&&v&&a.hostname!=="127.0.0.1"&&a.hostname!=="localhost"&&a.hostname!=="::1";return I?ha.publish(v,a.mdnsDomain):a.mdns&&e.warn("mDNS enabled but hostname is loopback; skipping mDNS publish"),{url:n,port:v,stop:async S=>(I&&ha.unpublish(),new Promise(w=>{p.close(()=>{w();});})),raw:p}}f.listen=d,f.Default=f.App;})(ya||(ya={}));var Sp=a.create({service:"plugin.codex"}),wa="app_EMoamEEZ73f0CkXaXp7hrann",hs="https://auth.openai.com",uR="https://chatgpt.com/backend-api/codex/responses",Qs=1455,pR=3e3;async function mR(){let e=fR(43),o=new TextEncoder().encode(e),n=await crypto.subtle.digest("SHA-256",o),s=ly(n);return {verifier:e,challenge:s}}function fR(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",o=crypto.getRandomValues(new Uint8Array(e));return Array.from(o).map(n=>t[n%t.length]).join("")}function ly(e){let t=new Uint8Array(e),o=String.fromCharCode(...t);return btoa(o).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function gR(){return ly(crypto.getRandomValues(new Uint8Array(32)).buffer)}function cy(e){let t=e.split(".");if(t.length===3)try{let o=t[1];return o?JSON.parse(Buffer.from(o,"base64url").toString()):void 0}catch{return}}function dy(e){return e.chatgpt_account_id||e["https://api.openai.com/auth"]?.chatgpt_account_id||e.organizations?.[0]?.id}function Ip(e){if(e.id_token){let t=cy(e.id_token),o=t&&dy(t);if(o)return o}if(e.access_token){let t=cy(e.access_token);return t?dy(t):void 0}}function hR(e,t,o){let n=new URLSearchParams({response_type:"code",client_id:wa,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:o,originator:"easbot"});return `${hs}/oauth/authorize?${n.toString()}`}async function yR(e,t,o){let n=await fetch(`${hs}/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:wa,code_verifier:o.verifier}).toString()});if(!n.ok)throw new Error(`Token exchange failed: ${n.status}`);return n.json()}async function bR(e){let t=await fetch(`${hs}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:wa}).toString()});if(!t.ok)throw new Error(`Token refresh failed: ${t.status}`);return t.json()}var wR=`<!doctype html>
942
- <html>
943
- <head>
944
- <title>EasBot - Codex Authorization Successful</title>
945
- <style>
946
- body {
947
- font-family:
948
- system-ui,
949
- -apple-system,
950
- sans-serif;
951
- display: flex;
952
- justify-content: center;
953
- align-items: center;
954
- height: 100vh;
955
- margin: 0;
956
- background: #131010;
957
- color: #f1ecec;
958
- }
959
- .container {
960
- text-align: center;
961
- padding: 2rem;
962
- }
963
- h1 {
964
- color: #f1ecec;
965
- margin-bottom: 1rem;
966
- }
967
- p {
968
- color: #b7b1b1;
969
- }
970
- </style>
971
- </head>
972
- <body>
973
- <div class="container">
974
- <h1>Authorization Successful</h1>
975
- <p>You can close this window and return to EasBot.</p>
976
- </div>
977
- <script>
978
- setTimeout(() => window.close(), 2000)
979
- </script>
980
- </body>
981
- </html>`,vp=e=>`<!doctype html>
982
- <html>
983
- <head>
984
- <title>EasBot - Codex Authorization Failed</title>
985
- <style>
986
- body {
987
- font-family:
988
- system-ui,
989
- -apple-system,
990
- sans-serif;
991
- display: flex;
992
- justify-content: center;
993
- align-items: center;
994
- height: 100vh;
995
- margin: 0;
996
- background: #131010;
997
- color: #f1ecec;
998
- }
999
- .container {
1000
- text-align: center;
1001
- padding: 2rem;
1002
- }
1003
- h1 {
1004
- color: #fc533a;
1005
- margin-bottom: 1rem;
1006
- }
1007
- p {
1008
- color: #b7b1b1;
1009
- }
1010
- .error {
1011
- color: #ff917b;
1012
- font-family: monospace;
1013
- margin-top: 1rem;
1014
- padding: 1rem;
1015
- background: #3c140d;
1016
- border-radius: 0.5rem;
1017
- }
1018
- </style>
1019
- </head>
1020
- <body>
1021
- <div class="container">
1022
- <h1>Authorization Failed</h1>
1023
- <p>An error occurred during authorization.</p>
1024
- <div class="error">${e}</div>
1025
- </div>
1026
- </body>
1027
- </html>`,ba,Co;async function xR(){return ba?{port:Qs,redirectUri:`http://localhost:${Qs}/auth/callback`}:(ba=serve({port:Qs,fetch(e){let t=new URL(e.url);if(t.pathname==="/auth/callback"){let o=t.searchParams.get("code"),n=t.searchParams.get("state"),s=t.searchParams.get("error"),r=t.searchParams.get("error_description");if(s){let c=r||s;return Co?.reject(new Error(c)),Co=void 0,new Response(vp(c),{headers:{"Content-Type":"text/html"}})}if(!o){let c="Missing authorization code";return Co?.reject(new Error(c)),Co=void 0,new Response(vp(c),{status:400,headers:{"Content-Type":"text/html"}})}if(!Co||n!==Co.state){let c="Invalid state - potential CSRF attack";return Co?.reject(new Error(c)),Co=void 0,new Response(vp(c),{status:400,headers:{"Content-Type":"text/html"}})}let i=Co;return Co=void 0,yR(o,`http://localhost:${Qs}/auth/callback`,i.pkce).then(c=>i.resolve(c)).catch(c=>i.reject(c)),new Response(wR,{headers:{"Content-Type":"text/html"}})}return t.pathname==="/cancel"?(Co?.reject(new Error("Login cancelled")),Co=void 0,new Response("Login cancelled",{status:200})):new Response("Not found",{status:404})}}),Sp.info("codex oauth server started",{port:Qs}),{port:Qs,redirectUri:`http://localhost:${Qs}/auth/callback`})}function IR(){ba&&(ba.close(),ba=void 0,Sp.info("codex oauth server stopped"));}function vR(e,t){return new Promise((o,n)=>{let s=setTimeout(()=>{Co&&(Co=void 0,n(new Error("OAuth callback timeout - authorization took too long")));},3e5);Co={pkce:e,state:t,resolve:r=>{clearTimeout(s),o(r);},reject:r=>{clearTimeout(s),n(r);}};})}async function uy(e){return {auth:{provider:"openai",loader:async(t,o)=>{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(o.models))s.has(r)||delete o.models[r];if(!o.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=bt.variants(r),o.models["gpt-5.3-codex"]=r;}for(let r of Object.values(o.models))r.cost={input:0,output:0,cache:{read:0,write:0}};return {apiKey:Bp,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()){Sp.info("refreshing codex access token");let a=await bR(c.refresh),p=Ip(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(uR):m;return fetch(f,{...i,headers:d})}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:t}=await xR(),o=await mR(),n=gR(),s=hR(t,o,n),r=vR(o,n);return {url:s,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{let i=await r;IR();let c=Ip(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(`${hs}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({client_id:wa})});if(!t.ok)throw new Error("Failed to initiate device authorization");let o=await t.json(),n=Math.max(parseInt(o.interval,10)||5,1)*1e3;return {url:`${hs}/codex/device`,instructions:`Enter code: ${o.user_code}`,method:"auto",async callback(){for(;;){let s=await fetch(`${hs}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({device_auth_id:o.device_auth_id,user_code:o.user_code})});if(s.ok){let r=await s.json(),i=await fetch(`${hs}/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:`${hs}/deviceauth/callback`,client_id:wa,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:Ip(c)}}if(s.status!==403&&s.status!==404)return {type:"failed"};await new Promise(r=>setTimeout(r,n+pR));}}}}},{label:"Manually enter API Key",type:"api"}]},"llm.headers":async(t,o)=>{t.model&&t.model.providerId==="openai"&&(t.headers??(t.headers={}),t.headers.originator="easbot",t.headers["User-Agent"]=`easbot/${b$3.getVersion()} (${nc.platform()} ${nc.release()}; ${nc.arch()})`,t.headers.session_id=t.sessionId,o.modified=true,o.input=t);}}}var py="Ov23li8tweQw6odWQebz",Cp=3e3;function my(e){return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}function CR(e){return {DEVICE_CODE_URL:`https://${e}/login/device/code`,ACCESS_TOKEN_URL:`https://${e}/login/oauth/access_token`}}async function fy(e){let t=e.client;return {auth:{provider:"github-copilot",async loader(o,n){let s=await o();if(!s||s.type!=="oauth")return {};let r=s.enterpriseUrl,i=r?`https://copilot-api.${my(r)}`:void 0;if(n?.models)for(let c of Object.values(n.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 o();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(v=>v.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(v=>v.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(v=>v?.type!=="tool_result");return {isVision:u.messages.some(v=>Array.isArray(v?.content)&&v.content.some(P=>P?.type==="image"||P?.type==="tool_result"&&Array.isArray(P?.content)&&P.content.some(I=>I?.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:o=>o.deploymentType==="enterprise",validate:o=>{if(!o)return "URL or domain is required";try{return (o.includes("://")?new URL(o):new URL(`https://${o}`)).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(o={}){let n=o.deploymentType||"github.com",s="github.com",r="github-copilot";if(n==="enterprise"){let d=o.enterpriseUrl;s=my(d),r="github-copilot-enterprise";}let i=CR(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:py,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:py,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+Cp));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+Cp));continue}if(m.error)return {type:"failed"};await new Promise(f=>setTimeout(f,l.interval*1e3+Cp));}}}}}]},"llm.headers":async(o,n)=>{!o.model||typeof o.model=="string"||!o.model.providerId.includes("github-copilot")||(o.headers??(o.headers={}),"api"in o.model&&typeof o.model.api=="object"&&o.model.api?.npm==="@ai-sdk/anthropic"&&(o.headers["anthropic-beta"]="interleaved-thinking-2025-05-14"),!(await t.session.get({sessionId:o.sessionId}).catch(()=>{}))?.data?.parentId)||(o.headers["x-initiator"]="agent",n.modified=true,n.input=o);}}}var fs;(m=>{let e=a.create({service:"plugin"}),t=[],o=[uy,fy],n;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 Ho.register({id:a,init:async()=>({parameters:U.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 n||(n=R.state(async()=>{let f=createEasbotClient({baseUrl:"http://localhost:4096",directory:R.directory,fetch:async(...g)=>ya.App().fetch(...g)}),a=await he.get(),p=[],u={client:f,project:R.project,worktree:R.worktree,directory:R.directory,serverUrl:ya.url(),$:shell};for(let g of o){e.info("loading internal plugin",{name:g.name});let v=await g(u).catch(P=>{e.error("failed to load internal plugin",{name:g.name,error:P});});v&&(p.push(v),s(v),await r(v));}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 v=g.lastIndexOf("@"),P=v>0?g.substring(0,v):g,I=v>0?g.substring(v+1):"latest",A=t.some(S=>S.startsWith(P+"@"));if(g=await Shell.install(P,I).catch(S=>{if(!A)throw S;let w=S instanceof Error?S.message:String(S);return e.error("failed to install builtin plugin",{pkg:P,version:I,error:w}),ue.publish(Z.Event.Error,{error:new NamedError.Unknown({message:`Failed to install built-in plugin ${P}@${I}: ${w}`}).toObject()}).catch(y=>{e.error("failed to publish error event",{error:y});}),""}),!g)continue}await import(g).then(async v=>{let P=new Set;for(let[I,A]of Object.entries(v)){if(P.has(A))continue;P.add(A);let S=await A(u);p.push(S),s(S),await r(S);}}).catch(v=>{let P=v instanceof Error?v.message:String(v);e.error("failed to load plugin",{path:g,error:P}),ue.publish(Z.Event.Error,{error:new NamedError.Unknown({message:`Failed to load plugin ${g}: ${P}`}).toObject()}).catch(I=>{e.error("failed to publish error event",{error:I});});});}return {plugins:p,input:u}})),n}function c(){return i()()}async function l(){return c().then(f=>f.plugins)}m.list=l;async function d(){await Le.init(),await So.init(),await Ho.init();let f=await c().then(p=>p.plugins),a=await he.get();for(let p of f)await p.config?.(a);ue.subscribeAll(async p=>{let u=await c().then(h=>h.plugins);for(let h of u)h.event?.({event:p});});}m.init=d;})(fs||(fs={}));var MR={"@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)},Se;(N=>{N.DEFAULT_CONTEXT_LIMIT=2e5,N.DEFAULT_INPUT_LIMIT_RATIO=.9,N.DEFAULT_OUTPUT_LIMIT=8192;function n(M=2e5){return Math.floor(M*.9)}N.getDefaultInputLimit=n;let s=a.create({service:"provider"});function r(M){let T=/^gpt-(\d+)/.exec(M);return T?Number(T[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 T=await(async()=>{let j=await tt.all();return !!(M.env.some(k=>j[k])||await Qe.get(M.id)||(await he.get()).provider?.opencode?.options?.apiKey)})();if(!T)for(let[j,x]of Object.entries(M.models))x.cost.input!==0&&delete M.models[j];return {autoload:Object.keys(M.models).length>0,options:T?{}:{apiKey:"public"}}},openai:async()=>{let M=await tt.get("OPENAI_BASE_URL");return {autoload:false,async getModel(T,j,x){return T.responses(j)},options:M?{baseURL:M}:{}}},"github-copilot":async()=>({autoload:false,async getModel(M,T,j){return M.responses===void 0&&M.chat===void 0?M.languageModel(T):i(T)?M.responses(T):M.chat(T)},options:{}}),"github-copilot-enterprise":async()=>({autoload:false,async getModel(M,T,j){return M.responses===void 0&&M.chat===void 0?M.languageModel(T):i(T)?M.responses(T):M.chat(T)},options:{}}),azure:async()=>({autoload:false,async getModel(M,T,j){return j?.useCompletionUrls?M.chat(T):M.responses(T)},options:{}}),"azure-cognitive-services":async()=>{let M=tt.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME");return {autoload:false,async getModel(T,j,x){return x?.useCompletionUrls?T.chat(j):T.responses(j)},options:{baseURL:M?`https://${M}.cognitiveservices.azure.com/openai`:void 0}}},"amazon-bedrock":async()=>{let T=(await he.get()).provider?.["amazon-bedrock"],j=await Qe.get("amazon-bedrock"),x=T?.options?.region,k=tt.get("AWS_REGION"),_=x??k??"us-east-1",L=T?.options?.profile,H=tt.get("AWS_PROFILE"),Y=L??H,X=tt.get("AWS_ACCESS_KEY_ID"),ne=iife(()=>{let Q=process.env.AWS_BEARER_TOKEN_BEDROCK;if(Q)return Q;if(j?.type==="api")return process.env.AWS_BEARER_TOKEN_BEDROCK=j.key,j.key}),ae=tt.get("AWS_WEB_IDENTITY_TOKEN_FILE"),le=!!(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(!Y&&!X&&!ne&&!ae&&!le)return {autoload:false};let be={region:_};if(!ne){let Q=await Shell.install("@aws-sdk/credential-providers"),{pathToFileURL:q}=await import('url'),F=Ce__default.join(Q,"dist-cjs","index.js"),{fromNodeProviderChain:te}=await import(q(F).href),G=Y?{profile:Y}:{};be.credentialProvider=te(G);}let se=T?.options?.endpoint??T?.options?.baseURL;return se&&(be.baseURL=se),{autoload:true,options:be,async getModel(Q,q,F){if(["global.","us.","eu.","jp.","apac.","au."].some(oe=>q.startsWith(oe)))return Q.languageModel(q);let G=F?.region??_,J=G.split("-")[0];switch(J){case "us":{let oe=["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek"].some(me=>q.includes(me)),ce=G.startsWith("us-gov");oe&&!ce&&(q=`${J}.${q}`);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=>G.includes(me)),ce=["claude","nova-lite","nova-micro","llama3","pixtral"].some(me=>q.includes(me));oe&&ce&&(q=`${J}.${q}`);break}case "ap":{let oe=["ap-southeast-2","ap-southeast-4"].includes(G),ce=G==="ap-northeast-1";oe&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some(me=>q.includes(me))?(J="au",q=`${J}.${q}`):ce?["claude","nova-lite","nova-micro","nova-pro"].some(pe=>q.includes(pe))&&(J="jp",q=`${J}.${q}`):["claude","nova-lite","nova-micro","nova-pro"].some(pe=>q.includes(pe))&&(J="apac",q=`${J}.${q}`);break}}return Q.languageModel(q)}}},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"),T=await tt.get("GOOGLE_CLOUD_LOCATION")??tt.get("VERTEX_LOCATION")??"us-east5";return !M?{autoload:false}:{autoload:true,vars(x){let k=T==="global"?"aiplatform.googleapis.com":`${T}-aiplatform.googleapis.com`;return {...M&&{GOOGLE_VERTEX_PROJECT:M},GOOGLE_VERTEX_LOCATION:T,GOOGLE_VERTEX_ENDPOINT:k}},options:{project:M,location:T,fetch:async(x,k)=>{let{GoogleAuth:_}=await import('google-auth-library'),Y=await(await new _().getApplicationDefault()).credential.getAccessToken(),X=new Headers(k?.headers);return X.set("Authorization",`Bearer ${Y.token}`),fetch(x,{...k,headers:X})}},async getModel(x,k){let _=String(k).trim();return x.languageModel(_)}}},"google-vertex-anthropic":async()=>{let M=tt.get("GOOGLE_CLOUD_PROJECT")??tt.get("GCP_PROJECT")??tt.get("GCLOUD_PROJECT"),T=tt.get("GOOGLE_CLOUD_LOCATION")??tt.get("VERTEX_LOCATION")??"global";return !M?{autoload:false}:{autoload:true,options:{project:M,location:T},async getModel(x,k){let _=String(k).trim();return x.languageModel(_)}}},"sap-ai-core":async()=>{let M=await Qe.get("sap-ai-core"),T=iife(()=>{let k=process.env.AICORE_SERVICE_KEY;if(k)return k;if(M?.type==="api")return process.env.AICORE_SERVICE_KEY=M.key,M.key}),j=process.env.AICORE_DEPLOYMENT_ID,x=process.env.AICORE_RESOURCE_GROUP;return {autoload:!!T,options:T?{deploymentId:j,resourceGroup:x}:{},async getModel(k,_){return k(_)}}},zenmux:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.cn/","X-Title":"easbot"}}}),gitlab:async M=>{let T=tt.get("GITLAB_INSTANCE_URL")||"https://gitlab.com",j=await Qe.get(M.id),x=await(async()=>j?.type==="oauth"?j.access:j?.type==="api"?j.key:tt.get("GITLAB_TOKEN"))(),_=(await he.get()).provider?.gitlab,{VERSION:L,createGitLab:H}=await import('gitlab-ai-provider'),Y={"User-Agent":`easbot/${b$3.getVersion()} gitlab-ai-provider/${L} (${nc.platform()} ${nc.release()}; ${nc.arch()})`,..._?.options?.aiGatewayHeaders||{}};return {autoload:!!x,options:{instanceUrl:T,apiKey:x,aiGatewayHeaders:Y,featureFlags:{duo_agent_platform_agentic_chat:true,duo_agent_platform:true,..._?.options?.featureFlags||{}}},async getModel(X,ne){return X.agenticChat(ne,{aiGatewayHeaders:Y,featureFlags:{duo_agent_platform_agentic_chat:true,duo_agent_platform:true,..._?.options?.featureFlags||{}}})}}},"cloudflare-workers-ai":async M=>{let T=tt.get("CLOUDFLARE_ACCOUNT_ID");if(!T)return {autoload:false};let j=await iife(async()=>{let x=tt.get("CLOUDFLARE_API_KEY");if(x)return x;let k=await Qe.get(M.id);if(k?.type==="api")return k.key});return {autoload:!!j,options:{apiKey:j,baseURL:`https://api.cloudflare.com/client/v4/accounts/${T}/ai/v1`},async getModel(x,k){return x.languageModel(k)}}},"cloudflare-ai-gateway":async M=>{let T=await tt.get("CLOUDFLARE_ACCOUNT_ID"),j=await tt.get("CLOUDFLARE_GATEWAY_ID");if(!T||!j)return {autoload:false};let x=await(async()=>{let Y=await tt.get("CLOUDFLARE_API_TOKEN")||await tt.get("CF_AIG_TOKEN");if(Y)return Y;let X=await Qe.get(M.id);if(X?.type==="api")return X.key})();if(!x)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:k}=await import('ai-gateway-provider'),{createUnified:_}=await import('ai-gateway-provider/providers/unified'),L=k({accountId:T,gateway:j,apiKey:x}),H=_();return {autoload:true,async getModel(Y,X,ne){return L(H(X))},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",T=a.file(),j=T?Ce__default.dirname(T):"",x=a.getLevel();return s.debug("Ollama loader initialized",{baseURL:M,logDir:j,logLevel:x}),{autoload:true,options:{baseURL:M,logDir:j,logLevel:x},async getModel(k,_,L){s.debug("Ollama getModel called",{modelId:_,options:L,baseURL:M});let H=k.languageModel?k.languageModel(_):k(_);return s.debug("Ollama model created",{modelId:_}),H}}},"easbot-local":async()=>{let{Global:M}=await import('./global-XQYOBWZR.mjs'),T=await tt.get("LOCAL_MODEL_PATH")||Ce__default.join(M.Path.cache,"models"),j=a.file(),x=j?Ce__default.dirname(j):"",k=a.getLevel();s.debug("Local Model loader initialized",{modelsPath:T,logDir:x,logLevel:k});let{SUPPORTED_EMBEDDING_MODELS:_}=await import('@easbot/local-model-sdk');return {autoload:true,options:{cacheDir:T,logDir:x,logLevel:k,verbose:true},async getModel(L,H,Y){if(s.debug("Local Model getModel called",{modelId:H,options:Y,modelsPath:T}),H in _){s.debug("Creating embedding model",{modelId:H});let ne=L.embeddingModel(H,Y);return s.debug("Embedding model created",{modelId:H}),ne}else if(H.startsWith("rerank-")){s.debug("Creating rerank model",{modelId:H});let ne=L.rerankingModel?L.rerankingModel(H.slice(6),Y):L(H);return s.debug("Language rerank created",{modelId:H}),ne}else {s.debug("Creating language model",{modelId:H});let ne=L.languageModel?L.languageModel(H,Y):L(H);return s.debug("Language model created",{modelId:H}),ne}}}}};N.Model=U.object({id:U.string(),providerId:U.string(),api:U.object({id:U.string(),url:U.string(),npm:U.string()}),name:U.string(),family:U.string().optional(),capabilities:U.object({temperature:U.boolean(),reasoning:U.boolean(),attachment:U.boolean(),toolcall:U.boolean(),input:U.object({text:U.boolean(),audio:U.boolean(),image:U.boolean(),video:U.boolean(),pdf:U.boolean()}),output:U.object({text:U.boolean(),audio:U.boolean(),image:U.boolean(),video:U.boolean(),pdf:U.boolean()}),interleaved:U.union([U.boolean(),U.object({field:U.enum(["reasoning_content","reasoning_details"])})])}),cost:U.object({input:U.number(),output:U.number(),cache:U.object({read:U.number(),write:U.number()}),experimentalOver200K:U.object({input:U.number(),output:U.number(),cache:U.object({read:U.number(),write:U.number()})}).optional()}),limit:U.object({context:U.number(),input:U.number().optional(),output:U.number()}),status:U.enum(["alpha","beta","deprecated","active"]),options:U.record(U.string(),U.any()),headers:U.record(U.string(),U.string()),release_date:U.string(),variants:U.record(U.string(),U.record(U.string(),U.any())).optional()}).meta({ref:"Model"}),N.Info=U.object({id:U.string(),name:U.string(),source:U.enum(["env","config","custom","api"]),env:U.string().array(),key:U.string().optional(),options:U.record(U.string(),U.any()),models:U.record(U.string(),N.Model)}).meta({ref:"Provider"});function m(M,T){let j={id:T.id,providerId:M.id,name:T.name,family:T.family,api:{id:T.id,url:M.api,npm:T.provider?.npm??M.npm??"@ai-sdk/openai-compatible"},status:T.status??"active",headers:T.headers??{},options:T.options??{},cost:{input:T.cost?.input??0,output:T.cost?.output??0,cache:{read:T.cost?.cache_read??0,write:T.cost?.cache_write??0},experimentalOver200K:T.cost?.context_over_200k?{cache:{read:T.cost.context_over_200k.cache_read??0,write:T.cost.context_over_200k.cache_write??0},input:T.cost.context_over_200k.input,output:T.cost.context_over_200k.output}:void 0},limit:{context:T.limit.context??2e5,input:T.limit.input??n(T.limit.context??2e5),output:T.limit.output??8192},capabilities:{temperature:T.temperature,reasoning:T.reasoning,attachment:T.attachment,toolcall:T.tool_call,input:{text:T.modalities?.input?.includes("text")??false,audio:T.modalities?.input?.includes("audio")??false,image:T.modalities?.input?.includes("image")??false,video:T.modalities?.input?.includes("video")??false,pdf:T.modalities?.input?.includes("pdf")??false},output:{text:T.modalities?.output?.includes("text")??false,audio:T.modalities?.output?.includes("audio")??false,image:T.modalities?.output?.includes("image")??false,video:T.modalities?.output?.includes("video")??false,pdf:T.modalities?.output?.includes("pdf")??false},interleaved:T.interleaved??false},release_date:T.release_date,variants:{}};return j.variants=mapValues(bt.variants(j),x=>x),j}function f(M){return {id:M.id,source:"custom",name:M.name,env:M.env??[],options:{},models:mapValues(M.models,T=>m(M,T))}}N.fromModelsDevProvider=f;async function a$1(){var Q=[];try{let M=c(Q,s.time("state"));let T=await he.get();let j=await a$3.get();let x=mapValues(j,f);let k=new Set(T.disabled_providers??[]);let _=T.enabled_providers?new Set(T.enabled_providers):null;function L(G){return !(_&&!_.has(G)||k.has(G))}let H={};let Y=new Map;let X={};let ne=new Map;let ae=new Map;s.info("init");let le=Object.entries(T.provider??{});if(x["github-copilot"]){let G=x["github-copilot"];x["github-copilot-enterprise"]={...G,id:"github-copilot-enterprise",name:"GitHub Copilot Enterprise",models:mapValues(G.models,J=>({...J,providerId:"github-copilot-enterprise"}))};}function be(G,J){let oe=H[G];if(oe){H[G]=mergeDeep(oe,J);return}let ce=x[G];ce&&(H[G]=mergeDeep(ce,J));}for(let[G,J]of le){let oe=x[G],ce={id:G,name:J.name??oe?.name??G,env:J.env??oe?.env??[],options:mergeDeep(oe?.options??{},J.options??{}),source:"config",models:oe?.models??{}};for(let[me,pe]of Object.entries(J.models??{})){let xe=ce.models[pe.id??me],qe=iife(()=>pe.name?pe.name:pe.id&&pe.id!==me?me:xe?.name??me),Ie={id:me,api:{id:pe.id??xe?.api.id??me,npm:pe.provider?.npm??J.npm??xe?.api.npm??j[G]?.npm??"@ai-sdk/openai-compatible",url:J?.api??xe?.api.url??j[G]?.api??""},status:pe.status??xe?.status??"active",name:qe,providerId:G,capabilities:{temperature:pe.temperature??xe?.capabilities.temperature??!1,reasoning:pe.reasoning??xe?.capabilities.reasoning??!1,attachment:pe.attachment??xe?.capabilities.attachment??!1,toolcall:pe.tool_call??xe?.capabilities.toolcall??!0,input:{text:pe.modalities?.input?.includes("text")??xe?.capabilities.input.text??!0,audio:pe.modalities?.input?.includes("audio")??xe?.capabilities.input.audio??!1,image:pe.modalities?.input?.includes("image")??xe?.capabilities.input.image??!1,video:pe.modalities?.input?.includes("video")??xe?.capabilities.input.video??!1,pdf:pe.modalities?.input?.includes("pdf")??xe?.capabilities.input.pdf??!1},output:{text:pe.modalities?.output?.includes("text")??xe?.capabilities.output.text??!0,audio:pe.modalities?.output?.includes("audio")??xe?.capabilities.output.audio??!1,image:pe.modalities?.output?.includes("image")??xe?.capabilities.output.image??!1,video:pe.modalities?.output?.includes("video")??xe?.capabilities.output.video??!1,pdf:pe.modalities?.output?.includes("pdf")??xe?.capabilities.output.pdf??!1},interleaved:pe.interleaved??!1},cost:{input:pe?.cost?.input??xe?.cost?.input??0,output:pe?.cost?.output??xe?.cost?.output??0,cache:{read:pe?.cost?.cache_read??xe?.cost?.cache.read??0,write:pe?.cost?.cache_write??xe?.cost?.cache.write??0}},options:mergeDeep(xe?.options??{},pe.options??{}),limit:{context:pe.limit?.context??xe?.limit?.context??2e5,input:pe.limit?.input??xe?.limit?.input??n(pe.limit?.context??2e5),output:pe.limit?.output??xe?.limit?.output??8192},headers:mergeDeep(xe?.headers??{},pe.headers??{}),family:pe.family??xe?.family??"",release_date:pe.release_date??xe?.release_date??"",variants:{}},we=mergeDeep(bt.variants(Ie),pe.variants??{});Ie.variants=mapValues(pickBy(we,re=>!re.disabled),re=>omit(re,["disabled"])),ce.models[me]=Ie;}x[G]=ce;}let se=await tt.all();for(let[G,J]of Object.entries(x)){if(k.has(G))continue;let oe=J.env.map(ce=>se[ce]).find(Boolean);oe&&be(G,{source:"env",key:J.env.length===1?oe:void 0});}for(let[G,J]of Object.entries(await Qe.all()))k.has(G)||J.type==="api"&&be(G,{source:"api",key:J.key});for(let G of await fs.list()){if(!G.auth)continue;let J=G.auth.provider;if(k.has(J))continue;let oe=!1,ce=await Qe.get(J);if(ce&&(oe=!0),J==="github-copilot"&&!oe&&await Qe.get("github-copilot-enterprise")&&(oe=!0),!!oe&&G.auth.loader){if(ce){let me=x[G.auth.provider];if(!me){s.error(`Auth provider ${G.auth.provider} not found in database`);return}let xe=await G.auth.loader(()=>Qe.get(J),me)??{},qe=H[J]?{options:xe}:{source:"custom",options:xe};be(J,qe);}if(J==="github-copilot"){let me="github-copilot-enterprise";if(!k.has(me)&&await Qe.get(me)){let xe=x[me];if(!xe){s.error(`Enterprise provider ${me} not found in database`);return}let Ie=await G.auth.loader(()=>Qe.get(me),xe)??{},we=H[me]?{options:Ie}:{source:"custom",options:Ie};be(me,we);}}}}for(let[G,J]of Object.entries(c$1)){if(k.has(G))continue;let oe=x[G];if(!oe){s.error("Provider does not exist in model list "+G);continue}let ce=await J(oe);if(ce&&(ce.autoload||H[G])){ce.getModel&&(X[G]=ce.getModel);let me=ce.options??{},pe=H[G]?{options:me}:{source:"custom",options:me};be(G,pe);}}for(let[G,J]of le){let oe={source:"config"};J.env&&(oe.env=J.env),J.name&&(oe.name=J.name),J.options&&(oe.options=J.options),be(G,oe);}for(let[G,J]of Object.entries(H)){if(!L(G)){delete H[G];continue}let oe=T.provider?.[G];for(let[ce,me]of Object.entries(J.models)){me.api.id=me.api.id??me.id??ce,(ce==="gpt-5-chat-latest"||G==="openrouter"&&ce==="openai/gpt-5-chat")&&delete J.models[ce],me.status==="alpha"&&!a$2.EASBOT_ENABLE_EXPERIMENTAL_MODELS&&delete J.models[ce],me.status==="deprecated"&&delete J.models[ce],(oe?.blacklist?.includes(ce)||oe?.whitelist&&!oe.whitelist.includes(ce))&&delete J.models[ce],me.variants=mapValues(bt.variants(me),xe=>xe);let pe=oe?.models?.[ce]?.variants;if(pe&&me.variants){let xe=mergeDeep(me.variants,pe);me.variants=mapValues(pickBy(xe,qe=>!qe.disabled),qe=>omit(qe,["disabled"]));}}if(Object.keys(J.models).length===0){delete H[G];continue}s.info("found",{providerId:G});}return {models:Y,providers:H,sdk:ne,localProxy:ae,modelLoaders:X}}catch(q){var F=q,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??{}}N.list=g;async function v(){return (await h())?.localProxy??{}}N.getLocalProxy=v;async function P(M){try{var T=[];try{let _=c(T,s.time("getSDK",{providerId:M.providerId}));let L=await h();if(!L)throw new Error("Provider state not available");let H=L.providers[M.providerId];if(!H)throw new Error(`Provider ${M.providerId} not found`);let Y={...H.options};M.api.npm.includes("@ai-sdk/openai-compatible")&&Y.includeUsage!==!1&&(Y.includeUsage=!0);Y.baseURL||(Y.baseURL=M.api.url);Y.apiKey===void 0&&H.key&&(Y.apiKey=H.key);M.headers&&(Y.headers={...Y.headers,...M.headers});let X=JSON.stringify({providerId:M.providerId,npm:M.api.npm,options:Y}).split("").reduce((xe,qe)=>(xe=(xe<<5)-xe+qe.charCodeAt(0),xe&xe),0);let ne=L.sdk.get(X);if(ne)return ne;let ae=Y.fetch;Y.fetch=async(xe,qe)=>{let Ie=ae??fetch,we=qe??{};if(Y.timeout!==void 0&&Y.timeout!==null){let re=[];we.signal&&re.push(we.signal),Y.timeout!==!1&&re.push(AbortSignal.timeout(Y.timeout));let Ee=re.length>1?AbortSignal.any(re):re[0];we.signal=Ee;}if(M.api.npm==="@ai-sdk/openai"&&we.body&&we.method==="POST"){let re=JSON.parse(we.body);if(!(M.providerId.includes("azure")&&re.store===!0)&&Array.isArray(re.input)){for(let _t of re.input)"id"in _t&&delete _t.id;we.body=JSON.stringify(re);}}return Ie(xe,{...we,timeout:!1})};let le=MR[M.api.npm];if(le){s.info("using bundled provider",{providerId:M.providerId,pkg:M.api.npm});let qe=(await le())({name:M.providerId,...Y});return L.sdk.set(X,qe),qe}let be;M.api.npm.startsWith("file://")?(s.info("loading local provider",{pkg:M.api.npm}),be=M.api.npm):be=await Shell.install(M.api.npm,"latest");let{pathToFileURL:se}=await import('url');let Q=await import('path');let q=await import('fs/promises');let F=Q.join(be,"package.json");let te=JSON.parse(await q.readFile(F,"utf-8"));let G;te.exports?.["."]?.import?G=te.exports["."].import:te.exports?.["."]?.require?G=te.exports["."].require:te.module?G=te.module:te.main?G=te.main:G="index.js";let J=Q.join(be,G);let oe=se(J).href;s.debug("Dynamic import",{npm:M.api.npm,entryPoint:G,fullPath:J,moduleURL:oe});let ce=await import(oe);let me=ce[Object.keys(ce).find(xe=>xe.startsWith("create"))];let pe=me({name:M.providerId,...Y});L.sdk.set(X,pe);return pe}catch(j){var x=j,k=!0;}finally{d(T,x,k);}}catch(_){throw new N.InitError({providerId:M.providerId},{cause:_})}}async function I(M){return (await h())?.providers[M]}N.getProvider=I;async function A(M,T){let j=await h();if(!j)throw new Error("Provider state not available");let x=j.providers[M];if(!x){let _=Object.keys(j.providers),H=hy.go(M,_,{limit:3,threshold:-1e4}).map(Y=>Y.target);throw new N.ModelNotFoundError({providerId:M,modelId:T,suggestions:H})}let k=x.models[T];if(!k){let _=Object.keys(x.models),H=hy.go(T,_,{limit:3,threshold:-1e4}).map(Y=>Y.target);throw new N.ModelNotFoundError({providerId:M,modelId:T,suggestions:H})}return k}N.getModel=A;async function S(M){s.debug("getLanguage called",{providerId:M.providerId,modelId:M.id});let T=await h();if(!T)throw new Error("Provider state not available");let j=`${M.providerId}/${M.id}`;if(T.models.has(j))return s.debug("Model found in cache",{key:j}),T.models.get(j);let x=T.providers[M.providerId];if(!x)throw new Error(`Provider ${M.providerId} not found`);s.debug("Getting SDK for model",{providerId:M.providerId,modelId:M.id});let k=await P(M);s.debug("SDK obtained",{providerId:M.providerId});try{let _=T.modelLoaders[M.providerId];s.debug("Model loader check",{providerId:M.providerId,hasLoader:!!_,apiId:M.api.id,options:x.options});let L=_?await _(k,M.api.id,x.options):k.languageModel(M.api.id);return s.debug("Language model created",{providerId:M.providerId,modelId:M.id}),T.models.set(j,L),L}catch(_){throw s.error("Failed to create language model",{providerId:M.providerId,modelId:M.id,error:_}),_ instanceof NoSuchModelError?new N.ModelNotFoundError({modelId:M.id,providerId:M.providerId},{cause:_}):_}}N.getLanguage=S;async function w(M,T){s.debug("getEmbedding called",{providerId:M,modelId:T});let j=await A(M,T),x=await P(j),k,_=x;if(typeof _.embeddingModel=="function")k=_.embeddingModel(j.api.id);else if(typeof _.textEmbeddingModel=="function")k=_.textEmbeddingModel(j.api.id);else throw new Error(`Provider ${M} does not support embedding model. SDK missing both 'embeddingModel' and 'textEmbeddingModel' methods.`);return s.debug("Embedding model created",{providerId:M,modelId:T}),k}N.getEmbedding=w;async function y(M,T){s.debug("getRerank called",{providerId:M,modelId:T});let j=await A(M,T),x=await P(j),k,_=x;if(typeof _.rerankingModel=="function")k=_.rerankingModel(j.api.id);else if(typeof _.languageModel=="function"){let L=await v(),H=`${M}/${T}`;if(H in L)return L[H];let Y=await S(j);if(Y){let X=await A("easbot-local","rerank-proxy"),ae=await P(X);k=ae.rerankingModel?ae.rerankingModel(X.api.id,{llm:Y,useEnhancedPrompt:true,promptLanguage:"cn",totalScore:1}):void 0,k&&L.set(H,k);}}if(!k)throw new Error(`Provider ${M} and model ${T} does not support rerank`);return s.debug("Rerank model created",{providerId:M,modelId:T}),k}N.getRerank=y;async function b(M,T){let j=await h();if(!j)return;let x=j.providers[M];if(x){for(let k of T)for(let _ of Object.keys(x.models))if(_.includes(k))return {providerId:M,modelId:_}}}N.closest=b;async function C(M){let T=await he.get();if(T.small_model){let _=$(T.small_model);if(!_.providerId||!_.modelId)throw new Error("Invalid small_model format");return A(_.providerId,_.modelId)}let j=await h(),x=j?.providers[M];if(x){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 L of _)if(M==="amazon-bedrock"){let H=["global.","us.","eu."],Y=Object.keys(x.models).filter(le=>le.includes(L)),X=Y.find(le=>le.startsWith("global."));if(X)return A(M,X);let ne=x.options?.region;if(ne){let le=ne.split("-")[0];if(le==="us"||le==="eu"){let be=Y.find(se=>se.startsWith(`${le}.`));if(be)return A(M,be)}}let ae=Y.find(le=>!H.some(be=>le.startsWith(be)));if(ae)return A(M,ae)}else for(let H of Object.keys(x.models))if(H.includes(L))return A(M,H)}if(j?.providers.easbot?.models["gpt-5-nano"])return A("easbot","gpt-5-nano")}N.getSmallModel=C;let E=["gpt-5","claude-sonnet-4","big-pickle","gemini-3-pro"];function O(M){return sortBy(M,[T=>E.findIndex(j=>T.id.includes(j)),"desc"],[T=>T.id.includes("latest")?0:1,"asc"],[T=>T.id,"desc"])}N.sort=O;async function D(){let M=await he.get();if(M.model)return $(M.model);let T=await g().then(x=>Object.values(x)).then(x=>x.find(k=>!M.provider||Object.keys(M.provider).includes(k.id)));if(!T)throw new Error("no providers found");let[j]=O(Object.values(T.models));if(!j)throw new Error("no models found");return {providerId:T.id,modelId:j.id}}N.defaultModel=D;function $(M){let{provider:T,model:j}=parseModelId(M);if(!T)throw new Error("Invalid model format: "+M);return {providerId:T,modelId:j}}N.parseModel=$,N.ModelNotFoundError=NamedError.create("ProviderModelNotFoundError",U.object({providerId:U.string(),modelId:U.string(),suggestions:U.array(U.string()).optional()})),N.InitError=NamedError.create("ProviderInitError",U.object({providerId:U.string()}));})(Se||(Se={}));var ms;(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"?`
1028
- `: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(U.object({sessionId:U.string(),messageId:U.string()}),async l=>{let d=await Z.messages({sessionId:l.sessionId});await Promise.all([n({sessionId:l.sessionId,messages:d}),s({messageId:l.messageId,messages:d})]);});async function n(l){let d=await i({messages:l.messages});await Z.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 ue.publish(Z.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 Z.updateMessage(f);let p=m.parts.find(u=>u.type==="text"&&!u.synthetic);if(p&&!f.summary?.title){let u=await Ne.get("title");if(!u)return;let h=await ts.stream({agent:u,user:f,tools:{},model:u.model?await Se.getModel(u.model.providerId,u.model.modelId):await Se.getSmallModel(f.model.providerId)??await Se.getModel(f.model.providerId,f.model.modelId),small:true,messages:[{role:"user",content:`
1029
- The following is the text to summarize:
1030
- <text>
1031
- ${p?.text??""}
1032
- </text>
1033
- `}],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 Z.updateMessage(f);}}c.diff=fn$1(U.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?ht.diffFull(d,m):[]}c.computeDiff=i;})(ms||(ms={}));var wn;(r=>{let e=a.create({service:"session.revert"});r.RevertInput=U.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message"),partId:Identifier.schema("part").optional()});async function o(i){Ke.assertNotBusy(i.sessionId);let c=await Z.messages({sessionId:i.sessionId}),l,d=await Z.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 Z.get(i.sessionId);m.snapshot=a.revert?.snapshot??await ht.track(),await ht.revert(f),m.snapshot&&(m.diff=await ht.diff(m.snapshot));let p=c.filter(h=>h.info.id>=m.messageId),u=await ms.computeDiff({messages:p});return await a$6.write(["session_diff",i.sessionId],u),await ue.publish(Z.Event.Diff,{sessionId:i.sessionId,diff:u}),Z.update(i.sessionId,h=>{h.revert=m,h.summary={additions:u.reduce((g,v)=>g+v.additions,0),deletions:u.reduce((g,v)=>g+v.deletions,0),files:u.length};})}return d}r.revert=o;async function n(i){e.info("unreverting",i),Ke.assertNotBusy(i.sessionId);let c=await Z.get(i.sessionId);return c.revert?(c.revert.snapshot&&await ht.restore(c.revert.snapshot),await Z.update(i.sessionId,d=>{d.revert=void 0;})):c}r.unrevert=n;async function s(i){if(!i.revert)return;let c=i.id,l=await Z.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 ue.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 ue.publish(ve.Event.PartRemoved,{sessionId:c,messageId:a.info.id,partId:g.id});}await Z.update(c,p=>{p.revert=void 0;});}r.cleanup=s;})(wn||(wn={}));var Ty=a$5.define("command.executed",U.object({name:U.string(),sessionId:U.string(),arguments:U.union([U.string(),U.record(U.string(),U.unknown())]),messageId:U.string().optional()})),Ey=a.create({service:"command.executor"});U.object({sessionId:Identifier.schema("session"),agent:U.string(),model:U.object({providerId:U.string(),modelId:U.string()}).optional(),command:U.string()});U.object({messageId:Identifier.schema("message").optional(),sessionId:Identifier.schema("session"),agent:U.string().optional(),model:U.string().optional(),arguments:U.union([U.string(),U.record(U.string(),U.unknown())]),command:U.string(),variant:U.string().optional(),parts:U.array(U.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 FR=/!`([^`]+)`/g;async function Ad(e){let o=(await ve.filterCompacted(ve.stream(e))).filter(s=>s.info.role==="user").at(-1);if(!o)throw new Error("No user message found");let n=o.info;return await Se.getModel(n.model.providerId,n.model.modelId)}async function NR(e){let t=[{type:"text",text:e}],o=a$9.files(e),n=new Set;for(let s of o){let r=s[1];if(!r||n.has(r))continue;n.add(r);let i=R.directory,c=Ce__default.isAbsolute(r)?r:Ce__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 xa;(o=>{async function e(n){let s=Ke.start(n.sessionId);if(!s)throw new Z.BusyError(n.sessionId);let r=async()=>{(Ke.state()[n.sessionId]?.callbacks??[]).length===0?await Ke.cancel(n.sessionId):Ke.loop({sessionId:n.sessionId,resume_existing:true}).catch(c=>{Ey.error("session loop failed to resume after shell command",{sessionId:n.sessionId,error:c});});};try{let i=await Z.get(n.sessionId);i.revert&&await wn.cleanup(i);let c=await Ne.get(n.agent);if(!c)throw new Error(`Agent not found: ${n.agent}`);let l;n.model?l=await Se.getModel(n.model.providerId,n.model.modelId):c.model?l=await Se.getModel(c.model.providerId,c.model.modelId):l=await Ad(n.sessionId);let d={id:Identifier.ascending("message"),sessionId:n.sessionId,time:{created:Date.now()},role:"user",agent:n.agent,model:{providerId:l.providerId,modelId:l.id}};await Z.updateMessage(d);let m={type:"text",id:Identifier.ascending("part"),messageId:d.id,sessionId:n.sessionId,text:"The following tool was executed by the user",synthetic:!0};await Z.updatePart(m);let f={id:Identifier.ascending("message"),sessionId:n.sessionId,parentId:d.id,mode:n.agent,agent:n.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 Z.updateMessage(f);let a={type:"tool",id:Identifier.ascending("part"),messageId:f.id,sessionId:n.sessionId,tool:"bash",callId:ulid(),state:{status:"running",time:{start:Date.now()},input:{command:n.command}}};await Z.updatePart(a);let p=Shell.acceptable(),u=await Promise.resolve(p),h=(process.platform==="win32"?Ce__default.win32.basename(u??"",".exe"):Ce__default.basename(u??"")).toLowerCase(),g={nu:{args:["-c",n.command]},fish:{args:["-c",n.command]},zsh:{args:["-c","-l",`
1034
- [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
1035
- [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
1036
- eval ${JSON.stringify(n.command)}
1037
- `]},bash:{args:["-c","-l",`
1038
- shopt -s expand_aliases
1039
- [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
1040
- eval ${JSON.stringify(n.command)}
1041
- `]},cmd:{args:["/c",n.command]},powershell:{args:["-NoProfile","-Command",n.command]},pwsh:{args:["-NoProfile","-Command",n.command]},"":{args:["-c",`${n.command}`]}},P=(g[h]??g[""])?.args??[];process.platform==="win32"&&(h==="cmd"?P=["/c",`chcp 65001 >nul 2>&1 && ${n.command}`]:(h==="powershell"||h==="pwsh")&&(P=["-NoProfile","-Command",`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${n.command}`]));let I=R.directory,S=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:I},{cwd:I})).output?.env??{},w=spawn(u??"sh",P,{cwd:I,detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"],env:{...process.env,...S,TERM:"dumb",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"}}),y="";w.stdout?.on("data",D=>{y+=D.toString("utf-8"),a.state.status==="running"&&(a.state.metadata={output:y,description:""},Z.updatePart(a));}),w.stderr?.on("data",D=>{y+=D.toString("utf-8"),a.state.status==="running"&&(a.state.metadata={output:y,description:""},Z.updatePart(a));});let b=!1,C=!1,E=()=>Shell.killTree(w,{exited:()=>C});s.aborted&&(b=!0,await E());let O=()=>{b=!0,E();};return s.addEventListener("abort",O,{once:!0}),await new Promise(D=>{w.on("close",()=>{C=!0,s.removeEventListener("abort",O),D();});}),b&&(y+=`
1042
-
1043
- `+["<metadata>","User aborted the command","</metadata>"].join(`
1044
- `)),f.time={...f.time,completed:Date.now()},await Z.updateMessage(f),a.state.status==="running"&&(a.state={status:"completed",time:{...a.state.time,end:Date.now()},input:a.state.input,title:"",metadata:{output:y,description:""},output:y},await Z.updatePart(a)),{info:f,parts:[a],title:"Shell Command",metadata:{command:n.command},output:y,success:!b}}finally{await r();}}o.shell=e;async function t(n){Ey.debug("command",n);let s=await So.get(n.command);if(!s)throw new Error(`Command not found: ${n.command}`);if(await Le.triggerEvent(HookEvent.CommandBefore,{command:n.command,sessionId:n.sessionId,arguments:n.arguments},{sessionId:n.sessionId}),s.commandType==="local"){let w={sessionId:n.sessionId,directory:R.worktree,model:n.model,agent:s.agent??n.agent??await Ne.defaultAgent(),arguments:n.arguments},y=await s.execute(n.arguments,w);y.metadata.commandType="local";let b={...y,success:y.success,error:y.metadata?.error};return await ue.publish(Ty,{name:n.command,sessionId:n.sessionId,arguments:n.arguments}),await Le.triggerEvent(HookEvent.CommandAfter,{command:n.command,sessionId:n.sessionId,arguments:n.arguments,result:b},{sessionId:n.sessionId}),b}let r=s.agent??n.agent??await Ne.defaultAgent(),i={sessionId:n.sessionId,directory:R.worktree,model:n.model,agent:r,arguments:n.arguments},l=(await s.execute(n.arguments,i)).output,d=l,m=a$9.shell(d);if(m.length>0){let w=await Promise.all(m.map(async([,b])=>{try{return await $`${{raw:b}}`.quiet().nothrow().text()}catch(C){return `Error executing command: ${C instanceof Error?C.message:String(C)}`}})),y=0;d=d.replace(FR,()=>w[y++]??"");}d=d.trim();let a=await(async()=>{if(s.model)return Se.parseModel(s.model);if(s.agent){let y=await Ne.get(s.agent);if(y?.model)return y.model}if(n.model)return Se.parseModel(n.model);let w=await Ad(n.sessionId);return {providerId:w.providerId,modelId:w.id}})();try{await Se.getModel(a.providerId,a.modelId);}catch(w){if(Se.ModelNotFoundError.isInstance(w)){let{providerId:y,modelId:b,suggestions:C}=w.data,E=C&&C.length>0?` Did you mean: ${C.join(", ")}?`:"";await ue.publish(Z.Event.Error,{sessionId:n.sessionId,error:new NamedError.Unknown({message:`Model not found: ${y}/${b}.${E}`}).toObject()});}throw w}let p=await Ne.get(r);if(!p){let w=await Ne.list().then(C=>C.filter(E=>!E.hidden).map(E=>E.name)),y=w.length>0?` Available agents: ${w.join(", ")}`:"",b=new NamedError.Unknown({message:`Agent not found: "${r}".${y}`});throw await ue.publish(Z.Event.Error,{sessionId:n.sessionId,error:b.toObject()}),b}let u=await NR(d),h=[],g=s.subtask===true,v=Identifier.ascending("task"),P=g?[{type:"subtask",taskId:v,agent:p.name,description:s.description??"",command:n.command,model:{providerId:a.providerId,modelId:a.modelId},prompt:[...u??[],...h].find(w=>w.type==="text")?.text??""}]:[...u??[],...h,...n.parts??[]],I=g?n.agent??await Ne.defaultAgent():r,A=g?n.model?Se.parseModel(n.model):{providerId:(await Ad(n.sessionId)).providerId,modelId:(await Ad(n.sessionId)).id}:a,S=await Ke.prompt({sessionId:n.sessionId,messageId:n.messageId,model:A,agent:I,parts:P,variant:n.variant});return await ue.publish(Ty,{name:n.command,sessionId:n.sessionId,arguments:n.arguments,messageId:S.info.id}),await Le.triggerEvent(HookEvent.CommandAfter,{command:n.command,sessionId:n.sessionId,arguments:n.arguments,result:{info:S.info,parts:S.parts,success:true}},{sessionId:n.sessionId}),{info:S.info,parts:S.parts,title:n.command,metadata:{command:n.command,arguments:n.arguments,commandType:"prompt"},output:l,success:true}}o.execute=t;})(xa||(xa={}));var _d=a.create({service:"tool.builder"}),Md;(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 Z.updatePart({...m,state:{title:d.title,metadata:d.metadata,status:"running",input:c,time:{start:Date.now()}}});},ask:async d=>{await Oe.ask({...d,sessionId:i.sessionId,tool:{messageId:i.processor?.message.id??"",callId:l.toolCallId??""},ruleset:Oe.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:v=!0,toolFilter:P}=i$1;let I=c(C,_d.time("buildTools"));let A=l.id;let S=l.contextMode??f$1;let w=e({sessionId:A,session:l,agent:c$1,model:d,agentName:c$1.name,messages:f??[],protocolMetadata:h,bypassAgentCheck:u,processor:p,userMessageId:a});let y={};if(v){let $=await Ho.tools({providerId:d.providerId,modelId:d.api.id},c$1);for(let K of $){if(P&&!P(K.id))continue;let ee=K.scope??i;if(ee!=="all"&&ee!==S)continue;let N=bt.schema(d,qR.toJSONSchema(K.parameters));y[K.id]=tool({description:K.description,inputSchema:jsonSchema(N),async execute(M,T){let j=w(M,T);await Le.triggerEvent(HookEvent.ToolBefore,{tool:K.id,sessionId:j.sessionId,userMessageId:a,callId:j.callId??""},{sessionId:j.sessionId});let x=await K.execute(M,j);return await Le.triggerEvent(HookEvent.ToolAfter,{tool:K.id,sessionId:j.sessionId,userMessageId:a,callId:j.callId??"",args:M},{sessionId:j.sessionId}),x}});}}if(g)try{let $=await Ue.tools(),K=await Ue.configInfo();for(let[ee,N]of Object.entries($)){if(P&&!P(ee))continue;let M=ee.split("_")[0];if(M){let x=K[M];if(x){let k=x.scope??i;if(k!=="all"&&k!==S)continue}}let T=N.execute;if(!T)continue;let j=bt.schema(d,await asSchema(N.inputSchema).jsonSchema);N.inputSchema=jsonSchema(j),N.execute=async(x,k)=>{let _=w(x,k);await Le.triggerEvent(HookEvent.ToolBefore,{tool:ee,sessionId:_.sessionId,userMessageId:a,callId:k.toolCallId},{sessionId:_.sessionId}),await _.ask({permission:ee,metadata:{},patterns:["*"],always:["*"]});let L=await T(x,k);await Le.triggerEvent(HookEvent.ToolAfter,{tool:ee,sessionId:_.sessionId,userMessageId:a,callId:k.toolCallId,args:x},{sessionId:_.sessionId});let H=[],Y=[];for(let ae of L.content)if(ae.type==="text")H.push(ae.text);else if(ae.type==="image")Y.push({id:Identifier.ascending("part"),sessionId:A,messageId:p?.message.id??"",type:"file",mime:ae.mimeType,url:`data:${ae.mimeType};base64,${ae.data}`});else if(ae.type==="resource"){let{resource:le}=ae;le.text&&H.push(le.text),le.blob&&Y.push({id:Identifier.ascending("part"),sessionId:A,messageId:p?.message.id??"",type:"file",mime:le.mimeType??"application/octet-stream",url:`data:${le.mimeType??"application/octet-stream"};base64,${le.blob}`,filename:le.uri});}let X=await Ve.output(H.join(`
1045
-
1046
- `),{},c$1);return {title:"",metadata:{...L.metadata??{},truncated:X.truncated,...X.truncated&&{outputPath:X.outputPath}},output:X.content,attachments:Y,content:L.content}},y[ee]=N;}}catch($){_d.error("Failed to load MCP tools",{error:$});}let b=o(y,c$1,m);_d.debug("built tools",{count:Object.keys(b).length,includeBuiltIn:v,includeMCP:g,contextMode:S,userToolsDisabled:Object.entries(m??{}).filter(([,$])=>$===!1).map(([$])=>$)});return b}catch(E){var O=E,D=true;}finally{d(C,O,D);}}r.buildTools=t;function o(i,c,l){let d=Oe.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 n(i={}){let{includeMCP:c=true,includeBuiltIn:l=true,toolFilter:d}=i,m=[];if(l){let f=await Ho.ids();for(let a of f)d&&!d(a)||m.push(a);}if(c)try{let f=await Ue.tools();for(let a of Object.keys(f))d&&!d(a)||m.includes(a)||m.push(a);}catch(f){_d.error("Failed to load MCP tools",{error:f});}return m}r.listTools=n;async function s(i){let c=await Ho.ids();if(Array.isArray(c)&&c.includes(i))return true;try{let l=await Ue.tools();return i in l}catch{return false}}r.hasTool=s;})(Md||(Md={}));globalThis.AI_SDK_LOG_WARNINGS=false;var Ke;(w=>{let e$1=a.create({service:"session.prompt"}),t;function o(){return t||(t=R.state(()=>({}),async y=>{for(let b of Object.values(y))b.abort.abort();})),t}function n(){return o()()}w.state=n;function s(y){if(n()[y])throw new Z.BusyError(y)}w.assertNotBusy=s,w.PromptInput=U.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message").optional(),model:U.object({providerId:U.string(),modelId:U.string()}).optional(),agent:U.string().optional(),contextMode:U.enum(e).optional(),noReply:U.boolean().optional(),tools:U.record(U.string(),U.boolean()).optional().describe("@deprecated tools and permissions have been merged, you can set permissions on the session itself now"),system:U.string().optional(),variant:U.string().optional(),parts:U.array(U.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"})]))}),w.prompt=fn$1(w.PromptInput,async y=>{let b=await Z.get(y.sessionId);await wn.cleanup(b),y.contextMode&&(await Z.update(b.id,O=>{O.contextMode=y.contextMode;}),b.contextMode=y.contextMode);let C=await g(y);await Z.touch(y.sessionId);let E=[];for(let[O,D]of Object.entries(y.tools??{}))E.push({permission:O,action:D?"allow":"deny",pattern:"*"});return E.length>0&&(b.permission=E,await Z.update(b.id,O=>{O.permission=E;})),y.noReply===true?C:(0, w.loop)({sessionId:y.sessionId})});async function c$1(y){let b=[{type:"text",text:y}],C=a$9.files(y),E=new Set;return await Promise.all(C.map(async O=>{let D=O[1];if(!D||E.has(D))return;E.add(D);let $=D.startsWith("~/")?Ce__default.join(nc.homedir(),D.slice(2)):Ce__default.resolve(R.worktree,D),K=await Tt__default.stat($).catch(()=>{});if(K){if(K.isDirectory()){b.push({type:"file",url:pathToFileURL($).href,filename:D,mime:"application/x-directory"});return}b.push({type:"file",url:pathToFileURL($).href,filename:D,mime:"text/plain"});}})),b}w.resolvePromptParts=c$1;function l(y){let b=n();if(b[y])return;let C=new AbortController;return b[y]={abort:C,callbacks:[]},C.signal}w.start=l;function d$1(y){let b=n();if(b[y])return b[y].abort.signal}w.resume=d$1;async function m(y){e$1.info("cancel",{sessionId:y});let b=n(),C=b[y];if(!C){await Mt.set(y,{type:"idle"});return}for(let E of C.callbacks)E.reject(new Error("Session aborted"));C.callbacks=[],C.abort.abort(),delete b[y],await Mt.set(y,{type:"idle"});}w.cancel=m,w.LoopInput=U.object({sessionId:Identifier.schema("session"),resume_existing:U.boolean().optional()}),w.loop=fn$1(w.LoopInput,async y=>{var j=[];try{let{sessionId:b,resume_existing:C}=y;let E=C?d$1(b):l(b);if(!E)return new Promise((H,Y)=>{let X=n()[b]?.callbacks;if(!X){let ne=n()[b]?.callbacks;ne&&ne.push({resolve:H,reject:Y});return}X.push({resolve:H,reject:Y});});let O=c(j,defer(async()=>await m(b)),!0);let D=0;let $=await Z.get(b);for(;;){var K=[];try{await Mt.set(b,{type:"busy"});e$1.info("loop",{step:D,sessionId:b});if(E.aborted)break;let H=await Le.triggerEvent(HookEvent.LoopStart,{sessionId:b,step:D,lastUserId:"",result:"start"},{sessionId:b});if(H.modified&&H.output?.result==="stop"){e$1.info("exiting loop due to hook",{sessionId:b});break}let Y=await ve.filterCompacted(ve.stream(b));let X;let ne;let ae;let le;let be=[];for(let Ie=Y.length-1;Ie>=0;Ie--){let we=Y[Ie];if(!we)continue;if(!X&&we.info.role==="user"&&(X=we.info,ne=we),!ae&&we.info.role==="assistant"&&(ae=we.info),!le&&we.info.role==="assistant"&&we.info.finish&&(le=we),X&&le)break;let re=we.parts.filter(Ee=>Ee.type==="compaction"||Ee.type==="subtask");re.length>0&&!le&&be.push(...re);}if(!X)throw new Error("No user message found in stream. This should never happen.");if(ae?.finish&&!["tool-calls","unknown"].includes(ae.finish)&&X.id<ae.id){e$1.info("exiting loop",{sessionId:b});break}D++;D===1&&await S({session:$,modelId:X.model.modelId,providerId:X.model.providerId,history:Y});let se=await Se.getModel(X.model.providerId,X.model.modelId).catch(async Ie=>{if(Se.ModelNotFoundError.isInstance(Ie)){let we=Ie.data.suggestions&&Ie.data.suggestions.length>0?` Did you mean: ${Ie.data.suggestions.join(", ")}?`:"";await ue.publish(Z.Event.Error,{sessionId:b,error:new NamedError.Unknown({message:`Model not found: ${Ie.data.providerId}/${Ie.data.modelId}.${we}`}).toObject()});}throw Ie});let Q=be.pop();if(Q?.type==="subtask"){let Ie=await Gi.init(),we=Q.model?await Se.getModel(Q.model.providerId,Q.model.modelId):se,re=await Z.updateMessage({id:Identifier.ascending("message"),role:"assistant",parentId:X.id,sessionId:b,mode:Q.agent,agent:Q.agent,variant:X.variant,path:{cwd:R.directory,root:R.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelId:we.id,providerId:we.providerId,time:{created:Date.now()}}),Ee=await Z.updatePart({id:Identifier.ascending("part"),messageId:re.id,sessionId:re.sessionId,type:"tool",callId:ulid(),tool:Gi.id,state:{status:"running",input:{prompt:Q.prompt,description:Q.description,subagent_type:Q.agent,command:Q.command},time:{start:Date.now()}}}),Ae={operation:"create",prompt:Q.prompt,description:Q.description,subagent_type:Q.agent};await Le.triggerEvent(HookEvent.ToolBefore,{tool:"task",sessionId:b,userMessageId:re.parentId,callId:Ee.id},{sessionId:b});let _t,ko=await Ne.get(Q.agent);if(!ko)throw new Error(`Task agent not found: ${Q.agent}`);let Do={agent:Q.agent,messageId:re.id,sessionId:b,abort:E,callId:Ee.callId,extra:{bypassAgentCheck:!0},messages:Y,async metadata(Gt){await Z.updatePart({...Ee,type:"tool",state:{...Ee.state,...Gt}});},async ask(Gt){await Oe.ask({...Gt,sessionId:b,ruleset:Oe.merge(ko.permission,$.permission??[])});}},Po=await Ie.execute(Ae,Do).catch(Gt=>{_t=Gt,e$1.error("subtask execution failed",{error:Gt,agent:Q.agent,description:Q.description});});if(await Le.triggerEvent(HookEvent.ToolAfter,{tool:"task",sessionId:b,userMessageId:re.parentId,callId:Ee.id,args:Ae},{sessionId:b}),re.finish="tool-calls",re.time.completed=Date.now(),await Z.updateMessage(re),Po&&Ee.state.status==="running"){let Gt;Po.attachments&&Po.attachments.length>0&&(Gt=Po.attachments.map(It=>({...It,id:It.id??Identifier.ascending("part"),sessionId:It.sessionId??Ee.sessionId,messageId:It.messageId??Ee.messageId}))),await Z.updatePart({...Ee,state:{status:"completed",input:Ee.state.input,title:Po.title,metadata:Po.metadata,output:Po.output,attachments:Gt,time:{...Ee.state.time,end:Date.now()}}});}if(Po||await Z.updatePart({...Ee,state:{status:"error",error:_t?`Tool execution failed: ${_t.message}`:"Tool execution failed",time:{start:Ee.state.status==="running"?Ee.state.time.start:Date.now(),end:Date.now()},metadata:Ee.metadata,input:Ee.state.input}}),Q.command){let Gt={id:Identifier.ascending("message"),sessionId:b,role:"user",time:{created:Date.now()},agent:X.agent,model:X.model};await Z.updateMessage(Gt),await Z.updatePart({id:Identifier.ascending("part"),messageId:Gt.id,sessionId:b,type:"text",text:"Summarize the task tool output above and continue with your task.",synthetic:!0});}continue}if(Q?.type==="compaction"){if(await io.compactConversation({messages:Y,parentId:X.id,abort:E,sessionId:b,auto:Q.auto})==="stop")break;continue}let q=await Ne.get(X.agent);if(!q)throw new Error(`Agent not found: ${X.agent}`);let F=q.steps??1/0;let te=D>=F;let G=Cr.create({assistantMessage:await Z.updateMessage({id:Identifier.ascending("message"),parentId:X.id,role:"assistant",mode:q.name,agent:q.name,variant:X.variant,path:{cwd:R.directory,root:R.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelId:se.id,providerId:se.providerId,time:{created:Date.now()},sessionId:b}),sessionId:b,model:se,abort:E});let J=c(K,defer(()=>Ds.clear(G.message.id)),!0);let oe=Y.findLast(Ie=>Ie.info.role==="user");let ce=oe?.parts.some(Ie=>Ie.type==="agent")??!1;let me=await hn.getProtocolMetadata(q);let pe=await Md.buildTools({agent:q,session:$,model:se,userTools:X.tools,processor:{message:{id:G.message.id,parentId:G.message.parentId},partFromToolCall:Ie=>G.partFromToolCall(Ie)},bypassAgentCheck:ce,messages:Y,protocolMetadata:me,userMessageId:G.message.parentId});let xe=await hn.build({sessionId:b,userMessage:ne,user:X,messages:Y,model:se,agent:q,session:$,tools:pe,isLastStep:te,step:D,lastFinished:le,maxMessages:100,mode:$.contextMode});if(xe.metadata.needsCompaction){await io.create({sessionId:b,agent:"compaction",model:X.model,auto:!0});continue}let qe=await G.process({user:X,agent:q,abort:E,sessionId:b,system:xe.system,messages:xe.messages,tools:pe,model:se,mode:xe.metadata.mode});if(qe==="stop"){let Ie=await Le.triggerEvent(HookEvent.LoopEnd,{sessionId:b,step:D,lastUserId:X.id,result:"stop"},{sessionId:b});if(Ie.modified&&Ie.output.result==="continue")continue;break}qe==="compact"&&await io.create({sessionId:b,agent:"compaction",model:X.model,auto:!0});}catch(ee){var N=ee,M=!0;}finally{var T=d(K,N,M);T&&await T;}}await io.prune({sessionId:b});for await(let H of ve.stream(b)){if(H.info.role==="user")continue;let Y=n()[b]?.callbacks??[];for(let X of Y)X.resolve(H);return H}throw new Error("Impossible")}catch(x){var k=x,_=true;}finally{var L=d(j,k,_);L&&await L;}});async function p(y){for await(let b of ve.stream(y))if(b.info.role==="user"&&b.info.model)return b.info.model;return Se.defaultModel()}w.lastModel=p;async function u(y){for await(let b of ve.stream(y))if(b.info.role==="user"&&b.info.agent)return b.info.agent;return await Ne.defaultAgent()}w.lastAgent=u;async function h(y){for await(let b of ve.stream(y))if(b.info.role==="user")return b.info}w.lastUserMessage=h;async function g(y){var ee=[];try{let b=await Ne.get(y.agent??await Ne.defaultAgent());if(!b)throw new Error(`Agent not found: ${y.agent}`);let C=y.model??b.model??await p(y.sessionId);let E=!y.variant&&b.variant&&C.providerId?await Se.getModel(C.providerId,C.modelId).catch(()=>{}):void 0;let O=y.variant??(b.variant&&E?.variants?.[b.variant]?b.variant:void 0);let D={id:y.messageId??Identifier.ascending("message"),role:"user",sessionId:y.sessionId,time:{created:Date.now()},tools:y.tools,agent:b.name,model:{providerId:C.providerId,modelId:C.modelId},system:y.system,variant:O};let $=c(ee,defer(()=>Ds.clear(D.id)),!0);let K=await Promise.all(y.parts.map(async x=>{if(x.type==="file"){if(x.source?.type==="resource"){let{clientName:_,uri:L}=x.source;e$1.info("mcp resource",{clientName:_,uri:L,mime:x.mime});let H=[{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`Reading MCP resource: ${x.filename} (${L})`}];try{let Y=await Ue.readResource(_,L);if(!Y)throw new Error(`Resource not found: ${_}/${L}`);let X=Array.isArray(Y.contents)?Y.contents:[Y.contents];for(let ne of X)if("text"in ne&&ne.text)H.push({id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:ne.text});else if("blob"in ne&&ne.blob){let ae="mimeType"in ne?ne.mimeType:x.mime;H.push({id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`[Binary content: ${ae}]`});}H.push({...x,id:x.id??Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId});}catch(Y){e$1.error("failed to read MCP resource",{error:Y,clientName:_,uri:L});let X=Y instanceof Error?Y.message:String(Y);H.push({id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`Failed to read MCP resource ${x.filename}: ${X}`});}return H}let k=new URL(x.url);switch(k.protocol){case "data:":if(x.mime==="text/plain")return [{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:x.filename})}`},{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:Buffer.from(x.url,"base64url").toString()},{...x,id:x.id??Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId}];break;case "file:":{e$1.info("file",{mime:x.mime});let _=fileURLToPath(x.url),L;try{L=await Tt__default.stat(_);}catch{L=void 0;}if(L?.isDirectory()&&(x.mime="application/x-directory"),x.mime==="text/plain"){let H,Y,X={start:k.searchParams.get("start"),end:k.searchParams.get("end")};if(X.start!=null){let le=x.url.split("?")[0]??"",be=parseInt(X.start,10),se=X.end?parseInt(X.end,10):void 0;if(be===se){let Q=fileURLToPath(le),q=await We.documentSymbol({file:Q}).catch(()=>[]);for(let F of q){let te;if("range"in F?te=F.range:"location"in F&&(te=F.location.range),te?.start?.line&&te?.start?.line===be){be=te.start.line,se=te?.end?.line??be;break}}}H=Math.max(be-1,0),se&&(Y=se-H);}let ne={filePath:_,offset:H,limit:Y},ae=[{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(ne)}`}];return await Nc.init().then(async le=>{let be=await Se.getModel(D.model.providerId,D.model.modelId),se={sessionId:y.sessionId,abort:new AbortController().signal,agent:y.agent,messageId:D.id,extra:{bypassCwdCheck:!0,model:be},messages:[],metadata:async()=>{},ask:async()=>{}},Q=await le.execute(ne,se);ae.push({id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:Q.output}),Q.attachments&&Q.attachments.length>0?ae.push(...Q.attachments.map(q=>({...q,id:q.id??Identifier.ascending("part"),synthetic:!0,filename:q.filename??x.filename,messageId:D.id,sessionId:y.sessionId}))):ae.push({...x,id:x.id??Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId});}).catch(async le=>{e$1.error("failed to read file",{error:le});let be=le instanceof Error?le.message:le.toString();await ue.publish(Z.Event.Error,{sessionId:y.sessionId,error:new NamedError.Unknown({message:be}).toObject()}),ae.push({id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`Read tool failed to read ${_} with the following error: ${be}`});}),ae}if(x.mime==="application/x-directory"){let H={path:_,limit:100},Y={sessionId:y.sessionId,abort:new AbortController().signal,agent:y.agent,messageId:D.id,extra:{bypassCwdCheck:!0},messages:[],metadata:async()=>{},ask:async()=>{}},X=await Wc.init().then(ne=>ne.execute(H,Y));return [{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:`Called the list tool with the following input: ${JSON.stringify(H)}`},{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:X.output},{...x,id:x.id??Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId}]}else {let H=await Tt__default.readFile(_);return _o.read(y.sessionId,_),[{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",text:`Called the Read tool with the following input: {"filePath":"${_}"}`,synthetic:!0},{id:x.id??Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"file",url:`data:${x.mime};base64,`+Buffer.from(H).toString("base64"),mime:x.mime,filename:x.filename,source:x.source}]}}}}if(x.type==="agent"){let _=Oe.evaluate("task",x.name,b.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return [{id:Identifier.ascending("part"),...x,messageId:D.id,sessionId:y.sessionId},{id:Identifier.ascending("part"),messageId:D.id,sessionId:y.sessionId,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+x.name+_}]}return [{id:Identifier.ascending("part"),...x,messageId:D.id,sessionId:y.sessionId}]})).then(x=>x.flat());await Le.triggerEvent(HookEvent.MessageReceive,{sessionId:y.sessionId,agent:y.agent,model:y.model,userMessageId:D.id,messageId:y.messageId,variant:y.variant});await Z.updateMessage(D);for(let x of K)await Z.updatePart(x);return {info:D,parts:K}}catch(N){var M=N,T=true;}finally{var j=d(ee,M,T);j&&await j;}}w.ShellInput=U.object({sessionId:Identifier.schema("session"),agent:U.string(),model:U.object({providerId:U.string(),modelId:U.string()}).optional(),command:U.string()});async function P(y){return xa.shell(y)}w.shell=P,w.CommandInput=U.object({messageId:Identifier.schema("message").optional(),sessionId:Identifier.schema("session"),agent:U.string().optional(),model:U.string().optional(),contextMode:U.enum(e).optional(),arguments:U.union([U.string(),U.record(U.string(),U.unknown())]),command:U.string(),variant:U.string().optional(),parts:U.array(U.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 A(y){return y.contextMode&&await Z.update(y.sessionId,b=>{b.contextMode=y.contextMode;}),xa.execute(y)}w.command=A;async function S(y){if(y.session.parentId||!Z.isDefaultTitle(y.session.title))return;let b=y.history.findIndex(T=>T.info.role==="user"&&!T.parts.every(j=>"synthetic"in j&&j.synthetic));if(b===-1||!(y.history.filter(T=>T.info.role==="user"&&!T.parts.every(j=>"synthetic"in j&&j.synthetic)).length===1))return;let E=y.history.slice(0,b+1),O=E[b];if(!O)return;let D=O.parts.filter(T=>T.type==="subtask"),$=D.length>0&&O.parts.every(T=>T.type==="subtask"),K=await Ne.get("title");if(!K)return;let ee=await iife(async()=>K.model?await Se.getModel(K.model.providerId,K.model.modelId):await Se.getSmallModel(y.providerId)??await Se.getModel(y.providerId,y.modelId)),N=await ts.stream({agent:K,user:O.info,system:[K.prompt??""],small:true,tools:{},model:ee,abort:new AbortController().signal,sessionId:y.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
1047
- `},...$?[{role:"user",content:D.map(T=>T.prompt).join(`
1048
- `)}]:await ve.toModelMessages(E,ee)]}),M=await Promise.resolve(N.text).catch(T=>{e$1.error("failed to generate title",{error:T});});if(M)return Z.update(y.session.id,T=>{let j=M.replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
1049
- `).map(k=>k.trim()).find(k=>k.length>0);if(!j)return;let x=j.length>100?j.substring(0,97)+"...":j;T.title=x;},{touch:false})}})(Ke||(Ke={}));var Z;(x=>{let e$1=a.create({service:"session"});function t(k=false){return SessionTitle.createDefault(k)}x.createDefaultTitle=t;function o(k){return SessionTitle.isDefault(k)}x.isDefaultTitle=o;function n(k){return SessionTitle.getForked(k)}x.Info=U.object({id:Identifier.schema("session"),slug:U.string(),providerId:U.string(),directory:U.string(),parentId:Identifier.schema("session").optional(),contextMode:U.enum(e).optional(),summary:U.object({additions:U.number(),deletions:U.number(),files:U.number(),diffs:ht.FileDiff.array().optional()}).optional(),share:U.object({url:U.string()}).optional(),title:U.string(),version:U.string(),time:U.object({created:U.number(),updated:U.number(),compacting:U.number().optional(),archived:U.number().optional()}),permission:Oe.Ruleset.optional(),revert:U.object({messageId:U.string(),partId:U.string().optional(),snapshot:U.string().optional(),diff:U.string().optional()}).optional()}).meta({ref:"Session"}),x.ProjectInfo=U.object({id:U.string(),name:U.string().optional(),worktree:U.string()}).meta({ref:"ProjectSummary"}),x.GlobalInfo=x.Info.extend({project:x.ProjectInfo.nullable()}).meta({ref:"GlobalSession"}),x.ShareInfo=U.object({secret:U.string(),url:U.string()}).meta({ref:"SessionShare"}),x.Event={Created:a$5.define("session.created",U.object({info:x.Info})),Updated:a$5.define("session.updated",U.object({info:x.Info})),Deleted:a$5.define("session.deleted",U.object({info:x.Info})),Diff:a$5.define("session.diff",U.object({sessionId:U.string(),diff:ht.FileDiff.array()})),Error:a$5.define("session.error",U.object({sessionId:U.string().optional(),error:ve.Assistant.shape.error})),ContextModeChanged:a$5.define("session.context_mode_changed",U.object({sessionId:U.string(),contextMode:U.enum(e)}))},x.create=fn$1(U.object({parentId:Identifier.schema("session").optional(),title:U.string().optional(),directory:U.string().optional(),permission:x.Info.shape.permission,contextMode:x.Info.shape.contextMode}).optional(),async k=>a$3({parentId:k?.parentId,directory:k?.directory??R.directory,title:k?.title,permission:k?.permission,contextMode:k?.contextMode})),x.fork=fn$1(U.object({sessionId:Identifier.schema("session"),directory:U.string().optional(),messageId:Identifier.schema("message").optional(),contextMode:x.Info.shape.contextMode}),async k=>{let _=await(0, x.get)(k.sessionId);if(!_)throw new Error("session not found");let L=n(_.title),H=await a$3({directory:k?.directory??_.directory??R.directory,title:L,contextMode:k.contextMode}),Y=await(0, x.messages)({sessionId:k.sessionId}),X=new Map;for(let ne of Y){if(k.messageId&&ne.info.id>=k.messageId)break;let ae=Identifier.ascending("message");X.set(ne.info.id,ae);let le=ne.info.role==="assistant"&&ne.info.parentId?X.get(ne.info.parentId):void 0,be=await(0, x.updateMessage)({...ne.info,sessionId:H.id,id:ae,...le&&{parentId:le}});for(let se of ne.parts)await(0, x.updatePart)({...se,id:Identifier.ascending("part"),messageId:be.id,sessionId:H.id});}return H}),x.touch=fn$1(Identifier.schema("session"),async k=>{await w(k,_=>{_.time.updated=Date.now();});});async function a$3(k){let _=await he.get(),L={id:Identifier.descending("session",k.id),slug:Slug.create(),version:b$3.getVersion(),providerId:R.project.id,directory:k.directory,parentId:k.parentId,contextMode:k.contextMode??_.context?.mode,title:k.title??t(!!k.parentId),permission:k.permission,time:{created:Date.now(),updated:Date.now()}};return e$1.info("created",L),await a$6.write(["session",R.project.id,L.id],L),await ue.publish(x.Event.Created,{info:L}),!L.parentId&&(a$2.EASBOT_AUTO_SHARE||_.share==="auto")&&(0, x.share)(L.id).then(H=>{w(L.id,Y=>{Y.share=H;});}).catch(()=>{}),await ue.publish(x.Event.Updated,{info:L}),L}x.createNext=a$3;function p(k){let _=R.project.vcs?Ce__default.join(R.worktree,".easbot","plans"):Ce__default.join(a$1.Path.data,"plans");return Ce__default.join(_,[k.time.created,k.slug].join("-")+".md")}x.plan=p,x.get=fn$1(Identifier.schema("session"),async k=>await a$6.read(["session",R.project.id,k])),x.getShare=fn$1(Identifier.schema("session"),async k=>a$6.read(["share",k])),x.getProjectInfo=fn$1(U.void(),async()=>({id:R.project.id,name:R.project.name,worktree:R.worktree})),x.getGlobalInfo=fn$1(Identifier.schema("session"),async k=>{let _=await(0, x.get)(k);if(_)return {..._,project:{id:R.project.id,name:R.project.name,worktree:R.worktree}}});async function P(k){let _=await(0, x.get)(k);if(_?.contextMode)return _.contextMode;let L=await he.get();return L.context?.mode?L.context.mode:"general"}x.getContextMode=P;async function I(k,_){if(!e.includes(_))throw new Error(`Invalid contextMode: ${_}. Must be one of: ${e.join(", ")}`);await w(k,L=>{L.contextMode=_;}),await ue.publish(x.Event.ContextModeChanged,{sessionId:k,contextMode:_});}x.setContextMode=I,x.share=fn$1(Identifier.schema("session"),async k=>{if((await he.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let{Share:L}=await import('./share-RUV4SIRB.mjs'),H=await L.create(k);return await w(k,Y=>{Y.share={url:H.url};},{touch:false}),H}),x.unshare=fn$1(Identifier.schema("session"),async k=>{let{Share:_}=await import('./share-RUV4SIRB.mjs');await _.remove(k),await w(k,L=>{L.share=void 0;},{touch:false});});async function w(k,_,L){let H=R.project,Y=await a$6.update(["session",H.id,k],X=>{_(X),L?.touch!==false&&(X.time.updated=Date.now());});return await ue.publish(x.Event.Updated,{info:Y}),Y}x.update=w,x.diff=fn$1(Identifier.schema("session"),async k=>await a$6.read(["session_diff",k])??[]),x.messages=fn$1(U.object({sessionId:Identifier.schema("session"),limit:U.number().optional()}),async k=>{let _=[];for await(let L of ve.stream(k.sessionId)){if(k.limit&&_.length>=k.limit)break;_.push(L);}return _.reverse(),_});async function*C(){let k=R.project;for(let _ of await a$6.list(["session",k.id])){let L=await a$6.read(_).catch(()=>{});L&&(yield L);}}x.list=C,x.children=fn$1(Identifier.schema("session"),async k=>{let _=R.project,L=[];for(let H of await a$6.list(["session",_.id])){let Y=await a$6.read(H).catch(()=>{});Y&&Y.parentId===k&&L.push(Y);}return L}),x.remove=fn$1(Identifier.schema("session"),async k=>{let _=R.project;try{let L=await(0,x.get)(k);for(let H of await(0,x.children)(k))await(0,x.remove)(H.id);await(0,x.unshare)(k).catch(()=>{});for(let H of await a$6.list(["message",k])){let Y=H.at(-1);for(let ae of await a$6.list(["part",Y]))await a$6.remove(ae);let X=await a$6.dir(["part",Y]);await a$6.rmdir(X).catch(()=>{}),await a$6.remove(H);let ne=await a$6.dir(["message",k]);await a$6.rmdir(ne).catch(()=>{});}await a$6.remove(["session",_.id,k]),await a$6.remove(["tui",k]).catch(()=>{}),await ue.publish(x.Event.Deleted,{info:L});}catch(L){e$1.error(L);}}),x.updateMessage=fn$1(ve.Info,async k=>(await a$6.write(["message",k.sessionId,k.id],k),ue.publish(ve.Event.Updated,{info:k}),k)),x.removeMessage=fn$1(U.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message")}),async k=>(await a$6.remove(["message",k.sessionId,k.messageId]),ue.publish(ve.Event.Removed,{sessionId:k.sessionId,messageId:k.messageId}),k.messageId)),x.removePart=fn$1(U.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message"),partId:Identifier.schema("part")}),async k=>(await a$6.remove(["part",k.messageId,k.partId]),ue.publish(ve.Event.PartRemoved,{sessionId:k.sessionId,messageId:k.messageId,partId:k.partId}),k.partId));let ee=U.union([ve.Part,U.object({part:ve.TextPart,delta:U.string()}),U.object({part:ve.ReasoningPart,delta:U.string()})]);x.updatePart=fn$1(ee,async k=>{let _="delta"in k?k.part:k,L="delta"in k?k.delta:void 0;return await a$6.write(["part",_.messageId,_.id],_),ue.publish(ve.Event.PartUpdated,{part:_,delta:L,time:Date.now()}),_}),x.getUsage=fn$1(U.object({model:U.custom(),usage:U.custom(),metadata:U.custom().optional()}),k=>{let _=q=>Number.isFinite(q)?q:0,L=_(k.usage.inputTokens??0),H=_(k.usage.outputTokens??0),Y=_(k.usage.reasoningTokens??0),X=_(k.usage.cachedInputTokens??0),ne=_(k.metadata?.anthropic?.cacheCreationInputTokens??k.metadata?.bedrock?.usage?.cacheWriteInputTokens??k.metadata?.venice?.usage?.cacheCreationInputTokens??0),ae=!!(k.metadata?.anthropic||k.metadata?.bedrock),le=_(ae?L:L-X-ne),se={total:iife(()=>k.model.api.npm==="@ai-sdk/anthropic"||k.model.api.npm==="@ai-sdk/amazon-bedrock"||k.model.api.npm==="@ai-sdk/google-vertex/anthropic"?le+H+X+ne:k.usage.totalTokens),input:le,output:H,reasoning:Y,cache:{write:ne,read:X}},Q=k.model.cost?.experimentalOver200K&&se.input+se.cache.read>2e5?k.model.cost.experimentalOver200K:k.model.cost;return {cost:_(new Decimal(0).add(new Decimal(se.input).mul(Q?.input??0).div(1e6)).add(new Decimal(se.output).mul(Q?.output??0).div(1e6)).add(new Decimal(se.cache.read).mul(Q?.cache?.read??0).div(1e6)).add(new Decimal(se.cache.write).mul(Q?.cache?.write??0).div(1e6)).add(new Decimal(se.reasoning).mul(Q?.output??0).div(1e6)).toNumber()),tokens:se}});class T extends Error{constructor(L){super(`Session ${L} is busy`);b$1(this,"sessionId",L);}}x.BusyError=T,x.initialize=fn$1(U.object({sessionId:Identifier.schema("session"),modelId:U.string(),providerId:U.string(),messageId:Identifier.schema("message")}),async k=>{await Ke.command({sessionId:k.sessionId,messageId:k.messageId,model:k.providerId+"/"+k.modelId,command:So.Default.INIT,arguments:""});});})(Z||(Z={}));var qt;(a$1=>{let e=a.create({service:"project"});a$1.Info=U.object({id:U.string(),worktree:U.string(),vcs:U.literal("git").optional(),name:U.string().optional(),icon:U.object({url:U.string().optional(),override:U.string().optional(),color:U.string().optional()}).optional(),commands:U.object({start:U.string().optional().describe("Startup script to run when creating a new workspace (worktree)")}).optional(),time:U.object({created:U.number(),updated:U.number(),initialized:U.number().optional()}),sandboxes:U.array(U.string())}).meta({ref:"Project"}),a$1.Event={Updated:a$5.define("project.updated",a$1.Info)};async function n(p){e.info("fromDirectory",{directory:p});let{id:u,sandbox:h,worktree:g,vcs:v}=await iife(async()=>{let A=Filesystem.up({targets:[".git"],start:p}),S=await A.next().then(y=>y.value);if(await A.return(void 0),S){let y=Ce__default.dirname(S),b=await PKG.which("git"),C=await Tt__default.readFile(Ce__default.join(S,"easbot"),"utf-8").then(D=>D.trim()).catch(()=>{});if(!b)return {id:C??"global",worktree:y,sandbox:y,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};if(!C){let D=await $`git rev-list --max-parents=0 --all`.quiet().nothrow().cwd(y).text().then($=>$.split(`
1050
- `).filter(Boolean).map(K=>K.trim()).toSorted()).catch(()=>{});if(!D)return {id:"global",worktree:y,sandbox:y,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};C=D[0],C&&Tt__default.writeFile(Ce__default.join(S,"easbot"),C).catch(()=>{});}if(!C)return {id:"global",worktree:y,sandbox:y,vcs:"git"};let E=await $`git rev-parse --show-toplevel`.quiet().nothrow().cwd(y).text().then(D=>Ce__default.resolve(y,D.trim())).catch(()=>{});if(!E)return {id:C,sandbox:y,worktree:y,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};y=E;let O=await $`git rev-parse --git-common-dir`.quiet().nothrow().cwd(y).text().then(D=>{let $=Ce__default.dirname(D.trim());return $==="."?y:$}).catch(()=>{});return O?{id:C,sandbox:y,worktree:O,vcs:"git"}:{id:C,sandbox:y,worktree:y,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)}}),P=await a$6.read(["project",u]).catch(()=>{});P||(P={id:u,worktree:g,vcs:v,sandboxes:[],time:{created:Date.now(),updated:Date.now()}},u!=="global"&&await r(u,g)),P?.sandboxes||(P.sandboxes=[]),a$2.EASBOT_ICON_DISCOVERY&&await s(P);let I={...P,worktree:g,vcs:v,time:{...P?.time,updated:Date.now()}};return h!==I.worktree&&!I.sandboxes.includes(h)&&I.sandboxes.push(h),I.sandboxes=I.sandboxes.filter(A=>existsSync(A)),await a$6.write(["project",u],I),mt.emit("event",{payload:{type:a$1.Event.Updated.type,properties:I}}),{project:I,sandbox:h}}a$1.fromDirectory=n;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,y)=>w.length-y.length)[0];if(!h)return;let v=(await Tt__default.readFile(h)).toString("base64"),P=Ce__default.extname(h).toLowerCase(),S=`data:${{".ico":"image/x-icon",".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"}[P]||"image/png"};base64,${v}`;await(0, a$1.update)({providerId:p.id,icon:{url:S}});}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 v=>{let P=v[v.length-1]??"",I=await a$6.read(v).catch(()=>{});I&&(I.directory&&I.directory!==u||(I.providerId=p,e.info("migrating session",{sessionId:P,from:"global",to:p}),await a$6.write(["session",p,P],I),await a$6.remove(v)));}).catch(v=>{e.error("failed to migrate sessions from global to project",{error:v,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(U.object({providerId:U.string(),name:U.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 mt.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 v=g.sandboxes??[];v.includes(u)||v.push(u),g.sandboxes=v,g.time.updated=Date.now();});return mt.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 v=g.sandboxes??[];g.sandboxes=v.filter(P=>P!==u),g.time.updated=Date.now();});return mt.emit("event",{payload:{type:a$1.Event.Updated.type,properties:h}}),h}a$1.removeSandbox=f;})(qt||(qt={}));var Ia;(s=>{let e=a.create({service:"state"}),t=new Map;function o(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=o;async function n(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=n;})(Ia||(Ia={}));var ai=Context.create("instance"),bs=new Map,va={all:void 0},R={async provide(e){let t=bs.get(e.directory);t||(a.Default.info("creating instance",{directory:e.directory}),t=iife(async()=>{let{project:n,sandbox:s}=await qt.fromDirectory(e.directory),r={directory:e.directory,worktree:s,project:n};return await ai.provide(r,async()=>{await e.init?.();}),r}),bs.set(e.directory,t));let o=await t;return ai.provide(o,async()=>e.fn())},get directory(){return ai.use().directory},get worktree(){return ai.use().worktree},get project(){return ai.use().project},containsPath(e){return Filesystem.contains(R.directory,e)?true:R.worktree==="/"?false:Filesystem.contains(R.worktree,e)},state(e,t){return Ia.create(()=>R.directory,e,t)},async dispose(){a.Default.info("disposing instance",{directory:R.directory}),await Ia.dispose(R.directory),bs.delete(R.directory),mt.emit("event",{directory:R.directory,payload:{type:"server.instance.disposed",properties:{directory:R.directory}}});},async disposeAll(){return va.all||(va.all=iife(async()=>{a.Default.info("disposing all instances");let e=[...bs.entries()];for(let[t,o]of e){if(bs.get(t)!==o)continue;let n=await o.catch(s=>{a.Default.warn("instance dispose failed",{key:t,error:s});});if(!n){bs.get(t)===o&&bs.delete(t);continue}bs.get(t)===o&&await ai.provide(n,async()=>{await R.dispose();});}}).finally(()=>{va.all=void 0;})),va.all}};var ue;(f=>{let e=a.create({service:"bus"});f.InstanceDisposed=a$5.define("server.instance.disposed",U.object({directory:U.string()}));let o;function n(){return o||(o=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);})),o}function s(){return n()()}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 v of [a.type,"*"]){let P=g.subscriptions.get(v);for(let I of P??[])h.push(I(u));}return mt.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,v=g.get(a)??[];v.push(p),g.set(a,v);});return ()=>{e.debug("unsubscribing",{type:a}),s().then(h=>{let g=h.subscriptions.get(a);if(!g)return;let v=g.indexOf(p);v!==-1&&g.splice(v,1);});}}async function m(){await s();}f.waitForSubscription=m;})(ue||(ue={}));export{Aa as $,Xo as $a,ui as A,Ke as Aa,pi as B,Le as Ba,Oa as C,Hg as Ca,mi as D,Bg as Da,pr as E,Ou as Ea,Qd as F,od as Fa,On as G,ds as Ga,Zd as H,ho as Ha,hi as I,el as J,ht as Ja,tl as K,ve as Ka,Fb as L,xd as La,Nb as M,Z as Ma,Ub as N,qt as Na,io as O,R as Oa,Ue as P,ja as Pa,jp as Q,sl as Qa,zd as R,rl as Ra,xi as S,il as Sa,Ja as T,La as Ta,fw as U,mr as Ua,dl as V,ow as Va,gw as W,Is as Wa,hw as X,Da as Xa,As as Y,$a as Ya,Lt as Z,Fa as Za,Ea as _,Na as _a,ue as a,Ra as aa,Ua as ab,We as b,sr as ba,gt as bb,Be as c,rr as ca,wi as cb,_u as d,ir as da,za as db,Fr as e,Gd as ea,qa as eb,cs as f,nl as fa,dn as fb,Qc as g,Qb as ga,Ha as gb,TP as h,Zb as ha,Ba as hb,Dg as i,bi as ia,Ga as ib,Se as j,so as ja,Wa as jb,Oe as k,yt as ka,Va as kb,wn as l,Vc as la,lr as lb,Ot as m,Cg as ma,al as mb,Kx as n,Ho as na,cl as nb,dc as o,RX as oa,ww as ob,Jx as p,yn as pa,he as pb,Xx as q,gd as qa,la as qb,rn as r,_X as ra,ci as s,MX as sa,di as t,Ph as ta,Mn as u,OX as ua,an as v,Th as va,cn as w,ya as wa,cr as x,Ch as xa,dr as y,KE as ya,li as z,So as za};