@easbot/agent 0.2.41 → 0.2.43

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 (122) hide show
  1. package/dist/assets/txt/command/builtin/loop.txt +10 -5
  2. package/dist/assets/txt/context/template/BOOT.txt +2 -0
  3. package/dist/assets/txt/scheduler/heartbeat.txt +18 -1
  4. package/dist/assets/txt/scheduler/scheduled.txt +17 -1
  5. package/dist/assets/txt/tool/agent-client.txt +6 -10
  6. package/dist/chunks/acp-OBY35HS7.mjs +22 -0
  7. package/dist/chunks/adapter-loader-ZXPJJRRY.mjs +1 -0
  8. package/dist/chunks/{agent-CYRU65IN.mjs → agent-EJ64O3VC.mjs} +1 -1
  9. package/dist/chunks/{agent-JHX64CI6.mjs → agent-WSRT77Z6.mjs} +1 -1
  10. package/dist/chunks/agent-service-registry-QA5V3B4G.mjs +1 -0
  11. package/dist/chunks/app-I6CHGBMN.mjs +58 -0
  12. package/dist/chunks/{auth-SUHJJM24.mjs → auth-F3UJX6TK.mjs} +1 -1
  13. package/dist/chunks/bootstrap-O5UL3UT2.mjs +1 -0
  14. package/dist/chunks/build-program-LX6IAAHW.mjs +11 -0
  15. package/dist/chunks/bus-XKXFTFNZ.mjs +1 -0
  16. package/dist/chunks/chunk-3CQA7CJG.mjs +2 -0
  17. package/dist/chunks/chunk-3UV6DBAA.mjs +2 -0
  18. package/dist/chunks/{chunk-UBCLKZWP.mjs → chunk-4Q3JAZPL.mjs} +1 -1
  19. package/dist/chunks/{chunk-D4GDS5UI.mjs → chunk-CDDE7L65.mjs} +1 -1
  20. package/dist/chunks/{chunk-IEQ4VD66.mjs → chunk-EFJHO4OX.mjs} +1 -1
  21. package/dist/chunks/{chunk-KTMZPMCI.mjs → chunk-G63GWBVD.mjs} +1 -1
  22. package/dist/chunks/{chunk-75IQNF4I.mjs → chunk-HIPEPY4E.mjs} +1 -1
  23. package/dist/chunks/chunk-IJVW4VME.mjs +1 -0
  24. package/dist/chunks/chunk-LGMGGNPW.mjs +1 -0
  25. package/dist/chunks/{chunk-X7KLQIAQ.mjs → chunk-LP2YYNMX.mjs} +1 -1
  26. package/dist/chunks/{chunk-TYD2M4SP.mjs → chunk-MYI75W3D.mjs} +1 -1
  27. package/dist/chunks/chunk-OSLGCE7R.mjs +1 -0
  28. package/dist/chunks/chunk-PT5TKWFJ.mjs +1051 -0
  29. package/dist/chunks/{chunk-UNBJ6Y7L.mjs → chunk-XQ3LMV3K.mjs} +2 -2
  30. package/dist/chunks/{chunk-R4BPTF6V.mjs → chunk-ZH674M7Q.mjs} +1 -1
  31. package/dist/chunks/{command-CPT2YSIR.mjs → command-34YNL5HZ.mjs} +1 -1
  32. package/dist/chunks/compaction-OCFEYJC4.mjs +1 -0
  33. package/dist/chunks/config-MLDSMYKU.mjs +1 -0
  34. package/dist/chunks/{confirm-dialog-SJOXJWYU.mjs → confirm-dialog-PT62UY3W.mjs} +1 -1
  35. package/dist/chunks/debug-GTUHAYVC.mjs +3 -0
  36. package/dist/chunks/event-2JDHF3UV.mjs +1 -0
  37. package/dist/chunks/{export-4CIOZYMY.mjs → export-5BWFWBI3.mjs} +1 -1
  38. package/dist/chunks/file-P2YWB5Q7.mjs +1 -0
  39. package/dist/chunks/gateway-GFZFVEHP.mjs +16 -0
  40. package/dist/chunks/gateway-loader-OH3VCEUD.mjs +1 -0
  41. package/dist/chunks/{generate-4UO6UCUB.mjs → generate-FNIRYTGT.mjs} +1 -1
  42. package/dist/chunks/{github-XIWTIRCK.mjs → github-JPCEWX4N.mjs} +2 -2
  43. package/dist/chunks/global-HVRSDT3G.mjs +1 -0
  44. package/dist/chunks/{i18n-OMQXNLBR.mjs → i18n-4TNHSVRN.mjs} +1 -1
  45. package/dist/chunks/{import-K45ZW3NR.mjs → import-B5RTBC2W.mjs} +1 -1
  46. package/dist/chunks/installation-JDBMIGTK.mjs +1 -0
  47. package/dist/chunks/instance-5OB47GH5.mjs +1 -0
  48. package/dist/chunks/loader-GNE7KLKQ.mjs +1 -0
  49. package/dist/chunks/loader-J6SV3FLI.mjs +1 -0
  50. package/dist/chunks/lsp-QWPGRLGX.mjs +1 -0
  51. package/dist/chunks/{mcp-JBHKJN6X.mjs → mcp-5DZTVP6Z.mjs} +1 -1
  52. package/dist/chunks/mcp-KWZSND4L.mjs +1 -0
  53. package/dist/chunks/models-JIMJ74AN.mjs +1 -0
  54. package/dist/chunks/{pr-MCLQ6KQO.mjs → pr-E7AEHZZT.mjs} +1 -1
  55. package/dist/chunks/preferences-KZ7TL4Q3.mjs +1 -0
  56. package/dist/chunks/project-3W6D3354.mjs +1 -0
  57. package/dist/chunks/prompt-7M7NMDG4.mjs +1 -0
  58. package/dist/chunks/provider-RGQTLMFK.mjs +1 -0
  59. package/dist/chunks/registry-AA7CYXUC.mjs +1 -0
  60. package/dist/chunks/revert-FOMRGDW5.mjs +1 -0
  61. package/dist/chunks/ripgrep-TBPFM3BV.mjs +1 -0
  62. package/dist/chunks/{run-EGRUZXP2.mjs → run-MYXJU4RX.mjs} +1 -1
  63. package/dist/chunks/scheduler-YYOW743S.mjs +1 -0
  64. package/dist/chunks/server-SQMRITFT.mjs +1 -0
  65. package/dist/chunks/session-EPFSKATV.mjs +1 -0
  66. package/dist/chunks/session-FQ5O5XZY.mjs +1 -0
  67. package/dist/chunks/{session-VCIKEQYZ.mjs → session-LWKQT4G7.mjs} +1 -1
  68. package/dist/chunks/{settings-panel-ZMAGAWRF.mjs → settings-panel-C32BQGOR.mjs} +1 -1
  69. package/dist/chunks/share-6NJ4W4CC.mjs +1 -0
  70. package/dist/chunks/snapshot-VO64Z4KV.mjs +1 -0
  71. package/dist/chunks/{stats-RPGHGZUR.mjs → stats-6IILCYBN.mjs} +1 -1
  72. package/dist/chunks/storage-23DKEFPY.mjs +1 -0
  73. package/dist/chunks/{tui-ZMS6CJQ7.mjs → tui-P4UKVVKY.mjs} +1 -1
  74. package/dist/chunks/types-2GDQRKMX.mjs +1 -0
  75. package/dist/chunks/{types-GCXI5X7B.mjs → types-OCGSLJEP.mjs} +1 -1
  76. package/dist/chunks/{update-KDCCJIPI.mjs → update-NNMG3LC7.mjs} +1 -1
  77. package/dist/cli.mjs +5 -5
  78. package/package.json +15 -14
  79. package/dist/chunks/acp-D5UOHKRU.mjs +0 -22
  80. package/dist/chunks/adapter-loader-SHO4LOSU.mjs +0 -1
  81. package/dist/chunks/app-S6QDTGNJ.mjs +0 -1
  82. package/dist/chunks/bootstrap-FHSG4M5N.mjs +0 -1
  83. package/dist/chunks/build-program-YDOM5ROT.mjs +0 -11
  84. package/dist/chunks/bus-7GPWVWOA.mjs +0 -1
  85. package/dist/chunks/chunk-2RSIOAZV.mjs +0 -1
  86. package/dist/chunks/chunk-CCRIJZBK.mjs +0 -1
  87. package/dist/chunks/chunk-EM2QJ5NQ.mjs +0 -59
  88. package/dist/chunks/chunk-FWVB6X4X.mjs +0 -1050
  89. package/dist/chunks/chunk-GRDTQW6K.mjs +0 -2
  90. package/dist/chunks/chunk-SB4J2R54.mjs +0 -2
  91. package/dist/chunks/chunk-ZBRXNYEM.mjs +0 -1
  92. package/dist/chunks/compaction-JR5FOLBX.mjs +0 -1
  93. package/dist/chunks/config-O5EE574O.mjs +0 -1
  94. package/dist/chunks/debug-BWJVMW7Q.mjs +0 -3
  95. package/dist/chunks/event-NO7SFKKX.mjs +0 -1
  96. package/dist/chunks/file-Q52INNX3.mjs +0 -1
  97. package/dist/chunks/gateway-XSXBPTB7.mjs +0 -16
  98. package/dist/chunks/gateway-loader-6P6BTWQP.mjs +0 -1
  99. package/dist/chunks/global-XQYOBWZR.mjs +0 -1
  100. package/dist/chunks/installation-55Z2PXMV.mjs +0 -1
  101. package/dist/chunks/instance-S5GBRS3K.mjs +0 -1
  102. package/dist/chunks/loader-JAKTXQ6M.mjs +0 -1
  103. package/dist/chunks/loader-S2BSLSAZ.mjs +0 -1
  104. package/dist/chunks/lsp-4VYPJGAN.mjs +0 -1
  105. package/dist/chunks/mcp-ZGGTG6YT.mjs +0 -1
  106. package/dist/chunks/models-TI5SNTLO.mjs +0 -1
  107. package/dist/chunks/preferences-LWCCEUB3.mjs +0 -1
  108. package/dist/chunks/project-OEBG6JHE.mjs +0 -1
  109. package/dist/chunks/prompt-JSZCNKQD.mjs +0 -1
  110. package/dist/chunks/provider-TU4AF2GP.mjs +0 -1
  111. package/dist/chunks/registry-NITFPORZ.mjs +0 -1
  112. package/dist/chunks/revert-PDDRJVNK.mjs +0 -1
  113. package/dist/chunks/ripgrep-7VVA7THG.mjs +0 -1
  114. package/dist/chunks/scheduler-VUQ33E5B.mjs +0 -1
  115. package/dist/chunks/server-3RDX4X3L.mjs +0 -1
  116. package/dist/chunks/session-GQAYKB6Q.mjs +0 -1
  117. package/dist/chunks/session-TXC5Z4O2.mjs +0 -1
  118. package/dist/chunks/share-RUV4SIRB.mjs +0 -1
  119. package/dist/chunks/snapshot-PXRGQ6JR.mjs +0 -1
  120. package/dist/chunks/storage-3T5H5KBY.mjs +0 -1
  121. package/dist/chunks/tui-5BQORL3N.mjs +0 -1
  122. package/dist/chunks/types-RWQQETDC.mjs +0 -1
@@ -0,0 +1,1051 @@
1
+ import {b as b$4,a as a$b}from'./chunk-4Q3JAZPL.mjs';import {b as b$2,a as a$a,c as c$2}from'./chunk-IJVW4VME.mjs';import {a as a$8}from'./chunk-CDDE7L65.mjs';import {a as a$4,b,c as c$1}from'./chunk-LGMGGNPW.mjs';import {f,e as e$1,c as c$3}from'./chunk-HIPEPY4E.mjs';import {a as a$9}from'./chunk-AAJAKVQY.mjs';import {e,h,g,i,f as f$1,o,m,r,q,l,n,p}from'./chunk-OSLGCE7R.mjs';import {i as i$1}from'./chunk-XQ3LMV3K.mjs';import {a as a$3}from'./chunk-LP2YYNMX.mjs';import {a as a$2,b as b$3}from'./chunk-G63GWBVD.mjs';import {a as a$5}from'./chunk-CJTCCLW4.mjs';import {a as a$6}from'./chunk-3CQA7CJG.mjs';import {a}from'./chunk-LFYBZHOI.mjs';import {a as a$1}from'./chunk-3UV6DBAA.mjs';import {b as b$1,a as a$7,c,d}from'./chunk-X6ISXWBN.mjs';import F,{z}from'zod';import {PKG,Filesystem,Archive,$,NamedError,lazy,fn as fn$1,Identifier,Wildcard,whichSync,Shell,loadTextFile,TruncateContent,lazyAsync,abortAfterAny,Fetch,iife,formatLocalISOCompact,defer,parseModelId,git,AsyncQueue,Slug,Context,PackageRegistry,proxied,withTimeout,Ignore,Token,createPkgShell,SessionTitle,Glob,retry,work,shell,loadTextFileAsync}from'@easbot/utils';import*as Tt from'fs/promises';import Tt__default,{realpath,mkdir,access,readFile,writeFile,unlink,readdir,copyFile,stat,rm as rm$1}from'fs/promises';import*as Ce from'path';import Ce__default,{join,sep}from'path';import {Decimal}from'decimal.js';import {convertToModelMessages,APICallError,LoadAPIKeyError,tool,jsonSchema,streamText,wrapLanguageModel,asSchema,streamObject,generateObject,NoSuchModelError,dynamicTool}from'ai';import sc from'os';import {mergeDeep,mapValues,pipe,splitWhen,values,sortBy,unique,filter,map,fromEntries,clone,pickBy,omit}from'remeda';import Sl,{createReadStream,existsSync,constants,readFileSync}from'fs';import {parse as parse$1,printParseErrorCode,modify,applyEdits}from'jsonc-parser';import {pathToFileURL,fileURLToPath}from'url';import {EventEmitter}from'events';import {createMessageConnection,StreamMessageReader,StreamMessageWriter}from'vscode-jsonrpc/node.js';import {createServer,STATUS_CODES}from'http';import {glob}from'glob';import {initLog as initLog$2,createNoteKnowledge}from'@easbot/note';import Ty 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 Lx from'open';import {HookEvent}from'@easbot/plugin';export{HookEvent as Ia}from'@easbot/plugin';import {LRUCache}from'lru-cache';import {createInterface}from'readline';import {ulid}from'ulid';import {ndJsonStream,ClientSideConnection}from'@agentclientprotocol/sdk';import {spawn}from'child_process';import {initLog,createMemorySystem}from'@easbot/memory';import {initLog as initLog$1,createCodebase}from'@easbot/codebase';import'@easbot/types';import yS from'bash-parser';import {createRequire}from'module';import lC from'turndown';import {parse}from'node-html-parser';import*as CC from'node-pty';import {createHash}from'crypto';import rP from'zod/v4';import {zodToJsonSchema}from'zod-to-json-schema';import {HTTPException}from'hono/http-exception';import UE from'bonjour-service';import {serve}from'@hono/node-server';var xo;(ie=>{let e=a.create({service:"lsp.server"}),t=process.platform==="win32"?"cmd":void 0;function n(Z,H=[],$){let te=H.length>0?`${Z} ${H.join(" ")}`:Z,W=process.platform==="win32"?{...$,windowsHide:true}:$;return Shell.spawn(t,te,W)}function o(Z,H){let $=process.platform==="win32"?{...H,windowsHide:true}:H;return Shell.spawn(t,Z.join(" "),$)}function s(Z,H=[],$){return PKG.spawn([Z,...H],$)}async function r(Z,H){let $=process.platform==="win32"?{...H,windowsHide:true}:H;return Shell.run(t,Z,$)}let i=async Z=>Tt__default.stat(Z).then(()=>true).catch(()=>false),c=(Z,H)=>async $=>{if(H){let V=Filesystem.up({targets:H,start:Ce__default.dirname($),stop:_.directory}),oe=await V.next();if(await V.return(void 0),oe.value)return}let te=Filesystem.up({targets:Z,start:Ce__default.dirname($),stop:_.directory}),W=await te.next();return await te.return(void 0),W.value?Ce__default.dirname(W.value):_.directory};ie.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(Z){if(Z in ie.ServerInitTimeout)return ie.ServerInitTimeout[Z];let H=Z.replace(/\s+/g,"_");if(H in ie.ServerInitTimeout)return ie.ServerInitTimeout[H];let $=Z.split(/\s+/).pop();return $&&$ in ie.ServerInitTimeout?ie.ServerInitTimeout[$]:a$2.EASBOT_LSP_INIT_TIMEOUT}ie.getServerInitTimeout=d,ie.Deno={id:"deno",initTimeout:ie.ServerInitTimeout.deno,root:async Z=>{let H=Filesystem.up({targets:["deno.json","deno.jsonc"],start:Ce__default.dirname(Z),stop:_.directory}),$=await H.next();if(await H.return(void 0),!!$.value)return Ce__default.dirname($.value)},extensions:[".ts",".tsx",".js",".jsx",".mjs"],async spawn(Z){let H=await PKG.which("deno");if(!H){e.info("deno not found, please install deno first");return}return {process:n(H,["lsp"],{cwd:Z,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"}];ie.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:ie.ServerInitTimeout.typescript,async spawn(Z){e.info("typescript server spawn",{PATH:process.env.PATH});let H=null,$;for(let V of f){if(e.info(`trying to find ${V.name}...`),H=await PKG.which(V.command),H){e.info(`${V.name} found`,{binary:H}),$=V;break}let oe=await PKG.resolve(V.name,_.directory).catch(()=>{});if(oe){H=oe,e.info(`${V.name} resolved`,{binary:H}),$=V;break}}if(!H||!$){let V=f.map(oe=>`npm install -g ${oe.name}`).join(" \u6216 ");e.error(`typescript LSP server not found, please install: ${V}`);return}e.info(`typescript server starting with ${$.name}`,{binary:H});let te=$.command==="vtsls"?["--stdio"]:["--stdio"];return {process:n(H,te,{cwd:Z,env:{...process.env},stderr:"ignore"})}}},ie.Vue={id:"vue",initTimeout:ie.ServerInitTimeout.vue,extensions:[".vue"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Z){let H=await PKG.which("vue-language-server"),$=[];if(!H){let V=Ce__default.join(a$1.Path.bin,"node_modules","@vue","language-server","bin","vue-language-server.js");if(!await PKG.file(V).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let de=await PKG.which();if(!de)return;await n(de,["install","@vue/language-server"],{cwd:a$1.Path.bin,env:{...process.env},stdout:"pipe",stderr:"pipe"}).exited;}let oe=await PKG.which();if(!oe)return;H=oe,$.push("run",V);}if(!H)return;let te=await PKG.which();return te?{process:n(te,$,{cwd:Z}),initialization:{}}:void 0}},ie.ESLint={id:"eslint",initTimeout:ie.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(Z){if(!await PKG.resolve("eslint",_.directory).catch(()=>{}))return;e.info("spawning eslint server");let $$1=Ce__default.join(a$1.Path.bin,"vscode-eslint","server","out","eslintServer.js");if(!await PKG.file($$1).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading and building VS Code ESLint server");let V=await fetch("https://github.com/microsoft/vscode-eslint/archive/refs/heads/main.zip");if(!V.ok)return;let oe=Ce__default.join(a$1.Path.bin,"vscode-eslint.zip");if(await PKG.write(oe,V),!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"),ce=Ce__default.join(a$1.Path.bin,"vscode-eslint");await Tt__default.stat(ce).catch(()=>{})&&(e.info("removing old eslint installation",{path:ce}),await Tt__default.rm(ce,{force:true,recursive:true})),await Tt__default.rename(me,ce);let je=process.platform==="win32"?"npm.cmd":"npm";await $`${je} install`.cwd(ce).quiet(),await $`${je} run compile`.cwd(ce).quiet(),e.info("installed VS Code ESLint server",{serverPath:$$1});}let te=await PKG.which();return te?{process:n(te,[$$1,"--stdio"],{cwd:Z,env:{...process.env},stderr:"ignore"})}:void 0}},ie.Oxlint={id:"oxlint",initTimeout:ie.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(Z){let H=process.platform==="win32"?".cmd":"",$=Ce__default.join("node_modules",".bin","oxc_language_server"+H),te=Ce__default.join("node_modules",".bin","oxlint"+H),W=async de=>{let me=Ce__default.join(Z,de);if(await PKG.file(me).exists())return me;let ce=Filesystem.up({targets:[de],start:Z,stop:_.worktree}),ye=await ce.next();if(await ce.return(void 0),ye.value)return ye.value},V=await W(te);if(!V){let de=await PKG.which("oxlint");de&&(V=de);}if(V){let de=n(V,["--help"],{stdout:"pipe"});if(await de.exited,(await PKG.nodeReadableStreamToText(de.stdout)).includes("--lsp"))return {process:n(V,["--lsp"],{cwd:Z,stderr:"ignore"})}}let oe=await W($);if(!oe){let de=await PKG.which("oxc_language_server");de&&(oe=de);}if(oe)return {process:n(oe,[],{cwd:Z,stderr:"ignore"})};e.info("oxlint not found, please install oxlint");}},ie.Biome={id:"biome",initTimeout:ie.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(Z){let H=process.platform==="win32",$=Ce__default.join(Z,"node_modules",".bin",H?"biome.cmd":"biome");if(await PKG.file($).exists())return {process:n($,["lsp-proxy","--stdio"],{cwd:Z,env:process.env,stderr:"ignore"})};let te=await PKG.which("biome");if(te)return {process:n(te,["lsp-proxy","--stdio"],{cwd:Z,env:process.env,stderr:"ignore"})};if(H){let de=await PKG.which("biome.cmd");if(de)return {process:n(de,["lsp-proxy","--stdio"],{cwd:Z,env:process.env,stderr:"ignore"})}}let W=Ce__default.join(a$1.Path.bin,"node_modules","@biomejs","biome","bin","biome");if(!await PKG.file(W).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD){e.info("Biome LSP download disabled by flag");return}e.info("Installing @biomejs/biome...");let de=await PKG.which();if(!de){e.warn("Package manager not found");return}try{await n(de,["install","@biomejs/biome"],{cwd:a$1.Path.bin,env:process.env,stdout:"pipe",stderr:"pipe",stdin:"pipe"}).exited,e.info("Biome installed successfully");}catch(me){e.error("Failed to install biome",{error:me});return}}let V=await PKG.which();return V?{process:n(V,["run",W,"lsp-proxy","--stdio"],{cwd:Z,env:process.env,timeout:false,stderr:"ignore"})}:void 0}},ie.Gopls={id:"gopls",initTimeout:ie.ServerInitTimeout.gopls,root:async Z=>{let H=await c(["go.work"])(Z);return H||c(["go.mod","go.sum"])(Z)},extensions:[".go"],async spawn(Z){let H=await PKG.which("gopls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("go")||a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing gopls");let te=await r("go install golang.org/x/tools/gopls@latest",{env:{...process.env,GOBIN:a$1.Path.bin}});if(te.code!==0){e.error("Failed to install gopls",{stderr:te.stderr});return}H=Ce__default.join(a$1.Path.bin,"gopls"+(process.platform==="win32"?".exe":"")),e.info("installed gopls",{bin:H});}if(H)return {process:n(H)}}},ie.Rubocop={id:"ruby-lsp",initTimeout:ie.ServerInitTimeout.ruby_lsp,root:c(["Gemfile"]),extensions:[".rb",".rake",".gemspec",".ru"],async spawn(Z){let H=await PKG.which("rubocop",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){let $=await PKG.which("ruby"),te=await PKG.which("gem");if(!$||!te){e.info("Ruby not found, please install Ruby first");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing rubocop");let W=await r(`gem install rubocop --bindir "${a$1.Path.bin}"`);if(W.code!==0){e.error("Failed to install rubocop",{stderr:W.stderr});return}H=Ce__default.join(a$1.Path.bin,"rubocop"+(process.platform==="win32"?".exe":"")),e.info("installed rubocop",{bin:H});}if(H)return {process:n(H,["--lsp"],{cwd:Z,stderr:"ignore"})}}},ie.Ty={id:"ty",initTimeout:ie.ServerInitTimeout.ty,extensions:[".py",".pyi"],root:c(["pyproject.toml","ty.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(Z){if(!a$2.EASBOT_LSP_TY)return;let H=await PKG.which("ty"),$={},te=[process.env.VIRTUAL_ENV,Ce__default.join(Z,".venv"),Ce__default.join(Z,"venv")].filter(V=>V!==void 0);for(let V of te){let de=process.platform==="win32"?Ce__default.join(V,"Scripts","python.exe"):Ce__default.join(V,"bin","python");if(await PKG.file(de).exists()){$.pythonPath=de;break}}if(!H)for(let V of te){let de=process.platform==="win32"?Ce__default.join(V,"Scripts","ty.exe"):Ce__default.join(V,"bin","ty");if(await PKG.file(de).exists()){H=de;break}}if(!H){e.error("ty not found, please install ty first");return}return {process:n(H,["server"],{cwd:Z,stderr:"ignore"}),initialization:$}}},ie.Pyright={id:"pyright",initTimeout:ie.ServerInitTimeout.pyright,extensions:[".py",".pyi"],root:c(["pyproject.toml","setup.py","setup.cfg","requirements.txt","Pipfile","pyrightconfig.json"]),async spawn(Z){let H=await PKG.which("pyright-langserver"),$=[];if(!H){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 de=await PKG.which();if(!de)return;H=de,$.push("run",oe);}$.push("--stdio");let te={},W=[process.env.VIRTUAL_ENV,Ce__default.join(Z,".venv"),Ce__default.join(Z,"venv")].filter(oe=>oe!==void 0);for(let oe of W){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 H?{process:n(H,$,{cwd:Z,env:{...process.env},stderr:"ignore"}),initialization:te}:void 0}},ie.ElixirLS={id:"elixir-ls",initTimeout:ie.ServerInitTimeout.elixir_ls,extensions:[".ex",".exs"],root:c(["mix.exs","mix.lock"]),async spawn(Z){let H=await PKG.which("elixir-ls");if(!H){let $$1=Ce__default.join(a$1.Path.bin,"elixir-ls");if(H=Ce__default.join(a$1.Path.bin,"elixir-ls-master","release",process.platform==="win32"?"language_server.bat":"language_server.sh"),!await PKG.file(H).exists()){if(!await PKG.which("elixir")){e.error("elixir is required to run elixir-ls");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading elixir-ls from GitHub releases");let W=await fetch("https://github.com/elixir-lsp/elixir-ls/archive/refs/heads/master.zip");if(!W.ok)return;let V=Ce__default.join(a$1.Path.bin,"elixir-ls.zip");if(await PKG.write(V,W),!await Archive.extractZip(V,a$1.Path.bin).then(()=>true).catch(de=>(e.error("Failed to extract elixir-ls archive",{error:de}),false)))return;await Tt__default.rm(V,{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:$$1});}}if(H)return {process:n(H)}}},ie.Zls={id:"zls",initTimeout:ie.ServerInitTimeout.zls,extensions:[".zig",".zon"],root:c(["build.zig"]),async spawn(Z){let H=await PKG.which("zls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("zig")){e.error("Zig is required to use zls. Please install Zig first.");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading zls from GitHub releases");let te=await fetch("https://api.github.com/repos/zigtools/zls/releases/latest");if(!te.ok){e.error("Failed to fetch zls release info");return}let W=await te.json(),V=process.platform,oe=process.arch,de="",me=oe;oe==="arm64"?me="aarch64":oe==="x64"?me="x86_64":oe==="ia32"&&(me="x86");let ce=V;V==="darwin"?ce="macos":V==="win32"&&(ce="windows");let ye=V==="win32"?"zip":"tar.xz";if(de=`zls-${me}-${ce}.${ye}`,!["zls-x86_64-linux.tar.xz","zls-x86_64-macos.tar.xz","zls-x86_64-windows.zip","zls-aarch64-linux.tar.xz","zls-aarch64-macos.tar.xz","zls-aarch64-windows.zip","zls-x86-linux.tar.xz","zls-x86-windows.zip"].includes(de)){e.error(`Platform ${V} and architecture ${oe} is not supported by zls`);return}let Ie=W.assets.find(Ae=>Ae.name===de);if(!Ie){e.error(`Could not find asset ${de} in latest zls release`);return}let ke=Ie.browser_download_url,re=await fetch(ke);if(!re.ok){e.error("Failed to download zls");return}let $e=Ce__default.join(a$1.Path.bin,de);if(await PKG.write($e,re),ye==="zip"){if(!await Archive.extractZip($e,a$1.Path.bin).then(()=>true).catch(pt=>(e.error("Failed to extract zls archive",{error:pt}),false)))return}else await $`tar -xf ${$e}`.cwd(a$1.Path.bin).quiet().nothrow();if(await Tt__default.rm($e,{force:true}),H=Ce__default.join(a$1.Path.bin,"zls"+(V==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract zls binary");return}V!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed zls",{bin:H});}return {process:n(H,[],{cwd:Z,stderr:"ignore"})}}},ie.CSharp={id:"csharp",initTimeout:ie.ServerInitTimeout.csharp,root:c([".slnx",".sln",".csproj","global.json"]),extensions:[".cs"],async spawn(Z){let H=await PKG.which("csharp-ls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("dotnet")){e.error(".NET SDK is required to install csharp-ls");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing csharp-ls via dotnet tool");let te=await r(`dotnet tool install csharp-ls --tool-path "${a$1.Path.bin}"`);if(te.code!==0){e.error("Failed to install csharp-ls",{stderr:te.stderr});return}H=Ce__default.join(a$1.Path.bin,"csharp-ls"+(process.platform==="win32"?".exe":"")),e.info("installed csharp-ls",{bin:H});}return {process:n(H,[],{cwd:Z,stderr:"ignore"})}}},ie.FSharp={id:"fsharp",initTimeout:ie.ServerInitTimeout.fsharp,root:c([".slnx",".sln",".fsproj","global.json"]),extensions:[".fs",".fsi",".fsx",".fsscript"],async spawn(Z){let H=await PKG.which("fsautocomplete",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(!await PKG.which("dotnet")){e.error(".NET SDK is required to install fsautocomplete");return}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("installing fsautocomplete via dotnet tool");let te=await r(`dotnet tool install fsautocomplete --tool-path "${a$1.Path.bin}"`);if(te.code!==0){e.error("Failed to install fsautocomplete",{stderr:te.stderr});return}H=Ce__default.join(a$1.Path.bin,"fsautocomplete"+(process.platform==="win32"?".exe":"")),e.info("installed fsautocomplete",{bin:H});}if(H)return {process:n(H,[],{cwd:Z,stderr:"ignore"})}}},ie.SourceKit={id:"sourcekit-lsp",initTimeout:ie.ServerInitTimeout.sourcekit_lsp,extensions:[".swift",".objc","objcpp"],root:c(["Package.swift","*.xcodeproj","*.xcworkspace"]),async spawn(Z){let H=await PKG.which("sourcekit-lsp");if(H)return {process:n(H,[],{cwd:Z,stderr:"ignore"})};if(!await PKG.which("xcrun"))return;let te=await $`xcrun --find sourcekit-lsp`.quiet().nothrow();if(te.exitCode!==0)return;let W=await te.text();if(W)return {process:n(W.trim(),[],{cwd:Z,stderr:"ignore"})}}},ie.RustAnalyzer={id:"rust",initTimeout:ie.ServerInitTimeout.rust,root:async Z=>{let H=await c(["Cargo.toml","Cargo.lock"])(Z);if(H===void 0)return;let $=H;for(;$!==Ce__default.dirname($);){let te=Ce__default.join($,"Cargo.toml");try{if((await PKG.file(te).text()).includes("[workspace]"))return $}catch{}let W=Ce__default.dirname($);if(W===$||($=W,!$.startsWith(_.worktree)))break}return H},extensions:[".rs"],async spawn(Z){let H=await PKG.which("rust-analyzer");if(!H){e.info("rust-analyzer not found in path, please install it");return}return {process:s(H,[],{cwd:Z,stderr:"ignore"})}}},ie.Clangd={id:"clangd",initTimeout:ie.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(Z){let H=["--background-index","--clang-tidy"],$$1=await PKG.which("clangd");if($$1)return {process:s($$1,H,{cwd:Z,stderr:"ignore"})};let te=process.platform==="win32"?".exe":"",W=Ce__default.join(a$1.Path.bin,"clangd"+te);if(await PKG.file(W).exists())return {process:s(W,H,{cwd:Z,stderr:"ignore"})};let V=await Tt__default.readdir(a$1.Path.bin,{withFileTypes:true}).catch(()=>[]);for(let Wt of V){if(!Wt.isDirectory()||!Wt.name.startsWith("clangd_"))continue;let nr=Ce__default.join(a$1.Path.bin,Wt.name,"bin","clangd"+te);if(await PKG.file(nr).exists())return {process:s(nr,H,{cwd:Z,stderr:"ignore"})}}if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading clangd from GitHub releases");let oe=await fetch("https://api.github.com/repos/clangd/clangd/releases/latest");if(!oe.ok){e.error("Failed to fetch clangd release info");return}let de=await oe.json(),me=de.tag_name;if(!me){e.error("clangd release did not include a tag name");return}let ce=process.platform,je={darwin:"mac",linux:"linux",win32:"windows"}[ce];if(!je){e.error(`Platform ${ce} is not supported by clangd auto-download`);return}let Ie=de.assets??[],ke=Wt=>!Wt.name||!Wt.browser_download_url||!Wt.name.includes(je)?false:Wt.name.includes(me),re=Ie.find(Wt=>ke(Wt)&&Wt.name?.endsWith(".zip"))??Ie.find(Wt=>ke(Wt)&&Wt.name?.endsWith(".tar.xz"))??Ie.find(Wt=>ke(Wt));if(!re?.name||!re.browser_download_url){e.error("clangd could not match release asset",{tag:me,platform:ce});return}let $e=re.name,Ae=await fetch(re.browser_download_url);if(!Ae.ok){e.error("Failed to download clangd");return}let pt=Ce__default.join(a$1.Path.bin,$e),Ct=await Ae.arrayBuffer();if(Ct.byteLength===0){e.error("Failed to write clangd archive");return}await PKG.write(pt,Buffer.from(Ct));let dn=$e.endsWith(".zip"),li=$e.endsWith(".tar.xz");if(!dn&&!li){e.error("clangd encountered unsupported asset",{asset:$e});return}if(dn&&!await Archive.extractZip(pt,a$1.Path.bin).then(()=>true).catch(nr=>(e.error("Failed to extract clangd archive",{error:nr}),false)))return;li&&await $`tar -xf ${pt}`.cwd(a$1.Path.bin).quiet().nothrow(),await Tt__default.rm(pt,{force:true});let ws=Ce__default.join(a$1.Path.bin,"clangd_"+me,"bin","clangd"+te);if(!await PKG.file(ws).exists()){e.error("Failed to extract clangd binary");return}return ce!=="win32"&&await $`chmod +x ${ws}`.quiet().nothrow(),await Tt__default.unlink(Ce__default.join(a$1.Path.bin,"clangd")).catch(()=>{}),await Tt__default.symlink(ws,Ce__default.join(a$1.Path.bin,"clangd")).catch(()=>{}),e.info("installed clangd",{bin:ws}),{process:n(ws,H,{cwd:Z,stderr:"ignore"})}}},ie.Svelte={id:"svelte",initTimeout:ie.ServerInitTimeout.svelte,extensions:[".svelte"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Z){let H=await PKG.which("svelteserver"),$=[];if(!H){let W=Ce__default.join(a$1.Path.bin,"node_modules","svelte-language-server","bin","server.js");if(!await PKG.file(W).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 V=await PKG.which();if(!V)return;H=V,$.push("run",W);}return H?($.push("--stdio"),{process:n(H,$,{cwd:Z,env:{...process.env},stderr:"ignore"}),initialization:{}}):void 0}},ie.Astro={id:"astro",initTimeout:ie.ServerInitTimeout.astro,extensions:[".astro"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Z){let H=await PKG.resolve("typescript/lib/tsserver.js",_.directory).catch(()=>{});if(!H){e.info("typescript not found, required for Astro language server");return}let $=Ce__default.dirname(H),te=await PKG.which("astro-ls"),W=[];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 de=await PKG.which();if(!de)return;te=de,W.push("run",oe);}return te?(W.push("--stdio"),{process:n(te,W,{cwd:Z,env:{...process.env},stderr:"ignore"}),initialization:{typescript:{tsdk:$}}}):void 0}},ie.JDTLS={id:"jdtls",initTimeout:ie.ServerInitTimeout.jdtls,root:c(["pom.xml","build.gradle","build.gradle.kts",".project",".classpath"]),extensions:[".java"],async spawn(Z){let H=await PKG.which("java");if(!H){e.error("Java 21 or newer is required to run the JDTLS. Please install it first.");return}let $$1=await $`java -version`.quiet().nothrow(),te=(()=>{let ke=/"(\d+)\.\d+\.\d+"/.exec($$1.stderr?.toString()??"");return ke?.[1]?parseInt(ke[1],10):void 0})();if(te==null||te<21){e.error("JDTLS requires at least Java 21.");return}let W=Ce__default.join(a$1.Path.bin,"jdtls"),V=Ce__default.join(W,"plugins");if(!await i(V)){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading JDTLS LSP server."),await Tt__default.mkdir(W,{recursive:true});let ke="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:ke,dest:W});let $e=await $`curl -L -o ${re} '${ke}'`.cwd(W).quiet().nothrow();if($e.exitCode!==0){e.error("Failed to download JDTLS",{exitCode:$e.exitCode,stderr:$e.stderr.toString()});return}e.info("Extracting JDTLS archive");let Ae=await $`tar -xzf ${re}`.cwd(W).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(W,re),{force:true}),e.info("JDTLS download and extraction completed");}let me=(await $`ls org.eclipse.equinox.launcher_*.jar`.cwd(V).quiet().nothrow()).stdout?.toString().trim();if(!me){e.error(`Failed to find JDTLS launcher jar in ${V}.`);return}let ce=Ce__default.join(V,me);if(!await i(ce)){e.error(`Failed to locate the JDTLS launcher module in the installed directory: ${W}.`);return}let ye=Ce__default.join(W,(()=>{switch(process.platform){case "darwin":return "config_mac";case "linux":return "config_linux";case "win32":return "config_win";default:return "config_linux"}})()),je=await Tt__default.mkdtemp(Ce__default.join(sc.tmpdir(),"easbot-jdtls-data"));return {process:o([H,"-jar",ce,"-configuration",ye,"-data",je,"-Declipse.application=org.eclipse.jdt.ls.core.id1","-Dosgi.bundles.defaultStartLevel=4","-Declipse.product=org.eclipse.jdt.ls.core.product","-Dlog.level=ALL","--add-modules=ALL-SYSTEM","--add-opens=java.base/java.util=ALL-UNNAMED","--add-opens=java.base/java.lang=ALL-UNNAMED"],{cwd:Z})}}},ie.KotlinLS={id:"kotlin-ls",initTimeout:ie.ServerInitTimeout.kotlin_ls,extensions:[".kt",".kts"],root:async Z=>{let H=await c(["settings.gradle.kts","settings.gradle"])(Z);if(H)return H;let $=await c(["gradlew","gradlew.bat"])(Z);if($)return $;let te=await c(["build.gradle.kts","build.gradle"])(Z);return te||c(["pom.xml"])(Z)},async spawn(Z){let H=Ce__default.join(a$1.Path.bin,"kotlin-ls"),$$1=process.platform==="win32"?Ce__default.join(H,"kotlin-lsp.cmd"):Ce__default.join(H,"kotlin-lsp.sh");if(!await PKG.file($$1).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("Downloading Kotlin Language Server from GitHub.");let W=await fetch("https://api.github.com/repos/Kotlin/kotlin-lsp/releases/latest");if(!W.ok){e.error("Failed to fetch kotlin-lsp release info");return}let oe=(await W.json()).name?.replace(/^v/,"");if(!oe){e.error("Could not determine Kotlin LSP version from release");return}let de=process.platform,me=process.arch,ce=me;me==="arm64"?ce="aarch64":me==="x64"&&(ce="x64");let ye=de;de==="darwin"?ye="mac":de==="linux"?ye="linux":de==="win32"&&(ye="win");let je=["mac-x64","mac-aarch64","linux-x64","linux-aarch64","win-x64","win-aarch64"],Ie=`${ye}-${ce}`;if(!je.includes(Ie)){e.error(`Platform ${de}/${me} is not supported by Kotlin LSP`);return}let ke=`kotlin-lsp-${oe}-${ye}-${ce}.zip`,re=`https://download-cdn.jetbrains.com/kotlin-lsp/${oe}/${ke}`;await Tt__default.mkdir(H,{recursive:true});let $e=Ce__default.join(H,"kotlin-ls.zip");if(await $`curl -L -o '${$e}' '${re}'`.quiet().nothrow(),!await Archive.extractZip($e,H).then(()=>true).catch(pt=>(e.error("Failed to extract Kotlin LS archive",{error:pt}),false)))return;await Tt__default.rm($e,{force:true}),process.platform!=="win32"&&await $`chmod +x ${$$1}`.quiet().nothrow(),e.info("Installed Kotlin Language Server",{path:$$1});}if(!await PKG.file($$1).exists()){e.error(`Failed to locate the Kotlin LS launcher script in the installed directory: ${H}.`);return}return {process:n($$1,["--stdio"],{cwd:Z,stderr:"ignore"})}}},ie.YamlLS={id:"yaml-ls",initTimeout:ie.ServerInitTimeout.yaml,extensions:[".yaml",".yml"],root:c(["package-lock.json","bun.lockb","bun.lock","pnpm-lock.yaml","yarn.lock"]),async spawn(Z){let H=await PKG.which("yaml-language-server"),$=[];if(!H){let W=Ce__default.join(a$1.Path.bin,"node_modules","yaml-language-server","out","server","src","server.js");if(!await PKG.file(W).exists()){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;let de=await PKG.which();if(!de)return;await r(`${de} install yaml-language-server`,{cwd:a$1.Path.bin,env:{...process.env}});}let oe=await PKG.which();if(!oe)return;H=oe,$.push("run",W);}return H?($.push("--stdio"),{process:n(H,$,{cwd:Z,env:{...process.env},stderr:"ignore"})}):void 0}},ie.LuaLS={id:"lua-ls",initTimeout:ie.ServerInitTimeout.lua,root:c([".luarc.json",".luarc.jsonc",".luacheckrc",".stylua.toml","stylua.toml","selene.toml","selene.yml"]),extensions:[".lua"],async spawn(Z){let H=await PKG.which("lua-language-server",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading lua-language-server from GitHub releases");let $$1=await fetch("https://api.github.com/repos/LuaLS/lua-language-server/releases/latest");if(!$$1.ok){e.error("Failed to fetch lua-language-server release info");return}let te=await $$1.json(),W=process.platform,V=process.arch,oe="",de=V;V==="arm64"?de="arm64":V==="x64"?de="x64":V==="ia32"&&(de="ia32");let me=W;W==="darwin"?me="darwin":W==="linux"?me="linux":W==="win32"&&(me="win32");let ce=W==="win32"?"zip":"tar.gz";oe=`lua-language-server-${te.tag_name}-${me}-${de}.${ce}`;let ye=["darwin-arm64.tar.gz","darwin-x64.tar.gz","linux-x64.tar.gz","linux-arm64.tar.gz","win32-x64.zip","win32-ia32.zip"],je=`${me}-${de}.${ce}`;if(!ye.includes(je)){e.error(`Platform ${W} and architecture ${V} is not supported by lua-language-server`);return}let Ie=te.assets.find(Ct=>Ct.name===oe);if(!Ie){e.error(`Could not find asset ${oe} in latest lua-language-server release`);return}let ke=Ie.browser_download_url,re=await fetch(ke);if(!re.ok){e.error("Failed to download lua-language-server");return}let $e=Ce__default.join(a$1.Path.bin,oe);await PKG.write($e,re);let Ae=Ce__default.join(a$1.Path.bin,`lua-language-server-${de}-${me}`);if(await Tt__default.stat(Ae).catch(()=>{})&&await Tt__default.rm(Ae,{force:true,recursive:true}),await Tt__default.mkdir(Ae,{recursive:true}),ce==="zip"){if(!await Archive.extractZip($e,Ae).then(()=>true).catch(dn=>(e.error("Failed to extract lua-language-server archive",{error:dn}),false)))return}else if(!await $`tar -xzf ${$e} -C ${Ae}`.quiet().then(()=>true).catch(dn=>(e.error("Failed to extract lua-language-server archive",{error:dn}),false)))return;if(await Tt__default.rm($e,{force:true}),H=Ce__default.join(Ae,"bin","lua-language-server"+(W==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract lua-language-server binary");return}if(W!=="win32"&&!await $`chmod +x ${H}`.quiet().catch(dn=>{e.error("Failed to set executable permission for lua-language-server binary",{error:dn});}))return;e.info("installed lua-language-server",{bin:H});}return {process:n(H,[],{cwd:Z,stderr:"ignore"})}}},ie.PHPIntelephense={id:"php intelephense",initTimeout:ie.ServerInitTimeout.intelephense,extensions:[".php"],root:c(["composer.json","composer.lock",".php-version"]),async spawn(Z){let H=await PKG.which("intelephense"),$=[];if(!H){let W=Ce__default.join(a$1.Path.bin,"node_modules","intelephense","lib","intelephense.js");if(!await PKG.file(W).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 V=await PKG.which();if(!V)return;H=V,$.push("run",W);}return H?($.push("--stdio"),{process:n(H,$,{cwd:Z,env:{...process.env}}),initialization:{telemetry:{enabled:false}}}):void 0}},ie.Prisma={id:"prisma",initTimeout:ie.ServerInitTimeout.prisma,extensions:[".prisma"],root:c(["schema.prisma","prisma/schema.prisma","prisma"],["package.json"]),async spawn(Z){let H=await PKG.which("prisma");if(!H){e.info("prisma not found, please install prisma");return}return {process:n(H,["language-server"],{cwd:Z,stderr:"ignore"})}}},ie.Dart={id:"dart",initTimeout:ie.ServerInitTimeout.dart,extensions:[".dart"],root:c(["pubspec.yaml","analysis_options.yaml"]),async spawn(Z){let H=await PKG.which("dart");if(!H){e.info("dart not found, please install dart first");return}return {process:s(H,["language-server","--lsp"],{cwd:Z,stderr:"ignore"})}}},ie.Ocaml={id:"ocaml-lsp",initTimeout:ie.ServerInitTimeout.ocaml_lsp,extensions:[".ml",".mli"],root:c(["dune-project","dune-workspace",".merlin","opam"]),async spawn(Z){let H=await PKG.which("ocamllsp");if(!H){e.info("ocamllsp not found, please install ocaml-lsp-server");return}return {process:s(H,[],{cwd:Z,stderr:"ignore"})}}},ie.BashLS={id:"bash",initTimeout:ie.ServerInitTimeout.bash,extensions:[".sh",".bash",".zsh",".ksh"],root:async()=>_.directory,async spawn(Z){let H=await PKG.which("bash-language-server"),$=[];if(!H){let W=Ce__default.join(a$1.Path.bin,"node_modules","bash-language-server","out","cli.js");if(!await PKG.file(W).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 V=await PKG.which();if(!V)return;H=V,$.push("run",W);}return H?($.push("start"),{process:n(H,$,{cwd:Z,env:{...process.env}})}):void 0}},ie.TerraformLS={id:"terraform",initTimeout:ie.ServerInitTimeout.terraform,extensions:[".tf",".tfvars"],root:c([".terraform.lock.hcl","terraform.tfstate","*.tf"]),async spawn(Z){let H=await PKG.which("terraform-ls",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading terraform-ls from GitHub releases");let $$1=await fetch("https://api.github.com/repos/hashicorp/terraform-ls/releases/latest");if(!$$1.ok){e.error("Failed to fetch terraform-ls release info");return}let te=await $$1.json(),W=te.tag_name?.replace("v","");if(!W){e.error("terraform-ls release did not include a version tag");return}let V=process.platform,de=process.arch==="arm64"?"arm64":"amd64",ce=`terraform-ls_${W}_${V==="win32"?"windows":V}_${de}.zip`,je=(te.assets??[]).find($e=>$e.name===ce);if(!je?.browser_download_url){e.error(`Could not find asset ${ce} in terraform-ls release`);return}let Ie=await fetch(je.browser_download_url);if(!Ie.ok){e.error("Failed to download terraform-ls");return}let ke=Ce__default.join(a$1.Path.bin,ce);if(await PKG.write(ke,Ie),!await Archive.extractZip(ke,a$1.Path.bin).then(()=>true).catch($e=>(e.error("Failed to extract terraform-ls archive",{error:$e}),false)))return;if(await Tt__default.rm(ke,{force:true}),H=Ce__default.join(a$1.Path.bin,"terraform-ls"+(V==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract terraform-ls binary");return}V!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed terraform-ls",{bin:H});}return {process:s(H,["serve"],{cwd:Z,stderr:"ignore"}),initialization:{experimentalFeatures:{prefillRequiredFields:true,validateOnSave:true}}}}},ie.TexLab={id:"texlab",initTimeout:ie.ServerInitTimeout.texlab,extensions:[".tex",".bib"],root:c([".latexmkrc","latexmkrc",".texlabroot","texlabroot"]),async spawn(Z){let H=await PKG.which("texlab",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading texlab from GitHub releases");let $$1=await fetch("https://api.github.com/repos/latex-lsp/texlab/releases/latest");if(!$$1.ok){e.error("Failed to fetch texlab release info");return}let te=await $$1.json();if(!te.tag_name?.replace("v","")){e.error("texlab release did not include a version tag");return}let V=process.platform,de=process.arch==="arm64"?"aarch64":"x86_64",me=V==="darwin"?"macos":V==="win32"?"windows":"linux",ce=V==="win32"?"zip":"tar.gz",ye=`texlab-${de}-${me}.${ce}`,Ie=(te.assets??[]).find($e=>$e.name===ye);if(!Ie?.browser_download_url){e.error(`Could not find asset ${ye} in texlab release`);return}let ke=await fetch(Ie.browser_download_url);if(!ke.ok){e.error("Failed to download texlab");return}let re=Ce__default.join(a$1.Path.bin,ye);if(await PKG.write(re,ke),ce==="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(ce==="tar.gz"&&await $`tar -xzf ${re}`.cwd(a$1.Path.bin).quiet().nothrow(),await Tt__default.rm(re,{force:true}),H=Ce__default.join(a$1.Path.bin,"texlab"+(V==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract texlab binary");return}V!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed texlab",{bin:H});}return {process:s(H,[],{cwd:Z,stderr:"ignore"})}}},ie.DockerfileLS={id:"dockerfile",initTimeout:ie.ServerInitTimeout.dockerfile,extensions:[".dockerfile","Dockerfile"],root:async()=>_.directory,async spawn(Z){let H=await PKG.which("docker-langserver"),$=[];if(!H){let W=Ce__default.join(a$1.Path.bin,"node_modules","dockerfile-language-server-nodejs","lib","server.js");if(!await PKG.file(W).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 V=await PKG.which();if(!V)return;H=V,$.push("run",W);}return H?($.push("--stdio"),{process:n(H,$,{cwd:Z,env:{...process.env}})}):void 0}},ie.Gleam={id:"gleam",initTimeout:ie.ServerInitTimeout.gleam,extensions:[".gleam"],root:c(["gleam.toml"]),async spawn(Z){let H=await PKG.which("gleam");if(!H){e.info("gleam not found, please install gleam first");return}return {process:s(H,["lsp"],{cwd:Z,stderr:"ignore"})}}},ie.Clojure={id:"clojure-lsp",initTimeout:ie.ServerInitTimeout.clojure_lsp,extensions:[".clj",".cljs",".cljc",".edn"],root:c(["deps.edn","project.clj","shadow-cljs.edn","bb.edn","build.boot"]),async spawn(Z){let H=await PKG.which("clojure-lsp");if(!H&&process.platform==="win32"&&(H=await PKG.which("clojure-lsp.exe")),!H){e.info("clojure-lsp not found, please install clojure-lsp first");return}return {process:s(H,["listen"],{cwd:Z,stderr:"ignore"})}}},ie.Nixd={id:"nixd",initTimeout:ie.ServerInitTimeout.nixd,extensions:[".nix"],root:async Z=>{let H=await c(["flake.nix"])(Z);return H&&H!==_.directory?H:_.worktree&&_.worktree!==_.directory?_.worktree:_.directory},async spawn(Z){let H=await PKG.which("nixd");if(!H){e.info("nixd not found, please install nixd first");return}return {process:s(H,[],{cwd:Z,env:{...process.env},stderr:"ignore"})}}},ie.Tinymist={id:"tinymist",initTimeout:ie.ServerInitTimeout.tinymist,extensions:[".typ",".typc"],root:c(["typst.toml"]),async spawn(Z){let H=await PKG.which("tinymist",{PATH:process.env.PATH+Ce__default.delimiter+a$1.Path.bin});if(!H){if(a$2.EASBOT_DISABLE_LSP_DOWNLOAD)return;e.info("downloading tinymist from GitHub releases");let $$1=await fetch("https://api.github.com/repos/Myriad-Dreamin/tinymist/releases/latest");if(!$$1.ok){e.error("Failed to fetch tinymist release info");return}let te=await $$1.json(),W=process.platform,oe=process.arch==="arm64"?"aarch64":"x86_64",de,me;W==="darwin"?(de="apple-darwin",me="tar.gz"):W==="win32"?(de="pc-windows-msvc",me="zip"):(de="unknown-linux-gnu",me="tar.gz");let ce=`tinymist-${oe}-${de}.${me}`,je=(te.assets??[]).find(re=>re.name===ce);if(!je?.browser_download_url){e.error(`Could not find asset ${ce} in tinymist release`);return}let Ie=await fetch(je.browser_download_url);if(!Ie.ok){e.error("Failed to download tinymist");return}let ke=Ce__default.join(a$1.Path.bin,ce);if(await PKG.write(ke,Ie),me==="zip"){if(!await Archive.extractZip(ke,a$1.Path.bin).then(()=>true).catch($e=>(e.error("Failed to extract tinymist archive",{error:$e}),false)))return}else await $`tar -xzf ${ke} --strip-components=1`.cwd(a$1.Path.bin).quiet().nothrow();if(await Tt__default.rm(ke,{force:true}),H=Ce__default.join(a$1.Path.bin,"tinymist"+(W==="win32"?".exe":"")),!await PKG.file(H).exists()){e.error("Failed to extract tinymist binary");return}W!=="win32"&&await $`chmod +x ${H}`.quiet().nothrow(),e.info("installed tinymist",{bin:H});}return {process:s(H,[],{cwd:Z,stderr:"ignore"})}}},ie.HLS={id:"haskell-language-server",initTimeout:ie.ServerInitTimeout.haskell_language_server,extensions:[".hs",".lhs"],root:c(["stack.yaml","cabal.project","hie.yaml","*.cabal"]),async spawn(Z){let H=await PKG.which("haskell-language-server-wrapper");if(!H){e.info("haskell-language-server-wrapper not found, please install haskell-language-server");return}return {process:s(H,["--lsp"],{cwd:Z,stderr:"ignore"})}}};})(xo||(xo={}));var Np=(o=>(o.STDIO="stdio",o.HTTP="http",o.WS="websocket",o))(Np||{});function Ky(e){return e==="local"?"stdio":e}var Up=z.object({command:z.string(),args:z.array(z.string())}),zp=z.object({baseUrl:z.string().url(),timeout:z.number().positive().default(3e4)}).strict(),qp=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)}),Jy=z.object({stdio:Up.optional(),http:zp.optional(),ws:qp.optional()});function Yy(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 Xy=z.object({id:z.string().min(1),options:z.record(z.string(),z.unknown()).optional()}),Qy=z.object({agent:z.string().optional(),model:Xy.optional()}),Hp=z.object({directory:z.string().default(process.cwd()),enabled:z.boolean().default(true),channel:z.preprocess(Ky,z.enum(["stdio","http","websocket"])).default("websocket"),port:z.number().int().min(1).max(65535).default(3e3),hostname:z.string().min(1).default("localhost"),timeout:z.number().positive().default(3e4),name:z.string().optional(),agentId:z.string().optional(),stdio:Up.optional(),http:zp.optional(),ws:qp.optional(),agent:Qy.optional()}).refine(e=>!!Yy(e.hostname),{message:"Invalid hostname format",path:["hostname"]}).transform(e=>{let n={stdio:"stdio",http:"http",websocket:"websocket"}[e.channel]??"websocket";return {...e,channel:n}}),Zy=z.object({id:z.string().min(1),type:z.enum(["easbot","custom"]),name:z.string().optional(),agentId:z.string().optional(),channel:z.enum(["stdio","http","websocket"]).optional(),connection:Jy,autoConnect:z.boolean().default(false),priority:z.number().int().nonnegative().default(0)}).transform(e=>{let t=e.channel;t||(e.connection.ws?t="websocket":e.connection.http?t="http":e.connection.stdio?t="stdio":t="websocket");let o={stdio:"stdio",http:"http",websocket:"websocket"}[t]??"websocket";return {...e,channel:o}}),Bp=z.object({clients:z.array(Zy).min(1),defaultClientId:z.string().optional()});z.object({server:Hp});z.object({clients:Bp});var Bd=z.object({server:Hp,clients:Bp.optional()}),Gp={enabled:true,directory:process.cwd(),channel:"websocket",port:3e3,hostname:"localhost",timeout:3e4};var Gd=F.object({model:F.string().optional().describe("Embedding model, defaults to config embedding model"),batchSize:F.number().int().positive().optional().describe("Batch size for embedding operations"),dimensions:F.number().int().positive().optional().describe("Embedding dimensions (optional, auto-detect)")}).optional(),Wd=F.object({maxResults:F.number().int().positive().optional().describe("Max search results"),minScore:F.number().min(0).max(1).optional().describe("Min score threshold (default: 0.3)"),hybrid:F.object({enabled:F.boolean().optional().describe("Enable hybrid search"),vectorWeight:F.number().min(0).max(1).optional().describe("Vector search weight (default: 0.7)"),textWeight:F.number().min(0).max(1).optional().describe("FTS text search weight (default: 0.3)")}).optional().describe("Hybrid search configuration")}).optional().describe("Search configuration"),Wp=F.object({ignorePatterns:F.array(F.string()).optional().describe("File patterns to ignore"),batchSize:F.number().int().positive().optional().describe("Batch size for indexing"),incremental:F.boolean().optional().describe("Enable incremental indexing")}).optional(),Vp=F.object({onBoot:F.boolean().optional().describe("Sync on boot"),onSearch:F.boolean().optional().describe("Sync on search"),onSessionStart:F.boolean().optional().describe("Sync on session start"),intervalMs:F.number().int().positive().optional().describe("Sync interval in milliseconds")}).optional().describe("Sync configuration"),Vd=F.object({dictPath:F.array(F.string()).optional().describe("Custom dictionary paths")}).optional().describe("Tokenizer configuration"),eb=F.object({model:F.string().optional().describe("Rerank model, defaults to config rerank_model"),topK:F.number().int().positive().optional().describe("Number of candidates for reranking")}).optional().describe("Rerank configuration"),Kp=F.object({model:F.string().optional().describe("Graph LLM model, defaults to config graph_model"),entityExtractionPrompt:F.string().optional().describe("Entity extraction prompt template"),relationExtractionPrompt:F.string().optional().describe("Relation extraction prompt template")}).optional().describe("Graph LLM configuration for entity and relation extraction"),Ra=F.object({enabled:F.boolean().optional().describe("Enable codebase knowledge base"),database:F.string().optional().describe("Codebase database path"),embedding:Gd,search:Wd,indexer:Wp,tokenizer:Vd,sync:Vp,parser:F.object({languages:F.array(F.string()).optional().describe("Supported languages"),lazyLoad:F.boolean().optional().describe("Lazy load parsers")}).optional().describe("Code parser configuration")}).optional().describe("Codebase knowledge base configuration"),_a=F.object({enabled:F.boolean().optional().describe("Enable memory knowledge base"),workspaceDir:F.string().optional().describe("Memory workspace directory (contains MEMORY.md, active/, archive/)"),sessionsDir:F.string().optional().describe("Sessions directory for extracting historical long-term memory"),database:F.string().optional().describe("Memory database path"),embedding:Gd,graph:Kp,search:Wd,tokenizer:Vd,archiveDays:F.number().int().positive().optional().describe("Days before archiving memories (default: 30)"),shortTermMaxRounds:F.number().int().positive().optional().describe("Max rounds for short-term memory (default: 20)")}).optional().describe("Memory knowledge base configuration"),Ma=F.object({enabled:F.boolean().optional().describe("Enable note knowledge base"),database:F.string().optional().describe("Note database path"),search:Wd,indexer:Wp,tokenizer:Vd,sync:Vp,embedding:Gd,graph:Kp,rerank:eb,extraPaths:F.array(F.string()).optional().describe("Extra search paths (extended directories)"),sources:F.array(F.enum(["docs"])).optional().describe("Source types"),chunkSize:F.number().int().positive().optional().describe("Chunk size"),chunkOverlap:F.number().int().min(0).optional().describe("Chunk overlap size")}).optional().describe("Note knowledge base configuration"),kn=a.create({service:"knowledge-loader"});async function rr(){try{let t=(await he.get())?.note;if(!t){kn.debug("No note config found in Config.Info");return}let n=Ma.safeParse(t);if(n.success)return kn.debug("Note config loaded"),n.data;kn.warn("Invalid note config",{issues:n.error.issues});return}catch(e){kn.error("Failed to load note config",{error:e});return}}async function ir(){try{let t=(await he.get())?.codebase;if(!t){kn.debug("No codebase config found in Config.Info");return}let n=Ra.safeParse(t);if(n.success)return kn.debug("Codebase config loaded"),n.data;kn.warn("Invalid codebase config",{issues:n.error.issues});return}catch(e){kn.error("Failed to load codebase config",{error:e});return}}async function ar(){try{let e=await he.get();kn.debug("loadMemory() configState.memory",{memoryConfig:e?.memory});let t=e?.memory;if(!t){kn.debug("No memory config found in Config.Info");return}let n=_a.safeParse(t);if(n.success)return kn.debug("Memory config loaded",{data:n.data}),n.data;kn.warn("Invalid memory config",{issues:n.error.issues});return}catch(e){kn.error("Failed to load memory config",{error:e});return}}async function Kd(){let e={},[t,n,o]=await Promise.all([rr(),ir(),ar()]);return t&&(e.note=t),n&&(e.codebase=n),o&&(e.memory=o),kn.debug("Knowledge configs loaded",{types:Object.keys(e),count:Object.keys(e).length}),e}var Jp="easbot-oauth-dummy-key",Qe;(d=>{d.Oauth=F.object({type:F.literal("oauth"),refresh:F.string(),access:F.string(),expires:F.number(),accountId:F.string().optional(),enterpriseUrl:F.string().optional()}).meta({ref:"OAuth"}),d.Api=F.object({type:F.literal("api"),key:F.string()}).meta({ref:"ApiAuth"}),d.WellKnown=F.object({type:F.literal("wellknown"),key:F.string(),token:F.string()}).meta({ref:"WellKnownAuth"}),d.Info=F.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 g=d.Info.safeParse(u);return g.success&&(a[p]=g.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 oo(e,t){let n=mergeDeep(e,t);return e.plugin&&t.plugin&&(n.plugin=Array.from(new Set([...e.plugin,...t.plugin]))),e.instructions&&t.instructions&&(n.instructions=Array.from(new Set([...e.instructions,...t.instructions]))),n}var Yd=a.create({service:"config"});async function ub(e){try{return await Tt__default.access(e,constants.W_OK),!0}catch{return false}}async function ui(e){if(!await ub(e))return Yd.debug("config dir is not writable, skipping dependency install",{dir:e}),false;let n=Ce__default.join(e,"node_modules");if(!existsSync(n))return true;let o=Ce__default.join(e,"package.json"),s=PKG.file(o);if(!await s.exists())return true;let l=((await s.json().catch(()=>null))?.dependencies??{})["@easbot/plugin"];if(!l)return true;let d=b$3.isLocal()?"latest":b$3.getVersion();return d==="latest"?await PackageRegistry.isOutdated("@easbot/plugin",l,e)?(Yd.info("Cached version is outdated, proceeding with install",{pkg:"@easbot/plugin",cachedVersion:l}),true):false:l!==d}async function pi(e){let t=Ce__default.join(e,"package.json"),n=b$3.isLocal()?"*":b$3.getVersion(),o=await PKG.file(t).json().catch(()=>({}));o.dependencies={...o.dependencies,"@easbot/plugin":n},await PKG.write(t,JSON.stringify(o,null,2)),await new Promise(d=>setTimeout(d,3e3));let s=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){Yd.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 Qd=a.create({service:"config"}),_o=NamedError.create("ConfigJsonError",F.object({path:F.string(),message:F.string().optional()})),so=NamedError.create("ConfigInvalidError",F.object({path:F.string(),issues:F.custom().optional(),message:F.string().optional()}));async function ro(e){Qd.info("loading",{path:e});let t=await PKG.file(e).text().catch(n=>{if(n.code!=="ENOENT")throw new _o({path:e},{cause:n})});return t?dr(t,e):{}}async function dr(e,t){let n=e;e=e.replace(/\{env:([^}]+)\}/g,(c,l)=>process.env[l]||"");let o=e.match(/\{file:[^}]+\}/g);if(o){let c=Ce__default.dirname(t),l=e.split(`
3
+ `);for(let d of o){let m=l.findIndex(g=>g.includes(d)),f=l[m];if(m!==-1&&f?.trim().startsWith("//"))continue;let a=d.replace(/^\{file:/,"").replace(/\}$/,"");a.startsWith("~/")&&(a=Ce__default.join(sc.homedir(),a.slice(2)));let p=Ce__default.isAbsolute(a)?a:Ce__default.resolve(c,a),u=(await PKG.file(p).text().catch(g=>{let h=`bad file reference: "${d}"`;throw g.code==="ENOENT"?new so({path:t,message:h+` ${p} does not exist`},{cause:g}):new so({path:t,message:h},{cause:g})})).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 _o({path:t,message:`
9
+ --- JSONC Input ---
10
+ ${e}
11
+ --- Errors ---
12
+ ${l}
13
+ --- End ---`})}let i=ur.safeParse(r);if(i.success){if(!i.data.$schema){i.data.$schema="https://easbot.cn/config.json";let l=n.replace(/^\s*\{/,`{
14
+ "$schema": "https://easbot.cn/config.json",`);await PKG.write(t,l).catch(()=>{});}let c=i.data;if(c.plugin)for(let l=0;l<c.plugin.length;l++){let d=c.plugin[l];if(d)try{c.plugin[l]=import.meta.resolve(d,t);}catch{}}return c}throw Qd.error("Configuration validation failed",{path:t,issues:i.error.issues}),new so({path:t,issues:i.error.issues})}function lr(e,t){let n=[],o=parse$1(e,n,{allowTrailingComma:true});if(n.length>0){let r=e.split(`
15
+ `),i=n.map(c=>{let l=e.substring(0,c.offset).split(`
16
+ `),d=l.length,m=l[l.length-1]?.length??1,f=r[d-1],a=`${printParseErrorCode(c.error)} at line ${d}, column ${m}`;return f?`${a}
17
+ Line ${d}: ${f}
18
+ ${"".padStart(m+9)}^`:a}).join(`
19
+ `);throw new _o({path:t,message:`
20
+ --- JSONC Input ---
21
+ ${e}
22
+ --- Errors ---
23
+ ${i}
24
+ --- End ---`})}let s=ur.safeParse(o);if(s.success)return s.data;throw Qd.error("Configuration validation failed",{path:t,issues:s.error.issues}),new so({path:t,issues:s.error.issues})}var yb=a.create({service:"config"});function bb(e,t){for(let n of t){let o=e.indexOf(n);if(o!==-1)return e.slice(o+n.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("{agent,agents}/**/*.md");async function mi(e){let{Agent:t}=await import('./types-2GDQRKMX.mjs'),n={};for await(let o of xb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e})){let s=await a$9.parse(o).catch(async m=>{let f=a$9.FrontmatterError.isInstance(m)?m.data.message:`Failed to parse agent ${o}`,{Session:a}=await import('./session-FQ5O5XZY.mjs');await pe.publish(a.Event.Error,{error:new NamedError.Unknown({message:f}).toObject()}),yb.error("failed to load agent",{agent:o,err:m});});if(!s)continue;let i=bb(o,["/.easbot/agent/","/.easbot/agents/","/agent/","/agents/"])??Ce__default.basename(o),l={name:wb(i),...s.data,prompt:s.content.trim()},d=t.safeParse(l);if(d.success){n[l.name]=d.data;continue}throw new so({path:o,issues:d.error.issues},{cause:d.error})}return n}var Cb=a.create({service:"config"});function kb(e,t){for(let n of t){let o=e.indexOf(n);if(o!==-1)return e.slice(o+n.length)}}function Pb(e){let t=Ce__default.extname(e);return t.length>0?e.slice(0,-t.length):e}var Tb=new PKG.Glob("{command,commands}/**/*.md");async function fi(e){let{Command:t}=await import('./types-2GDQRKMX.mjs'),n={};for await(let o of Tb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e})){let s=await a$9.parse(o).catch(async m=>{let f=a$9.FrontmatterError.isInstance(m)?m.data.message:`Failed to parse command ${o}`,{Session:a}=await import('./session-FQ5O5XZY.mjs');await pe.publish(a.Event.Error,{error:new NamedError.Unknown({message:f}).toObject()}),Cb.error("failed to load command",{command:o,err:m});});if(!s)continue;let i=kb(o,["/.easbot/command/","/.easbot/commands/","/command/","/commands/"])??Ce__default.basename(o),l={name:Pb(i),...s.data,template:s.content.trim()},d=t.safeParse(l);if(d.success){n[l.name]=d.data;continue}throw new so({path:o,issues:d.error.issues},{cause:d.error})}return n}var Mb=new PKG.Glob("{plugin,plugins}/*.{ts,js}");async function gi(e){let t=[];for await(let n of Mb.scan({absolute:true,followSymlinks:true,dot:true,cwd:e}))t.push(pathToFileURL(n).href);return t}function La(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 hi(e){let t=new Set,n=[];for(let o of e.toReversed()){let s=La(o);t.has(s)||(t.add(s),n.push(o));}return n.toReversed()}var pr=a.create({service:"config"}),tm=process.env.EASBOT_TEST_MANAGED_CONFIG_DIR||Ub();function Ub(){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 el;function zb(){return el||(el=_.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,pr.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=oo(t,await dr(JSON.stringify(l),`${s}/.well-known/easbot`)),pr.debug("loaded remote config from well-known",{url:s});}if(t=oo(t,await wi()),!a$2.EASBOT_DISABLE_PROJECT_CONFIG)for(let s of ["easbot.json"]){let r=await Filesystem.findUp(s,_.directory,_.worktree);for(let i of r.toReversed())t=oo(t,await ro(i));}a$2.EASBOT_CONFIG&&(t=oo(t,await ro(a$2.EASBOT_CONFIG)),pr.debug("loaded custom config",{path:a$2.EASBOT_CONFIG})),t.agent=t.agent||{},t.plugin=t.plugin||[];let n=[a$1.Path.config,...a$2.EASBOT_DISABLE_PROJECT_CONFIG?[]:await Array.fromAsync(Filesystem.up({targets:[".easbot"],start:_.directory,stop:_.worktree})),...await Array.fromAsync(Filesystem.up({targets:[".easbot"],start:a$1.Path.home,stop:a$1.Path.home}))];a$2.EASBOT_CONFIG_DIR&&(n.push(a$2.EASBOT_CONFIG_DIR),pr.debug("loading config from EASBOT_CONFIG_DIR",{path:a$2.EASBOT_CONFIG_DIR}));let o=[];for(let s of unique(n)){if(s.endsWith(".easbot")||s===a$2.EASBOT_CONFIG_DIR)for(let r of ["easbot.json"])pr.debug(`loading config from ${Ce__default.join(s,r)}`),t=oo(t,await ro(Ce__default.join(s,r))),t.agent??(t.agent={}),t.plugin??(t.plugin=[]);o.push(iife(async()=>{await ui(s)&&await pi(s);})),t.command=mergeDeep(t.command??{},await fi(s)),t.agent=mergeDeep(t.agent,await mi(s)),t.plugin.push(...await gi(s));}if(a$2.EASBOT_CONFIG_CONTENT&&(t=oo(t,JSON.parse(a$2.EASBOT_CONFIG_CONTENT)),pr.debug("loaded custom config from EASBOT_CONFIG_CONTENT")),existsSync(tm))for(let s of ["easbot.json"])t=oo(t,await ro(Ce__default.join(tm,s)));if(a$2.EASBOT_PERMISSION&&(t.permission=mergeDeep(t.permission??{},JSON.parse(a$2.EASBOT_PERMISSION))),t.tools){await import('./types-2GDQRKMX.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=sc.userInfo().username),t.autoshare===true&&!t.share&&(t.share="auto"),!t.keybinds){let{Info:s}=await import('./types-2GDQRKMX.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=hi(t.plugin??[]),{config:t,directories:n,deps:o}})),el}function mr(){return zb()()}async function tl(){let e=await mr().then(t=>t.deps);await Promise.all(e);}async function Mo(){return mr().then(e=>e.config)}async function nl(){return mr().then(e=>e.directories)}var wi=lazy(async()=>{let e={},{pipe:t}=await import('remeda');return e=t({},mergeDeep(await ro(Ce__default.join(a$1.Path.config,"easbot.json")))),e});async function ol(){return wi()}var Hb=F.object({enabled:F.boolean().optional(),timeThresholdMs:F.number().int().nonnegative().optional(),keepRecentTools:F.number().int().positive().optional(),tokenThreshold:F.number().int().nonnegative().optional(),protectedTools:F.array(F.string()).optional()}),Bb=F.object({enabled:F.boolean().optional(),ttlMs:F.number().int().positive().optional(),maxSizeBytes:F.number().int().positive().optional(),maxEntries:F.number().int().positive().optional(),persist:F.boolean().optional()}),sl=F.object({auto:F.boolean().optional(),prune:Hb.optional(),reserved:F.number().int().min(0).optional(),backup:Bb.optional()}),om=a.create({service:"compaction-loader"}),sm={enabled:true,timeThresholdMs:3e5,keepRecentTools:3,tokenThreshold:5e3,protectedTools:["skill"]},rm={enabled:true,ttlMs:3e5,maxSizeBytes:25*1024*1024,maxEntries:100,persist:false},im={auto:true};async function xi(){try{let t=(await Mo())?.compaction??{},n={prune:mergeDeep(sm,t.prune??{}),backup:mergeDeep(rm,t.backup??{}),auto:t.auto??im.auto,reserved:t.reserved};return om.debug("compaction config loaded",{auto:n.auto,pruneEnabled:n?.prune?.enabled,backupEnabled:n?.backup?.enabled}),n}catch(e){return om.warn("failed to load compaction config, using defaults",{error:String(e)}),{prune:sm,backup:rm,auto:im.auto}}}async function rl(){return xi()}async function Gb(){return (await rl()).auto!==false}async function Wb(){return (await rl())?.prune?.enabled!==false}async function Vb(){return (await rl())?.backup?.enabled!==false}var Yb=F.enum(e),Xb=F.enum(h),Qb=F.enum(["read","write"]),Zb=F.object({name:F.string(),description:F.string().optional(),type:F.enum(["system","extension"]).default("extension"),scope:Xb.default("all"),priority:F.number().int().default(1e3),owner:F.array(F.string()).optional(),share:F.array(F.string()).optional(),permission:Qb.default("read"),dynamic:F.boolean().optional()}),ew=F.record(F.string(),F.array(F.string())),tw=F.object({maxEntries:F.number().int().positive().optional(),maxBytes:F.number().int().positive().optional(),timestampCheck:F.boolean().optional()}),nw=F.object({charsPerToken:F.number().positive().optional()}),il=F.object({mode:Yb.optional(),fileCache:tw.optional(),tokenEstimation:nw.optional(),maxTokens:F.number().int().nonnegative().optional(),searchMaxResults:F.number().int().positive().optional(),files:F.record(F.string(),Zb).optional(),contextFiles:ew.optional()}),am=a.create({service:"context-loader"}),ow={maxEntries:100,maxBytes:25*1024*1024,timestampCheck:true},sw={charsPerToken:4},cm={mode:"general",maxTokens:2e3,searchMaxResults:3};function rw(){return ow}function iw(){return sw}async function Ii(){try{let t=(await Mo()).context??{},n=mergeDeep(cm,t);return am.debug("loaded context config",{context:n}),n}catch(e){return am.warn("failed to load context config from config, using defaults",{error:String(e)}),cm}}var dm=a.create({service:"subagent-loader"}),Da=F.enum(["ephemeral","persistent"]).meta({ref:"SubAgentRunMode"}),al=F.enum(["stdio","http","websocket","cli"]).meta({ref:"SubAgentTransportType"}),cl=F.object({modelId:F.string().describe("Model ID"),providerId:F.string().describe("Provider ID")}).strict().meta({ref:"SubAgentModel"}),dl=F.object({name:F.string().describe("Unique name for this agent"),role:F.string().describe("Agent role type (e.g., researcher, planner, coder, executor)"),transport:al.describe("Transport type for communication"),runMode:Da.describe("Run mode: ephemeral or persistent"),uri:F.string().optional().describe("Connection URI for HTTP/WebSocket transport"),command:F.string().optional().describe("Command to execute for StdIO/CLI transport"),args:F.string().array().optional().describe("Command line arguments"),env:F.record(F.string(),F.string()).optional().describe("Environment variables to pass to subprocess"),timeout:F.number().int().positive().optional().describe("Timeout in milliseconds"),maxConcurrent:F.number().int().positive().optional().describe("Maximum concurrent instances"),cwd:F.string().optional().describe("Working directory for subprocess"),mcpServers:F.string().array().optional().describe("MCP server list to pass to subprocess"),agentConfig:F.object({model:cl.optional().describe("Model configuration"),system:F.string().optional().describe("System prompt"),tools:F.record(F.string(),F.boolean()).optional().describe("Tools to enable")}).strict().optional().describe("Agent-specific configuration")}).strict().meta({ref:"SubAgentConfig"}),$a=F.object({enabled:F.boolean().optional().default(true).describe("Enable SubAgent system"),defaultRunMode:Da.optional().default("ephemeral").describe("Default run mode"),timeout:F.number().int().positive().optional().default(12e4).describe("Global timeout in milliseconds"),maxConcurrent:F.number().int().positive().optional().default(5).describe("Maximum concurrent agents"),idleTimeout:F.number().int().positive().optional().default(1800*1e3).describe("Idle timeout in milliseconds"),idleCheckInterval:F.number().int().positive().optional().default(300*1e3).describe("Idle cleanup check interval in milliseconds"),agents:F.array(dl).optional().default([]).describe("List of SubAgent configurations")}).strict().meta({ref:"SubAgentConfigSchema"}),lm={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 fr(){try{let t=(await Mo())?.subagent??{},{agents:n,...o}=lm;t.agents=n.concat(t?.agents??[]);let s=mergeDeep(o,t);return dm.debug("subagent config loaded",{enabled:s.enabled,agentCount:s.agents.length}),s}catch(e){return dm.warn("failed to load subagent config, using defaults",{error:String(e)}),lm}}async function dw(){return fr()}var vs=F.string().meta({$ref:"https://models.dev/model-schema.json#/$defs/Model"}),Fa=F.object({type:F.literal("local").describe("Type of MCP server connection"),command:F.string().describe("Command to run the MCP server"),args:F.string().array().optional().describe("Arguments to pass to the command"),env:F.record(F.string(),F.string()).optional().describe("Environment variables to set when running the MCP server"),enabled:F.boolean().optional().describe("Enable or disable the MCP server on startup"),timeout:F.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),description:F.string().optional().describe("Description of the MCP server"),scope:F.enum(h).optional().default(g.All).describe("Context mode scope for the MCP server: all/general/coder. Defaults to all.")}).strict().meta({ref:"McpLocalConfig"}),Na=F.object({clientId:F.string().optional().describe("OAuth client ID. If not provided, dynamic client registration (RFC 7591) will be attempted."),clientSecret:F.string().optional().describe("OAuth client secret (if required by the authorization server)"),scope:F.string().optional().describe("OAuth scopes to request during authorization")}).strict().meta({ref:"McpOAuthConfig"}),Ua=F.object({type:F.literal("remote").describe("Type of MCP server connection"),url:F.string().describe("URL of the remote MCP server"),enabled:F.boolean().optional().describe("Enable or disable the MCP server on startup"),headers:F.record(F.string(),F.string()).optional().describe("Headers to send with the request"),oauth:F.union([Na,F.literal(false)]).optional().describe("OAuth authentication configuration for the MCP server. Set to false to disable OAuth auto-detection."),timeout:F.number().int().positive().optional().describe("Timeout in ms for MCP server requests. Defaults to 5000 (5 seconds) if not specified."),description:F.string().optional().describe("Description of the MCP server"),scope:F.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"}),za=F.discriminatedUnion("type",[Fa,Ua]),Jn=F.enum(["ask","allow","deny"]).meta({ref:"PermissionActionConfig"}),qa=F.record(F.string(),Jn).meta({ref:"PermissionObjectConfig"}),ht=F.union([Jn,qa]).meta({ref:"PermissionRuleConfig"}),uw=e=>typeof e=="object"&&e!==null&&!Array.isArray(e)?{__originalKeys:Object.keys(e),...e}:e,pw=e=>{if(typeof e=="string")return {"*":e};let t=e,{__originalKeys:n,...o}=t;if(!n)return o;let s={};for(let r of n)r in o&&(s[r]=o[r]);return s},vi=F.preprocess(uw,F.object({__originalKeys:F.string().array().optional(),read:ht.optional(),edit:ht.optional(),glob:ht.optional(),grep:ht.optional(),list:ht.optional(),bash:ht.optional(),task:ht.optional(),external_directory:ht.optional(),todo:Jn.optional(),question:Jn.optional(),webfetch:Jn.optional(),websearch:Jn.optional(),codesearch:Jn.optional(),lsp:ht.optional(),doom_loop:Jn.optional(),skill:ht.optional(),pty_session:ht.optional(),pty_manage:ht.optional(),write:ht.optional(),multiedit:ht.optional(),note:ht.optional(),memory:ht.optional(),codebase:ht.optional(),agent_client:ht.optional(),gateway:ht.optional(),apply_patch:ht.optional(),batch:ht.optional(),plan:ht.optional()}).catchall(ht).or(Jn)).transform(pw).meta({ref:"PermissionConfig"}),Ha=F.object({template:F.string(),description:F.string().optional(),agent:F.string().optional(),model:vs.optional(),subtask:F.boolean().optional(),scope:F.enum(h).optional().describe("Context mode scope")}),Ba=F.object({paths:F.array(F.string()).optional().describe("Additional paths to skill folders"),urls:F.array(F.string()).optional().describe("URLs to fetch skills from (e.g., https://example.com/.well-known/skills/)")}),io=F.object({model:vs.optional(),variant:F.string().optional().describe("Default model variant for this agent (applies only when using the agent's configured model)."),temperature:F.number().optional(),top_p:F.number().optional(),prompt:F.string().optional(),tools:F.record(F.string(),F.boolean()).optional().describe("@deprecated Use 'permission' field instead"),disable:F.boolean().optional(),description:F.string().optional().describe("Description of when to use the agent"),mode:F.enum(["subagent","primary","all"]).optional(),hidden:F.boolean().optional().describe("Hide this subagent from the @ autocomplete menu (default: false, only applies to mode: subagent)"),options:F.record(F.string(),F.any()).optional(),color:F.union([F.string().regex(/^#[0-9a-fA-F]{6}$/,"Invalid hex color format"),F.enum(["primary","secondary","accent","success","warning","error","info"])]).optional().describe("Hex color code (e.g., #FF5733) or theme color (e.g., primary)"),steps:F.number().int().positive().optional().describe("Maximum number of agentic iterations before forcing text-only response"),maxSteps:F.number().int().positive().optional().describe("@deprecated Use 'steps' field instead."),permission:vi.optional()}).catchall(F.any()).transform((e,t)=>{let n=new Set(["name","model","variant","prompt","description","temperature","top_p","mode","hidden","color","steps","maxSteps","options","permission","disable","tools"]),o={...e.options};for(let[i,c]of Object.entries(e))n.has(i)||(o[i]=c);let s={};for(let[i,c]of Object.entries(e.tools??{})){let l=c?"allow":"deny";i==="write"||i==="edit"||i==="patch"||i==="multiedit"?s.edit=l:s[i]=l;}Object.assign(s,e.permission);let r=e.steps??e.maxSteps;return {...e,options:o,permission:s,steps:r}}).meta({ref:"AgentConfig"}),Ga=F.object({leader:F.string().optional().default("ctrl+x").describe("Leader key for keybind combinations"),app_exit:F.string().optional().default("ctrl+c,ctrl+d,<leader>q").describe("Exit the application"),editor_open:F.string().optional().default("<leader>e").describe("Open external editor"),theme_list:F.string().optional().default("<leader>t").describe("List available themes"),sidebar_toggle:F.string().optional().default("<leader>b").describe("Toggle sidebar"),scrollbar_toggle:F.string().optional().default("none").describe("Toggle session scrollbar"),username_toggle:F.string().optional().default("none").describe("Toggle username visibility"),status_view:F.string().optional().default("<leader>s").describe("View status"),session_export:F.string().optional().default("<leader>x").describe("Export session to editor"),session_new:F.string().optional().default("<leader>n").describe("Create a new session"),session_list:F.string().optional().default("<leader>l").describe("List all sessions"),session_timeline:F.string().optional().default("<leader>g").describe("Show session timeline"),session_fork:F.string().optional().default("none").describe("Fork session from message"),session_rename:F.string().optional().default("ctrl+r").describe("Rename session"),session_delete:F.string().optional().default("ctrl+d").describe("Delete session"),stash_delete:F.string().optional().default("ctrl+d").describe("Delete stash entry"),model_provider_list:F.string().optional().default("ctrl+a").describe("Open provider list from model dialog"),model_favorite_toggle:F.string().optional().default("ctrl+f").describe("Toggle model favorite status"),session_share:F.string().optional().default("none").describe("Share current session"),session_unshare:F.string().optional().default("none").describe("Unshare current session"),session_interrupt:F.string().optional().default("escape").describe("Interrupt current session"),session_compact:F.string().optional().default("<leader>c").describe("Compact the session"),messages_page_up:F.string().optional().default("pageup,ctrl+alt+b").describe("Scroll messages up by one page"),messages_page_down:F.string().optional().default("pagedown,ctrl+alt+f").describe("Scroll messages down by one page"),messages_line_up:F.string().optional().default("ctrl+alt+y").describe("Scroll messages up by one line"),messages_line_down:F.string().optional().default("ctrl+alt+e").describe("Scroll messages down by one line"),messages_half_page_up:F.string().optional().default("ctrl+alt+u").describe("Scroll messages up by half page"),messages_half_page_down:F.string().optional().default("ctrl+alt+d").describe("Scroll messages down by half page"),messages_first:F.string().optional().default("ctrl+g,home").describe("Navigate to first message"),messages_last:F.string().optional().default("ctrl+alt+g,end").describe("Navigate to last message"),messages_next:F.string().optional().default("none").describe("Navigate to next message"),messages_previous:F.string().optional().default("none").describe("Navigate to previous message"),messages_last_user:F.string().optional().default("none").describe("Navigate to last user message"),messages_copy:F.string().optional().default("<leader>y").describe("Copy message"),messages_undo:F.string().optional().default("<leader>u").describe("Undo message"),messages_redo:F.string().optional().default("<leader>r").describe("Redo message"),messages_toggle_conceal:F.string().optional().default("<leader>h").describe("Toggle code block concealment in messages"),tool_details:F.string().optional().default("none").describe("Toggle tool details visibility"),model_list:F.string().optional().default("<leader>m").describe("List available models"),model_cycle_recent:F.string().optional().default("f2").describe("Next recently used model"),model_cycle_recent_reverse:F.string().optional().default("shift+f2").describe("Previous recently used model"),model_cycle_favorite:F.string().optional().default("none").describe("Next favorite model"),model_cycle_favorite_reverse:F.string().optional().default("none").describe("Previous favorite model"),command_list:F.string().optional().default("ctrl+p").describe("List available commands"),agent_list:F.string().optional().default("<leader>a").describe("List agents"),agent_cycle:F.string().optional().default("tab").describe("Next agent"),agent_cycle_reverse:F.string().optional().default("shift+tab").describe("Previous agent"),variant_cycle:F.string().optional().default("ctrl+t").describe("Cycle model variants"),input_clear:F.string().optional().default("ctrl+c").describe("Clear input field"),input_paste:F.string().optional().default("ctrl+v").describe("Paste from clipboard"),input_submit:F.string().optional().default("return").describe("Submit input"),input_newline:F.string().optional().default("shift+return,ctrl+return,alt+return,ctrl+j").describe("Insert newline in input"),input_move_left:F.string().optional().default("left,ctrl+b").describe("Move cursor left in input"),input_move_right:F.string().optional().default("right,ctrl+f").describe("Move cursor right in input"),input_move_up:F.string().optional().default("up").describe("Move cursor up in input"),input_move_down:F.string().optional().default("down").describe("Move cursor down in input"),input_select_left:F.string().optional().default("shift+left").describe("Select left in input"),input_select_right:F.string().optional().default("shift+right").describe("Select right in input"),input_select_up:F.string().optional().default("shift+up").describe("Select up in input"),input_select_down:F.string().optional().default("shift+down").describe("Select down in input"),input_line_home:F.string().optional().default("ctrl+a").describe("Move to start of line in input"),input_line_end:F.string().optional().default("ctrl+e").describe("Move to end of line in input"),input_select_line_home:F.string().optional().default("ctrl+shift+a").describe("Select to start of line in input"),input_select_line_end:F.string().optional().default("ctrl+shift+e").describe("Select to end of line in input"),input_visual_line_home:F.string().optional().default("alt+a").describe("Move to start of visual line in input"),input_visual_line_end:F.string().optional().default("alt+e").describe("Move to end of visual line in input"),input_select_visual_line_home:F.string().optional().default("alt+shift+a").describe("Select to start of visual line in input"),input_select_visual_line_end:F.string().optional().default("alt+shift+e").describe("Select to end of visual line in input"),input_buffer_home:F.string().optional().default("home").describe("Move to start of buffer in input"),input_buffer_end:F.string().optional().default("end").describe("Move to end of buffer in input"),input_select_buffer_home:F.string().optional().default("shift+home").describe("Select to start of buffer in input"),input_select_buffer_end:F.string().optional().default("shift+end").describe("Select to end of buffer in input"),input_delete_line:F.string().optional().default("ctrl+shift+d").describe("Delete line in input"),input_delete_to_line_end:F.string().optional().default("ctrl+k").describe("Delete to end of line in input"),input_delete_to_line_start:F.string().optional().default("ctrl+u").describe("Delete to start of line in input"),input_backspace:F.string().optional().default("backspace,shift+backspace").describe("Backspace in input"),input_delete:F.string().optional().default("ctrl+d,delete,shift+delete").describe("Delete character in input"),input_undo:F.string().optional().default("ctrl+-,super+z").describe("Undo in input"),input_redo:F.string().optional().default("ctrl+.,super+shift+z").describe("Redo in input"),input_word_forward:F.string().optional().default("alt+f,alt+right,ctrl+right").describe("Move word forward in input"),input_word_backward:F.string().optional().default("alt+b,alt+left,ctrl+left").describe("Move word backward in input"),input_select_word_forward:F.string().optional().default("alt+shift+f,alt+shift+right").describe("Select word forward in input"),input_select_word_backward:F.string().optional().default("alt+shift+b,alt+shift+left").describe("Select word backward in input"),input_delete_word_forward:F.string().optional().default("alt+d,alt+delete,ctrl+delete").describe("Delete word forward in input"),input_delete_word_backward:F.string().optional().default("ctrl+w,ctrl+backspace,alt+backspace").describe("Delete word backward in input"),history_previous:F.string().optional().default("up").describe("Previous history item"),history_next:F.string().optional().default("down").describe("Next history item"),session_child_cycle:F.string().optional().default("<leader>right").describe("Next child session"),session_child_cycle_reverse:F.string().optional().default("<leader>left").describe("Previous child session"),session_parent:F.string().optional().default("<leader>up").describe("Go to parent session"),terminal_suspend:F.string().optional().default("ctrl+z").describe("Suspend terminal"),terminal_title_toggle:F.string().optional().default("none").describe("Toggle terminal title"),tips_toggle:F.string().optional().default("<leader>h").describe("Toggle tips on home screen"),display_thinking:F.string().optional().default("none").describe("Toggle thinking blocks visibility")}).strict().meta({ref:"KeybindsConfig"}),Wa=F.object({scroll_speed:F.number().min(.001).optional().describe("TUI scroll speed"),scroll_acceleration:F.object({enabled:F.boolean().describe("Enable scroll acceleration")}).optional().describe("Scroll acceleration settings"),diff_style:F.enum(["auto","stacked"]).optional().describe("Control diff rendering style: 'auto' adapts to terminal width, 'stacked' always shows single column")}),Va=F.object({port:F.number().int().positive().optional().describe("Port to listen on"),hostname:F.string().optional().describe("Hostname to listen on"),mdns:F.boolean().optional().describe("Enable mDNS service discovery"),mdnsDomain:F.string().optional().describe("Custom domain name for mDNS service (default: easbot.local)"),cors:F.array(F.string()).optional().describe("Additional domains to allow for CORS")}).strict().meta({ref:"ServerConfig"}),Ka=F.enum(["auto","stretch"]).meta({ref:"LayoutConfig"}),Ja=a$3.Provider.partial().extend({whitelist:F.array(F.string()).optional(),blacklist:F.array(F.string()).optional(),models:F.record(F.string(),a$3.Model.partial().extend({variants:F.record(F.string(),F.object({disabled:F.boolean().optional().describe("Disable this variant for the model")}).catchall(F.any())).optional().describe("Variant-specific configuration")})).optional(),options:F.object({apiKey:F.string().optional(),baseURL:F.string().optional(),enterpriseUrl:F.string().optional().describe("GitHub Enterprise URL for copilot authentication"),setCacheKey:F.boolean().optional().describe("Enable promptCacheKey for this provider (default false)"),timeout:F.union([F.number().int().positive().describe("Timeout in milliseconds for requests to this provider. Default is 300000 (5 minutes). Set to false to disable timeout."),F.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(F.any()).optional()}).strict().meta({ref:"ProviderConfig"}),ur=F.object({$schema:F.string().optional().describe("JSON schema reference for configuration validation"),theme:F.string().optional().describe("Theme name to use for the interface"),keybinds:Ga.optional().describe("Custom keybind configurations"),logLevel:a.Level.optional().describe("Log level"),tui:Wa.optional().describe("TUI specific settings"),server:Va.optional().describe("Server configuration for easbot serve and web commands"),command:F.record(F.string(),Ha).optional().describe("Command configuration, see https://easbot.cn/docs/commands"),skills:Ba.optional().describe("Additional skill folder paths"),watcher:F.object({ignore:F.array(F.string()).optional()}).optional(),plugin:F.string().array().optional(),snapshot:F.boolean().optional(),share:F.enum(["manual","auto","disabled"]).optional().describe("Control sharing behavior:'manual' allows manual sharing via commands, 'auto' enables automatic sharing, 'disabled' disables all sharing"),autoshare:F.boolean().optional().describe("@deprecated Use 'share' field instead. Share newly created sessions automatically"),autoupdate:F.union([F.boolean(),F.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:F.array(F.string()).optional().describe("Disable providers that are loaded automatically"),enabled_providers:F.array(F.string()).optional().describe("When set, ONLY these providers will be enabled. All other providers will be ignored"),model:vs.describe("Model to use in the format of provider/model, eg anthropic/claude-2").optional(),small_model:vs.describe("Small model to use for tasks like title generation in the format of provider/model").optional(),default_agent:F.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:F.string().optional().describe("Custom username to display in conversations instead of system username"),agent:F.object({plan:io.optional(),build:io.optional(),general:io.optional(),explore:io.optional(),title:io.optional(),summary:io.optional(),compaction:io.optional()}).catchall(io).optional().describe("Agent configuration, see https://easbot.cn/docs/agents"),provider:F.record(F.string(),Ja).optional().describe("Custom provider configurations and model overrides"),mcp:F.record(F.string(),F.union([za,F.object({enabled:F.boolean()}).strict()])).optional().describe("MCP (Model Context Protocol) server configurations"),acp:Bd.optional(),gateway:a$4.optional().describe("Gateway configuration for multi-channel communication"),subagent:$a.optional().describe("SubAgent system configuration"),formatter:F.union([F.literal(false),F.record(F.string(),F.object({disabled:F.boolean().optional(),command:F.array(F.string()).optional(),environment:F.record(F.string(),F.string()).optional(),extensions:F.array(F.string()).optional()}))]).optional(),lsp:F.union([F.literal(false),F.record(F.string(),F.union([F.object({disabled:F.literal(true)}),F.object({command:F.array(F.string()),extensions:F.array(F.string()).optional(),disabled:F.boolean().optional(),env:F.record(F.string(),F.string()).optional(),initialization:F.record(F.string(),F.any()).optional()})]))]).optional().refine(e=>{if(!e||typeof e=="boolean")return true;let t=new Set(Object.values(xo).filter(n=>"id"in n&&"extensions"in n&&"spawn"in n).map(n=>n.id));return Object.entries(e).every(([n,o])=>o.disabled||t.has(n)?true:!!o.extensions)},{error:"For custom LSP servers, 'extensions' array is required."}),instructions:F.array(F.string()).optional().describe("Additional instruction files or patterns to include"),layout:Ka.optional().describe("@deprecated Always uses stretch layout."),permission:vi.optional(),tools:F.record(F.string(),F.boolean()).optional(),enterprise:F.object({url:F.string().optional().describe("Enterprise URL")}).optional(),compaction:sl.optional(),context:il.optional(),embedding_model:F.string().optional().describe("Embedding model, defaults to easbot-local/bge-base-zh-v1.5"),graph_model:F.string().optional().describe("Graph model for entity and relation extraction, defaults to easbot-local/qwen2.5-7b-instruct"),rerank_model:F.string().optional().describe("Rerank model for search result reranking, defaults to easbot-local/qwen2.5-7b-instruct"),codebase:Ra.optional(),memory:_a.optional(),note:Ma.optional(),local:F.string().optional(),timezone:F.string().optional(),experimental:F.object({disable_paste_summary:F.boolean().optional(),batch_tool:F.boolean().optional().describe("Enable the batch tool"),openTelemetry:F.boolean().optional().describe("Enable OpenTelemetry spans for AI SDK calls (using the 'experimental_telemetry' flag)"),primary_tools:F.array(F.string()).optional().describe("Tools that should only be available to primary agents."),continue_loop_on_deny:F.boolean().optional().describe("Continue the agent loop when a tool call is denied"),mcp_timeout:F.number().int().positive().optional().describe("Timeout in milliseconds for model context protocol (MCP) requests")}).optional()}).strict().meta({ref:"Config"});var ft=new EventEmitter;function bw(){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 ww(e){return !!e&&typeof e=="object"&&!Array.isArray(e)}function mm(e,t,n=[]){if(!ww(t)){let o=modify(e,n,t,{formattingOptions:{insertSpaces:true,tabSize:2}});return applyEdits(e,o)}return Object.entries(t).reduce((o,[s,r])=>r===void 0?o:mm(o,r,[...n,s]),e)}async function ll(e){let t=Ce__default.join(_.directory,"config.json"),n=await ro(t);await PKG.write(t,JSON.stringify(mergeDeep(n,e),null,2)),await _.dispose();}async function ul(e){let{global:t}=await import('./loader-J6SV3FLI.mjs'),n=bw();if(!n)throw new _o({path:"global",message:"Could not determine global config file path"});let o=await PKG.file(n).text().catch(r=>{if(r.code==="ENOENT")return "{}";throw new _o({path:n},{cause:r})}),s=await(async()=>{if(!n.endsWith(".jsonc")){let c=lr(o,n),l=mergeDeep(c,e);return await PKG.write(n,JSON.stringify(l,null,2)),l}let r=mm(o,e),i=lr(r,n);return await PKG.write(n,r),i})();return t.reset(),_.disposeAll().catch(()=>{}).finally(()=>{ft.emit("event",{directory:"global",payload:{type:a$a.Disposed.type,properties:{}}});}),s}var gr=a.create({service:"adapter-loader"});async function Si(){try{let t=(await he.get())?.acp;if(!t){gr.debug("No ACP config found in Config.Info");return}let o={server:fm(t.server),clients:t.clients};return gr.info("ACP config loaded",{config:o}),o}catch(e){gr.error("Failed to load ACP config",{error:e});return}}async function Xa(){let e=await Si();return e?.server?e.server:fm(Gp)}async function Iw(){return (await Si())?.clients}function fm(e){let t={...e};if(process.env.ACP_CHANNEL){let n=process.env.ACP_CHANNEL.toLowerCase();["stdio","http","websocket"].includes(n)?t.channel=n:gr.warn("Invalid ACP_CHANNEL environment variable",{value:process.env.ACP_CHANNEL});}if(process.env.ACP_PORT){let n=parseInt(process.env.ACP_PORT,10);!Number.isNaN(n)&&n>0&&n<=65535?t.port=n:gr.warn("Invalid ACP_PORT environment variable",{value:process.env.ACP_PORT});}if(process.env.ACP_HOSTNAME&&(t.hostname=process.env.ACP_HOSTNAME),process.env.ACP_TIMEOUT){let n=parseInt(process.env.ACP_TIMEOUT,10);!Number.isNaN(n)&&n>0?t.timeout=n:gr.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 pl(){return (await Xa()).agent}async function vw(){return (await pl())?.model}async function Sw(){return (await pl())?.agent}var Pw=NamedError.create("ConfigDirectoryTypoError",F.object({path:F.string(),dir:F.string(),suggestion:F.string()})),Tw=Pw,he;($=>($.ModelId=vs,$.McpLocal=Fa,$.McpOAuth=Na,$.McpRemote=Ua,$.Mcp=za,$.PermissionAction=Jn,$.PermissionObject=qa,$.PermissionRule=ht,$.Permission=vi,$.Command=Ha,$.Skills=Ba,$.Agent=io,$.Keybinds=Ga,$.TUI=Wa,$.Server=Va,$.Layout=Ka,$.Provider=Ja,$.Info=ur,$.mergeConfigConcatArrays=oo,$.needsInstall=ui,$.installDependencies=pi,$.loadFile=ro,$.load=dr,$.parseConfig=lr,$.JsonError=_o,$.InvalidError=so,$.loadAgent=mi,$.loadCommand=fi,$.loadPlugin=gi,$.getPluginName=La,$.deduplicatePlugins=hi,$.loadNote=rr,$.loadCodebase=ir,$.loadMemory=ar,$.loadKnowledge=Kd,$.update=ll,$.updateGlobal=ul,$.state=mr,$.waitForDependencies=tl,$.get=Mo,$.directories=nl,$.global=wi,$.getGlobal=ol,$.loadACPConfig=Si,$.getACPServerConfig=Xa,$.loadCompaction=xi,$.loadContextConfig=Ii,$.loadGatewayConfig=b,$.loadSubAgentConfig=fr,$.ConfigDirectoryTypoError=Tw))(he||(he={}));var gm={".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 Ow=150;a$2.EASBOT_LSP_INIT_TIMEOUT;var hm=a$2.EASBOT_LSP_DIAGNOSTICS_TIMEOUT,jw=1,Lw=2,Dw=2,Za;(u=>{let e=a.create({service:"lsp.client"}),t=new Map;function n(g){return t.get(g)}u.getActiveClient=n;function o(g){return t.has(g)}u.hasActiveClient=o;function s(g){t.delete(g);}u.removeActiveClient=s,u.InitializeError=NamedError.create("LSPInitializeError",F.object({serverId:F.string()})),u.Event={Diagnostics:a$5.define("lsp.client.diagnostics",F.object({serverId:F.string(),path:F.string()}))};function c(g){if(!g)return;let h=g.textDocumentSync;return typeof h=="number"?h:h?.change}async function l(g,h){let S=g.server.capabilities;if(!S)return;let A=pathToFileURL(g.root+"/").href,y=3e4,x=async()=>{if(S.workspace?.symbolProvider===void 0)try{await withTimeout(h.sendRequest("workspace/symbol",{query:""}),y),S.workspace=S.workspace||{},S.workspace.symbolProvider=!0,e.debug("probed workspaceSymbol capability",{serverId:g.serverId});}catch(C){let k=C instanceof Error?C.message:String(C);(k.includes("methodNotFound")||k.includes("not found")||k.includes("undefined method"))&&(S.workspace=S.workspace||{},S.workspace.symbolProvider=false,e.debug("probed workspaceSymbol capability: not supported",{serverId:g.serverId}));}},b=async()=>{if(S.implementationProvider===void 0)try{await withTimeout(h.sendRequest("textDocument/implementation",{textDocument:{uri:A},position:{line:0,character:0}}),y),S.implementationProvider=!0,e.debug("probed implementation capability",{serverId:g.serverId});}catch(C){let k=C instanceof Error?C.message:String(C);(k.includes("methodNotFound")||k.includes("not found")||k.includes("undefined method"))&&(S.implementationProvider=false,e.debug("probed implementation capability: not supported",{serverId:g.serverId}));}},w=async()=>{if(S.callHierarchyProvider===void 0)try{await withTimeout(h.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:A},position:{line:0,character:0}}),y),S.callHierarchyProvider=!0,e.debug("probed callHierarchy capability",{serverId:g.serverId});}catch(C){let k=C instanceof Error?C.message:String(C);(k.includes("methodNotFound")||k.includes("not found")||k.includes("undefined method"))&&(S.callHierarchyProvider=false,e.debug("probed callHierarchy capability: not supported",{serverId:g.serverId}));}};setTimeout(()=>{x().catch(()=>{}),b().catch(()=>{}),w().catch(()=>{});},100);}function d(g){let h=g.split(/\r\n|\r|\n/);return {line:h.length-1,character:h.at(-1)?.length??0}}function m(g){let h=new Set;return g.filter(S=>{let A=JSON.stringify({code:S.code,severity:S.severity,message:S.message,source:S.source,range:S.range});return h.has(A)?false:(h.add(A),true)})}function f(g,h){return h?h.split(".").reduce((A,y)=>{if(!(!A||typeof A!="object"||!(y in A)))return A[y]},g)??null:g??null}function a$1(g){return g==="typescript"}async function p(g){let h=e.clone().tag("serverId",g.serverId);h.info("starting client");let S=`${g.serverId}:${g.root}`;if(t.has(S)){let L=t.get(S);if(L.createdAt>Date.now()-5e3)return h.warn("duplicate LSP client detected, reusing existing client",{clientKey:S}),L;h.info("removing stale LSP client",{clientKey:S});try{await L.shutdown();}catch{}t.delete(S);}let A=g.initTimeout??xo.getServerInitTimeout(g.serverId),y=createMessageConnection(new StreamMessageReader(g.server.process.stdout),new StreamMessageWriter(g.server.process.stdin));g.server.process.stderr?.on("data",L=>{let K=L.toString().trim();K&&h.debug("server stderr",{text:K.slice(0,1e3)});});let x=new Map,b=new Map,w=new Map,C=L=>m([...x.get(L)??[],...b.get(L)??[]]),k=(L,K)=>{x.set(L,K),pe.publish(u.Event.Diagnostics,{path:L,serverId:g.serverId});};y.onNotification("textDocument/publishDiagnostics",L=>{let K=Filesystem.normalize(fileURLToPath(L.uri));if(K){if(h.info("textDocument/publishDiagnostics",{path:K,count:L.diagnostics.length,version:L.version}),w.set(K,{at:Date.now(),version:typeof L.version=="number"?L.version:void 0}),a$1(g.serverId)&&!x.has(K)){x.set(K,L.diagnostics);return}k(K,L.diagnostics);}}),y.onRequest("window/workDoneProgress/create",L=>(h.info("window/workDoneProgress/create",L),null)),y.onRequest("workspace/configuration",async L=>(L.items??[]).map(Q=>f(g.server.initialization,Q.section))),y.onRequest("client/registerCapability",async()=>{}),y.onRequest("client/unregisterCapability",async()=>{}),y.onRequest("workspace/workspaceFolders",async()=>[{name:"workspace",uri:pathToFileURL(g.root).href}]),y.onRequest("workspace/diagnostic/refresh",async()=>null),y.listen(),h.info("sending initialize",{timeout:A});let P=await withTimeout(y.sendRequest("initialize",{rootUri:pathToFileURL(g.root).href,processId:g.server.process.pid,workspaceFolders:[{name:"workspace",uri:pathToFileURL(g.root).href}],initializationOptions:{...g.server.initialization},capabilities:{window:{workDoneProgress:true},workspace:{configuration:true,didChangeWatchedFiles:{dynamicRegistration:true},diagnostics:{refreshSupport:false}},textDocument:{synchronization:{didOpen:true,didChange:true},publishDiagnostics:{versionSupport:false}}}}),A).catch(L=>{throw h.error("initialize error",{error:L,timeout:A}),new u.InitializeError({serverId:g.serverId},{cause:L})}),E=c(P.capabilities);g.server.capabilities=P.capabilities,l(g,y).catch(()=>{}),await y.sendNotification("initialized",{}),g.server.initialization&&await y.sendNotification("workspace/didChangeConfiguration",{settings:g.server.initialization});let O={},N={root:g.root,get serverId(){return g.serverId},get connection(){return y},get capabilities(){return g.server.capabilities},notify:{async open(L){L.path=Ce__default.isAbsolute(L.path)?L.path:Ce__default.resolve(_.directory,L.path);let K=await Filesystem.readText(L.path),Q=Ce__default.extname(L.path),ue=gm[Q]??"plaintext",D=O[L.path];if(D!==void 0){h.info("workspace/didChangeWatchedFiles",L),await y.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pathToFileURL(L.path).href,type:Lw}]});let I=D.version+1;return O[L.path]={version:I,text:K},h.info("textDocument/didChange",{path:L.path,version:I}),await y.sendNotification("textDocument/didChange",{textDocument:{uri:pathToFileURL(L.path).href,version:I},contentChanges:E===Dw?[{range:{start:{line:0,character:0},end:d(D.text)},text:K}]:[{text:K}]}),I}return h.info("workspace/didChangeWatchedFiles",L),await y.sendNotification("workspace/didChangeWatchedFiles",{changes:[{uri:pathToFileURL(L.path).href,type:jw}]}),h.info("textDocument/didOpen",L),x.delete(L.path),b.delete(L.path),await y.sendNotification("textDocument/didOpen",{textDocument:{uri:pathToFileURL(L.path).href,languageId:ue,version:0,text:K}}),O[L.path]={version:0,text:K},0}},get diagnostics(){let L=new Map;for(let K of new Set([...x.keys(),...b.keys()]))L.set(K,C(K));return L},async waitForDiagnostics(L){let K=Filesystem.normalize(Ce__default.isAbsolute(L.path)?L.path:Ce__default.resolve(_.directory,L.path));h.info("waiting for diagnostics",{path:K,timeout:hm});let Q,ue;return await withTimeout(new Promise(D=>{Q=pe.subscribe(u.Event.Diagnostics,I=>{I.properties.path===K&&I.properties.serverId===N.serverId&&(ue&&clearTimeout(ue),ue=setTimeout(()=>{h.info("got diagnostics",{path:K}),Q?.(),D();},Ow));});}),hm).catch(()=>{}).finally(()=>{ue&&clearTimeout(ue),Q?.();})},async shutdown(){h.info("shutting down"),y.end(),y.dispose(),g.server.process.kill(),t.delete(S),h.info("shutdown");},clientKey:S,createdAt:Date.now()};return t.set(S,N),h.info("initialized"),N}u.create=p;})(Za||(Za={}));var ym=3,Nw=1e3,We;(M=>{let e=a.create({service:"lsp"});M.Event={Updated:a$5.define("lsp.updated",F.object({}))},M.Range=F.object({start:F.object({line:F.number(),character:F.number()}),end:F.object({line:F.number(),character:F.number()})}).meta({ref:"Range"}),M.LspSymbol=F.object({name:F.string(),kind:F.number(),location:F.object({uri:F.string(),range:M.Range})}).meta({ref:"LspSymbol"}),M.DocumentSymbol=F.object({name:F.string(),detail:F.string().optional(),kind:F.number(),range:M.Range,selectionRange:M.Range}).meta({ref:"DocumentSymbol"});let r=v=>{a$2.EASBOT_LSP_TY?v.pyright&&(e.info("LSP server pyright is disabled because EASBOT_LSP_TY is enabled"),delete v.pyright):v.ty&&delete v.ty;},i;async function c(){let v=[],T={},R=await he.get();if(R.lsp===false)return e.info("all LSPs are disabled"),{servers:T,clients:v,broken:new Set,spawning:new Map};for(let j of Object.values(xo))"id"in j&&"extensions"in j&&"spawn"in j&&(T[j.id]=j);r(T);for(let[j,U]of Object.entries(R.lsp??{})){let Y=T[j];if(U.disabled){e.info(`LSP server ${j} is disabled`),delete T[j];continue}T[j]={...Y,id:j,root:Y?.root??(async()=>_.directory),extensions:U.extensions??Y?.extensions??[],initTimeout:Y?.initTimeout??xo.getServerInitTimeout(j),spawn:async J=>({process:PKG.spawn([U.command[0],...U.command.slice(1)],{cwd:J,env:{...process.env,...U.env}}),initialization:U.initialization})};}return e.info("enabled LSP servers",{serverIds:Object.values(T).map(j=>j.id).join(", ")}),{servers:T,clients:v,broken:new Set,spawning:new Map}}async function l(v){await Promise.all(v.clients.map(T=>T.shutdown()));}function d(){return i||(i=_.state(c,l)),i}function m(){return d()()}async function f(){return m()}M.init=f;async function a$1(v){if(!a$2.EASBOT_LSP_TOOL||!v)return false;let{Session:T}=await import('./session-EPFSKATV.mjs'),R=await T.getContextMode(v);return !(R&&R!=="coder")}M.isAvailable=a$1,M.Status=F.object({id:F.string(),name:F.string(),root:F.string(),status:F.union([F.literal("connected"),F.literal("error")])}).meta({ref:"LSPStatus"});async function u(){return m().then(v=>{let T=[];for(let R of v.clients)T.push({id:R.serverId,name:v.servers[R.serverId]?.id??"unknown",root:Ce__default.posix.relative(_.directory,R.root),status:"connected"});return T})}M.status=u;async function g(v,T){try{let R=await h(T);if(R.length===0)return !1;let j=R[0]?.capabilities;if(!j)return !1;switch(v){case "workspaceSymbol":return !!j.workspace?.symbolProvider;case "callHierarchy":return !!j.callHierarchyProvider;case "implementation":return !!j.implementationProvider;default:return !1}}catch{return false}}M.hasCapability=g;async function h(v){let T=await m(),R=Ce__default.parse(v).ext||v,j=[],U=new Map;async function Y(J,ee,se){let ae;try{ae=await J.spawn(ee);}catch(Z){T.broken.add(se),e.error(`Failed to spawn LSP server ${J.id}`,{error:Z,root:ee});return}if(!ae){T.broken.add(se),e.warn(`LSP server ${J.id} spawn returned undefined`,{root:ee});return}ae.initTimeout=J.initTimeout??xo.getServerInitTimeout(J.id),e.debug("spawned lsp server",{serverId:J.id,initTimeout:ae.initTimeout,root:ee}),ae.process.exited.catch(Z=>{let H=Z instanceof Error?Z.message:String(Z),$=Z instanceof Error?Z.stack:void 0;e.error("LSP process exited with error",{serverId:J.id,root:ee,error:H,stack:$});let te=T.clients.findIndex(V=>V.root===ee&&V.serverId===J.id);te!==-1&&(T.clients.splice(te,1),e.info("removed disconnected LSP client",{serverId:J.id,root:ee}));let W=U.get(se)??0;W<ym?(U.set(se,W+1),e.info(`LSP server ${J.id} will restart (attempt ${W+1}/${ym})`,{serverId:J.id,root:ee}),setTimeout(async()=>{if(!T.broken.has(se)){let V=await Y(J,ee,se);V&&(j.push(V),await pe.publish(M.Event.Updated,{}));}},Nw)):(e.error(`LSP server ${J.id} exceeded max restart attempts, marking as broken`,{serverId:J.id,root:ee}),T.broken.add(se),U.delete(se));});let we;try{we=await Za.create({serverId:J.id,server:ae,root:ee,initTimeout:J.initTimeout});}catch(Z){T.broken.add(se),e.error(`Failed to initialize LSP client ${J.id}`,{error:Z,root:ee}),ae.process.kill();return}let ie=T.clients.find(Z=>Z.root===ee&&Z.serverId===J.id);return ie?(ae.process.kill(),ie):(U.delete(se),T.clients.push(we),we)}for(let J of Object.values(T.servers)){if(J.extensions.length>0&&!J.extensions.includes(R))continue;let ee=await J.root(v);if(!ee||T.broken.has(ee+J.id))continue;let se=T.clients.find(Z=>Z.root===ee&&Z.serverId===J.id);if(se){j.push(se);continue}let ae=T.spawning.get(ee+J.id);if(ae){let Z=await ae;if(!Z)continue;j.push(Z);continue}let we=Y(J,ee,ee+J.id);T.spawning.set(ee+J.id,we),await we.finally(()=>{T.spawning.get(ee+J.id)===we&&T.spawning.delete(ee+J.id);});let ie=await we;ie&&(j.push(ie),await pe.publish(M.Event.Updated,{}));}return j}M.getClients=h;async function S(v){let T=await m(),R=Ce__default.parse(v).ext||v;for(let j of Object.values(T.servers)){if(j.extensions.length>0&&!j.extensions.includes(R))continue;let U=await j.root(v);if(U&&!T.broken.has(U+j.id))return true}return false}M.hasClients=S;async function A(v,T){e.debug("touching file",{file:v});let R=await h(v);await Promise.all(R.map(async j=>{let U=T?j.waitForDiagnostics({path:v}):Promise.resolve();return await j.notify.open({path:v}),U})).catch(j=>{e.error("failed to touch file",{err:j,file:v});});}M.touchFile=A;async function y(){let v={};for(let T of await ue(async R=>R.diagnostics))for(let[R,j]of T.entries()){let U=v[R]||[];U.push(...j),v[R]=U;}return v}M.diagnostics=y;async function x(v){let T=await h(v),R=Filesystem.normalize(v),j=[];for(let U of T){let Y=U.diagnostics.get(R);Y&&j.push(...Y);}return j}M.getFileDiagnostics=x;async function b(v){return D(v.file,T=>T.connection.sendRequest("textDocument/hover",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character}}).catch(()=>null))}M.hover=b;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 C=[5,12,6,11,13,14,23,10];async function k(v,T){let R=T??await _.directory+"/package.json",j=await h(R);if(j.length===0)throw new Error("No LSP client available");let U=j[0]?.capabilities;if(U&&!U.workspace?.symbolProvider)throw new Error("LSP server does not support workspaceSymbol");return D(R,Y=>Y.connection.sendRequest("workspace/symbol",{query:v}).then(J=>!J||!Array.isArray(J)?[]:J.filter(ee=>C.includes(ee.kind))).then(J=>J.slice(0,10)).catch(()=>[])).then(Y=>Y.flat())}M.workspaceSymbol=k;async function P(v){let T=pathToFileURL(v.file).href;return D(v.file,R=>R.connection.sendRequest("textDocument/documentSymbol",{textDocument:{uri:T}}).catch(()=>[])).then(R=>R.flat()).then(R=>R.filter(Boolean))}M.documentSymbol=P;async function E(v){return D(v.file,T=>T.connection.sendRequest("textDocument/definition",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character}}).catch(()=>null)).then(T=>T.flat().filter(Boolean))}M.definition=E;async function O(v){return D(v.file,T=>T.connection.sendRequest("textDocument/references",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character},context:{includeDeclaration:true}}).catch(()=>[])).then(T=>T.flat().filter(Boolean))}M.references=O;async function N(v){let T=await h(v.file);if(T.length>0){let R=T[0]?.capabilities;if(R&&!R.implementationProvider)throw new Error("LSP server does not support implementation")}return D(v.file,R=>R.connection.sendRequest("textDocument/implementation",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character}}).catch(()=>null)).then(R=>R.flat().filter(Boolean))}M.implementation=N;async function L(v){let T=await h(v.file);if(T.length>0){let R=T[0]?.capabilities;if(R&&!R.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return D(v.file,R=>R.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character}}).catch(()=>[])).then(R=>R.flat().filter(Boolean))}M.prepareCallHierarchy=L;async function K(v){let T=await h(v.file);if(T.length>0){let R=T[0]?.capabilities;if(R&&!R.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return D(v.file,async R=>{try{let j=await R.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character}}).catch(()=>[]);return j?.length===0?[]:await R.connection.sendRequest("callHierarchy/incomingCalls",{item:j[0]}).catch(()=>[])}catch{return []}}).then(R=>R.flat().filter(Boolean))}M.incomingCalls=K;async function Q(v){let T=await h(v.file);if(T.length>0){let R=T[0]?.capabilities;if(R&&!R.callHierarchyProvider)throw new Error("LSP server does not support callHierarchy")}return D(v.file,async R=>{try{let j=await R.connection.sendRequest("textDocument/prepareCallHierarchy",{textDocument:{uri:pathToFileURL(v.file).href},position:{line:v.line,character:v.character}}).catch(()=>[]);return j?.length===0?[]:await R.connection.sendRequest("callHierarchy/outgoingCalls",{item:j[0]}).catch(()=>[])}catch{return []}}).then(R=>R.flat().filter(Boolean))}M.outgoingCalls=Q;async function ue(v){let T=await m().then(j=>j.clients);return (await Promise.allSettled(T.map(j=>v(j)))).filter(j=>j.status==="fulfilled").map(j=>j.value)}async function D(v,T){try{let R=await h(v);await Promise.all(R.map(U=>U.notify.open({path:v})));let j=R.map(U=>T(U));return await Promise.all(j)}catch(R){return e.error("LSP run failed",{file:v,error:R}),[]}}(T=>{function v(R){let U={1:"ERROR",2:"WARN",3:"INFO",4:"HINT"}[R.severity||1],Y=R.range.start.line+1,J=R.range.start.character+1;return `${U} [${Y}:${J}] ${R.message}`}T.pretty=v;})(M.Diagnostic||(M.Diagnostic={}));})(We||(We={}));var yt;(p=>{let e=a.create({service:"snapshot"}),t="7.days";async function n(){try{let{Scheduler:u}=await import('./scheduler-YYOW743S.mjs');await u.createCommand({id:"cmd_snapshot-cleanup",name:"snapshot-cleanup",cron:"0 * * * *",command:"cleanup",arguments:"snapshot",recurring:!0,durable:!0});}catch(u){e.error("Failed to register cleanup task",{error:u});}}p.init=n;async function o(){if(_.project.vcs!=="git"||(await he.get()).snapshot===false)return;let g=a$2();if(!await Tt__default.stat(g).then(()=>true).catch(()=>false))return;let S=await $`git --git-dir ${g} --work-tree ${_.worktree} gc --prune=${t}`.quiet().cwd(_.directory).nothrow();if(S.exitCode!==0){e.warn("cleanup failed",{exitCode:S.exitCode,stderr:S.stderr.toString(),stdout:S.stdout.toString()});return}e.info("cleanup",{prune:t});}p.cleanup=o;async function s(){if(_.project.vcs!=="git"||(await he.get()).snapshot===false)return;let g=a$2();await Tt__default.mkdir(g,{recursive:true})&&(await $`git init`.env({...process.env,GIT_DIR:g,GIT_WORK_TREE:_.worktree}).quiet().nothrow(),await $`git --git-dir ${g} config core.autocrlf false`.quiet().nothrow(),e.info("initialized")),await $`git --git-dir ${g} --work-tree ${_.worktree} add .`.quiet().cwd(_.directory).nothrow();let h=await $`git --git-dir ${g} --work-tree ${_.worktree} write-tree`.quiet().cwd(_.directory).nothrow().text();return e.info("tracking",{hash:h,cwd:_.directory,git:g}),h.trim()}p.track=s,p.Patch=F.object({hash:F.string(),files:F.string().array()});async function i(u){let g=a$2();await $`git --git-dir ${g} --work-tree ${_.worktree} add .`.quiet().cwd(_.directory).nothrow();let h=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${g} --work-tree ${_.worktree} diff --no-ext-diff --name-only ${u} -- .`.quiet().cwd(_.directory).nothrow();if(h.exitCode!==0)return e.warn("failed to get diff",{hash:u,exitCode:h.exitCode}),{hash:u,files:[]};let S=h.text();return {hash:u,files:S.trim().split(`
25
+ `).map(A=>A.trim()).filter(Boolean).map(A=>Ce__default.join(_.worktree,A))}}p.patch=i;async function c(u){e.info("restore",{commit:u});let g=a$2(),h=await $`git --git-dir ${g} --work-tree ${_.worktree} read-tree ${u} && git --git-dir ${g} --work-tree ${_.worktree} checkout-index -a -f`.quiet().cwd(_.worktree).nothrow();h.exitCode!==0&&e.error("failed to restore snapshot",{snapshot:u,exitCode:h.exitCode,stderr:h.stderr.toString(),stdout:h.stdout.toString()});}p.restore=c;async function l(u){let g=new Set,h=a$2();for(let S of u)for(let A of S.files){if(g.has(A))continue;if(e.info("reverting",{file:A,hash:S.hash}),(await $`git --git-dir ${h} --work-tree ${_.worktree} checkout ${S.hash} -- ${A}`.quiet().cwd(_.worktree).nothrow()).exitCode!==0){let x=Ce__default.posix.relative(_.worktree,A),b=await $`git --git-dir ${h} --work-tree ${_.worktree} ls-tree ${S.hash} -- ${x}`.quiet().cwd(_.worktree).nothrow();b.exitCode===0&&b.text().trim()?e.info("file existed in snapshot but checkout failed, keeping",{file:A}):(e.info("file did not exist in snapshot, deleting",{file:A}),await Tt__default.unlink(A).catch(()=>{}));}g.add(A);}}p.revert=l;async function d(u){let g=a$2();await $`git --git-dir ${g} --work-tree ${_.worktree} add .`.quiet().cwd(_.directory).nothrow();let h=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${g} --work-tree ${_.worktree} diff --no-ext-diff ${u} -- .`.quiet().cwd(_.worktree).nothrow();return h.exitCode!==0?(e.warn("failed to get diff",{hash:u,exitCode:h.exitCode,stderr:h.stderr.toString(),stdout:h.stdout.toString()}),""):h.text().trim()}p.diff=d,p.FileDiff=F.object({file:F.string(),before:F.string(),after:F.string(),additions:F.number(),deletions:F.number(),status:F.enum(["added","deleted","modified"]).optional()}).meta({ref:"FileDiff"});async function f(u,g){let h=a$2(),S=[],A=new Map,y=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${h} --work-tree ${_.worktree} diff --no-ext-diff --name-status --no-renames ${u} ${g} -- .`.quiet().cwd(_.directory).nothrow().text();for(let b of y.trim().split(`
26
+ `)){if(!b)continue;let[w,C]=b.split(" ");if(!w||!C)continue;let k=w.startsWith("A")?"added":w.startsWith("D")?"deleted":"modified";A.set(C,k);}let x=await $`git -c core.autocrlf=false -c core.quotepath=false --git-dir ${h} --work-tree ${_.worktree} diff --no-ext-diff --no-renames --numstat ${u} ${g} -- .`.quiet().cwd(_.directory).nothrow().lines();for(let b of x){if(!b)continue;let w=b.split(" ");if(w.length<3)continue;let[C,k,P]=w;if(!C||!k||!P)continue;let E=C==="-"&&k==="-",O=E?"":await $`git -c core.autocrlf=false --git-dir ${h} --work-tree ${_.worktree} show ${u}:${P}`.quiet().nothrow().text(),N=E?"":await $`git -c core.autocrlf=false --git-dir ${h} --work-tree ${_.worktree} show ${g}:${P}`.quiet().nothrow().text(),L=E?0:parseInt(C,10),K=E?0:parseInt(k,10);S.push({file:P,before:O,after:N,additions:Number.isFinite(L)?L:0,deletions:Number.isFinite(K)?K:0,status:A.get(P)??"modified"});}return S}p.diffFull=f;function a$2(){let u=_.project;return Ce__default.join(a$1.Path.data,"snapshot",u.id)}})(yt||(yt={}));var Ti;(l=>{let e=[/prompt is too long/i,/input is too long for requested model/i,/exceeds the context window/i,/input token count.*exceeds the maximum/i,/maximum prompt length is \d+/i,/reduce the length of the messages/i,/maximum context length is \d+ tokens/i,/exceeds the limit of \d+/i,/exceeds the available context size/i,/greater than the context length/i,/context window exceeds limit/i,/exceeded model token limit/i,/context[_ ]length[_ ]exceeded/i,/request entity too large/i,/context length is only \d+ tokens/i,/input length.*exceeds.*context length/i,/prompt too long; exceeded (?:max )?context length/i,/too large for model with \d+ maximum context length/i,/model_context_window_exceeded/i];function t(d){let m=d.statusCode;return m&&m===404||d.isRetryable}function n(d){return e.some(m=>m.test(d))?true:/^4(00|13)\s*(status code)?\s*\(no body\)/i.test(d)}function o(d,m){return d.includes("github-copilot")&&m.statusCode===403?"Please reauthenticate with the copilot provider to ensure your credentials work properly with EasBot.":m.message}function s(d,m){return iife(()=>{let f=m.message;if(f===""){if(m.responseBody)return m.responseBody;if(m.statusCode){let p=STATUS_CODES[m.statusCode];if(p)return p}return "Unknown error"}let a=o(d,m);if(a!==f)return a;if(!m.responseBody||m.statusCode&&f!==STATUS_CODES[m.statusCode])return f;try{let p=JSON.parse(m.responseBody),u=p.message||p.error||p.error?.message;if(u&&typeof u=="string")return `${f}: ${u}`}catch{}return `${f}: ${m.responseBody}`}).trim()}function r(d){if(typeof d=="string")try{let m=JSON.parse(d);return m&&typeof m=="object"?m:void 0}catch{return}if(typeof d=="object"&&d!==null)return d}function i(d){let m=r(d),f=typeof m?.message=="string"?r(m.message)??m:m;if(!f)return;let a=JSON.stringify(f);if(f.type==="error")switch(f?.error?.code){case "context_length_exceeded":return {type:"context_overflow",message:"Input exceeds context window of this model",responseBody:a};case "insufficient_quota":return {type:"api_error",message:"Quota exceeded. Check your plan and billing details.",isRetryable:false,responseBody:a};case "usage_not_included":return {type:"api_error",message:"To use Codex with your ChatGPT plan, upgrade to Plus: https://chatgpt.com/explore/plus.",isRetryable:false,responseBody:a};case "invalid_prompt":return {type:"api_error",message:typeof f?.error?.message=="string"?f?.error?.message:"Invalid prompt.",isRetryable:false,responseBody:a};case "server_error":return {type:"api_error",message:typeof f?.error?.message=="string"?f?.error?.message:"Server error.",isRetryable:true,responseBody:a}}}l.parseStreamError=i;function c(d){let m=s(d.providerId,d.error),f=r(d.error.responseBody);if(n(m)||d.error.statusCode===413||f?.error?.code==="context_length_exceeded")return {type:"context_overflow",message:m,responseBody:d.error.responseBody};let a=d.error.url?{url:d.error.url}:void 0;return {type:"api_error",message:m,statusCode:d.error.statusCode,isRetryable:d.providerId.startsWith("openai")?t(d.error):d.error.isRetryable,responseHeaders:d.error.responseHeaders,responseBody:d.error.responseBody,metadata:a}}l.parseAPICallError=c;})(Ti||(Ti={}));var ve;($=>{function e(te){return te.startsWith("image/")||te==="application/pdf"}$.isMedia=e,$.OutputLengthError=NamedError.create("MessageOutputLengthError",F.object({})),$.AbortedError=NamedError.create("MessageAbortedError",F.object({message:F.string()})),$.StructuredOutputError=NamedError.create("StructuredOutputError",F.object({message:F.string(),retries:F.number()})),$.AuthError=NamedError.create("ProviderAuthError",F.object({providerId:F.string(),message:F.string()})),$.APIError=NamedError.create("APIError",F.object({message:F.string(),statusCode:F.number().optional(),isRetryable:F.boolean(),responseHeaders:F.record(F.string(),F.string()).optional(),responseBody:F.string().optional(),metadata:F.record(F.string(),F.string()).optional()})),$.ContextOverflowError=NamedError.create("ContextOverflowError",F.object({message:F.string(),responseBody:F.string().optional()})),$.OutputFormatText=F.object({type:F.literal("text")}).meta({ref:"OutputFormatText"}),$.OutputFormatJsonSchema=F.object({type:F.literal("json_schema"),schema:F.record(F.string(),F.any()).meta({ref:"JSONSchema"}),retryCount:F.number().int().min(0).default(2)}).meta({ref:"OutputFormatJsonSchema"}),$.Format=F.discriminatedUnion("type",[$.OutputFormatText,$.OutputFormatJsonSchema]).meta({ref:"OutputFormat"});let m=F.object({id:F.string(),sessionId:F.string(),messageId:F.string()});$.SnapshotPart=m.extend({type:F.literal("snapshot"),snapshot:F.string()}).meta({ref:"SnapshotPart"}),$.PatchPart=m.extend({type:F.literal("patch"),hash:F.string(),files:F.string().array()}).meta({ref:"PatchPart"}),$.TextPart=m.extend({type:F.literal("text"),text:F.string(),synthetic:F.boolean().optional(),ignored:F.boolean().optional(),time:F.object({start:F.number(),end:F.number().optional()}).optional(),metadata:F.record(F.string(),F.any()).optional()}).meta({ref:"TextPart"}),$.ReasoningPart=m.extend({type:F.literal("reasoning"),text:F.string(),metadata:F.record(F.string(),F.any()).optional(),time:F.object({start:F.number(),end:F.number().optional()})}).meta({ref:"ReasoningPart"});let g=F.object({text:F.object({value:F.string(),start:F.number().int(),end:F.number().int()}).meta({ref:"FilePartSourceText"})});$.FileSource=g.extend({type:F.literal("file"),path:F.string()}).meta({ref:"FileSource"}),$.SymbolSource=g.extend({type:F.literal("symbol"),path:F.string(),range:We.Range,name:F.string(),kind:F.number().int()}).meta({ref:"SymbolSource"}),$.ResourceSource=g.extend({type:F.literal("resource"),clientName:F.string(),uri:F.string()}).meta({ref:"ResourceSource"}),$.FilePartSource=F.discriminatedUnion("type",[$.FileSource,$.SymbolSource,$.ResourceSource]).meta({ref:"FilePartSource"}),$.FilePart=m.extend({type:F.literal("file"),mime:F.string(),filename:F.string().optional(),url:F.string(),source:$.FilePartSource.optional()}).meta({ref:"FilePart"}),$.AgentPart=m.extend({type:F.literal("agent"),name:F.string(),source:F.object({value:F.string(),start:F.number().int(),end:F.number().int()}).optional()}).meta({ref:"AgentPart"}),$.CompactionPart=m.extend({type:F.literal("compaction"),auto:F.boolean(),overflow:F.boolean().optional()}).meta({ref:"CompactionPart"}),$.MemoryPart=m.extend({type:F.literal("memory"),status:F.enum(["pending","processing","completed","failed","skipped"]),time:F.object({start:F.number(),end:F.number().optional()}),result:F.string().optional(),error:F.string().optional(),reason:F.string().optional()}).meta({ref:"MemoryPart"}),$.SubtaskPart=m.extend({type:F.literal("subtask"),taskId:F.string().describe("Task unique identifier"),prompt:F.string(),description:F.string(),agent:F.string(),model:F.object({providerId:F.string(),modelId:F.string()}).optional(),command:F.string().optional()}).meta({ref:"SubtaskPart"}),$.SubtaskResultPart=m.extend({type:F.literal("subtask-result"),taskId:F.string().describe("Task unique identifier"),source:F.enum(["tool","scheduler","cli","api","agent-client"]).describe("Task source"),agent:F.string().describe("Agent name"),status:F.enum(["pending","running","completed","error"]).describe("Task status"),result:F.string().optional().describe("Task result content"),error:F.string().optional().describe("Error message if failed"),duration:F.number().optional().describe("Duration in milliseconds"),time:F.object({start:F.number().describe("Start timestamp"),end:F.number().optional().describe("End timestamp")}).optional().describe("Task time"),rounds:F.object({current:F.number(),max:F.number()}).optional().describe("Interaction rounds"),thinking:F.string().optional().describe("Thinking content"),tools:F.array(F.object({name:F.string(),status:F.string(),input:F.record(F.string(),F.unknown()).optional(),output:F.string().optional()})).optional().describe("Tool calls during task"),attachments:F.array(F.lazy(()=>$.FilePart)).optional().describe("Result attachments"),metadata:F.record(F.string(),F.unknown()).optional().describe("Source-specific metadata")}).meta({ref:"SubtaskResultPart"});function E(te){let W=[];if(W.push("=== SubAgent Result ==="),W.push(`Task ID: ${te.taskId}`),W.push(`Source: ${te.source}`),W.push(`Agent: ${te.agent}`),W.push(`Status: ${te.status}`),te.duration&&W.push(`Duration: ${te.duration}ms`),te.rounds&&W.push(`Rounds: ${te.rounds.current}/${te.rounds.max}`),te.time&&(W.push(`Start(Local): ${formatLocalISOCompact(new Date(te.time.start))}`),te.time.end&&W.push(`End(Local): ${formatLocalISOCompact(new Date(te.time.end))}`)),te.metadata&&Object.keys(te.metadata).length>0){W.push("");for(let[V,oe]of Object.entries(te.metadata))W.push(`${V}: ${oe}`);}if(te.thinking&&W.push("","<think>",te.thinking,"</think>"),(te?.tools?.length??0)>0){W.push("","<tool_calls>");for(let V of te?.tools??[])W.push(`- ${V.name}: ${String(V.input)}`);W.push("</tool_calls>");}return W.push(""),te.status==="error"?W.push("Error:",te.error??"Unknown error"):W.push("Result:",te.result??""),W.push("=================="),W.join(`
27
+ `)}$.formatSubtaskResultPart=E,$.RetryPart=m.extend({type:F.literal("retry"),attempt:F.number(),error:$.APIError.Schema,time:F.object({created:F.number()})}).meta({ref:"RetryPart"}),$.StepStartPart=m.extend({type:F.literal("step-start"),snapshot:F.string().optional()}).meta({ref:"StepStartPart"}),$.StepFinishPart=m.extend({type:F.literal("step-finish"),reason:F.string(),snapshot:F.string().optional(),cost:F.number(),tokens:F.object({total:F.number().optional(),input:F.number(),output:F.number(),reasoning:F.number(),cache:F.object({read:F.number(),write:F.number()})})}).meta({ref:"StepFinishPart"}),$.ToolStatePending=F.object({status:F.literal("pending"),input:F.record(F.string(),F.any()),raw:F.string()}).meta({ref:"ToolStatePending"}),$.ToolStateRunning=F.object({status:F.literal("running"),input:F.record(F.string(),F.any()),title:F.string().optional(),metadata:F.record(F.string(),F.any()).optional(),time:F.object({start:F.number()})}).meta({ref:"ToolStateRunning"}),$.ToolStateCompleted=F.object({status:F.literal("completed"),input:F.record(F.string(),F.any()),output:F.string(),title:F.string(),metadata:F.record(F.string(),F.any()),time:F.object({start:F.number(),end:F.number(),compacted:F.number().optional()}),attachments:$.FilePart.array().optional()}).meta({ref:"ToolStateCompleted"}),$.ToolStateError=F.object({status:F.literal("error"),input:F.record(F.string(),F.any()),error:F.string(),metadata:F.record(F.string(),F.any()).optional(),time:F.object({start:F.number(),end:F.number()})}).meta({ref:"ToolStateError"}),$.ToolState=F.discriminatedUnion("status",[$.ToolStatePending,$.ToolStateRunning,$.ToolStateCompleted,$.ToolStateError]).meta({ref:"ToolState"}),$.ToolPart=m.extend({type:F.literal("tool"),callId:F.string(),tool:F.string(),state:$.ToolState,metadata:F.record(F.string(),F.any()).optional()}).meta({ref:"ToolPart"});let v=F.object({id:F.string(),sessionId:F.string()});$.User=v.extend({role:F.literal("user"),time:F.object({created:F.number()}),format:$.Format.optional(),summary:F.object({title:F.string().optional(),body:F.string().optional(),diffs:yt.FileDiff.array()}).optional(),agent:F.string(),model:F.object({providerId:F.string(),modelId:F.string()}),system:F.string().optional(),tools:F.record(F.string(),F.boolean()).optional(),variant:F.string().optional()}).meta({ref:"UserMessage"}),$.Part=F.discriminatedUnion("type",[$.TextPart,$.SubtaskPart,$.ReasoningPart,$.FilePart,$.ToolPart,$.StepStartPart,$.StepFinishPart,$.SnapshotPart,$.PatchPart,$.AgentPart,$.SubtaskResultPart,$.RetryPart,$.CompactionPart,$.MemoryPart]).meta({ref:"Part"}),$.Assistant=v.extend({role:F.literal("assistant"),time:F.object({created:F.number(),completed:F.number().optional()}),error:F.discriminatedUnion("name",[$.AuthError.Schema,NamedError.Unknown.Schema,$.OutputLengthError.Schema,$.AbortedError.Schema,$.StructuredOutputError.Schema,$.ContextOverflowError.Schema,$.APIError.Schema]).optional(),parentId:F.string(),modelId:F.string(),providerId:F.string(),mode:F.string(),agent:F.string(),path:F.object({cwd:F.string(),root:F.string()}),summary:F.boolean().optional(),cost:F.number(),tokens:F.object({total:F.number().optional(),input:F.number(),output:F.number(),reasoning:F.number(),cache:F.object({read:F.number(),write:F.number()})}),structured:F.any().optional(),variant:F.string().optional(),finish:F.string().optional()}).meta({ref:"AssistantMessage"}),$.Info=F.discriminatedUnion("role",[$.User,$.Assistant]).meta({ref:"Message"}),$.Event={Updated:a$5.define("message.updated",F.object({info:$.Info})),Removed:a$5.define("message.removed",F.object({sessionId:F.string(),messageId:F.string()})),PartUpdated:a$5.define("message.part.updated",F.object({part:$.Part,delta:F.string().optional(),time:F.number()})),PartRemoved:a$5.define("message.part.removed",F.object({sessionId:F.string(),messageId:F.string(),partId:F.string()}))},$.WithParts=F.object({info:$.Info,parts:F.array($.Part)});async function ee(te,W,V){let oe=new Set,de=(()=>{if(W.api.npm==="@ai-sdk/anthropic"||W.api.npm==="@ai-sdk/openai"||W.api.npm==="@ai-sdk/amazon-bedrock"||W.api.npm==="@ai-sdk/google-vertex/anthropic")return true;if(W.api.npm==="@ai-sdk/google"){let Ie=W.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 ke=Ie,re=(ke.attachments??[]).filter(Ae=>Ae.url.startsWith("data:")&&Ae.url.includes(","));return {type:"content",value:[{type:"text",text:ke.text??ke.output??"[Tool result content missing]"},...re.map(Ae=>({type:"media",mediaType:Ae.mime,data:iife(()=>{let pt=Ae.url.indexOf(",");return pt===-1?Ae.url:Ae.url.slice(pt+1)})}))]}}return {type:"json",value:Ie}},ce=[];for(let Ie of te)if(Ie.parts.length!==0){if(Ie.info.role==="user"){let ke={id:Ie.info.id,role:"user",parts:[]};ce.push(ke);for(let re of Ie.parts)re.type==="text"&&!re.ignored&&ke.parts.push({type:"text",text:re.text}),re.type==="file"&&re.mime!=="text/plain"&&re.mime!=="application/x-directory"&&(V?.stripMedia&&e(re.mime)?ke.parts.push({type:"text",text:`[Attached ${re.mime}: ${re.filename??"file"}]`}):ke.parts.push({type:"file",url:re.url,mediaType:re.mime,filename:re.filename})),re.type==="compaction"&&ke.parts.push({type:"text",text:"What did we do so far?"}),re.type==="subtask"&&ke.parts.push({type:"text",text:"The following tool was executed by user"}),re.type==="subtask-result"&&ke.parts.push({type:"text",text:$.formatSubtaskResultPart(re)});}if(Ie.info.role==="assistant"){let ke=`${W.providerId}/${W.id}`!=`${Ie.info.providerId}/${Ie.info.modelId}`,re=[];if(Ie.info.error&&!($.AbortedError.isInstance(Ie.info.error)&&Ie.parts.some(Ae=>Ae.type!=="step-start"&&Ae.type!=="reasoning")))continue;let $e={id:Ie.info.id,role:"assistant",parts:[]};for(let Ae of Ie.parts){if(Ae.type==="text"&&$e.parts.push({type:"text",text:Ae.text,...ke?{}:{providerMetadata:Ae.metadata}}),Ae.type==="step-start"&&$e.parts.push({type:"step-start"}),Ae.type==="tool"){if(oe.add(Ae.tool),Ae.state.status==="completed"){let pt=Ae.state.time.compacted?"[Old tool result content cleared]":Ae.state.output??"[Tool result content missing]",Ct=Ae.state.time.compacted||V?.stripMedia?[]:Ae.state.attachments??[],dn=ka=>ka.mime.startsWith("image/")||ka.mime==="application/pdf",li=Ct.filter(dn),ws=Ct.filter(ka=>!dn(ka));!de&&li.length>0&&re.push(...li);let Wt=de?Ct:ws,nr=Wt.length>0?{text:pt,attachments:Wt}:pt;$e.parts.push({type:"tool-"+Ae.tool,state:"output-available",toolCallId:Ae.callId,input:Ae.state.input,output:nr,...ke?{}:{callProviderMetadata:Ae.metadata}});}Ae.state.status==="error"&&$e.parts.push({type:"tool-"+Ae.tool,state:"output-error",toolCallId:Ae.callId,input:Ae.state.input,errorText:Ae.state.error,...ke?{}:{callProviderMetadata:Ae.metadata}}),(Ae.state.status==="pending"||Ae.state.status==="running")&&$e.parts.push({type:"tool-"+Ae.tool,state:"output-error",toolCallId:Ae.callId,input:Ae.state.input,errorText:"[Tool execution was interrupted]",...ke?{}:{callProviderMetadata:Ae.metadata}});}Ae.type==="reasoning"&&$e.parts.push({type:"reasoning",text:Ae.text,...ke?{}:{providerMetadata:Ae.metadata}});}$e.parts.length>0&&(ce.push($e),re.length>0&&ce.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 ye=Object.fromEntries(Array.from(oe).map(Ie=>[Ie,{toModelOutput:me}])),je=ce.filter(Ie=>Ie.parts.some(ke=>ke.type!=="step-start"));return await convertToModelMessages(je,{tools:ye})}$.toModelMessages=ee,$.stream=fn$1(Identifier.schema("session"),async function*(te){let W=await Array.fromAsync(await a$6.list(["message",te]));for(let V=W.length-1;V>=0;V--){let oe=W[V]?.[2];oe&&(yield await(0, $.get)({sessionId:te,messageId:oe}));}}),$.parts=fn$1(Identifier.schema("message"),async te=>{let W=[];for(let V of await a$6.list(["part",te])){let oe=await a$6.read(V);W.push(oe);}return W.sort((V,oe)=>V.id>oe.id?1:-1),W}),$.get=fn$1(F.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message")}),async te=>({info:await a$6.read(["message",te.sessionId,te.messageId]),parts:await(0, $.parts)(te.messageId)}));async function ie(te){let W=[],V=new Set;for await(let oe of te){if(W.push(oe),oe.info.role==="user"&&V.has(oe.info.id)&&oe.parts.some(de=>de.type==="compaction"))break;oe.info.role==="assistant"&&oe.info.summary&&oe.info.finish&&V.add(oe.info.parentId);}return W.reverse(),W}$.filterCompacted=ie;async function Z(te,W){let V=await ie((0, $.stream)(te)),oe=V;W?.maxMessages&&W.maxMessages>0&&(oe=V.slice(-W.maxMessages));let de,me,ce,ye,je;for(let Ie=oe.length-1;Ie>=0;Ie--){let ke=oe[Ie];if(ke&&(!de&&ke.info.role==="user"&&(de=ke.info,me=ke),!ce&&ke.info.role==="assistant"&&(ce=ke.info),!ye&&ke.info.role==="assistant"&&ke.info.finish&&(ye=ke),W?.filterByText!==false&&!je&&ke.info.role==="assistant"&&ke.parts.some(re=>re.type==="text")&&(je=ke),de&&je&&ye))break}return {lastUser:de,lastUserMessage:me,lastAssistant:ce,lastFinished:ye,lastAssistantWithText:je}}$.getLastMessages=Z;function H(te,W){switch(true){case(te instanceof DOMException&&te.name==="AbortError"):return new $.AbortedError({message:te.message},{cause:te}).toObject();case $.OutputLengthError.isInstance(te):return te;case LoadAPIKeyError.isInstance(te):{let V=te;return new $.AuthError({providerId:W.providerId,message:V.message},{cause:V}).toObject()}case te?.code==="ECONNRESET":{let V=te;return new $.APIError({message:"Connection reset by server",isRetryable:true,metadata:{code:V.code??"",syscall:V.syscall??"",message:V.message??""}},{cause:V}).toObject()}case(te instanceof Error&&te.code==="ZlibError"):{let V=te;return W.aborted?new $.AbortedError({message:V.message},{cause:V}).toObject():new $.APIError({message:"Response decompression failed",isRetryable:true,metadata:{code:V.code,message:V.message}},{cause:V}).toObject()}case APICallError.isInstance(te):{let V=Ti.parseAPICallError({providerId:W.providerId,error:te});return V.type==="context_overflow"?new $.ContextOverflowError({message:V.message,responseBody:V.responseBody},{cause:te}).toObject():new $.APIError({message:V.message,statusCode:V.statusCode,isRetryable:V.isRetryable,responseHeaders:V.responseHeaders,responseBody:V.responseBody,metadata:V.metadata},{cause:te}).toObject()}default:{let V=te;try{let oe=Ti.parseStreamError(V);if(oe)return oe.type==="context_overflow"?new $.ContextOverflowError({message:oe.message,responseBody:oe.responseBody},{cause:V}).toObject():new $.APIError({message:oe.message,isRetryable:oe.isRetryable,responseBody:oe.responseBody},{cause:V}).toObject()}catch{}return new NamedError.Unknown({message:String(V)},{cause:V}).toObject()}}}$.fromError=H;})(ve||(ve={}));var xm=a.create({service:"context-workspace"}),wl=".easbot",Ww="protocol.json",Im=1;function Vw(e){return Ce__default.join(e,Ww)}async function xl(e){try{let t=await Tt__default.readFile(e,"utf-8"),n=JSON.parse(t);return {version:Im,bootstrapSeededAt:n.bootstrapSeededAt,setupCompletedAt:n.setupCompletedAt,metadata:n.metadata}}catch{return {version:Im}}}async function Ei(e){return e?Ce__default.join(e,wl):Ce__default.join(_.directory,wl)}async function ec(e){let t=e?await Ei(e):await Ei(),n=Vw(t);xm.debug("isSetupCompleted checking",{workspace:e,easbotDir:t,statePath:n});let o=await xl(n),s=typeof o.setupCompletedAt=="string"&&o.setupCompletedAt.trim().length>0;return xm.debug("isSetupCompleted result",{statePath:n,setupCompletedAt:o.setupCompletedAt,completed:s}),s}var tc;(s=>{let e=a.create({service:"skill-discovery"});function t(){return Ce__default.join(a$1.Path.cache,"skills")}s.dir=t;async function n(r,i){try{return await access(i),!0}catch{}try{let c=await Fetch.get(r);return c.ok?(await writeFile(i,String(c.data)),!0):(e.error("failed to download",{url:r,status:c.status}),!1)}catch(c){return e.error("failed to download",{url:r,err:c}),false}}async function o(r){let i=[],c=r.endsWith("/")?r:`${r}/`,l=new URL("index.json",c).href,d=t(),m=c.slice(0,-1);e.info("fetching index",{url:l});try{let f=await Fetch.get(l);if(!f.ok)return e.error("failed to fetch index",{url:l,status:f.status}),i;let a=f.data;if(!a?.skills||!Array.isArray(a.skills))return e.warn("invalid index format",{url:l}),i;let p=a.skills.filter(u=>!u?.name||!Array.isArray(u.files)?(e.warn("invalid skill entry",{url:l,skill:u}),!1):!0);await Promise.all(p.map(async u=>{let g=Ce__default.join(d,u.name);await Promise.all(u.files.map(async S=>{let A=new URL(S,`${m}/${u.name}/`).href,y=Ce__default.join(g,S);await mkdir(Ce__default.dirname(y),{recursive:!0}),await n(A,y);}));let h=Ce__default.join(g,"SKILL.md");try{await access(h),i.push(g);}catch{}}));}catch(f){e.error("failed to fetch index",{url:l,err:f});}return i}s.pull=o;})(tc||(tc={}));var Me;(C=>{let e=a.create({service:"permission"});function t(k){return k.startsWith("~/")?sc.homedir()+k.slice(1):k==="~"?sc.homedir():k.startsWith("$HOME/")?sc.homedir()+k.slice(5):k.startsWith("$HOME")?sc.homedir()+k.slice(5):k}C.Action=F.enum(["allow","deny","ask"]).meta({ref:"PermissionAction"}),C.Rule=F.object({permission:F.string(),pattern:F.string(),action:C.Action}).meta({ref:"PermissionRule"}),C.Ruleset=C.Rule.array().meta({ref:"PermissionRuleset"});function r(k){let P=[];for(let[E,O]of Object.entries(k)){if(typeof O=="string"){P.push({permission:E,action:O,pattern:"*"});continue}P.push(...Object.entries(O).map(([N,L])=>({permission:E,pattern:t(N),action:L})));}return P}C.fromConfig=r;function i(...k){return k.flat()}C.merge=i,C.Request=F.object({id:Identifier.schema("permission"),sessionId:Identifier.schema("session"),permission:F.string(),patterns:F.string().array(),metadata:F.record(F.string(),F.any()),always:F.string().array(),tool:F.object({messageId:F.string(),callId:F.string()}).optional()}).meta({ref:"PermissionRequest"}),C.Reply=F.enum(["once","always","reject"]),C.Approval=F.object({providerId:F.string(),patterns:F.string().array()}),C.Event={Asked:a$5.define("permission.asked",C.Request),Replied:a$5.define("permission.replied",F.object({sessionId:F.string(),requestId:F.string(),reply:C.Reply}))};let f;function a$1(){return f||(f=_.state(async()=>{let k=_.project.id,P=await a$6.read(["permission",k]).catch(()=>[]);return {pending:{},approved:P}})),f}function p(){return a$1()()}C.ask=fn$1(C.Request.partial({id:true}).extend({ruleset:C.Ruleset}),async k=>{let P=await p(),{ruleset:E,...O}=k;for(let N of O.patterns??[]){let L=h(O.permission,N,E,P.approved);if(e.debug("evaluated",{permission:O.permission,pattern:N,action:L}),L.action==="deny")throw new b(E.filter(K=>Wildcard.match(O.permission,K.permission)));if(L.action==="ask"){let K=k.id??Identifier.ascending("permission");return new Promise((Q,ue)=>{let D={id:K,...O};P.pending[K]={info:D,resolve:Q,reject:ue},pe.publish(C.Event.Asked,D);})}}}),C.reply=fn$1(F.object({requestId:Identifier.schema("permission"),reply:C.Reply,message:F.string().optional()}),async k=>{let P=await p(),E=P.pending[k.requestId];if(E){if(delete P.pending[k.requestId],await pe.publish(C.Event.Replied,{sessionId:E.info.sessionId,requestId:E.info.id,reply:k.reply}),k.reply==="reject"){E.reject(k.message?new x(k.message):new y);let O=E.info.sessionId;for(let[N,L]of Object.entries(P.pending))L.info.sessionId===O&&(delete P.pending[N],await pe.publish(C.Event.Replied,{sessionId:L.info.sessionId,requestId:L.info.id,reply:"reject"}),L.reject(new y));return}if(k.reply==="once"){E.resolve();return}if(k.reply==="always"){for(let N of E.info.always)P.approved.push({permission:E.info.permission,pattern:N,action:"allow"});E.resolve();let O=E.info.sessionId;for(let[N,L]of Object.entries(P.pending))L.info.sessionId!==O||!L.info.patterns.every(Q=>h(L.info.permission,Q,P.approved).action==="allow")||(delete P.pending[N],await pe.publish(C.Event.Replied,{sessionId:L.info.sessionId,requestId:L.info.id,reply:"always"}),L.resolve());return}}});function h(k,P,...E){let O=i(...E);return e.debug("evaluate",{permission:k,pattern:P,ruleset:O}),O.findLast(L=>Wildcard.match(k,L.permission)&&Wildcard.match(P,L.pattern))??{action:"ask",permission:k,pattern:"*"}}C.evaluate=h;let S=["edit","write","patch","multiedit"];function A(k,P){let E=new Set;for(let O of k){let N=S.includes(O)?"edit":O,L=P.findLast(K=>Wildcard.match(N,K.permission));L&&L.pattern==="*"&&L.action==="deny"&&E.add(O);}return E}C.disabled=A;class y extends Error{constructor(){super("The user rejected permission to use this specific tool call.");}}C.RejectedError=y;class x extends Error{constructor(P){super(`The user rejected permission to use this specific tool call with the following feedback: ${P}`);}}C.CorrectedError=x;class b extends Error{constructor(E){super(`The user has specified a rule which prevents you from using this specific tool call. Here are some of the relevant rules ${JSON.stringify(E)}`);b$1(this,"ruleset",E);}}C.DeniedError=b;async function w(){return p().then(k=>Object.values(k.pending).map(P=>P.info))}C.list=w;})(Me||(Me={}));var Jt;(h$1=>{let e=a.create({service:"skill"});h$1.Info=F.object({name:F.string(),description:F.string(),location:F.string(),content:F.string(),scope:F.enum(h).optional().describe("Context mode scope")}),h$1.InvalidError=NamedError.create("SkillInvalidError",F.object({path:F.string(),message:F.string().optional(),issues:F.custom().optional()})),h$1.NameMismatchError=NamedError.create("SkillNameMismatchError",F.object({message:F.string(),path:F.string(),expected:F.string(),actual:F.string()}));let s=[".agents"],r="skills/**/SKILL.md",i$1="skills/**/SKILL.md",c="**/SKILL.md",l;function d(){return l||(l=_.state(async()=>{let S={},A=new Set,y=async w=>{let C=await a$9.parse(w).catch(P=>{let E=a$9.FrontmatterError.isInstance(P)?P.data.message:`Failed to parse skill ${w}`;pe.publish(X.Event.Error,{error:new NamedError.Unknown({message:E}).toObject()}),e.error("failed to load skill",{skill:w,err:P});});if(!C)return;let k=h$1.Info.pick({name:true,description:true}).safeParse(C.data);k.success&&(S[k.data.name]&&e.warn("duplicate skill name",{name:k.data.name,existing:S[k.data.name]?.location,duplicate:w}),A.add(Ce__default.dirname(w)),S[k.data.name]={name:k.data.name,description:k.data.description,location:w,content:C.content,scope:C.data.scope});},x=async(w,C)=>glob(r,{cwd:w,absolute:true,nodir:true,follow:true,dot:true}).then(k=>Promise.all(k.map(y))).catch(k=>{e.error(`failed to scan ${C} skills`,{dir:w,error:k});});if(!a$2.EASBOT_DISABLE_EXTERNAL_SKILLS){for(let w of s){let C=Ce__default.join(a$1.Path.home,w);await Filesystem.isDir(C)&&await x(C,"global");}for await(let w of Filesystem.up({targets:s,start:_.directory,stop:_.worktree}))await x(w,"project");}for(let w of await he.directories()){let C=await glob(i$1,{cwd:w,absolute:true,nodir:true,follow:true});for(let k of C)await y(k);}let b=await he.get();for(let w of b.skills?.paths??[]){let C=w.startsWith("~/")?Ce__default.join(sc.homedir(),w.slice(2)):w,k=Ce__default.isAbsolute(C)?C:Ce__default.join(_.directory,C);if(!await Filesystem.isDir(k)){e.warn("skill path not found",{path:k});continue}let P=await glob(c,{cwd:k,absolute:true,nodir:true,follow:true});for(let E of P)await y(E);}for(let w of b.skills?.urls??[]){let C=await tc.pull(w);for(let k of C){A.add(k);let P=await glob(c,{cwd:k,absolute:true,nodir:true,follow:true});for(let E of P)await y(E);}}return {skills:S,dirs:Array.from(A)}})),l}function m(){return d()()}h$1.state=m;async function f(S){return m().then(A=>A.skills[S])}h$1.get=f;async function a$3(){return m().then(S=>Object.values(S.skills))}h$1.all=a$3;async function p(){return m().then(S=>S.dirs)}h$1.dirs=p;async function u(S,A=i){let y=await m();return Object.values(y.skills).toSorted((b,w)=>b.name.localeCompare(w.name)).filter(b=>{if(S&&Me.evaluate("skill",b.name,S.permission).action==="deny")return false;if(A){let w=b.scope??i;if(w!=="all"&&w!==A)return false}return true})}h$1.available=u;function g(S,A){if(S.length===0)return "No skills are currently available.";let y=S.toSorted((x,b)=>x.name.localeCompare(b.name));return A.verbose?["<available_skills>",...y.flatMap(x=>[" <skill>",` <name>${x.name}</name>`,` <description>${x.description}</description>`,` <location>${pathToFileURL(x.location).href}</location>`," </skill>"]),"</available_skills>"].join(`
28
+ `):["## Available Skills","Skills provide specialized instructions and workflows for specific tasks.","Use the skill tool to load a skill when a task matches its description.","",...y.map(x=>[`- **${x.name}**: ${x.description}`,` - Location: ${pathToFileURL(x.location).href}`].join(`
29
+ `))].join(`
30
+ `)}h$1.format=g;})(Jt||(Jt={}));var bt;(b=>{let e=a.create({service:"file"});b.Info=F.object({path:F.string(),added:F.number().int(),removed:F.number().int(),status:F.enum(["added","deleted","modified"])}).meta({ref:"File"}),b.Node=F.object({name:F.string(),path:F.string(),absolute:F.string(),type:F.enum(["file","directory"]),ignored:F.boolean()}).meta({ref:"FileNode"}),b.Content=F.object({type:F.enum(["text","binary"]),content:F.string(),diff:F.string().optional(),patch:F.object({oldFileName:F.string(),newFileName:F.string(),oldHeader:F.string().optional(),newHeader:F.string().optional(),hunks:F.array(F.object({oldStart:F.number(),oldLines:F.number(),newStart:F.number(),newLines:F.number(),lines:F.array(F.string())})),index:F.string().optional()}).optional(),encoding:F.literal("base64").optional(),mimeType:F.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 C=Filesystem.extname(w).toLowerCase().slice(1);return r.has(C)}function c$1(w){let C=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"}[C]||"image/"+C}function l(w){let C=Filesystem.extname(w).toLowerCase().slice(1);return s.has(C)}function d$1(w){return w.startsWith("image/")}async function m(w){let C=w.type?.toLowerCase();if(e.info("shouldEncode",{type:C}),!C||C.startsWith("text/")||C.includes("charset="))return false;let P=C.split("/",2)[0];return !!["image","audio","video","font","model","multipart"].includes(P)}b.Event={Edited:a$5.define("file.edited",F.object({file:F.string()}))};async function a$2(){let w={files:[],dirs:[]},C=false,k=_.directory===a$1.Path.home&&_.project.id==="global",P=async E=>{if(_.directory===Ce__default.parse(_.directory).root)return;if(C=true,k){let N=new Set,L=new Set;process.platform==="darwin"&&L.add("Library"),process.platform==="win32"&&L.add("AppData");let K=new Set(["node_modules","dist","build","target","vendor"]),Q=I=>I.startsWith(".")||L.has(I),ue=I=>I.startsWith(".")||K.has(I),D=await Sl.promises.readdir(_.directory,{withFileTypes:true}).catch(()=>[]);for(let I of D){if(!I.isDirectory()||Q(I.name))continue;N.add(I.name+"/");let M=Filesystem.join(_.directory,I.name),v=await Sl.promises.readdir(M,{withFileTypes:true}).catch(()=>[]);for(let T of v)T.isDirectory()&&(ue(T.name)||N.add(I.name+"/"+T.name+"/"));}E.dirs=Array.from(N).toSorted(),w=E,C=false;return}let O=new Set;for await(let N of a$8.files({cwd:_.directory})){E.files.push(N);let L=N;for(;;){let K=Ce__default.posix.dirname(L);if(K==="."||K===L)break;L=K,!O.has(K)&&(O.add(K),E.dirs.push(K+"/"));}}w=E,C=false;};return await P(w),{async files(){return C||await P({files:[],dirs:[]}),w}}}let p;function u(){return p||(p=_.state(a$2)),p}function g(){return u()()}async function h(){g();}b.init=h;async function S(){if(_.project.vcs!=="git")return [];let C=await $`git -c core.quotepath=false diff --numstat HEAD`.cwd(_.directory).quiet().nothrow().text(),k=[];if(C.trim()){let O=C.trim().split(`
31
+ `);for(let N of O){let L=N.split(" "),K=L[2];K&&k.push({path:K,added:L[0]==="-"?0:parseInt(L[0]||"0",10),removed:L[1]==="-"?0:parseInt(L[1]||"0",10),status:"modified"});}}let P=await $`git -c core.quotepath=false ls-files --others --exclude-standard`.cwd(_.directory).quiet().nothrow().text();if(P.trim()){let O=P.trim().split(`
32
+ `);for(let N of O)try{let K=(await PKG.file(Filesystem.join(_.directory,N)).text()).split(`
33
+ `).length;k.push({path:N,added:K,removed:0,status:"added"});}catch{}}let E=await $`git -c core.quotepath=false diff --name-only --diff-filter=D HEAD`.cwd(_.directory).quiet().nothrow().text();if(E.trim()){let O=E.trim().split(`
34
+ `);for(let N of O)k.push({path:N,added:0,removed:0,status:"deleted"});}return k.map(O=>({...O,path:Ce__default.posix.relative(_.directory,O.path)}))}b.status=S;async function A(w){var K=[];try{let C=c(K,e.time("read",{file:w}));let k=_.project;let P=Filesystem.join(_.directory,w);if(!_.containsPath(P))throw new Error("Access denied: path escapes project directory");if(i(w)){let I=PKG.file(P);if(await I.exists()){let M=await I.arrayBuffer().catch(()=>new ArrayBuffer(0)),v=Buffer.from(M).toString("base64"),T=c$1(w);return {type:"text",content:v,mimeType:T,encoding:"base64"}}return {type:"text",content:""}}if(l(w))return {type:"binary",content:""};let E=PKG.file(P);if(!await E.exists())return {type:"text",content:""};let O=await m(E);let N=E.type||"application/octet-stream";if(O&&!d$1(N))return {type:"binary",content:"",mimeType:N};if(O){let I=await E.bytes().catch(()=>new Uint8Array(0));return {type:"text",content:Buffer.from(I).toString("base64"),mimeType:N,encoding:"base64"}}let L=await E.text().catch(()=>"").then(I=>I.trim());if(k.vcs==="git"){let I=await $`git diff ${w}`.cwd(_.directory).quiet().nothrow().text();if(I.trim()||(I=await $`git diff --staged ${w}`.cwd(_.directory).quiet().nothrow().text()),I.trim()){let M=await $`git show HEAD:${w}`.cwd(_.directory).quiet().nothrow().text(),v=structuredPatch(w,w,M,L,"old","new",{context:1/0,ignoreWhitespace:!0}),T=formatPatch(v);return {type:"text",content:L,patch:{oldFileName:v.oldFileName??w,newFileName:v.newFileName??w,oldHeader:v.oldHeader,newHeader:v.newHeader,hunks:v.hunks,index:v.index},diff:T}}}return {type:"text",content:L}}catch(Q){var ue=Q,D=true;}finally{d(K,ue,D);}}b.read=A;async function y(w){let C=[".git",".DS_Store"],k=_.project,P=N=>false;if(k.vcs==="git"){let N=Ignore.create(),L=PKG.file(Filesystem.join(_.worktree,".gitignore"));await L.exists()&&N.add((await L.text()).split(`
35
+ `));let K=PKG.file(Filesystem.join(_.worktree,".ignore"));await K.exists()&&N.add((await K.text()).split(`
36
+ `)),P=N.createFilter();}let E=w?Filesystem.join(_.directory,w):_.directory;if(!_.containsPath(E))throw new Error("Access denied: path escapes project directory");let O=[];for(let N of await Sl.promises.readdir(E,{withFileTypes:true}).catch(()=>[])){if(C.includes(N.name))continue;let L=Filesystem.join(E,N.name),K=Ce__default.posix.relative(_.directory,L),Q=N.isDirectory()?"directory":"file";O.push({name:N.name,path:K,absolute:L,type:Q,ignored:P(Q==="directory"?K+"/":K)});}return O.sort((N,L)=>N.type!==L.type?N.type==="directory"?-1:1:N.name.localeCompare(L.name))}b.list=y;async function x(w){let C=w.query.trim(),k=w.limit??100,P=w.type??(w.dirs===false?"file":"all");e.info("search",{query:C,kind:P});let E=await(await g()).files(),O=I=>I.replaceAll("\\","/").replace(/\/+$/,"").split("/").some(v=>v.startsWith(".")&&v.length>1),N=C.startsWith(".")||C.includes("/."),L=I=>{if(N)return I;let M=[],v=[];for(let T of I){let R=O(T);R&&v.push(T),R||M.push(T);}return [...M,...v]};if(!C)return P==="file"?E.files.slice(0,k):L(E.dirs.toSorted()).slice(0,k);let K=P==="file"?E.files:P==="directory"?E.dirs:[...E.files,...E.dirs],Q=P==="directory"&&!N?k*20:k,ue=Ty.go(C,K,{limit:Q}).map(I=>I.target),D=P==="directory"?L(ue).slice(0,k):ue;return e.info("search",{query:C,kind:P,results:D.length}),D}b.search=x;})(bt||(bt={}));var kl={};a$7(kl,{biome:()=>rx,clang:()=>ax,dart:()=>fx,gleam:()=>bx,gofmt:()=>tx,htmlbeautifier:()=>mx,ktlint:()=>cx,latexindent:()=>yx,mix:()=>nx,nixfmt:()=>xx,ocamlformat:()=>gx,ormolu:()=>Sx,oxfmt:()=>sx,pint:()=>vx,prettier:()=>ox,rlang:()=>dx,rubocop:()=>ux,ruff:()=>Tm,rustfmt:()=>Ix,shfmt:()=>wx,standardrb:()=>px,terraform:()=>hx,uvformat:()=>lx,zig:()=>ix});var tx={name:"gofmt",command:["gofmt","-w","$FILE"],extensions:[".go"],async enabled(){return await PKG.which("gofmt")!==null}},nx={name:"mix",command:["mix","format","$FILE"],extensions:[".ex",".exs",".eex",".heex",".leex",".neex",".sface"],async enabled(){return await PKG.which("mix")!==null}},ox={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",_.directory,_.worktree);for(let t of e){let n=await PKG.file(t).json();if(n.dependencies?.prettier||n.devDependencies?.prettier)return true}return false}},sx={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",_.directory,_.worktree);for(let t of e){let n=await PKG.file(t).json();if(n.dependencies?.oxfmt||n.devDependencies?.oxfmt)return true}return false}},rx={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,_.directory,_.worktree)).length>0)return true;return false}},ix={name:"zig",command:["zig","fmt","$FILE"],extensions:[".zig",".zon"],async enabled(){return await PKG.which("zig")!==null}},ax={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",_.directory,_.worktree)).length>0}},cx={name:"ktlint",command:["ktlint","-F","$FILE"],extensions:[".kt",".kts"],async enabled(){return await PKG.which("ktlint")!==null}},Tm={name:"ruff",command:["ruff","format","$FILE"],extensions:[".py",".pyi"],async enabled(){if(!await PKG.which("ruff"))return false;let e=["pyproject.toml","ruff.toml",".ruff.toml"];for(let n of e){let o=await Filesystem.findUp(n,_.directory,_.worktree);if(o.length>0)if(n==="pyproject.toml"){if((await PKG.file(o[0]).text()).includes("[tool.ruff]"))return true}else return true}let t=["requirements.txt","pyproject.toml","Pipfile"];for(let n of t){let o=await Filesystem.findUp(n,_.directory,_.worktree);if(o.length>0&&(await PKG.file(o[0]).text()).includes("ruff"))return true}return false}},dx={name:"air",command:["air","format","$FILE"],extensions:[".R"],async enabled(){if(await PKG.which("air")==null)return false;try{let t=process.platform==="win32"?"cmd":void 0,n=Shell.spawn(t,"air --help",{stdout:"pipe",stderr:"pipe"});await n.exited;let s=(await PKG.nodeReadableStreamToText(n.stdout)).split(`
37
+ `)[0];if(!s)return !1;let r=s.includes("R language"),i=s.includes("formatter");return r&&i}catch{return false}}},lx={name:"uv",command:["uv","format","--","$FILE"],extensions:[".py",".pyi"],async enabled(){if(await Tm.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}},ux={name:"rubocop",command:["rubocop","--autocorrect","$FILE"],extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){return await PKG.which("rubocop")!==null}},px={name:"standardrb",command:["standardrb","--fix","$FILE"],extensions:[".rb",".rake",".gemspec",".ru"],async enabled(){return await PKG.which("standardrb")!==null}},mx={name:"htmlbeautifier",command:["htmlbeautifier","$FILE"],extensions:[".erb",".html.erb"],async enabled(){return await PKG.which("htmlbeautifier")!==null}},fx={name:"dart",command:["dart","format","$FILE"],extensions:[".dart"],async enabled(){return await PKG.which("dart")!==null}},gx={name:"ocamlformat",command:["ocamlformat","-i","$FILE"],extensions:[".ml",".mli"],async enabled(){return await PKG.which("ocamlformat")?(await Filesystem.findUp(".ocamlformat",_.directory,_.worktree)).length>0:false}},hx={name:"terraform",command:["terraform","fmt","$FILE"],extensions:[".tf",".tfvars"],async enabled(){return await PKG.which("terraform")!==null}},yx={name:"latexindent",command:["latexindent","-w","-s","$FILE"],extensions:[".tex"],async enabled(){return await PKG.which("latexindent")!==null}},bx={name:"gleam",command:["gleam","format","$FILE"],extensions:[".gleam"],async enabled(){return await PKG.which("gleam")!==null}},wx={name:"shfmt",command:["shfmt","-w","$FILE"],extensions:[".sh",".bash"],async enabled(){return await PKG.which("shfmt")!==null}},xx={name:"nixfmt",command:["nixfmt","$FILE"],extensions:[".nix"],async enabled(){return await PKG.which("nixfmt")!==null}},Ix={name:"rustfmt",command:["rustfmt","$FILE"],extensions:[".rs"],async enabled(){return await PKG.which("rustfmt")!==null}},vx={name:"pint",command:["./vendor/bin/pint","$FILE"],extensions:[".php"],async enabled(){let e=await Filesystem.findUp("composer.json",_.directory,_.worktree);for(let t of e){let n=await PKG.file(t).json();if(n.require?.["laravel/pint"]||n["require-dev"]?.["laravel/pint"])return true}return false}},Sx={name:"ormolu",command:["ormolu","-i","$FILE"],extensions:[".hs"],async enabled(){return await PKG.which("ormolu")!==null}};var Ss;(m=>{let e=a.create({service:"format"});m.Status=F.object({name:F.string(),extensions:F.string().array(),enabled:F.boolean()}).meta({ref:"FormatterStatus"});async function n(){let f={},a=await he.get(),p={};if(a.formatter===false)return e.info("all formatters are disabled"),{enabled:f,formatters:p};for(let u of Object.values(kl))p[u.name]=u;for(let[u,g]of Object.entries(a.formatter??{})){if(g.disabled){delete p[u];continue}let h=mergeDeep(p[u]??{},{name:u,enabled:async()=>true,command:[],extensions:[],...g});h.command.length!==0&&(p[u]=h);}return {enabled:f,formatters:p}}let o;function s(){return o||(o=_.state(n)),o}async function r(){return s()()}async function i(f){let a=await r(),p=a.enabled[f.name];return p===void 0&&(p=await f.enabled(),a.enabled[f.name]=p),p}async function c(f){let a=await r().then(u=>u.formatters),p=[];for(let u of Object.values(a))e.debug("checking",{name:u.name,ext:f}),u.extensions.includes(f)&&await i(u)&&(e.debug("enabled",{name:u.name,ext:f}),p.push(u));return p}async function l(){let f=await r(),a=[];for(let p of Object.values(f.formatters)){let u=await i(p);a.push({name:p.name,extensions:p.extensions,enabled:u});}return a}m.status=l;async function d(){e.debug("init"),pe.subscribe(bt.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 g=u.command.map(S=>S.replace("$FILE",a)),h=await PKG.run(g,{cwd:_.directory,env:{...process.env,...u.environment},stdout:"ignore",stderr:"pipe"});h.code!==0&&e.error("format failed",{command:g,exitCode:h.code,stderr:h.stderr});}catch(g){e.error("failed to format file",{error:g,command:u.command,...u.environment,file:a});}}});}m.init=d;})(Ss||(Ss={}));var Tn;(S=>{S.Tokens=F.object({accessToken:F.string(),refreshToken:F.string().optional(),expiresAt:F.number().optional(),scope:F.string().optional()}),S.ClientInfo=F.object({clientId:F.string(),clientSecret:F.string().optional(),clientIdIssuedAt:F.number().optional(),clientSecretExpiresAt:F.number().optional()}),S.Entry=F.object({tokens:S.Tokens.optional(),clientInfo:S.ClientInfo.optional(),codeVerifier:F.string().optional(),oauthState:F.string().optional(),serverUrl:F.string().optional()});let o=Ce__default.join(a$1.Path.data,"mcp-auth.json");async function s(A){return (await i())[A]}S.get=s;async function r(A,y){let x=await s(A);if(x&&x.serverUrl&&x.serverUrl===y)return x}S.getForUrl=r;async function i(){return PKG.file(o).json().catch(()=>({}))}S.all=i;async function c(A,y,x){PKG.file(o);let w=await i();x&&(y.serverUrl=x),await PKG.write(o,JSON.stringify({...w,[A]:y},null,2));}S.set=c;async function l(A){PKG.file(o);let x=await i();delete x[A],await PKG.write(o,JSON.stringify(x,null,2));}S.remove=l;async function d(A,y,x){let b=await s(A)??{};b.tokens=y,await c(A,b,x);}S.updateTokens=d;async function m(A,y,x){let b=await s(A)??{};b.clientInfo=y,await c(A,b,x);}S.updateClientInfo=m;async function f(A,y){let x=await s(A)??{};x.codeVerifier=y,await c(A,x);}S.updateCodeVerifier=f;async function a(A){let y=await s(A);y&&(delete y.codeVerifier,await c(A,y));}S.clearCodeVerifier=a;async function p(A,y){let x=await s(A)??{};x.oauthState=y,await c(A,x);}S.updateOAuthState=p;async function u(A){return (await s(A))?.oauthState}S.getOAuthState=u;async function g(A){let y=await s(A);y&&(delete y.oauthState,await c(A,y));}S.clearOAuthState=g;async function h(A){let y=await s(A);return y?.tokens?y.tokens.expiresAt?y.tokens.expiresAt<Date.now()/1e3:false:null}S.isTokenExpired=h;})(Tn||(Tn={}));a.create({service:"mcp.oauth"});var yr=19876,Am="/mcp/oauth/callback";var br=a.create({service:"mcp.oauth-callback"}),Rx=`<!DOCTYPE html>
38
+ <html>
39
+ <head>
40
+ <title>EasBot - Authorization Successful</title>
41
+ <style>
42
+ body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
43
+ .container { text-align: center; padding: 2rem; }
44
+ h1 { color: #4ade80; margin-bottom: 1rem; }
45
+ p { color: #aaa; }
46
+ </style>
47
+ </head>
48
+ <body>
49
+ <div class="container">
50
+ <h1>Authorization Successful</h1>
51
+ <p>You can close this window and return to EasBot.</p>
52
+ </div>
53
+ <script>setTimeout(() => window.close(), 2000);</script>
54
+ </body>
55
+ </html>`,cc=e=>`<!DOCTYPE html>
56
+ <html>
57
+ <head>
58
+ <title>EasBot - Authorization Failed</title>
59
+ <style>
60
+ body { font-family: system-ui, -apple-system, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #1a1a2e; color: #eee; }
61
+ .container { text-align: center; padding: 2rem; }
62
+ h1 { color: #f87171; margin-bottom: 1rem; }
63
+ p { color: #aaa; }
64
+ .error { color: #fca5a5; font-family: monospace; margin-top: 1rem; padding: 1rem; background: rgba(248,113,113,0.1); border-radius: 0.5rem; }
65
+ </style>
66
+ </head>
67
+ <body>
68
+ <div class="container">
69
+ <h1>Authorization Failed</h1>
70
+ <p>An error occurred during authorization.</p>
71
+ <div class="error">${e}</div>
72
+ </div>
73
+ </body>
74
+ </html>`,wr;(d=>{let e,t=new Map,n=300*1e3;async function o(){if(e)return;if(await i()){br.info("oauth callback server already running on another instance",{port:yr});return}e=createServer((f,a)=>{let p=new URL(f.url||"",`http://localhost:${yr}`);if(p.pathname!==Am){a.writeHead(404,{"Content-Type":"text/plain"}),a.end("Not found");return}let u=p.searchParams.get("code"),g=p.searchParams.get("state"),h=p.searchParams.get("error"),S=p.searchParams.get("error_description");if(br.info("received oauth callback",{hasCode:!!u,state:g,error:h}),!g){let y="Missing required state parameter - potential CSRF attack";br.error("oauth callback missing state parameter",{url:p.toString()}),a.writeHead(400,{"Content-Type":"text/html"}),a.end(cc(y));return}if(h){let y=S||h;if(t.has(g)){let x=t.get(g);clearTimeout(x.timeout),t.delete(g),x.reject(new Error(y));}a.writeHead(200,{"Content-Type":"text/html"}),a.end(cc(y));return}if(!u){a.writeHead(400,{"Content-Type":"text/html"}),a.end(cc("No authorization code provided"));return}if(!t.has(g)){let y="Invalid or expired state parameter - potential CSRF attack";br.error("oauth callback with invalid state",{state:g,pendingStates:Array.from(t.keys())}),a.writeHead(400,{"Content-Type":"text/html"}),a.end(cc(y));return}let A=t.get(g);clearTimeout(A.timeout),t.delete(g),A.resolve(u),a.writeHead(200,{"Content-Type":"text/html"}),a.end(Rx);}).listen(yr),br.info("oauth callback server started",{port:yr});}d.ensureRunning=o;function s(m){return new Promise((f,a)=>{let p=setTimeout(()=>{t.has(m)&&(t.delete(m),a(new Error("OAuth callback timeout - authorization took too long")));},n);t.set(m,{resolve:f,reject:a,timeout:p});})}d.waitForCallback=s;function r(m){let f=t.get(m);f&&(clearTimeout(f.timeout),t.delete(m),f.reject(new Error("Authorization cancelled")));}d.cancelPending=r;async function i(){return new Promise(m=>{let f=connect({host:"127.0.0.1",port:yr});f.on("connect",()=>{f.end(),m(true);}),f.on("error",()=>{m(false);});})}d.isPortInUse=i;async function c(){e&&(e.close(),e=void 0,br.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;})(wr||(wr={}));var ze;(M=>{let e=a.create({service:"mcp"}),t=3e4;M.ToolsChanged=a$5.define("mcp.tools.changed",F.object({server:F.string()})),M.BrowserOpenFailed=a$5.define("mcp.browser.open.failed",F.object({mcpName:F.string(),url:F.string()})),M.Failed=NamedError.create("MCPFailed",F.object({name:F.string()}));function r(v){return typeof v=="object"&&v!==null&&"type"in v}async function i(){let T=(await he.get()).mcp??{},R={},j={};return await Promise.all(Object.entries(T).map(async([U,Y])=>{if(!r(Y)){e.error("Ignoring MCP config entry without type",{key:U});return}if(Y.enabled===false)return;let J=await p(U,Y).catch(()=>{});J&&(R[U]=J),j[U]={name:U,config:Y,scope:Y.scope};})),{clients:R,configInfo:j}}let c;function l(){return c||(c=_.state(i,async v=>{await initLog$3({logDir:a$1.Path.log,logFile:"mcp.log",level:a.getLevel(),print:false}),await Promise.all(Object.values(v.clients).map(T=>T.disconnect().catch(R=>{e.error("Failed to close MCP client",{error:R});}))),O.clear();})),c}async function d(){return l()()}function m(v){return v?v.status:{status:"disconnected"}}async function f(v,T){let R=await T.listPrompts().catch(U=>(e.error("failed to get prompts",{clientName:v,error:U.message}),[])),j={};for(let U of R){let Y=v.replace(/[^a-zA-Z0-9_-]/g,"_"),J=U.name.replace(/[^a-zA-Z0-9_-]/g,"_"),ee=Y+":"+J;j[ee]={...U,client:v};}return j}async function a$2(v,T){let R=await T.listResources().catch(U=>(e.error("failed to get resources",{clientName:v,error:U.message}),[])),j={};for(let U of R){let Y=v.replace(/[^a-zA-Z0-9_-]/g,"_"),J=U.name.replace(/[^a-zA-Z0-9_-]/g,"_"),ee=Y+":"+J;j[ee]={...U,client:v};}return j}async function p(v,T){if(T.enabled===false){e.info("mcp server disabled",{key:v});return}e.info("found",{key:v,type:T.type});let R=new MCPClient;if(T.type==="remote"){let U=T.oauth===false,Y=typeof T.oauth=="object"?T.oauth:void 0,J={type:"remote",url:T.url,headers:T.headers,oauth:U?false:Y,timeout:T.timeout},ee=T.timeout??t;try{await Pl(R.connect(v,J),ee),R.setToolListChangedHandler(async()=>{e.info("tools list changed notification received",{server:v}),await pe.publish(M.ToolsChanged,{server:v});}),e.info("connected",{key:v});}catch(se){R.isAuthRequired()?(O.set(v,R),pe.publish(b$2.ToastShow,{title:"MCP Authentication Required",message:`Server "${v}" requires authentication. Run: easbot mcp auth ${v}`,variant:"warning",duration:8e3}).catch(ae=>e.debug("failed to show toast",{error:ae}))):R.isClientRegistrationRequired()?pe.publish(b$2.ToastShow,{title:"MCP Authentication Required",message:`Server "${v}" requires a pre-registered client ID. Add clientId to your config.`,variant:"warning",duration:8e3}).catch(ae=>e.debug("failed to show toast",{error:ae})):e.error("remote mcp connection failed",{key:v,error:se instanceof Error?se.message:String(se)});}}if(T.type==="local"){if(!T.command){e.error("MCP command is empty",{key:v});return}let U={type:"local",command:[T.command,...T.args??[]],cwd:_.directory,environment:T.env,timeout:T.timeout},Y=T.timeout??t;try{await Pl(R.connect(v,U),Y),R.setToolListChangedHandler(async()=>{e.info("tools list changed notification received",{server:v}),await pe.publish(M.ToolsChanged,{server:v});}),e.info("local mcp connected",{key:v});}catch(J){e.error("local mcp startup failed",{key:v,command:T.command,args:T.args,cwd:_.directory,error:J instanceof Error?J.message:String(J)});}}if(R.status.status!=="connected")return R;let j=await Pl(Promise.resolve(R.listTools()).then(U=>({tools:Object.values(U).map(Y=>Y)})),T.timeout??t).catch(U=>{e.error("failed to get tools from client",{key:v,error:U});});if(!j){await R.disconnect().catch(U=>{e.error("Failed to close MCP client",{error:U});});return}return e.info("create() successfully created client",{key:v,toolCount:j.tools.length}),R}async function u(v,T){let R=await d(),j=await p(v,T);if(!j)return {status:await g()};let U=R.clients[v];return U&&await U.disconnect().catch(Y=>{e.error("Failed to close existing MCP client",{name:v,error:Y});}),R.clients[v]=j,{status:await g()}}M.add=u;async function g(){let v=await d(),R=(await he.get()).mcp??{},j={};for(let[U,Y]of Object.entries(R)){if(!r(Y))continue;let J=v.clients[U];Y.enabled===false?j[U]={status:"disabled"}:j[U]=m(J);}return j}M.status=g;async function h(){return d().then(v=>v.clients)}M.clients=h;async function S(){return d().then(v=>v.configInfo)}M.configInfo=S;async function A(v){return (await S())[v]}M.getConfig=A;async function y(v){let j=((await he.get()).mcp??{})[v];if(!j){e.error("MCP config not found",{name:v});return}if(!r(j)){e.error("Ignoring MCP connect request for config without type",{name:v});return}let U=await p(v,j),Y=await d();if(U){let J=Y.clients[v];J&&await J.disconnect().catch(ee=>{e.error("Failed to close existing MCP client",{name:v,error:ee});}),Y.clients[v]=U;}}M.connect=y;async function x(v){let T=await d(),R=T.clients[v];R&&(await R.disconnect().catch(j=>{e.error("Failed to close MCP client",{name:v,error:j});}),delete T.clients[v]);}M.disconnect=x;async function b(){let v={},T=await he.get(),R=await h(),j=T.experimental?.mcp_timeout;for(let[U,Y]of Object.entries(R)){if(Y.status.status!=="connected")continue;let J=await Y.listTools().catch(ee=>(e.error("failed to get tools",{clientName:U,error:ee.message}),{}));for(let[ee,se]of Object.entries(J)){let ae=se,we=U.replace(/[^a-zA-Z0-9_-]/g,"_"),ie=ee.replace(/[^a-zA-Z0-9_-]/g,"_"),Z=we+"_"+ie;v[Z]=await w(ae,Y,j);}}return v}M.tools=b;async function w(v,T,R){let j=v.inputSchema,U={...j,type:"object",properties:j.properties??{},additionalProperties:false};return dynamicTool({description:v.description??"",inputSchema:jsonSchema(U),execute:async Y=>{let J=await T.callTool(v.name,Y||{},R);return {content:J.content.map(ee=>ee.type==="text"?{type:"text",text:ee.text??""}:ee.type==="image"?{type:"image",data:ee.data??"",mimeType:ee.mimeType}:ee.type==="resource"&&ee.resource?{type:"resource",resource:ee.resource}:{type:"text",text:String(ee)}),metadata:J.metadata}}})}async function C(){let v=await h(),T=await S(),R=[];for(let[j,U]of Object.entries(v)){if(U.status.status!=="connected")continue;let Y=await f(j,U),ee=T[j]?.scope??"all";for(let[se,ae]of Object.entries(Y))R.push([se,{...ae,scope:ee}]);}return Object.fromEntries(R)}M.prompts=C;async function k(){let v=await h();return Object.fromEntries((await Promise.all(Object.entries(v).map(async([R,j])=>j.status.status!=="connected"?[]:Object.entries(await a$2(R,j))))).flat())}M.resources=k;async function P(v,T,R){let U=(await h())[v];if(!U){e.warn("client not found for prompt",{clientName:v});return}return U.getPrompt(T,R).catch(Y=>{e.error("failed to get prompt from MCP server",{clientName:v,promptName:T,error:Y.message});})}M.getPrompt=P;async function E(v,T){let j=(await h())[v];if(!j){e.warn("client not found for resource",{clientName:v});return}return j.readResource(T).catch(U=>{e.error("failed to read resource from MCP server",{clientName:v,resourceUri:T,error:U.message});})}M.readResource=E;let O=new Map;async function N(v){let R=(await he.get()).mcp?.[v];if(!R)throw new Error(`MCP server not found: ${v}`);if(!r(R))throw new Error(`MCP server ${v} is disabled or missing configuration`);if(R.type!=="remote")throw new Error(`MCP server ${v} is not a remote server`);if(R.oauth===false)throw new Error(`MCP server ${v} has OAuth explicitly disabled`);await wr.ensureRunning();let j=Array.from(crypto.getRandomValues(new Uint8Array(32))).map(J=>J.toString(16).padStart(2,"0")).join("");await Tn.updateOAuthState(v,j);let U=typeof R.oauth=="object"?R.oauth:void 0,Y=new MCPClient;try{return await Y.connect(v,{type:"remote",url:R.url,headers:R.headers,oauth:U,timeout:R.timeout}),{authorizationUrl:""}}catch(J){if(Y.isAuthRequired())return O.set(v,Y),{authorizationUrl:Y.getAuthorizationUrl()};throw J}}M.startAuth=N;async function L(v){let{authorizationUrl:T}=await N(v);if(!T){let ee=(await d()).clients[v];return m(ee)}let R=await Tn.getOAuthState(v);if(!R)throw new Error("OAuth state not found");e.info("opening browser for oauth",{mcpName:v,url:T,state:R});let j=wr.waitForCallback(R);try{let J=await Lx(T);await new Promise((ee,se)=>{let ae=setTimeout(()=>ee(),500);J.on("error",we=>{clearTimeout(ae),se(we);}),J.on("exit",we=>{we!==null&&we!==0&&(clearTimeout(ae),se(new Error(`Browser open failed with exit code ${we}`)));});});}catch(J){e.warn("failed to open browser, user must open URL manually",{mcpName:v,error:J}),await pe.publish(M.BrowserOpenFailed,{mcpName:v,url:T});}let U=await j;if(await Tn.getOAuthState(v)!==R)throw await Tn.clearOAuthState(v),new Error("OAuth state mismatch");return await Tn.clearOAuthState(v),K(v,U)}M.authenticate=L;async function K(v,T){let R=O.get(v);if(!R)throw new Error(`No pending OAuth flow for MCP server: ${v}`);try{await R.finishAuth(T),await Tn.clearCodeVerifier(v);let U=(await he.get()).mcp?.[v];if(!U||!r(U))throw new Error(`MCP server not found: ${v}`);O.delete(v),await u(v,U);let Y=await d();return m(Y.clients[v])}catch(j){return e.error("failed to finish oauth",{mcpName:v,error:j}),{status:"failed",error:j instanceof Error?j.message:String(j)}}}M.finishAuth=K;async function Q(v){await Tn.remove(v),wr.cancelPending(v),O.delete(v),await Tn.clearOAuthState(v),e.info("removed oauth credentials",{mcpName:v});}M.removeAuth=Q;async function ue(v){let R=(await he.get()).mcp?.[v];return !R||!r(R)?false:R.type==="remote"&&R.oauth!==false}M.supportsOAuth=ue;async function D(v){return !!(await Tn.get(v))?.tokens}M.hasStoredTokens=D;async function I(v){return await D(v)?await Tn.isTokenExpired(v)?"expired":"authenticated":"not_authenticated"}M.getAuthStatus=I;})(ze||(ze={}));function Pl(e,t){return new Promise((n,o)=>{let s=setTimeout(()=>o(new Error(`Operation timed out after ${t}ms`)),t);e.then(r=>{clearTimeout(s),n(r);}).catch(r=>{clearTimeout(s),o(r);});})}var ps={};a$7(ps,{create:()=>eT,createAgent:()=>wh,getAgent:()=>ld,getDefaultAgent:()=>QP,list:()=>ZP,listAgents:()=>bh});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-YYOW743S.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(g=>g.startsWith("tool_"));for(let g of u)Identifier.timestamp(g)>=a||await Tt__default.unlink(Filesystem.join(f.DIR,g)).catch(()=>{});}f.cleanup=c;function l(a){return a?.permission?Me.evaluate("task","*",a.permission).action!=="deny":false}async function d(a,p={},u){let g=p.maxLines??f.MAX_LINES,h=p.maxBytes??f.MAX_BYTES,S=p.direction??"head",A=a.split(`
75
+ `),y=Buffer.byteLength(a,"utf-8");if(A.length<=g&&y<=h)return {content:a,truncated:false};let x=[],b=0,w=0;if(S==="head")for(b=0;b<A.length&&b<g;b++){let ue=A[b];if(!ue)continue;let D=Buffer.byteLength(ue,"utf-8")+(b>0?1:0);if(w+D>h){break}x.push(ue),w+=D;}else for(b=A.length-1;b>=0&&x.length<g;b--){let ue=A[b];if(!ue)continue;let D=Buffer.byteLength(ue,"utf-8")+(x.length>0?1:0);if(w+D>h){break}x.unshift(ue),w+=D;}let k=A.length-x.length,P=y-w,E=x.join(`
76
+ `),O=Identifier.ascending("tool"),N=Filesystem.join(f.DIR,O);await Tt__default.mkdir(f.DIR,{recursive:true}).catch(()=>{}),await Tt__default.writeFile(N,a,"utf-8");let L=l(u)?`The tool call succeeded but the output was truncated. Full output saved to: ${N}
77
+ Use the Task tool to have explore agent process this file with Grep and Read (with offset/limit). Do NOT read the full file yourself - delegate to save context.`:`The tool call succeeded but the output was truncated. Full output saved to: ${N}
78
+ Use Grep to search the full content or Read with offset/limit to view specific sections.`,K=`${k}/${A.length} lines (${P}/${y} bytes) truncated`;return {content:S==="head"?`${E}
79
+
80
+ ...${K}...
81
+
82
+ ${L}`:`...${K}...
83
+
84
+ ${L}
85
+
86
+ ${E}`,truncated:true,outputPath:N}}f.output=d;function m(a,p){if(!a.truncated)return "";let{outputPath:u}=a;return l(p)?`The tool call succeeded but the output was truncated. Full output saved to: ${u}
87
+ Use the Task tool to have explore agent process this file (with Grep and Read tools). Do NOT read the full file yourself - delegate to save context.`:`The tool call succeeded but the output was truncated. Full output saved to: ${u}
88
+ Use Grep to search the full content, or use Read tool with offset/limit parameters to view specific sections.`}f.formatHint=m;})(Ve||(Ve={}));a.create({service:"provider-transform"});function $x(e){if(e.startsWith("image/"))return "image";if(e.startsWith("audio/"))return "audio";if(e.startsWith("video/"))return "video";if(e==="application/pdf")return "pdf"}var wt;(A=>{A.OUTPUT_TOKEN_MAX=a$2.EASBOT_OUTPUT_TOKEN_MAX||32e3;function t(y){switch(y){case "@ai-sdk/github-copilot":return "copilot";case "@ai-sdk/openai":case "@ai-sdk/azure":return "openai";case "@ai-sdk/amazon-bedrock":return "bedrock";case "@ai-sdk/anthropic":case "@ai-sdk/google-vertex/anthropic":return "anthropic";case "@ai-sdk/google-vertex":case "@ai-sdk/google":return "google";case "@ai-sdk/gateway":return "gateway";case "@openrouter/ai-sdk-provider":return "openrouter";case "@easbot/ollama-sdk":return "ollama";case "@easbot/local-model-sdk":return "easbot-local"}}function n(y,x,b){if(x.api.npm==="@ai-sdk/anthropic"&&(y=y.map(w=>{if(typeof w.content=="string")return w.content===""?void 0:w;if(!Array.isArray(w.content))return w;let C=w.content.filter(k=>k.type==="text"||k.type==="reasoning"?k.text!=="":true);if(C.length!==0)return {...w,content:C}}).filter(w=>w!==void 0&&w.content!=="")),x.api.id.includes("claude"))return y.map(w=>((w.role==="assistant"||w.role==="tool")&&Array.isArray(w.content)&&(w.content=w.content.map(C=>(C.type==="tool-call"||C.type==="tool-result")&&"toolCallId"in C?{...C,toolCallId:C.toolCallId.replace(/[^a-zA-Z0-9_-]/g,"_")}:C)),w));if(x.providerId==="mistral"||x.api.id.toLowerCase().includes("mistral")||x.api.id.toLocaleLowerCase().includes("devstral")){let w=[];for(let C=0;C<y.length;C++){let k=y[C];if(!k)continue;let P=y[C+1];(k.role==="assistant"||k.role==="tool")&&Array.isArray(k.content)&&(k.content=k.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(k),k.role==="tool"&&P?.role==="user"&&w.push({role:"assistant",content:[{type:"text",text:"Done."}]});}return w}if(typeof x.capabilities.interleaved=="object"&&x.capabilities.interleaved.field){let w=x.capabilities.interleaved.field;return y.map(C=>{if(C.role==="assistant"&&Array.isArray(C.content)){let P=C.content.filter(O=>O.type==="reasoning").map(O=>O.text).join(""),E=C.content.filter(O=>O.type!=="reasoning");return P?{...C,content:E,providerOptions:{...C.providerOptions,openaiCompatible:{...C.providerOptions?.openaiCompatible,[w]:P}}}:{...C,content:E}}return C})}return y}function o(y,x){let b=y.filter(k=>k.role==="system").slice(0,2),w=y.filter(k=>k.role!=="system").slice(-2),C={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 k of unique([...b,...w])){if(!(x==="anthropic"||x.includes("bedrock"))&&Array.isArray(k.content)&&k.content.length>0){let O=k.content[k.content.length-1];if(O&&typeof O=="object"){O.providerOptions=mergeDeep(O.providerOptions??{},C);continue}}k.providerOptions=mergeDeep(k.providerOptions??{},C);}return y}function s(y,x){return y.map(b=>{if(b.role!=="user"||!Array.isArray(b.content))return b;let w=b.content.map(C=>{if(C.type!=="file"&&C.type!=="image")return C;if(C.type==="image"){let N=C.image.toString();if(N.startsWith("data:")){let L=N.match(/^data:([^;]+);base64,(.*)$/);if(L&&(!L[2]||L[2].length===0))return {type:"text",text:"ERROR: Image file is empty or corrupted. Please provide a valid image."}}}let k=C.type==="image"?C.image?.toString()?.split(";")?.[0]?.replace("data:",""):C.mediaType,P=C.type==="file"?C.filename:void 0,E=$x(k??"");return !E||x.capabilities.input[E]?C:{type:"text",text:`ERROR: Cannot read ${P?`"${P}"`:E} (this model does not support ${E} input). Inform the user.`}});return {...b,content:w}})}function r(y,x,b){y=s(y,x),y=n(y,x),(x.providerId==="anthropic"||x.api.id.includes("anthropic")||x.api.id.includes("claude")||x.id.includes("anthropic")||x.id.includes("claude")||x.api.npm==="@ai-sdk/anthropic")&&(y=o(y,x.providerId));let w=t(x.api.npm);if(w&&w!==x.providerId&&x.api.npm!=="@ai-sdk/azure"){let C=k=>{if(!k||!(x.providerId in k))return k;let P={...k};return P[w]=P[x.providerId],delete P[x.providerId],P};y=y.map(k=>Array.isArray(k.content)?{...k,providerOptions:C(k.providerOptions),content:k.content.map(P=>({...P,providerOptions:C(P.providerOptions)}))}:{...k,providerOptions:C(k.providerOptions)});}return y}A.message=r;function i(y){let x=y.id.toLowerCase();if(x.includes("qwen"))return .55;if(!x.includes("claude")){if(x.includes("gemini")||x.includes("glm-4.6")||x.includes("glm-4.7")||x.includes("minimax-m2"))return 1;if(x.includes("kimi-k2"))return x.includes("thinking")||x.includes("k2.")||x.includes("k2p")?1:.6}}A.temperature=i;function c(y){let x=y.id.toLowerCase();if(x.includes("qwen"))return 1;if(x.includes("minimax-m2")||x.includes("kimi-k2.5")||x.includes("kimi-k2p5")||x.includes("gemini"))return .95}A.topP=c;function l(y){let x=y.id.toLowerCase();if(x.includes("minimax-m2"))return x.includes("m2.1")?40:20;if(x.includes("gemini"))return 64}A.topK=l;let d=["low","medium","high"],m=["none","minimal",...d,"xhigh"];function f(y){if(!y.capabilities.reasoning)return {};let x=y.id.toLowerCase();if(x.includes("deepseek")||x.includes("minimax")||x.includes("glm")||x.includes("mistral")||x.includes("kimi")||x.includes("k2p5"))return {};if(x.includes("grok")&&x.includes("grok-3-mini"))return y.api.npm==="@openrouter/ai-sdk-provider"?{low:{reasoning:{effort:"low"}},high:{reasoning:{effort:"high"}}}:{low:{reasoningEffort:"low"},high:{reasoningEffort:"high"}};if(x.includes("grok"))return {};switch(y.api.npm){case "@openrouter/ai-sdk-provider":return !y.id.includes("gpt")&&!y.id.includes("gemini-3")?{}:Object.fromEntries(m.map(b=>[b,{reasoning:{effort:b}}]));case "@ai-sdk/gateway":return Object.fromEntries(m.map(b=>[b,{reasoningEffort:b}]));case "@ai-sdk/github-copilot":{if(y.id.includes("gemini"))return {};if(y.id.includes("claude"))return {thinking:{thinking_budget:4e3}};let b=iife(()=>x.includes("5.1-codex-max")||x.includes("5.2")||x.includes("5.3")?[...d,"xhigh"]:d);return Object.fromEntries(b.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/cerebras":case "@ai-sdk/togetherai":case "@ai-sdk/xai":case "@ai-sdk/deepinfra":case "@ai-sdk/openai-compatible":return Object.fromEntries(d.map(b=>[b,{reasoningEffort:b}]));case "@ai-sdk/azure":{if(x==="o1-mini")return {};let b=["low","medium","high"];return (x.includes("gpt-5-")||x==="gpt-5")&&b.unshift("minimal"),Object.fromEntries(b.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/openai":{if(x==="gpt-5-pro")return {};let b=iife(()=>{if(x.includes("codex"))return x.includes("5.2")||x.includes("5.3")?[...d,"xhigh"]:d;let w=[...d];return (x.includes("gpt-5-")||x==="gpt-5")&&w.unshift("minimal"),y.release_date>="2025-11-13"&&w.unshift("none"),y.release_date>="2025-12-04"&&w.push("xhigh"),w});return Object.fromEntries(b.map(w=>[w,{reasoningEffort:w,reasoningSummary:"auto",include:["reasoning.encrypted_content"]}]))}case "@ai-sdk/anthropic":case "@ai-sdk/google-vertex/anthropic":return {high:{thinking:{type:"enabled",budgetTokens:Math.min(16e3,Math.floor(y.limit.output/2-1))}},max:{thinking:{type:"enabled",budgetTokens:Math.min(31999,y.limit.output-1)}}};case "@ai-sdk/amazon-bedrock":return y.api.id.includes("anthropic")?{high:{reasoningConfig:{type:"enabled",budgetTokens:16e3}},max:{reasoningConfig:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(d.map(b=>[b,{reasoningConfig:{type:"enabled",maxReasoningEffort:b}}]));case "@ai-sdk/google-vertex":case "@ai-sdk/google":return x.includes("2.5")?{high:{thinkingConfig:{includeThoughts:true,thinkingBudget:16e3}},max:{thinkingConfig:{includeThoughts:true,thinkingBudget:24576}}}:Object.fromEntries(["low","high"].map(b=>[b,{includeThoughts:true,thinkingLevel:b}]));case "@ai-sdk/mistral":return {};case "@ai-sdk/cohere":return {};case "@ai-sdk/groq":{let b=["none",...d];return Object.fromEntries(b.map(w=>[w,{includeThoughts:true,thinkingLevel:w}]))}case "@ai-sdk/perplexity":return {};case "@mymediset/sap-ai-provider":case "@jerome-benoit/sap-ai-provider-v2":return y.api.id.includes("anthropic")?{high:{thinking:{type:"enabled",budgetTokens:16e3}},max:{thinking:{type:"enabled",budgetTokens:31999}}}:Object.fromEntries(d.map(b=>[b,{reasoningEffort:b}]))}return {}}A.variants=f;function a(y){let x={};(y.model.providerId==="openai"||y.model.api.npm==="@ai-sdk/openai"||y.model.api.npm==="@ai-sdk/github-copilot")&&(x.store=false),y.model.api.npm==="@openrouter/ai-sdk-provider"&&(x.usage={include:true},y.model.api.id.includes("gemini-3")&&(x.reasoning={effort:"high"})),(y.model.providerId==="baseten"||y.model.providerId==="easbot"&&["kimi-k2-thinking","glm-4.6"].includes(y.model.api.id))&&(x.chat_template_args={enable_thinking:true}),["zai","zhipuai"].includes(y.model.providerId)&&y.model.api.npm==="@ai-sdk/openai-compatible"&&(x.thinking={type:"enabled",clear_thinking:false}),(y.model.providerId==="openai"||y.providerOptions?.setCacheKey)&&(x.promptCacheKey=y.sessionId),(y.model.api.npm==="@ai-sdk/google"||y.model.api.npm==="@ai-sdk/google-vertex")&&(x.thinkingConfig={includeThoughts:true},y.model.api.id.includes("gemini-3")&&(x.thinkingConfig.thinkingLevel="high"));let b=y.model.api.id.toLowerCase();return (y.model.api.npm==="@ai-sdk/anthropic"||y.model.api.npm==="@ai-sdk/google-vertex/anthropic")&&(b.includes("k2p5")||b.includes("kimi-k2.5")||b.includes("kimi-k2p5"))&&(x.thinking={type:"enabled",budgetTokens:Math.min(16e3,Math.floor(y.model.limit.output/2-1))}),y.model.providerId==="alibaba-cn"&&y.model.capabilities.reasoning&&y.model.api.npm==="@ai-sdk/openai-compatible"&&!b.includes("kimi-k2-thinking")&&(x.enable_thinking=true),y.model.api.id.includes("gpt-5")&&!y.model.api.id.includes("gpt-5-chat")&&(y.model.api.id.includes("gpt-5-pro")||(x.reasoningEffort="medium",x.reasoningSummary="auto"),y.model.api.id.includes("gpt-5.")&&!y.model.api.id.includes("codex")&&!y.model.api.id.includes("-chat")&&y.model.providerId!=="azure"&&(x.textVerbosity="low"),y.model.providerId.startsWith("easbot")&&(x.promptCacheKey=y.sessionId,x.include=["reasoning.encrypted_content"],x.reasoningSummary="auto")),y.model.providerId==="venice"&&(x.promptCacheKey=y.sessionId),x}A.options=a;function p(y){return y.providerId==="openai"||y.api.npm==="@ai-sdk/openai"||y.api.npm==="@ai-sdk/github-copilot"?y.api.id.includes("gpt-5")?y.api.id.includes("5.")?{store:false,reasoningEffort:"low"}:{store:false,reasoningEffort:"minimal"}:{store:false}:y.providerId==="google"?y.api.id.includes("gemini-3")?{thinkingConfig:{thinkingLevel:"minimal"}}:{thinkingConfig:{thinkingBudget:0}}:y.providerId==="openrouter"?y.api.id.includes("google")?{reasoning:{enabled:false}}:{reasoningEffort:"minimal"}:{}}A.smallOptions=p;let u={amazon:"bedrock"};function g(y,x){if(y.api.npm==="@ai-sdk/gateway"){let w=y.api.id.indexOf("/"),C=w>0?y.api.id.slice(0,w):void 0,k=C?u[C]??C:void 0,P=x.gateway,E=Object.fromEntries(Object.entries(x).filter(([L])=>L!=="gateway")),O=Object.keys(E).length>0,N={};return P!==void 0&&(N.gateway=P),O&&(k?N[k]=E:P&&typeof P=="object"&&!Array.isArray(P)?N.gateway={...P,...E}:N.gateway=E),N}return {[t(y.api.npm)??y.providerId]:x}}A.providerOptions=g;function h(y){return Math.min(y.limit.output,A.OUTPUT_TOKEN_MAX)||A.OUTPUT_TOKEN_MAX}A.maxOutputTokens=h;function S(y,x){if(y.providerId==="google"||y.api.id.includes("gemini")){let b=w=>{if(w===null||typeof w!="object")return w;if(Array.isArray(w))return w.map(b);let C={};for(let[k,P]of Object.entries(w))k==="enum"&&Array.isArray(P)?(C[k]=P.map(E=>String(E)),(C.type==="integer"||C.type==="number")&&(C.type="string")):typeof P=="object"&&P!==null?C[k]=b(P):C[k]=P;return C.type==="object"&&C.properties&&Array.isArray(C.required)&&(C.required=C.required.filter(k=>k in C.properties)),C.type==="array"&&(C.items==null&&(C.items={}),typeof C.items=="object"&&!Array.isArray(C.items)&&!C.items.type&&(C.items.type="string")),C.type&&C.type!=="object"&&(delete C.properties,delete C.required),C};x=b(x);}return x}A.schema=S;})(wt||(wt={}));function zt(e,t){let n=typeof e=="string"?e:"anonymous",o=typeof e=="string"?t:e,{init:s}=o,r=s instanceof Function?s:()=>s;return {name:n,init:r}}var Xo;(s=>{let e=a.create({service:"llm"});s.OUTPUT_TOKEN_MAX=wt.OUTPUT_TOKEN_MAX;async function n(r){let i=e.clone().tag("providerId",r.model.providerId).tag("modelId",r.model.id).tag("sessionId",r.sessionId).tag("small",(r.small??false).toString()).tag("agent",r.agent.name).tag("mode",r.agent.mode);i.info("stream",{modelId:r.model.id,providerId:r.model.providerId});let[c,l,d,m]=await Promise.all([xe.getLanguage(r.model),he.get(),xe.getProvider(r.model.providerId),Qe.get(r.model.providerId)]),f=d?.id==="openai"&&m?.type==="oauth",a=[r.system.filter(E=>E).join(`
89
+ `)],p=a[0];if(a.length>2&&a[0]===p){let E=a.slice(1);a.length=0,a.push(p,E.join(`
90
+ `));}let u=!r.small&&r.model.variants&&r.user.variant?r.model.variants[r.user.variant]:{},g=r.small?wt.smallOptions(r.model):wt.options({model:r.model,sessionId:r.sessionId,providerOptions:d?.options??{}}),h=pipe(g,mergeDeep(r.model.options??{}),mergeDeep(r.agent.options??{}),mergeDeep(u??{}));f&&(h.instructions=a.join(`
91
+ `));let S=await Le.triggerEvent(HookEvent.LlmParams,{sessionId:r.sessionId,agent:r.agent.name,model:r.model,provider:d,message:r.user}),A=Object.assign({temperature:r.model.capabilities.temperature?r.agent.temperature??wt.temperature(r.model):void 0,topP:r.agent.topP??wt.topP(r.model),topK:wt.topK(r.model),options:h},S.output??{}),x=(await Le.triggerEvent(HookEvent.LlmHeaders,{sessionId:r.sessionId,agent:r.agent.name,model:r.model,provider:d,message:r.user})).output?.headers??{},b=f||d?.id?.includes("github-copilot")?void 0:wt.maxOutputTokens(r.model),w=r.tools;(d?.options?.litellmProxy===true||r.model.providerId.toLowerCase().includes("litellm")||r.model.api.id.toLowerCase().includes("litellm")||r.model.providerId.includes("github-copilot"))&&Object.keys(w).length===0&&o(r.messages)&&(w._noop=tool({description:"Do not call this tool. It exists only for API compatibility and must never be invoked.",inputSchema:jsonSchema({type:"object",properties:{reason:{type:"string",description:"Unused"}}}),execute:async()=>({output:"",title:"",metadata:{}})}));let k=[...a.map(E=>({role:"system",content:E??""}))],P=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:A.temperature,topP:A.topP,topK:A.topK,providerOptions:wt.providerOptions(r.model,A.options??{}),activeTools:Object.keys(w).filter(E=>E!=="invalid"),tools:w,maxOutputTokens:b,abortSignal:r.abort,headers:{...r.model.providerId.startsWith("easbot")?{"x-easbot-project":_.project.id,"x-easbot-session":r.sessionId,"x-easbot-request":r.user.id,"x-easbot-client":a$2.EASBOT_CLIENT}:r.model.providerId!=="anthropic"?{"User-Agent":`easbot/${b$3.getVersion()}`}:void 0,...r.model.headers,...x},maxRetries:r.retries??0,system:k,messages:r.messages,model:wrapLanguageModel({model:c,middleware:[{specificationVersion:"v3",async transformParams(E){if(E.type==="stream"){let O=E.params.prompt;O&&Array.isArray(O)&&(E.params.prompt=wt.message(O,r.model,h));}return E.params}}]}),experimental_telemetry:{isEnabled:l.experimental?.openTelemetry,metadata:{userId:l.username??"unknown",sessionId:r.sessionId}}});return i.debug("streamText returned",{hasFullStream:!!P.fullStream,fullStreamType:typeof P.fullStream,resultKeys:Object.keys(P),baseStreamType:typeof P.baseStream,hasBaseStream:!!P.baseStream,textStreamType:typeof P.textStream,hasTextStream:!!P.textStream}),P}s.stream=n;function o(r){for(let i of r)if(Array.isArray(i.content)){for(let c of i.content)if(c.type==="tool-call"||c.type==="tool-result")return true}return false}s.hasToolCalls=o;})(Xo||(Xo={}));var Qo;(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 h=d.slice(f+1,f+4).match(/^[0-7]{1,3}/);if(!h){m.push(p.charCodeAt(0)),f++;continue}m.push(parseInt(h[0],8)),f+=h[0].length;continue}let u=p==="n"?`
92
+ `:p==="r"?"\r":p==="t"?" ":p==="b"?"\b":p==="f"?"\f":p==="v"?"\v":p==="\\"||p==='"'?p:void 0;m.push((u??p).charCodeAt(0)),f++;}return Buffer.from(m).toString()}c.summarize=fn$1(F.object({sessionId:F.string(),messageId:F.string()}),async l=>{let d=await X.messages({sessionId:l.sessionId});await Promise.all([o({sessionId:l.sessionId,messages:d}),s({messageId:l.messageId,messages:d})]);});async function o(l){let d=await i({messages:l.messages});await X.update(l.sessionId,m=>{m.summary={additions:d.reduce((f,a)=>f+a.additions,0),deletions:d.reduce((f,a)=>f+a.deletions,0),files:d.length};}),await a$6.write(["session_diff",l.sessionId],d),await pe.publish(X.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 X.updateMessage(f);let p=m.parts.find(u=>u.type==="text"&&!u.synthetic);if(p&&!f.summary?.title){let u=await Ue.get("title");if(!u)return;let g=await Xo.stream({agent:u,user:f,tools:{},model:u.model?await xe.getModel(u.model.providerId,u.model.modelId):await xe.getSmallModel(f.model.providerId)??await xe.getModel(f.model.providerId,f.model.modelId),small:true,messages:[{role:"user",content:`
93
+ The following is the text to summarize:
94
+ <text>
95
+ ${p?.text??""}
96
+ </text>
97
+ `}],abort:new AbortController().signal,sessionId:f.sessionId,system:[u.prompt??""],retries:3});e.debug("stream object received",{hasFullStream:!!g.fullStream,hasText:!!g.text,streamKeys:Object.keys(g)});let h=await g.text;e.debug("title",{title:h}),f.summary.title=h,await X.updateMessage(f);}}c.diff=fn$1(F.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message").optional()}),async l=>{let d=await a$6.read(["session_diff",l.sessionId]).catch(()=>[]),m=d.map(a=>{let p=t(a.file);return p===a.file?a:{...a,file:p}});return m.some((a,p)=>a.file!==d[p]?.file)&&a$6.write(["session_diff",l.sessionId],m).catch(()=>{}),m});async function i(l){let d,m;for(let f of l.messages){if(!d){for(let a of f.parts)if(a.type==="step-start"&&a.snapshot){d=a.snapshot;break}}for(let a of f.parts)a.type==="step-finish"&&a.snapshot&&(m=a.snapshot);}return d&&m?yt.diffFull(d,m):[]}c.computeDiff=i;})(Qo||(Qo={}));var ao;(r=>{let e=a.create({service:"session.revert"});r.RevertInput=F.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message"),partId:Identifier.schema("part").optional()});async function n(i){Je.assertNotBusy(i.sessionId);let c=await X.messages({sessionId:i.sessionId}),l,d=await X.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 g=p.some(h=>["text","tool"].includes(h.type))?i.partId:void 0;m={messageId:!g&&l?l.id:a.info.id,partId:g};}p.push(u);}}}if(m){let a=await X.get(i.sessionId);m.snapshot=a.revert?.snapshot??await yt.track(),await yt.revert(f),m.snapshot&&(m.diff=await yt.diff(m.snapshot));let p=c.filter(g=>g.info.id>=m.messageId),u=await Qo.computeDiff({messages:p});return await a$6.write(["session_diff",i.sessionId],u),await pe.publish(X.Event.Diff,{sessionId:i.sessionId,diff:u}),X.update(i.sessionId,g=>{g.revert=m,g.summary={additions:u.reduce((h,S)=>h+S.additions,0),deletions:u.reduce((h,S)=>h+S.deletions,0),files:u.length};})}return d}r.revert=n;async function o(i){e.debug("unreverting",i),Je.assertNotBusy(i.sessionId);let c=await X.get(i.sessionId);return c.revert?(c.revert.snapshot&&await yt.restore(c.revert.snapshot),await X.update(i.sessionId,d=>{d.revert=void 0;})):c}r.unrevert=o;async function s(i){if(!i.revert)return;let c=i.id,l=await X.messages({sessionId:c}),d=i.revert.messageId,[m,f]=splitWhen(l,p=>p.info.id===d);l=m;for(let p of f)await a$6.remove(["message",c,p.info.id]),await pe.publish(ve.Event.Removed,{sessionId:c,messageId:p.info.id});let a=m.at(-1);if(i.revert.partId&&a){let p=i.revert.partId,[u,g]=splitWhen(a.parts,h=>h.id===p);a.parts=u;for(let h of g)await a$6.remove(["part",a.info.id,h.id]),await pe.publish(ve.Event.PartRemoved,{sessionId:c,messageId:a.info.id,partId:h.id});}await X.update(c,p=>{p.revert=void 0;});}r.cleanup=s;})(ao||(ao={}));async function Zo(e){for await(let t of ve.stream(e))if(t.info.role==="user"&&t.info.model)return t.info.model;return xe.defaultModel()}async function Lm(e){for await(let t of ve.stream(e))if(t.info.role==="user")return t.info}var xr;(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;})(xr||(xr={}));var Mt;(l=>{l.Info=F.union([F.object({type:F.literal("idle")}),F.object({type:F.literal("retry"),attempt:F.number(),message:F.string(),next:F.number()}),F.object({type:F.literal("busy")})]).meta({ref:"SessionStatus"}),l.Event={Status:a$5.define("session.status",F.object({sessionId:F.string(),status:l.Info}))};let n;function o(){return n||(n=_.state(async()=>({}))),n}function s(){return o()()}async function r(d){return (await s())[d]??{type:"idle"}}l.get=r;async function i(){return s()}l.list=i;async function c(d,m){if(await pe.publish(l.Event.Status,{sessionId:d,status:m}),m.type==="idle"){let a=await s();delete a[d];return}let f=await s();f[d]=m;}l.set=c;})(Mt||(Mt={}));var Ot;(g=>{let e=a.create({service:"question"});g.Option=F.object({label:F.string().describe("Display text (1-5 words, concise)"),description:F.string().describe("Explanation of choice")}).meta({ref:"QuestionOption"}),g.Info=F.object({question:F.string().describe("Complete question"),header:F.string().describe("Very short label (max 30 chars)"),options:F.array(g.Option).describe("Available choices"),multiple:F.boolean().optional().describe("Allow selecting multiple choices"),custom:F.boolean().optional().describe("Allow typing a custom answer (default: true)")}).meta({ref:"QuestionInfo"}),g.Request=F.object({id:Identifier.schema("question"),sessionId:Identifier.schema("session"),questions:F.array(g.Info).describe("Questions to ask"),tool:F.object({messageId:F.string(),callId:F.string()}).optional()}).meta({ref:"QuestionRequest"}),g.Answer=F.array(F.string()).meta({ref:"QuestionAnswer"}),g.Reply=F.object({answers:F.array(g.Answer).describe("User answers in order of questions (each answer is an array of selected labels)")}),g.Event={Asked:a$5.define("question.asked",g.Request),Replied:a$5.define("question.replied",F.object({sessionId:F.string(),requestId:F.string(),answers:F.array(g.Answer)})),Rejected:a$5.define("question.rejected",F.object({sessionId:F.string(),requestId:F.string()}))};let c;function l(){return c||(c=_.state(async()=>({pending:{}}))),c}function d(){return l()()}async function m(h){let S=await d(),A=Identifier.ascending("question");return e.debug("asking",{id:A,questions:h.questions.length}),new Promise((y,x)=>{let b={id:A,sessionId:h.sessionId,questions:h.questions,tool:h.tool};S.pending[A]={info:b,resolve:y,reject:x},pe.publish(g.Event.Asked,b);})}g.ask=m;async function f(h){let S=await d(),A=S.pending[h.requestId];if(!A){e.warn("reply for unknown request",{requestId:h.requestId});return}delete S.pending[h.requestId],e.info("replied",{requestId:h.requestId,answers:h.answers}),await pe.publish(g.Event.Replied,{sessionId:A.info.sessionId,requestId:A.info.id,answers:h.answers}),A.resolve(h.answers);}g.reply=f;async function a$1(h){let S=await d(),A=S.pending[h];if(!A){e.warn("reject for unknown request",{requestId:h});return}delete S.pending[h],e.debug("rejected",{requestId:h}),await pe.publish(g.Event.Rejected,{sessionId:A.info.sessionId,requestId:A.info.id}),A.reject(new p);}g.reject=a$1;class p extends Error{constructor(){super("The user dismissed this question");}}g.RejectedError=p;async function u(){return d().then(h=>Object.values(h.pending).map(S=>S.info))}g.list=u;})(Ot||(Ot={}));var vr;(o=>{let t=a.create({service:"session.processor"});function n(s){let r={},i=false,c=0,l=false;s.mode??"general";return {get message(){return s.assistantMessage},partFromToolCall(f){return r[f]},async process(f){l=false;let a=(await he.get()).experimental?.continue_loop_on_deny!==true;for(;;){try{let u,g={},h=await Xo.stream(f);for await(let S of h.fullStream){switch(s.abort.throwIfAborted(),S.type){case "start":await Mt.set(s.sessionId,{type:"busy"});break;case "reasoning-start":if(S.id in g)continue;g[S.id]={id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"reasoning",text:"",time:{start:Date.now()},metadata:S.providerMetadata},await X.updatePart(g[S.id]);break;case "reasoning-delta":if(S.id in g){let A=g[S.id];if(!A){t.warn("reasoning-delta: part not found in map",{id:S.id});break}let y=S.delta||S.text||"";A.text+=y,S.providerMetadata&&(A.metadata=S.providerMetadata),A.text&&await X.updatePart({part:A,delta:y});}break;case "reasoning-end":if(S.id in g){let A=g[S.id];if(!A){t.warn("reasoning-end: part not found in map",{id:S.id});break}A.text=A.text.trimEnd(),A.time={...A.time,end:Date.now()},S.providerMetadata&&(A.metadata=S.providerMetadata),await X.updatePart(A),delete g[S.id];}break;case "tool-input-start":{let A=await X.updatePart({id:r[S.id]?.id??Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"tool",tool:S.toolName,callId:S.id,state:{status:"pending",input:{},raw:""}});r[S.id]=A;break}case "tool-input-delta":break;case "tool-input-end":break;case "tool-call":{let A=r[S.toolCallId];if(A){let y=await X.updatePart({...A,tool:S.toolName,state:{status:"running",input:S.input,time:{start:Date.now()}},metadata:S.providerMetadata});r[S.toolCallId]=y;let b=(await ve.parts(s.assistantMessage.id)).slice(-3);if(b.length===3&&b.every(w=>w.type==="tool"&&w.tool===S.toolName&&w.state.status!=="pending"&&JSON.stringify(w.state.input)===JSON.stringify(S.input))){let w=await Ue.get(s.assistantMessage.agent);if(!w)break;await Me.ask({permission:"doom_loop",patterns:[S.toolName],sessionId:s.assistantMessage.sessionId,metadata:{tool:S.toolName,input:S.input},always:[S.toolName],ruleset:w.permission});}}break}case "tool-result":{let A=r[S.toolCallId];if(A&&A.state.status==="running"){let y;S.output.attachments&&S.output.attachments.length>0&&(y=S.output.attachments.map(x=>({...x,id:x.id??Identifier.ascending("part"),sessionId:x.sessionId??A.sessionId,messageId:x.messageId??A.messageId}))),await X.updatePart({...A,state:{status:"completed",input:S.input??A.state.input,output:S.output.output,metadata:S.output.metadata,title:S.output.title,time:{start:A.state.time.start,end:Date.now()},attachments:y}}),delete r[S.toolCallId];}break}case "tool-error":{let A=r[S.toolCallId];A&&A.state.status==="running"&&(await X.updatePart({...A,state:{status:"error",input:S.input??A.state.input,error:S.error instanceof Error?S.error.message:String(S.error),time:{start:A.state.time.start,end:Date.now()}}}),(S.error instanceof Me.RejectedError||S.error instanceof Ot.RejectedError)&&(i=a),delete r[S.toolCallId]);break}case "error":throw S.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 X.updatePart({id:Identifier.ascending("part"),messageId:s.assistantMessage.id,sessionId:s.sessionId,type:"step-start"});break;case "finish-step":{let A=X.getUsage({model:s.model,usage:S.usage,metadata:S.providerMetadata});s.assistantMessage.finish=S.finishReason,s.assistantMessage.cost+=A.cost,s.assistantMessage.tokens=A.tokens,await X.updatePart({id:Identifier.ascending("part"),reason:S.finishReason,messageId:s.assistantMessage.id,sessionId:s.assistantMessage.sessionId,type:"step-finish",tokens:A.tokens,cost:A.cost}),await X.updateMessage(s.assistantMessage),await Le.triggerEvent(HookEvent.StepFinish,{sessionId:s.sessionId,userMessageId:s.assistantMessage.parentId,messageId:s.assistantMessage.id,model:s.model,finishReason:S.finishReason},{sessionId:s.sessionId,model:s.model?.id}),!s.assistantMessage.summary&&await sn.isOverflow({tokens:A.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:S.providerMetadata},await X.updatePart(u);break;case "text-delta":if(u){let A=S.delta||S.text||"";u.text+=A,S.providerMetadata&&(u.metadata=S.providerMetadata),u.text&&await X.updatePart({part:u,delta:A});}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()},S.providerMetadata&&(u.metadata=S.providerMetadata),await X.updatePart(u)):t.warn("text-end: no currentText available or time not set"),u=void 0;break;case "finish":break;default:t.debug("unhandled",{...S});continue}if(l)break}}catch(u){let g=u?.message??String(u);t.error("process",{error:g});let h=ve.fromError(u,{providerId:s.model.providerId,aborted:s.abort.aborted});if(ve.ContextOverflowError.isInstance(h))l=true,pe.publish(X.Event.Error,{sessionId:s.sessionId,error:h});else {let S=xr.retryable(h);if(S!==void 0){c++;let A=xr.delay(c,ve.APIError.isInstance(h)?h:void 0);await Mt.set(s.sessionId,{type:"retry",attempt:c,message:S,next:Date.now()+A}),await xr.sleep(A,s.abort).catch(()=>{});continue}s.assistantMessage.error=h,await pe.publish(X.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 X.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 X.updateMessage(s.assistantMessage),l?"compact":i||s.assistantMessage.error?"stop":"continue"}}}}o.create=n;})(vr||(vr={}));var Dm=`Provide a detailed summary of the conversation above that will help continue the work.
98
+
99
+ Focus on information that would be helpful for continuing the conversation, including what was accomplished, what is being worked on, and what comes next.`;function Gx(e){return `<compaction_summary>
100
+ ${e}
101
+ </compaction_summary>`}function $m(e,t){let n=[Gx(e)];return n.push("Continue if you have next steps, or stop and ask for clarification if you are unsure how to proceed."),t?.customInstructions&&n.push(t.customInstructions),n.join(`
102
+
103
+ `)}var co=a.create({service:"compaction.cache"}),Um=100,zm=25*1024*1024,qm=300*1e3,Fm="cache.json",Yx={maxEntries:Um,maxSizeBytes:zm,ttlMs:qm,persist:false};function Ml(e){return join(a$1.Path.cache,"compaction",e)}var mc=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??Um,maxSizeBytes:t?.maxSizeBytes??zm,ttlMs:t?.ttlMs??qm,persist:t?.persist??false,sessionId:t?.sessionId},this.cache=new LRUCache({max:this.config.maxEntries,maxSize:this.config.maxSizeBytes,sizeCalculation:n=>{let o=n.value,s=typeof o=="string"?o:o==null?"":typeof o=="object"?JSON.stringify(o):String(o);return Math.max(1,Buffer.byteLength(s,"utf8"))},ttl:this.config.ttlMs,updateAgeOnGet:true,updateAgeOnHas:true}),co.debug("compaction cache initialized",{maxEntries:this.config.maxEntries,maxSizeBytes:this.config.maxSizeBytes,ttlMs:this.config.ttlMs});}get(t){let n=this.cache.get(t);if(n!==void 0)return this.hits++,n.value;this.misses++;}set(t,n){let o={value:n,timestamp:Date.now()};return this.cache.set(t,o),this}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear(),this.hits=0,this.misses=0,co.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){co.debug("persist skipped: persistence disabled or no sessionId");return}let t=Ml(this.config.sessionId),n=join(t,Fm),o={entries:this.entries(),stats:this.getStats(),timestamp:Date.now()};try{await mkdir(t,{recursive:!0}),await writeFile(n,JSON.stringify(o),"utf-8"),co.debug("cache persisted",{path:n,entries:o.entries.length});}catch(s){throw co.error("cache persist failed",{error:String(s)}),s}}async restoreFromFile(){if(!this.config.persist||!this.config.sessionId){co.debug("restore skipped: persistence disabled or no sessionId");return}let t=Ml(this.config.sessionId),n=join(t,Fm);try{let o=await readFile(n,"utf-8"),s=JSON.parse(o);if(s.entries&&Array.isArray(s.entries))for(let[r,i]of s.entries)Date.now()-i.timestamp<this.config.ttlMs&&this.cache.set(r,i);co.debug("cache restored",{path:n,entries:this.cache.size});}catch(o){co.warn("cache restore failed, starting fresh",{error:String(o)});}}dump(){return {entries:this.entries(),stats:this.getStats()}}load(t){for(let[n,o]of t.entries)Date.now()-o.timestamp<this.config.ttlMs&&this.cache.set(n,o);co.debug("cache loaded",{entries:this.cache.size});}};function Xx(e){return new mc(e)}async function Qx(e){let t=Ml(e);try{await rm$1(t,{recursive:!0,force:!0}),co.info("session cache cleared",{sessionId:e,path:t});}catch(n){co.warn("failed to clear session cache",{sessionId:e,error:String(n)});}}function Zx(){pe.subscribe(X.Event.Deleted,async e=>{await Qx(e.properties.info.id);});}var Ol=class{constructor(t){b$1(this,"cache");b$1(this,"config");let n={ttlMs:3e5,maxSizeBytes:26214400,maxEntries:100,persist:false};this.config={...n,...t},this.cache=new LRUCache({max:this.config.maxEntries,maxSize:this.config.maxSizeBytes,sizeCalculation:o=>Buffer.byteLength(o.originalOutput,"utf8")+Buffer.byteLength(JSON.stringify(o.metadata),"utf8"),ttl:this.config.ttlMs,updateAgeOnGet:true});}getKey(t,n){return `${t}:${n}`}async backup(t){let n=this.getKey(t.sessionId,t.partId);this.cache.set(n,t);}get(t,n){let o=this.getKey(t,n);return this.cache.get(o)}has(t,n){let o=this.getKey(t,n);return this.cache.has(o)}delete(t,n){let o=this.getKey(t,n);return this.cache.delete(o)}clearSession(t){let n=`${t}:`;for(let o of this.cache.keys())o.startsWith(n)&&this.cache.delete(o);}clear(){this.cache.clear();}size(){return this.cache.size}getStats(){return {size:this.cache.size,calculatedSize:this.cache.calculatedSize??0}}},Rl;function es(){return Rl||(Rl=new Ol),Rl}var ji={async backup(e){await es().backup(e);},get(e,t){return es().get(e,t)},has(e,t){return es().has(e,t)},delete(e,t){return es().delete(e,t)},clearSession(e){es().clearSession(e);},clear(){es().clear();},size(){return es().size()},getStats(){return es().getStats()}};var Et=a.create({service:"compaction"}),sn;(D=>{D.COMPACTION_BUFFER=2e4,D.AUTOCOMPACT_BUFFER_TOKENS=13e3,D.WARNING_THRESHOLD_BUFFER_TOKENS=2e4,D.MANUAL_COMPACT_BUFFER_TOKENS=3e3,D.PRUNE_MINIMUM=2e4,D.PRUNE_PROTECT=4e4,D.MAX_COMPACTION_FAILURES=3,D.PRUNE_PROTECTED_TOOLS=["skill"],D.BLOCKING_LIMIT_THRESHOLD=1e3,D.COMPACTION_WINDOW_MS=6e4,D.COMPACTION_WINDOW_THRESHOLD=3;let f;function a(){return f||(f=_.state(async()=>({config:await xi(),consecutiveFailures:new Map,compactionAttempts:new Map,initialized:true}))),f}async function p(){return a()()}async function u(){return (await p()).config}D.getConfig=u;async function g(I){let M=await p(),v=Date.now(),T=M.compactionAttempts.get(I);if(T){let R=v-T.firstAttemptTime;if(R<6e4){if(T.count>=3)return Et.warn("compaction skipped: time window circuit breaker open",{sessionId:I,attempts:T.count,elapsed:R,windowMs:6e4,threshold:3}),await pe.publish(D.Event.CircuitBreakerOpened,{sessionId:I,consecutiveFailures:T.count,maxFailures:3}),true;T.count++;}else T.count=1,T.firstAttemptTime=v;}else M.compactionAttempts.set(I,{count:1,firstAttemptTime:v});return false}async function h(I){(await p()).compactionAttempts.delete(I);}D.resetTimeWindowAttempts=h;async function S(I){return (await p()).consecutiveFailures.get(I)??0}async function A(I){let M=await p(),T=(M.consecutiveFailures.get(I)??0)+1;return M.consecutiveFailures.set(I,T),T}async function y(I){(await p()).consecutiveFailures.set(I,0);}D.resetSessionFailures=y;function x(I){if(a$2.EASBOT_AUTO_COMPACT_WINDOW)return a$2.EASBOT_AUTO_COMPACT_WINDOW;let M=wt.maxOutputTokens(I),v=Math.min(M,2e4),T=I.limit.context??0,j=(T>0?T:xe.DEFAULT_CONTEXT_LIMIT)-v;return Math.max(j,5e4)}D.getEffectiveContextWindowSize=x;function b(I,M){let v=x(M),T=Math.max(0,(v-I)/v*100),R=v-2e4,j=v-13e3;a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE&&(j=v*(1-a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE/100));let U=v-1e3;return a$2.EASBOT_BLOCKING_LIMIT_OVERRIDE&&(U=a$2.EASBOT_BLOCKING_LIMIT_OVERRIDE),{percentLeft:T,isAboveWarningThreshold:I>=R,isAboveAutoCompactThreshold:I>=j,isAtBlockingLimit:I>=U}}D.calculateTokenUsageState=b;async function w(I){if(a$2.EASBOT_DISABLE_COMPACT||a$2.EASBOT_DISABLE_AUTO_COMPACT)return false;let M=await u();if(M.auto===false)return false;let v=I.model.limit.context??0,T=v>0?v:xe.DEFAULT_CONTEXT_LIMIT;if(T===0)return false;let R=wt.maxOutputTokens(I.model),j=M.reserved??Math.min(2e4,R),U=I.model.limit.input?I.model.limit.input-j:T-j,Y=Math.max(U,5e4);if(a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE)return I.tokens?Token.total(I.tokens)>=Y*(1-a$2.EASBOT_AUTOCOMPACT_PCT_OVERRIDE/100):false;if(I.tokens)return Token.total(I.tokens)>=Y;if(!I.sessionId)return false;let J=await X.messages({sessionId:I.sessionId});for(let ee=J.length-1;ee>=0;ee--){let se=J[ee];if(se&&se.info.role==="assistant"&&!se.info.summary)return Token.total(se.info.tokens)>=U}return false}D.isOverflow=w;async function C(I){let M=await u(),v=M.prune;if(v?.enabled===false)return Et.debug("prune skipped: config.compaction.prune.enabled is false"),{prunedCount:0,prunedTokens:0,success:true};let T=v?.timeThresholdMs??3e5,R=v?.keepRecentTools??3,j=v?.tokenThreshold??5e3,U=v?.protectedTools??D.PRUNE_PROTECTED_TOOLS,Y=M?.backup?.enabled!==false,J=await X.messages({sessionId:I.sessionId}),ee=Date.now(),se=0,ae=0,we=0,ie=[],Z=[],H=0;e:for(let te=J.length-1;te>=0;te--){let W=J[te];if(W&&(W.info.role==="user"&&H++,!(H<2))){if(W.info.role==="assistant"&&W.info.summary)break;for(let V=W.parts.length-1;V>=0;V--){let oe=W.parts[V];if(oe&&oe.type==="tool"&&oe.state.status==="completed"){if(U.includes(oe.tool))continue;if(oe.state.time.compacted)break e;let me=ee-(oe.state.time.end??0)>T;if(Z.length<R){Z.push(oe.id);continue}if(!me)continue;let ce=Token.estimate(oe.state.output??"");se+=ce,se>4e4&&(ae+=ce,ie.push(oe));}}}}Et.debug("pruning analysis",{prunedTokens:ae,toPruneCount:ie.length});let $=ae>j;if($&&ie.length>0){let te=I.reason??"prune";for(let W of ie)W.type==="tool"&&W.state.status==="completed"&&(Y&&W.state.output&&(await ji.backup({sessionId:I.sessionId,messageId:W.messageId,partId:W.id,tool:W.tool,originalOutput:W.state.output,metadata:{input:W.state.input??{},title:W.state.title,attachments:W.state.attachments},compactedAt:ee,reason:te}),we++),W.state.time.compacted=ee,await X.updatePart(W));Et.debug("pruning completed",{count:ie.length,tokens:ae,backups:we});}else Et.debug("pruning skipped: insufficient benefit",{prunedTokens:ae,minimum:j});return {prunedCount:ie.length,prunedTokens:ae,success:$,backups:we}}D.prune=C;async function k(I){let M=await X.messages({sessionId:I.sessionId}),v=0,T=0;for(let R of M)if(!(I.messageId&&R.info.id!==I.messageId))for(let j of R.parts){if(I.partId&&j.id!==I.partId||j.type!=="tool"||j.state.status!=="completed"||!j.state.time.compacted)continue;let U=ji.get(I.sessionId,j.id);if(!U){Et.warn("restore skipped: no backup found",{partId:j.id});continue}j.state.output=U.originalOutput,j.state.time.compacted=void 0,await X.updatePart(j),v++,T+=Token.estimate(U.originalOutput),Et.debug("restore completed",{partId:j.id,tokens:Token.estimate(U.originalOutput)});}return Et.debug("restore completed",{restoredCount:v,restoredTokens:T}),{restoredCount:v,restoredTokens:T,success:true}}D.restore=k;function P(){return ji}D.getBackupCache=P;function E(I){ji.clearSession(I);}D.clearBackups=E;async function O(I){let M=await S(I.sessionId);if(M>=3)return Et.warn("compaction skipped: circuit breaker open (failures)",{sessionId:I.sessionId,consecutiveFailures:M,maxFailures:3}),await pe.publish(D.Event.CircuitBreakerOpened,{sessionId:I.sessionId,consecutiveFailures:M,maxFailures:3}),await Je.cancel(I.sessionId),"stop";if(await g(I.sessionId))return await Je.cancel(I.sessionId),"stop";let v=I.messages.findLast(se=>se.info.id===I.parentId).info,T=await Ue.get("compaction");if(!T)return Et.error("compaction agent not found"),"stop";let R=T.model?await xe.getModel(T.model.providerId,T.model.modelId):await xe.getModel(v.model.providerId,v.model.modelId),j=await X.updateMessage({id:Identifier.ascending("message"),role:"assistant",parentId:I.parentId,sessionId:I.sessionId,mode:"compaction",agent:"compaction",variant:v.variant,summary:true,path:{cwd:_.directory,root:_.worktree},cost:0,tokens:{output:0,input:0,reasoning:0,cache:{read:0,write:0}},modelId:R.id,providerId:R.providerId,time:{created:Date.now()}}),U=vr.create({assistantMessage:j,sessionId:I.sessionId,model:R,abort:I.abort}),Y=[],J;try{let se=await Le.triggerEvent(HookEvent.SessionCompacting,{sessionId:I.sessionId,auto:I.auto});if(se.success&&se.output){let ae=se.output;ae.context&&Y.push(...ae.context),ae.prompt&&(J=ae.prompt);}}catch(se){Et.warn("session.compacting hook error, using default",{error:String(se)});}let ee=J??[Dm,...Y].join(`
104
+
105
+ `);try{if(await U.process({user:v,agent:T,abort:I.abort,sessionId:I.sessionId,tools:{},system:T.prompt?[T.prompt]:[],messages:[...await ve.toModelMessages(I.messages.filter(ae=>!ae.parts.some(we=>we.type==="compaction")),R),{role:"user",content:[{type:"text",text:ee}]}],model:R})==="continue"&&I.auto){let we=(await ve.parts(j.id)).find(H=>H.type==="text")?.text??"",ie=$m(we,{continuePrompt:!0}),Z=await X.updateMessage({id:Identifier.ascending("message"),role:"user",sessionId:I.sessionId,time:{created:Date.now()},agent:v.agent,model:v.model});await X.updatePart({id:Identifier.ascending("part"),messageId:Z.id,sessionId:I.sessionId,type:"text",synthetic:!0,text:ie,time:{start:Date.now(),end:Date.now()}});}return U.message.error?(Et.error("compaction failed: processor error",{error:U.message.error}),await A(I.sessionId),"stop"):(await pe.publish(D.Event.Compacted,{sessionId:I.sessionId}),Et.debug("compaction completed successfully",{sessionId:I.sessionId}),await y(I.sessionId),"continue")}catch(se){let ae=await A(I.sessionId);throw Et.error("compaction failed",{sessionId:I.sessionId,error:String(se),consecutiveFailures:ae,maxFailures:3}),se}}D.compactConversation=O;async function N(I){if(a$2.EASBOT_DISABLE_COMPACT||a$2.EASBOT_DISABLE_AUTO_COMPACT)return Et.debug("auto compact skipped: disabled by flag"),"not_needed";if((await u()).auto===false)return Et.debug("auto compact skipped: config.compaction.auto is false"),"not_needed";if(!await w({sessionId:I.sessionId,model:I.model,tokens:I.tokens}))return Et.debug("no overflow detected, skipping auto compact"),"not_needed";Et.debug("auto compact triggered",{sessionId:I.sessionId});let T=await ve.filterCompacted(ve.stream(I.sessionId));if(T.length===0)return Et.debug("auto compact skipped: no uncompacted messages",{sessionId:I.sessionId}),"not_needed";let R=T.findLast(J=>J?.info.role==="user"&&!J.parts.some(ee=>ee.type==="compaction"));if(!R)return Et.error("no user message found for compaction"),"not_needed";let j=new AbortController,U=I.sessionId?Object.assign(j.signal,{sessionId:I.sessionId}):j.signal,Y=await O({sessionId:I.sessionId,parentId:R.info.id,messages:T,abort:U,auto:true});return await D.prune({sessionId:I.sessionId}),Y==="continue"?(Et.debug("auto compact succeeded",{sessionId:I.sessionId}),"compacted"):"not_needed"}D.autoCompactIfNeeded=N;async function L(I){await y(I),Et.debug("circuit breaker reset",{sessionId:I});}D.resetCircuitBreaker=L;async function K(I){return S(I)}D.getConsecutiveFailures=K,D.Event={Compacted:a$5.define("session.compacted",F.object({sessionId:F.string()})),CircuitBreakerOpened:a$5.define("session.compaction.circuit_breaker_opened",F.object({sessionId:F.string(),consecutiveFailures:F.number(),maxFailures:F.number()}))},D.create=fn$1(F.object({sessionId:Identifier.schema("session"),agent:F.string().optional(),model:F.object({providerId:F.string(),modelId:F.string()}).optional(),auto:F.boolean()}),async I=>{let{sessionId:M,model:v,agent:T="compaction",auto:R=false}=I,j;v?.providerId&&v.modelId?j={providerId:v.providerId,modelId:v.modelId}:j=(await Ue.get(T))?.model??await Zo(M);let U=await X.updateMessage({id:Identifier.ascending("message"),role:"user",model:j,sessionId:M,agent:T,time:{created:Date.now()}});await X.updatePart({id:Identifier.ascending("part"),messageId:U.id,sessionId:U.sessionId,type:"compaction",auto:R}),Et.debug("compaction task created",{sessionId:M,auto:R});});})(sn||(sn={}));var oI=a.create({service:"instruction"}),Hm=["AGENTS.md"];function sI(){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 rI(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(()=>[]):(oI.warn(`Skipping relative instruction "${e}" - no EASBOT_CONFIG_DIR set while project config is disabled`),[]):Filesystem.globUp(e,_.directory,_.worktree).catch(()=>[])}var ks;(f=>{let e;function t(){return e||(e=_.state(async()=>({claims:new Map}))),e}function n(){return t()()}async function o(a,p){let g=(await n()).claims.get(a);return g?g.has(p):false}async function s(a,p){let u=await n(),g=u.claims.get(a);g||(g=new Set,u.claims.set(a,g)),g.add(p);}async function r(a){(await n()).claims.delete(a);}f.clear=r;async function i(){let a=await he.get(),p=new Set;if(!a$2.EASBOT_DISABLE_PROJECT_CONFIG)for(let u of Hm){let g=await Filesystem.findUp(u,_.directory,_.worktree);if(g.length>0){g.forEach(h=>{p.add(Ce__default.resolve(h));});break}}for(let u of sI())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(sc.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 rI(u)).forEach(h=>{p.add(Ce__default.resolve(h));});}return p}f.systemPaths=i;async function c(){let a=await he.get(),p=await i(),u=Array.from(p).map(async S=>{let A=await Tt__default.readFile(S,"utf-8").catch(()=>"");return {path:S,content:A}}),g=[];if(a.instructions)for(let S of a.instructions)(S.startsWith("https://")||S.startsWith("http://"))&&g.push(S);let h=g.map(S=>fetch(S,{signal:AbortSignal.timeout(5e3)}).then(A=>A.ok?A.text():"").catch(()=>"").then(A=>A?"Instructions from: "+S+`
106
+ `+A:""));return Promise.all([...u,...h]).then(S=>S.filter(Boolean))}f.system=c;function l(a){let p=new Set;for(let u of a)for(let g of u.parts)if(g.type==="tool"&&g.tool==="read"&&g.state.status==="completed"){if(g.state.time.compacted)continue;let h=g.state.metadata?.loaded;if(!h||!Array.isArray(h))continue;for(let S of h)typeof S=="string"&&p.add(S);}return p}f.loaded=l;async function d(a){for(let p of Hm){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 g=await i(),h=l(a),S=[],A=Ce__default.resolve(p),y=Ce__default.dirname(A),x=Ce__default.resolve(_.directory);for(;y.startsWith(x)&&y!==x;){let b=await d(y);if(b&&b!==A&&!g.has(b)&&!h.has(b)&&!o(u,b)){await s(u,b);let w=await Tt__default.readFile(b,"utf-8").catch(()=>{});w&&S.push({filepath:b,content:"Instructions from: "+b+`
107
+ `+w});}y=Ce__default.dirname(y);}return S}f.resolve=m;})(ks||(ks={}));var De;(t=>{function e(n,o){return {id:n,isEnabled:typeof o=="function"?void 0:o.isEnabled,scope:typeof o=="function"?void 0:o.scope,init:async s=>{let r=typeof o=="function"?await o(s):o,i=r.execute;return r.execute=async(c,l)=>{try{r.parameters.parse(c);}catch(f){throw f instanceof F.ZodError&&r.formatValidationError?new Error(r.formatValidationError(f),{cause:f}):new Error(`The ${n} tool was called with invalid arguments: ${f instanceof Error?f.message:String(f)}.
108
+ Please rewrite the input so it satisfies the expected schema.`,{cause:f})}let d=await i(c,l);if(d.metadata?.truncated===true)return d;let m=await Ve.output(d.output,{},s?.agent);return {...d,output:m.content,metadata:{...d.metadata||{},truncated:m.truncated,...m.truncated&&{outputPath:m.outputPath}}}},{description:r.description,parameters:r.parameters,execute:r.execute,formatValidationError:r.formatValidationError}}}}t.define=e;})(De||(De={}));var An;(l=>{let e=a.create({service:"file.time"}),t;function n(){return t||(t=_.state(()=>({read:{},locks:new Map}))),t}function o(){return n()()}l.state=o;function s(d,m){e.debug("read",{sessionId:d,file:m});let{read:f}=o();f[d]=f[d]||{},f[d][m]=new Date;}l.read=s;function r(d,m){return o().read[d]?.[m]}l.get=r;async function i(d,m){let f=o(),a=f.locks.get(d)??Promise.resolve(),p=()=>{},u=new Promise(h=>{p=h;}),g=a.then(()=>u);f.locks.set(d,g),await a;try{return await m()}finally{p(),f.locks.get(d)===g&&f.locks.delete(d);}}l.withLock=i;async function c(d,m){if(a$2.EASBOT_DISABLE_FILETIME_CHECK===true)return;let f=r(d,m);if(!f)throw new Error(`You must read file ${m} before overwriting it. Use the Read tool first`);let a=await PKG.file(m).stat();if(a.mtime.getTime()>f.getTime())throw new Error(`File ${m} has been modified since it was last read.
109
+ Last modification: ${a.mtime.toISOString()}
110
+ Last read: ${f.toISOString()}
111
+
112
+ Please read the file again before modifying it.`)}l.assert=c;})(An||(An={}));async function Yt(e,t,n){if(!t||n?.bypass)return;let o=Filesystem.normalize(Ce__default.isAbsolute(t)?t:Ce__default.resolve(_.directory,t)),s=await cI(o),r=s??o;if(_.containsPath(r))return;let c=(n?.kind??"file")==="directory"?o:Ce__default.posix.dirname(o),l=Ce__default.posix.join(c,"*");await e.ask({permission:"external_directory",patterns:[l],always:[l],metadata:{filepath:o,realPath:s??void 0,parentDir:c,tool:n?.tool??"read"}});}async function cI(e){try{let t=await Tt.realpath(e);return Filesystem.normalize(t)}catch{return}}var pI=loadTextFile("./read.txt",import.meta.url),mI=pI(),Wm=2e3,Ll=2e3,fI=`... (line truncated to ${Ll} chars)`,Vm=50*1024,gI=`${Vm/1024} KB`,yc=De.define("read",{description:mI,parameters:F.object({filePath:F.string().describe("The absolute path to the file or directory to read"),offset:F.coerce.number().describe("The line number to start reading from (1-indexed)").optional(),limit:F.coerce.number().describe("The maximum number of lines to read (defaults to 2000)").optional()}),async execute(e,t){if(e.offset!==void 0&&e.offset<1)throw new Error("offset must be greater than or equal to 1");let n=Filesystem.normalize(Ce.isAbsolute(e.filePath)?e.filePath:Ce.resolve(_.directory,e.filePath)),o=Ce.posix.relative(_.worktree,n),s=Filesystem.stat(n);if(await Yt(t,n,{bypass:!!t.extra?.bypassCwdCheck,kind:s?.isDirectory()?"directory":"file",tool:"read"}),await t.ask({permission:"read",patterns:[Ce.posix.relative(_.worktree,n)],always:["*"],metadata:{}}),!s){let O=Filesystem.dirname(n),N=Filesystem.basename(n),L=await Tt.readdir(O).then(K=>K.filter(Q=>Q.toLowerCase().includes(N.toLowerCase())||N.toLowerCase().includes(Q.toLowerCase())).map(Q=>Filesystem.join(O,Q)).slice(0,3)).catch(()=>[]);throw L.length>0?new Error(`File not found: ${n}
113
+
114
+ Did you mean one of these?
115
+ ${L.join(`
116
+ `)}`):new Error(`File not found: ${n}`)}if(s.isDirectory()){let O=await Tt.readdir(n,{withFileTypes:true}),N=await Promise.all(O.map(async M=>M.isDirectory()||M.isSymbolicLink()&&(await Tt.stat(Filesystem.join(n,M.name)).catch(()=>{}))?.isDirectory()?M.name+"/":M.name));N.sort((M,v)=>M.localeCompare(v));let L=e.limit??Wm,K=e.offset??1,Q=K-1,ue=N.slice(Q,Q+L),D=Q+ue.length<N.length,I=[`<path>${n}</path>`,"<type>directory</type>","<entries>",ue.join(`
117
+ `),D?`
118
+ (Showing ${ue.length} of ${N.length} entries. Use 'offset' parameter to read beyond entry ${K+ue.length})`:`
119
+ (${N.length} entries)`,"</entries>"].join(`
120
+ `);return {title:o,output:I,metadata:{preview:ue.slice(0,20).join(`
121
+ `),truncated:D,loaded:[]}}}let r=await ks.resolve(t.messages,n,t.messageId),i=Filesystem.mimeType(n),c=i?.startsWith("image/")&&i!=="image/svg+xml"&&i!=="image/vnd.fastbidsheet";if(c||i==="application/pdf"){let O=`${c?"Image":"PDF"} read successfully`;return {title:o,output:O,metadata:{preview:O,truncated:false,loaded:r.map(N=>N.filepath)},attachments:[{type:"file",mime:i??"application/octet-stream",url:`data:${i??"application/octet-stream"};base64,${Buffer.from(await Filesystem.readBytes(n)).toString("base64")}`}]}}if(await hI(n,Number(s.size)))throw new Error(`Cannot read binary file: ${n}`);let m=createReadStream(n,{encoding:"utf8"}),f=createInterface({input:m,crlfDelay:1/0}),a=e.limit??Wm,p=e.offset??1,u=p-1,g=[],h=0,S=0,A=false,y=false;try{for await(let O of f){if(S+=1,S<=u)continue;if(g.length>=a){y=!0;continue}let N=O.length>Ll?O.substring(0,Ll)+fI:O,L=Buffer.byteLength(N,"utf-8")+(g.length>0?1:0);if(h+L>Vm){A=!0,y=!0;break}g.push(N),h+=L;}}finally{f.close(),m.destroy();}if(S<p&&!(S===0&&p===1))throw new Error(`Offset ${p} is out of range for this file (${S} lines)`);let x=g.map((O,N)=>`${N+p}: ${O}`),b=g.slice(0,20).join(`
122
+ `),w=[`<path>${n}</path>`,"<type>file</type>","<content>"].join(`
123
+ `);w+=x.join(`
124
+ `);let C=S,k=p+g.length-1,P=k+1,E=y||A;return A?w+=`
125
+
126
+ (Output capped at ${gI}. Showing lines ${p}-${k}. Use offset=${P} to continue.)`:y?w+=`
127
+
128
+ (Showing lines ${p}-${k} of ${C}. Use offset=${P} to continue.)`:w+=`
129
+
130
+ (End of file - total ${C} lines)`,w+=`
131
+ </content>`,await We.isAvailable(t.sessionId)&&await We.touchFile(n,false),An.read(t.sessionId,n),r.length>0&&(w+=`
132
+
133
+ <system-reminder>
134
+ ${r.map(O=>O.content).join(`
135
+
136
+ `)}
137
+ </system-reminder>`),{title:o,output:w,metadata:{filepath:n,preview:b,truncated:E,loaded:r.map(O=>O.filepath)}}}});async function hI(e,t){switch(Filesystem.extname(e).toLowerCase()){case ".zip":case ".tar":case ".gz":case ".exe":case ".dll":case ".so":case ".class":case ".jar":case ".war":case ".7z":case ".doc":case ".docx":case ".xls":case ".xlsx":case ".ppt":case ".pptx":case ".odt":case ".ods":case ".odp":case ".bin":case ".dat":case ".obj":case ".o":case ".a":case ".lib":case ".wasm":case ".pyc":case ".pyo":return true;}if(t===0)return false;let o=await Tt.open(e,"r");try{let s=Math.min(4096,t),r=Buffer.alloc(s),i=await o.read(r,0,s,0);if(i.bytesRead===0)return !1;let c=0;for(let l=0;l<i.bytesRead;l++){let d=r[l];if(d!==void 0){if(d===0)return !0;(d<9||d>13&&d<32)&&c++;}}return c/i.bytesRead>.3}finally{await o.close();}}var bI=loadTextFile("./ls.txt",import.meta.url),wI=bI(),xI=["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/"],II=100,bc=De.define("list",{description:wI,parameters:F.object({path:F.string().default(".").optional().describe("The directory to list (default: current directory"),ignore:F.array(F.string()).default([]).optional().describe("List of glob patterns to ignore"),limit:F.number().default(100).optional().describe("Maximum number of entries to return (default: 100")}),execute:async(e,t)=>{let n=Filesystem.normalize(Ce.isAbsolute(e.path||".")?e.path||".":Ce.resolve(_.directory,e.path||"."));await Yt(t,n,{kind:"directory",tool:"list"}),await t.ask({permission:"list",patterns:[Ce.posix.relative(_.worktree,n)],always:["*"],metadata:{path:n}});let o=e.limit??II,s="/",r=xI.map(a=>`!${a}*`).concat(e.ignore?.map(a=>`!${a}`)||[]),i=[],c=false;for await(let a of a$8.files({cwd:n,glob:r,signal:t.abort})){if(i.length>=o){c=true;break}i.push(Filesystem.toUnixPath(a));}let l=new Set,d=new Map;for(let a of i){let p=Ce.posix.dirname(a),u=p==="."?[]:p.split(s);for(let g=0;g<=u.length;g++){let h=g===0?".":u.slice(0,g).join(s);l.add(h);}d.has(p)||d.set(p,[]),d.get(p).push(Ce.posix.basename(a));}let m=(a,p)=>{let u=" ".repeat(p),g="";p>0&&(g+=`${u}${Ce.posix.basename(a)}/
138
+ `);let h=" ".repeat(p+1),S=Array.from(l).filter(y=>Ce.posix.dirname(y)===a&&y!==a).sort();for(let y of S)g+=m(y,p+1);let A=d.get(a)||[];for(let y of A.sort())g+=`${h}${y}
139
+ `;return g},f=`${n}/
140
+ `+m(".",0);return c&&(f+=`
141
+ [${o} entries limit reached, Use limit=${o*2} for more]`),{title:Ce.posix.relative(_.worktree,n),metadata:{path:n,count:i.length,truncated:c},output:f}}});function Dl(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 $l(e){let t=e;t.startsWith("wss://")?t=t.replace("wss://","https://"):t.startsWith("ws://")?t=t.replace("ws://","http://"):!t.startsWith("http://")&&!t.startsWith("https://")&&(t=`http://${t}`);try{let n=new URL(t);return `${n.protocol}//${n.host}`}catch{let n=t.match(/^(https?:\/\/[^/]+)/);return n?n[1]:t}}var Be=a.create({service:"acp-client-connection"}),Nl=class{constructor(t){b$1(this,"ws",null);b$1(this,"config");b$1(this,"_state","disconnected");b$1(this,"pendingRequests",new Map);b$1(this,"requestId",1);b$1(this,"subscriptions",new Map);b$1(this,"reconnectAttempts",0);b$1(this,"abortController",null);let n=t.url;n.startsWith("acp-ws://")&&(n=n.replace("acp-ws://","ws://")),n.includes("/acp")||(n=n.replace(/\/$/,"")+"/acp"),this.config={...t,url:n};}get state(){return this._state}async connect(){this._state!=="connected"&&(this._state="connecting",Be.debug("WebSocketConnection: connecting",{url:this.config.url}),await retry(async()=>new Promise((t,n)=>{try{this.abortController=new AbortController,this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{Be.debug("WebSocketConnection: connected"),this._state="connected",this.reconnectAttempts=0,t();},this.ws.onmessage=async o=>{let s;if(typeof o.data=="string")s=o.data;else if(o.data instanceof Blob){let r=await o.data.arrayBuffer();s=new TextDecoder("utf-8").decode(r);}else o.data instanceof ArrayBuffer?s=new TextDecoder("utf-8").decode(o.data):s=String(o.data);this.handleMessage(s);},this.ws.onerror=o=>{Be.error("WebSocketConnection: error",{error:String(o)}),this._state==="connecting"&&n(new Error("WebSocket connection error"));},this.ws.onclose=()=>{Be.debug("WebSocketConnection: closed"),this._state="disconnected";for(let[,o]of this.pendingRequests)o.reject(new Error("Connection closed"));this.pendingRequests.clear(),this.handleReconnect();};}catch(o){this._state="disconnected",n(o);}}),{attempts:3}));}async disconnect(){Be.debug("WebSocketConnection: disconnecting"),this.abortController&&(this.abortController.abort(),this.abortController=null),this.ws&&(this.ws.close(),this.ws=null),this._state="disconnected";for(let[t,n]of this.pendingRequests)n.reject(new Error("Connection closed"));this.pendingRequests.clear(),this.subscriptions.clear();}async send(t,n){if(!this.ws||this.ws.readyState!==WebSocket.OPEN)throw new Error("WebSocket not connected");let o=this.requestId++,s={jsonrpc:"2.0",id:o,method:t,params:n};return new Promise((r,i)=>{let c=setTimeout(()=>{this.pendingRequests.delete(o),i(new Error(`Request timeout: ${t}`));},this.config.timeout??3e5);this.pendingRequests.set(o,{resolve:l=>{clearTimeout(c),l.error?i(new Error(l.error.message)):r(l.result);},reject:i}),this.ws.send(JSON.stringify(s)),Be.debug("WebSocketConnection: sent request",{method:t,id:o});})}subscribe(t,n){return Be.debug("WebSocketConnection: subscribe called",{sessionId:t}),this.subscriptions.has(t)?Be.debug("WebSocketConnection: already subscribed",{sessionId:t,callbackCount:this.subscriptions.get(t)?.size}):(this.subscriptions.set(t,new Set),Be.debug("WebSocketConnection: subscribing to session",{sessionId:t}),this.send("session.subscribe",{sessionId:t}).catch(o=>{Be.error("WebSocketConnection: subscribe failed",{sessionId:t,error:String(o)});})),this.subscriptions.get(t).add(n),Be.debug("WebSocketConnection: callback added",{sessionId:t,callbackCount:this.subscriptions.get(t)?.size}),()=>{Be.debug("WebSocketConnection: unsubscribe called",{sessionId:t});let o=this.subscriptions.get(t);o&&(o.delete(n),Be.debug("WebSocketConnection: callback removed",{sessionId:t,remainingCallbacks:o.size}),o.size===0&&(this.subscriptions.delete(t),this.send("session.unsubscribe",{sessionId:t}).catch(s=>{Be.error("WebSocketConnection: unsubscribe failed",{sessionId:t,error:String(s)});})));}}isConnected(){return this._state==="connected"}handleMessage(t){Be.debug("WebSocketConnection: received message",{data:t.slice(0,200)});try{let n=JSON.parse(t);if(Be.debug("WebSocketConnection: parsed message",{method:n.method,id:n.id,hasParams:!!n.params}),n.id!==void 0&&n.id!==null){Be.debug("WebSocketConnection: handling response",{id:n.id});let o=this.pendingRequests.get(n.id);if(o){this.pendingRequests.delete(n.id),o.resolve(n);return}Be.debug("WebSocketConnection: no handler for response",{id:n.id});return}if(n.jsonrpc==="2.0"&&n.method&&!n.id){Be.debug("WebSocketConnection: notification",{method:n.method});let o=n.params||{},s=o.sessionId;if(Be.debug("WebSocketConnection: sessionId from notification",{sessionId:s}),s){let r=this.subscriptions.get(s);if(Be.debug("WebSocketConnection: callbacks for notification",{sessionId:s,callbackCount:r?.size??0}),r&&r.size>0){let i={type:n.method,properties:o};for(let c of r)try{c(i);}catch(l){Be.error("WebSocketConnection: notification callback error",{method:n.method,error:String(l)});}}else Be.debug("WebSocketConnection: no callbacks for notification",{method:n.method,sessionId:s});}else Be.debug("WebSocketConnection: no sessionId in notification",{method:n.method});}}catch(n){Be.warn("WebSocketConnection: failed to parse message",{error:String(n)});}}handleReconnect(){if(!this.config.reconnect?.enabled)return;if(this.reconnectAttempts>=this.config.reconnect.maxAttempts){Be.warn("WebSocketConnection: max reconnect attempts reached");return}this.reconnectAttempts++;let t=this.config.reconnect.delayMs*this.reconnectAttempts;Be.debug("WebSocketConnection: attempting reconnect",{attempt:this.reconnectAttempts,delay:t}),this._state="reconnecting",setTimeout(async()=>{try{await this.connect();for(let n of this.subscriptions.keys())await this.send("session.subscribe",{sessionId:n});}catch(n){Be.error("WebSocketConnection: reconnect failed",{error:String(n)});}},t);}},Ul=class{constructor(t){b$1(this,"config");b$1(this,"_state","disconnected");b$1(this,"connectionId",null);b$1(this,"abortController",null);b$1(this,"sseAbortFn",null);b$1(this,"reader",null);b$1(this,"subscriptions",new Map);b$1(this,"pendingRequests",new Map);b$1(this,"requestId",1);let n=t.url.replace(/\/$/,"");n.includes("/acp")||(n+="/acp"),this.config={...t,url:n};}get state(){return this._state}async connect(){this._state!=="connected"&&(this._state="connected");}async disconnect(){if(this.sseAbortFn&&(this.sseAbortFn(),this.sseAbortFn=null),this.connectionId)try{let t={};this.config.token&&(t.Authorization=`Bearer ${this.config.token}`),t["Acp-Connection-Id"]=this.connectionId,await Fetch.request(this.config.url,{method:"DELETE",headers:t});}catch{}if(this.abortController&&(this.abortController.abort(),this.abortController=null),this.reader){try{await this.reader.cancel();}catch{}this.reader=null;}this._state="disconnected",this.connectionId=null,this.subscriptions.clear();}async send(t,n){let o=this.config.url,s="POST",r=["initialize","session.new","session.load","session.fork","session.resume","session.prompt","session.cancel","session.setMode","session.setConfigOption","session.setModel","session.close","authenticate"],i={"Content-Type":"application/json"};this.config.token&&(i.Authorization=`Bearer ${this.config.token}`);let c;n&&typeof n=="object"&&"sessionId"in n&&(c=n.sessionId,this.connectionId&&(i["Acp-Connection-Id"]=this.connectionId,i["Acp-Session-Id"]=c));let l={jsonrpc:"2.0",id:String(this.requestId++),method:t,params:n};r.includes(t)&&(s="POST");let d=await Fetch.request(o,{method:s,headers:i,body:JSON.stringify(l),timeout:this.config.timeout??300*1e3});if(!d.ok)throw new Error(`HTTP ${d.status}: ${d.statusText}`);let m=d.headers.get("Acp-Connection-Id");return m&&t==="initialize"&&!this.connectionId&&(this.connectionId=m,Be.debug("HTTPConnection: got connectionId",{connectionId:m})),d.data.result??d.data}subscribe(t,n){return this.subscriptions.has(t)||(this.subscriptions.set(t,new Set),this.startSSE(t).catch(o=>{Be.error("HTTPConnection: startSSE failed",{sessionId:t,error:String(o)});})),this.subscriptions.get(t).add(n),()=>{let o=this.subscriptions.get(t);o&&(o.delete(n),o.size===0&&this.subscriptions.delete(t));}}isConnected(){return this._state==="connected"}async startSSE(t){let n=this.config.url,o={};this.config.token&&(o.Authorization=`Bearer ${this.config.token}`),this.connectionId&&(o["Acp-Connection-Id"]=this.connectionId,o["Acp-Session-Id"]=t),this.abortController=new AbortController,this.sseAbortFn=Fetch.sse(n,{onMessage:s=>{try{let r=JSON.parse(s);if(r.jsonrpc==="2.0"&&r.method&&!r.id){let i={type:r.method,properties:{...r.params,sessionId:r.params?.sessionId||t}},c=this.subscriptions.get(t);if(c)for(let l of c)try{l(i);}catch(d){Be.error("HTTPConnection: callback error",{sessionId:t,error:String(d)});}}}catch{}},onError:s=>{Be.error("HTTPConnection: SSE connection failed",{sessionId:t,error:s.message});},onComplete:()=>{Be.debug("HTTPConnection: SSE stream completed",{sessionId:t});}},{headers:o});}},zl=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",Be.debug("STDIOConnection: connecting",{command:this.config.command});try{let t=process.platform==="win32"?"cmd":void 0;if(this.process=Shell.spawn(t,this.config.command,{stdout:"pipe",stderr:"pipe",stdin:"pipe",env:this.config.env,cwd:this.config.cwd||process.cwd(),timeout:this.config.timeout??1800*1e3}),!this.process.stdout||!this.process.stdin)throw new Error("Failed to create stdio pipes");let n=this.process.stdin,o=this.process.stdout,s=new WritableStream({write:d=>new Promise((m,f)=>{n.write(d,a=>{a?f(a):m();});})}),r=new ReadableStream({start(d){let m="";o.on("data",f=>{m+=f.toString();let a=m.split(`
142
+ `);m=a.pop()??"";for(let p of a)p.trim()?.startsWith("{")&&d.enqueue(new TextEncoder().encode(p+`
143
+ `));}),o.on("end",()=>{m.trim()&&m.startsWith("{")&&d.enqueue(new TextEncoder().encode(m+`
144
+ `)),d.close();}),o.on("error",f=>d.error(f));}}),i=ndJsonStream(s,r),c=this,l={async sessionUpdate(d){let m=d.sessionId,f=c.subscriptions.get(m),a=Array.from(c.subscriptions.keys());if(Be.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(g){Be.error("STDIOConnection: sessionUpdate callback error",{sessionId:m,error:String(g)});}}else Be.debug("STDIOConnection: sessionUpdate skipped - session not subscribed",{sessionId:m,updateType:d.update?.sessionUpdate,messageId:d.update?.messageId});},async requestPermission(d){return Be.debug("STDIOConnection: requestPermission",{toolCall:d.toolCall}),{outcome:{outcome:"selected",optionId:"allow"}}},async extNotification(d,m){Be.debug("STDIOConnection: extNotification",{method:d,params:m});},async extMethod(d,m){return Be.debug("STDIOConnection: extMethod",{method:d,params:m}),{}},async requestQuestion(d){if(Be.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=>{Be.debug("STDIOConnection: subprocess exited",{code:d}),this._state="disconnected",this.connection=null;}).catch(d=>{Be.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",Be.debug("STDIOConnection: connected");}catch(t){throw Be.error("STDIOConnection: failed to connect",{error:String(t)}),this._state="disconnected",t}}}async disconnect(){Be.debug("STDIOConnection: disconnecting"),this.process&&(this.process.kill(),this.process=null),this.connection=null,this._state="disconnected",this.subscriptions.clear();}async send(t,n){if(!this.connection)throw new Error("Not connected");if(this._state!=="connected")throw new Error(`Cannot send ${t}: connection state is ${this._state}`);Be.debug("STDIOConnection: send",{method:t,state:this._state});try{switch(t){case "initialize":return this.connection.initialize(n);case "session.new":return this.connection.newSession(n);case "session.load":return this.connection.loadSession(n);case "session.list":return this.connection.listSessions(n);case "session.fork":return this.connection.unstable_forkSession(n);case "session.resume":return this.connection.resumeSession(n);case "session.close":return this.connection.closeSession(n);case "session.prompt":return this.connection.prompt(n);case "session.cancel":return this.connection.cancel(n);case "session.setMode":return this.connection.setSessionMode(n);case "session.setConfigOption":return this.connection.setSessionConfigOption(n);case "authenticate":return this.connection.authenticate(n);default:throw new Error(`Unsupported method: ${t}`)}}catch(o){throw o instanceof Error&&o.message.includes("stream")&&(Be.error("STDIOConnection: stream error, marking as disconnected",{error:o.message,method:t}),this._state="disconnected",this.connection=null),o}}subscribe(t,n){return this.subscriptions.has(t)||this.subscriptions.set(t,new Set),this.subscriptions.get(t).add(n),()=>{let o=this.subscriptions.get(t);o&&(o.delete(n),o.size===0&&this.subscriptions.delete(t));}}isConnected(){return this._state==="connected"}};function ql(e){switch(e.type){case "websocket":return new Nl({url:e.url,token:e.token,reconnect:e.reconnect,timeout:e.timeout});case "http":return new Ul({url:e.url,token:e.token,timeout:e.timeout});case "stdio":return new zl({command:e.url,env:e.token?{EASBOT_TOKEN:e.token}:void 0,cwd:e.cwd,timeout:e.timeout});default:throw new Error(`Unsupported connection type: ${e.type}`)}}var En={includeThinking:false,includeToolDetails:false,includeToolOutput:false};var Oe=a.create({service:"acp-client"}),PI=300*1e3,jo=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=ql(t),Oe.debug("ACPClient created",{type:t.type,url:t.url});}async initialize(t={protocolVersion:1}){if(this.initialized)return Oe.debug("ACPClient: already initialized"),{protocolVersion:t.protocolVersion,agentInfo:{name:"acp-client",version:"1.0.0"}};Oe.debug("ACPClient: initializing connection");try{await this.connection.connect();let n=await this.connection.send("initialize",t);return this.initialized=!0,Oe.debug("ACPClient: initialization complete"),n}catch(n){throw Oe.error("ACPClient: initialization failed",{error:n instanceof Error?n.message:String(n)}),n}}async authenticate(t){this.ensureInitialized(),Oe.debug("ACPClient: authenticate");try{return await this.connection.send("authenticate",t)}catch(n){throw Oe.error("ACPClient: authentication failed",{error:n instanceof Error?n.message:String(n)}),n}}async disconnect(){this.disconnected||(Oe.debug("ACPClient: disconnecting"),this.disconnected=true,await this.connection.disconnect(),Oe.debug("ACPClient: disconnected"));}async newSession(t){this.ensureInitialized(),Oe.debug("ACPClient: newSession",{cwd:t.cwd});let n=await this.connection.send("session.new",t);return Oe.debug("ACPClient: newSession complete",{sessionId:n.sessionId}),n}async loadSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: loadSession",{sessionId:t.sessionId}),this.connection.send("session.load",t)}async listSessions(t){return this.ensureInitialized(),Oe.debug("ACPClient: listSessions",{cwd:t.cwd}),this.connection.send("session.list",t)}async unstable_forkSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: forkSession",{sessionId:t.sessionId}),this.connection.send("session.fork",t)}async resumeSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: resumeSession",{sessionId:t.sessionId}),this.connection.send("session.resume",t)}async closeSession(t){return this.ensureInitialized(),Oe.debug("ACPClient: closeSession",{sessionId:t.sessionId}),this.connection.send("session.close",t)}async prompt(t){this.ensureInitialized();let n=t.sessionId;Oe.debug("ACPClient: prompt",{sessionId:n,promptLength:t.prompt.length});let o=await this.connection.send("session.prompt",t);return Oe.debug("ACPClient: prompt complete",{sessionId:n,stopReason:o.stopReason}),o}async cancel(t){this.ensureInitialized(),Oe.debug("ACPClient: cancel",{sessionId:t.sessionId}),await this.connection.send("session.cancel",t),Oe.debug("ACPClient: cancel complete",{sessionId:t.sessionId});}async setSessionMode(t){return this.ensureInitialized(),Oe.debug("ACPClient: setSessionMode",{sessionId:t.sessionId,modeId:t.modeId}),this.connection.send("session.setMode",t)}async setSessionConfigOption(t){return this.ensureInitialized(),Oe.debug("ACPClient: setSessionConfigOption",{sessionId:t.sessionId,configId:t.configId}),this.connection.send("session.setConfigOption",t)}subscribeSessionEvents(t,n,o=En){return n.onMessage&&this.messageCallbacks.add(n.onMessage),this.connection.subscribe(t,s=>{let r=s.properties.messageId;if(s.type==="agent_thought_chunk"&&o.includeThinking&&r){let d=s.properties;if(d.content?.type==="text"&&d.content.text){let m=this.messageCollectors.get(r);m||(m={sessionId:t,text:"",thinkings:[],tools:[],hasText:false,hasUsage:false,filterConfig:o,createdAt:Date.now()},this.messageCollectors.set(r,m)),m.thinkings.push(d.content.text);}}if(s.type==="agent_message_chunk")if(Oe.debug("agent_message_chunk: received",{eventMessageId:r}),r){let d=s.properties;if(d.content?.type==="text"&&d.content.text){let m=this.messageCollectors.get(r);m||(m={sessionId:t,text:"",thinkings:[],tools:[],hasText:false,hasUsage:false,filterConfig:o,createdAt:Date.now()},this.messageCollectors.set(r,m),Oe.debug("agent_message_chunk: created new collector",{eventMessageId:r,collectorCount:this.messageCollectors.size})),m.text+=d.content.text,m.hasText=true,Oe.debug("agent_message_chunk: hasText=true",{eventMessageId:r,hasUsage:m.hasUsage}),m.hasUsage&&(Oe.debug("agent_message_chunk: triggering send",{eventMessageId:r}),this.checkAndSendMessage(r,m.tokens));}else Oe.debug("agent_message_chunk: skipped - no text content",{contentType:d.content?.type});}else Oe.debug("agent_message_chunk: skipped - no messageId");let i=d=>["agent_message_chunk","agent_message","tool_call_update","message_text","message_end","thinking_chunk","usage_update","available_commands_update","config_option_update","current_mode_update","error"].includes(d),c=s.type,l=s.properties?.sessionUpdate||c;if(!i(l))Oe.debug("subscribeSessionEvents: non-standard event type, dispatching as notification",{actualEventType:l,rawEventType:c,properties:s.properties}),this.dispatchNotification(l,s.properties);else {let d={...s,type:l};this.dispatchEvent(d);}n.onSessionUpdate&&n.onSessionUpdate(s);})}dispatchNotification(t,n){let o=this.notificationCallbacks.get(t);if(o&&o.size>0){Oe.debug("ACPClient: dispatching notification",{method:t,callbackCount:o.size});for(let s of o)try{s(n);}catch(r){Oe.error("ACPClient: notification callback error",{method:t,error:String(r)});}}if(t==="session.status"){let s=n.status?.type??"idle";for(let r of this.sessionStatusCallbacks)try{r(s);}catch(i){Oe.error("ACPClient: sessionStatus callback error",{error:String(i)});}}}checkAndSendMessage(t,n){let o=this.messageCollectors.get(t);if(!o){Oe.debug("checkAndSendMessage: collector not found",{messageId:t});return}if(!o.hasText||!o.hasUsage){Oe.debug("checkAndSendMessage: conditions not met",{messageId:t,hasText:o.hasText,hasUsage:o.hasUsage});return}Oe.debug("checkAndSendMessage: sending message",{messageId:t,callbackCount:this.messageCallbacks.size}),this.messageCallbacks.size===0&&Oe.warn("checkAndSendMessage: no message callbacks registered",{messageId:t});try{let r={role:"assistant",text:o.text||void 0,thinking:o.filterConfig.includeThinking&&o.thinkings.join("")||void 0,tools:o.filterConfig.includeToolDetails&&(o.tools?.length??0)>0?o.tools:void 0,metadata:{sessionId:o.sessionId,messageId:t,timestamp:Date.now(),tokens:n?{input:n.input,output:n.output,total:n.input+n.output+(n.reasoning??0)}:void 0}};for(let i of this.messageCallbacks)i(r);}catch(r){Oe.error("ACPClient: checkAndSendMessage error",{error:r instanceof Error?r.message:String(r)});}this.messageCollectors.delete(t);let s=this.collectorCleanupTimers.get(t);s&&(clearTimeout(s),this.collectorCleanupTimers.delete(t)),Oe.debug("checkAndSendMessage: message sent and collector cleaned",{messageId:t});}dispatchEvent(t){let{type:n,properties:o}=t;switch(n){case "tool_call_update":{let s=o.status==="running"?"in_progress":o.status??"pending",r={callId:o.toolCallId??"",tool:o.title??"",status:s,kind:o.kind,title:o.title,input:o.rawInput,output:o.rawOutput?.output,error:o.rawOutput?.error,content:o.content,locations:[]},c=o._meta?.messageId;if(c){let l=this.messageCollectors.get(c);l?.filterConfig.includeToolDetails&&(s==="completed"||s==="error")&&(l.tools||(l.tools=[]),l.tools.push({name:r.tool,status:s==="completed"?"completed":"error",output:l.filterConfig.includeToolOutput?r.output:void 0,error:r.error}));}for(let l of this.toolCallbacks)try{l(r);}catch(d){Oe.error("ACPClient: tool callback error",{error:d instanceof Error?d.message:String(d)});}break}case "error":{o.error&&Oe.error("ACPClient: received error event",{name:o.error.name,data:o.error.data});break}case "usage_update":{let s=o,r=s._meta?.messageId;if(r){let i=this.messageCollectors.get(r);i||(i={sessionId:o.sessionId??"",text:"",thinkings:[],tools:[],hasText:false,hasUsage:true,tokens:void 0,filterConfig:s._meta?.filterConfig??En,createdAt:Date.now()},this.messageCollectors.set(r,i),Oe.debug("usage_update: created new collector",{messageId:r,collectorCount:this.messageCollectors.size})),i.hasUsage=true,i.tokens={input:0,output:0,reasoning:0,...o.tokens},Oe.debug("usage_update: hasUsage=true",{messageId:r,hasText:i.hasText}),i.hasText?(Oe.debug("usage_update: triggering send",{messageId:r}),this.checkAndSendMessage(r,i.tokens)):this.scheduleCollectorCleanup(r);}for(let i of this.usageCallbacks)try{i({used:o.used??0,size:o.size??0});}catch(c){Oe.error("ACPClient: usage callback error",{error:c instanceof Error?c.message:String(c)});}break}case "available_commands_update":{for(let s of this.commandsCallbacks)try{s(o.availableCommands??[]);}catch(r){Oe.error("ACPClient: commands callback error",{error:r instanceof Error?r.message:String(r)});}break}case "config_option_update":{for(let s of this.configCallbacks)try{s(o.configOptions??[]);}catch(r){Oe.error("ACPClient: config callback error",{error:r instanceof Error?r.message:String(r)});}break}case "current_mode_update":{for(let s of this.modeCallbacks)try{s(o.currentModeId??"");}catch(r){Oe.error("ACPClient: mode callback error",{error:r instanceof Error?r.message:String(r)});}break}}}onToolCall(t){return this.toolCallbacks.add(t),Oe.debug("ACPClient: tool callback registered",{callbackCount:this.toolCallbacks.size}),()=>{this.toolCallbacks.delete(t),Oe.debug("ACPClient: tool callback unregistered",{callbackCount:this.toolCallbacks.size});}}onQuestion(t){return this.questionCallbacks.add(t),Oe.debug("ACPClient: question callback registered",{callbackCount:this.questionCallbacks.size}),()=>{this.questionCallbacks.delete(t),Oe.debug("ACPClient: question callback unregistered",{callbackCount:this.questionCallbacks.size});}}onPermission(t){return this.permissionCallbacks.add(t),Oe.debug("ACPClient: permission callback registered",{callbackCount:this.permissionCallbacks.size}),()=>{this.permissionCallbacks.delete(t),Oe.debug("ACPClient: permission callback unregistered",{callbackCount:this.permissionCallbacks.size});}}onUsage(t){return this.usageCallbacks.add(t),()=>{this.usageCallbacks.delete(t);}}onCommands(t){return this.commandsCallbacks.add(t),()=>{this.commandsCallbacks.delete(t);}}onConfig(t){return this.configCallbacks.add(t),()=>{this.configCallbacks.delete(t);}}onMode(t){return this.modeCallbacks.add(t),()=>{this.modeCallbacks.delete(t);}}onSessionStatus(t){return this.sessionStatusCallbacks.add(t),()=>{this.sessionStatusCallbacks.delete(t);}}onNotification(t,n){return this.notificationCallbacks.has(t)||this.notificationCallbacks.set(t,new Set),this.notificationCallbacks.get(t).add(n),Oe.debug("ACPClient: notification callback registered",{method:t,callbackCount:this.notificationCallbacks.get(t)?.size}),()=>{let o=this.notificationCallbacks.get(t);o&&(o.delete(n),o.size===0&&this.notificationCallbacks.delete(t)),Oe.debug("ACPClient: notification callback unregistered",{method:t});}}registerQuestionHandler(t){return this.questionHandlers.push(t),Oe.debug("ACPClient: question handler registered",{handlerCount:this.questionHandlers.length}),()=>{let n=this.questionHandlers.indexOf(t);n>-1&&this.questionHandlers.splice(n,1),Oe.debug("ACPClient: question handler unregistered",{handlerCount:this.questionHandlers.length});}}async answerQuestion(t){this.ensureInitialized(),Oe.debug("ACPClient: answerQuestion",{sessionId:t.sessionId,requestId:t.requestId,answerCount:t.answers.length});let n=t.answers.map(o=>`[QUESTION_ANSWER:${t.requestId}] answer: "${o.join(", ")}"`).join(`
145
+ `);await this.connection.send("session.prompt",{sessionId:t.sessionId,prompt:[{type:"text",text:n}]}),Oe.debug("ACPClient: answerQuestion sent",{sessionId:t.sessionId,requestId:t.requestId});}ensureInitialized(){if(!this.initialized)throw new Error("ACPClient not initialized. Call initialize() first.");if(this.disconnected)throw new Error("ACPClient disconnected")}scheduleCollectorCleanup(t){if(this.collectorCleanupTimers.has(t))return;let n=setTimeout(()=>{this.collectorCleanupTimers.delete(t);let o=this.messageCollectors.get(t);o&&(!o.hasText||!o.hasUsage)&&(Oe.debug("scheduleCollectorCleanup: cleaning orphaned collector",{messageId:t,hasText:o.hasText,hasUsage:o.hasUsage}),this.messageCollectors.delete(t));},PI);this.collectorCleanupTimers.set(t,n);}};var TI=a.create({service:"websocket-subscriber"});function Hl(e){return new wc(e)}var wc=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"websocket",url:""},TI.info("WebSocketSubscriber created",{config:this._config});}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,n){let o=n??this._config,s=t||o.url||await this.getConfigWebSocketUrl();if(!s)throw new Error("No WebSocket URL provided and no config URL found");this._client||(this._client=new jo({...o,type:"websocket",url:s}),await this._client.initialize());}async subscribe(t,n,o){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client.subscribeSessionEvents(t,{onMessage:n,onError:o},En)}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}async getConfigWebSocketUrl(){let t=process.env.EASBOT_WS_URL;return t||""}};var AI=a.create({service:"http-subscriber"});function Gl(e){return new Bl(e)}var Bl=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"http",url:""},AI.info("HTTPSubscriber created",{config:this._config});}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,n){let o=n??this._config,s=t||o.url;this._client||(this._client=new jo({...o,type:"http",url:s}),await this._client.initialize());}async subscribe(t,n,o){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client.subscribeSessionEvents(t,{onMessage:n,onError:o},En)}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}};a.create({service:"stdio-subscriber"});function Wl(e){return new xc(e)}var xc=class{constructor(t){b$1(this,"_client",null);b$1(this,"_config");this._config=t??{type:"stdio",url:""};}get client(){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client}async connect(t,n){let o=n??this._config,s=t||o.url;if(this._client)return;let r;s.startsWith("stdio://")?r=`${new URL(s).hostname||"easbot"} acp --channel stdio --log-level ${a.getLevel()}`:s.startsWith("easbot")?r=`${s} --log-level ${a.getLevel()}`:r=`node dist/cli.mjs acp --channel stdio --log-level ${a.getLevel()}`,this._client=new jo({...o,type:"stdio",url:r}),await this._client.initialize();}async subscribe(t,n,o){if(!this._client)throw new Error("Not connected. Call connect() first.");return this._client.subscribeSessionEvents(t,{onMessage:n,onError:o},En)}async disconnect(){if(this._client){try{await this._client.disconnect();}catch{}this._client=null;}}};var kr=class{constructor(t){b$1(this,"log",a.create({service:"gateway:client"}));b$1(this,"config");b$1(this,"ws",null);b$1(this,"state","disconnected");b$1(this,"lastNotifiedState","disconnected");b$1(this,"subscriptions",new Map);b$1(this,"messageCallbacks",new Set);b$1(this,"agentListCallbacks",new Set);b$1(this,"stateCallbacks",new Set);b$1(this,"cachedAgentList",[]);b$1(this,"localAgentList",[]);b$1(this,"heartbeatTimer",null);b$1(this,"heartbeatTimeoutTimer",null);b$1(this,"lastPongReceived",0);b$1(this,"agentListRequestId",null);b$1(this,"agentListRequestResolve",null);b$1(this,"isClosing",false);b$1(this,"connectReject",null);b$1(this,"connectPendingResolve");b$1(this,"connectPendingReject",new Set);this.config={url:t.url,type:t.type,id:t.id??`client_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,heartbeat:{enabled:t.heartbeat?.enabled??true,interval:t.heartbeat?.interval??6e4}},this.log=a.create({service:`gateway:client:${this.config.id}`}),this.connect().catch(()=>{}).finally(()=>{if(this.config.heartbeat.enabled)try{this.startHeartbeat();}catch(n){this.log.error("[gateway:client] failed to start heartbeat:",{error:String(n)});}});}async connect(){if(this.state!=="connected")return this.state==="connecting"?new Promise((t,n)=>{let o=setTimeout(()=>{this.connectPendingReject?.delete(n),n(new Error("Connection timeout while waiting"));},3e4);this.connectPendingReject?.add(n);this.connectPendingResolve;this.connectPendingResolve=()=>{clearTimeout(o),this.connectPendingReject?.delete(n),t(void 0);};}):(this.state="connecting",this.log.info("connecting to gateway",{url:this.config.url}),this.isClosing=false,new Promise((t,n)=>{this.connectReject=n;let o=setTimeout(()=>{this.state==="connecting"&&(this.log.warn("connection timeout, closing socket"),this.state="disconnected",this.connectReject=null,this.ws&&(this.ws.close(4001,"Connection timeout"),this.ws=null),n(new Error("Connection timeout")));},3e4);try{this.ws=new WebSocket(this.config.url),this.ws.onopen=()=>{clearTimeout(o),this.state="connected",this.connectReject=null,this.lastPongReceived=Date.now(),this.notifyStateChange(),this.connectPendingResolve?.(),this.connectPendingResolve=void 0,this.resubscribeAll(),t();},this.ws.onmessage=s=>{this.handleMessage(s.data);},this.ws.onclose=s=>{clearTimeout(o),this.handleClose(s.code,s.reason);},this.ws.onerror=s=>{clearTimeout(o);};}catch(s){clearTimeout(o),this.state="disconnected",this.connectReject=null,this.notifyStateChange(),n(s);}}))}async disconnect(){this.state!=="disconnected"&&(this.isClosing=true,this.stopHeartbeat(),this.cachedAgentList=[],this.localAgentList=[],this.agentListRequestId=null,this.agentListRequestResolve&&(this.agentListRequestResolve([]),this.agentListRequestResolve=null),this.subscriptions.clear(),this.ws&&(this.ws.close(1e3,"Client disconnect"),this.ws=null),this.state="disconnected",this.log.info("disconnected from gateway"),this.notifyStateChange());}async subscribe(t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.subscriptions.has(t)||(this.subscriptions.set(t,{sessionId:t}),this.sendData({type:"subscribe",sessionId:t,clientId:this.config.id}));}async unsubscribe(t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"unsubscribe",sessionId:t,clientId:this.config.id}),this.subscriptions.delete(t);}async send(t){if(this.state!=="connected")throw new Error("Not connected to gateway");this.sendData({type:"message",message:t});}onMessage(t){this.messageCallbacks.add(t);}offMessage(t){this.messageCallbacks.delete(t);}getState(){return this.state}getId(){return this.config.id}getSubscriptions(){return [...this.subscriptions.keys()]}setLocalAgents(t){this.localAgentList=t,this.updateMergedAgentList();}async fetchAgentList(){if(this.state!=="connected")throw new Error("Not connected to gateway");return new Promise((t,n)=>{let o=`req_${Date.now()}_${Math.random().toString(36).substring(2,9)}`;this.agentListRequestId=o,this.agentListRequestResolve=t,this.sendData({type:"agent_list_request",requestId:o}),setTimeout(()=>{this.agentListRequestId===o&&(this.agentListRequestId=null,this.agentListRequestResolve=null,n(new Error("Agent list request timeout")));},1e4);})}async registerAgent(t){if(this.state!=="connected")throw new Error("Not connected to gateway");if(!t.agentId||!t.name||!t.address)throw new Error("Agent ID, name and address are required");this.sendData({type:"agent_register",payload:{agentId:t.agentId,name:t.name,address:t.address,capabilities:t.capabilities,metadata:t.metadata}});}async deregisterAgent(t){if(this.state!=="connected")throw new Error("Not connected to gateway");if(!t)throw new Error("Agent ID is required");this.sendData({type:"agent_deregister",payload:{agentId:t}}),this.log.debug("Agent deregistration sent",{agentId:t});}async subscribeAgentList(t){if(this.state!=="connected"){this.log.debug("Cannot subscribe to agent list: not connected to gateway",{state:this.state});return}this.sendData({type:"agent_subscribe",subscribe:t,clientId:this.config.id}),this.log.debug("Agent list subscription changed",{subscribe:t,clientId:this.config.id});}async agentHeartbeat(t,n){if(this.state!=="connected"){this.log.debug("Cannot send agent heartbeat: not connected to gateway",{state:this.state});return}this.sendData({type:"agent_register",payload:{agentId:t,...n??{}}}),this.log.debug("Agent heartbeat sent",{agentId:t});}getConnectableAgents(t={}){let{localAgents:n,preferLocal:o=true,filterOffline:s=true}=t,r=n||this.localAgentList,i=this.cachedAgentList,c=this.mergeAgentLists(r,i,o);return s?c.filter(l=>l.status!=="offline"):c}onAgentListChange(t){this.agentListCallbacks.add(t);}offAgentListChange(t){this.agentListCallbacks.delete(t);}mergeAgentLists(t,n,o){let s=new Map,r=o?n:t,i=o?t:n;for(let c of r)s.set(c.id,c);for(let c of i)s.set(c.id,c);return Array.from(s.values())}updateMergedAgentList(){let t=this.getConnectableAgents({filterOffline:false});for(let n of this.agentListCallbacks)try{n(t);}catch(o){this.log.error("agent list callback error",{error:String(o)});}}handleAgentListResponse(t,n){n&&this.agentListRequestId===n&&this.agentListRequestResolve&&(this.agentListRequestId=null,this.agentListRequestResolve(t),this.agentListRequestResolve=null),this.cachedAgentList=t,this.updateMergedAgentList(),this.log.debug("received agent list",{count:t.length});}sendData(t){if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.log.warn("WebSocket not ready, cannot send");return}this.ws.send(JSON.stringify(t));}handleMessage(t){try{let n=JSON.parse(t);switch(n.type){case "message":if(this.log.debug("message received",{type:n.type,sessionId:n.sessionId,payloadId:n.payload?.id,payloadType:n.payload?.type}),n.payload&&typeof n.payload=="object"){let o={...n.payload,sessionId:n.sessionId};this.handleGatewayMessage(o);}else this.log.warn("received message with invalid or missing payload");break;case "subscribed":this.subscriptions.set(n.sessionId,n.subscription);break;case "unsubscribed":this.subscriptions.delete(n.sessionId);break;case "pong":this.lastPongReceived=Date.now(),this.log.debug("pong received");break;case "agent_list_response":this.handleAgentListResponse(n.agents||[],n.requestId);break;case "agent_update":this.handleAgentUpdate(n.agent,n.action);break;default:this.log.debug("unknown message type",{type:n.type});}}catch(n){this.log.error("failed to parse message",{error:String(n)});}}handleAgentUpdate(t,n){switch(n){case "add":case "update":{let o=this.cachedAgentList.findIndex(s=>s.id===t.id);o>=0?this.cachedAgentList[o]=t:this.cachedAgentList.push(t);break}case "remove":this.cachedAgentList=this.cachedAgentList.filter(o=>o.id!==t.id);break}this.updateMergedAgentList();}handleGatewayMessage(t){for(let n of this.messageCallbacks)try{n(t);}catch(o){this.log.error("message callback error",{error:String(o)});}}handleClose(t,n){if(this.log.debug("connection closed",{code:t,reason:n,isClosing:this.isClosing}),this.isClosing){this.log.debug("intentional close, skipping reconnect"),this.isClosing=false;return}this.connectReject&&(this.connectReject(new Error(`Connection failed: ${n||t}`)),this.connectReject=null);for(let o of this.connectPendingReject)o(new Error(`Connection failed: ${n||t}`));this.connectPendingReject.clear(),this.connectPendingResolve=void 0,this.state="disconnected",this.ws=null,this.notifyStateChange();}startHeartbeat(){this.lastPongReceived=Date.now(),this.log.info("heartbeat started",{interval:this.config.heartbeat.interval}),this.heartbeatTimer=setInterval(()=>{this.state==="disconnected"?(this.log.debug("heartbeat: disconnected, attempting to connect with backoff"),retry(()=>this.connectWithBackoff(),{attempts:3,delay:1e3,factor:2,maxDelay:4e3,retryIf:()=>false}).catch(()=>{this.log.debug("heartbeat: all retry attempts failed, waiting for next cycle");})):this.state==="connected"&&(this.sendData({type:"ping"}),this.log.debug("ping sent"));},this.config.heartbeat.interval);let t=this.config.heartbeat.interval*5;this.log.debug("heartbeat check started",{interval:this.config.heartbeat.interval,timeout:t}),this.heartbeatTimeoutTimer=setInterval(()=>{if(this.state==="connected"){let n=Date.now()-this.lastPongReceived;n>t&&(this.log.warn("heartbeat timeout",{elapsed:n,timeout:t}),this.ws&&this.ws.close(4e3,"Heartbeat timeout"));}},this.config.heartbeat.interval);}async connectWithBackoff(){this.state==="connected"||this.state==="connecting"||await this.connect();}notifyStateChange(){if(this.state===this.lastNotifiedState){this.log.debug("state unchanged, skipping notification",{state:this.state});return}let t=this.lastNotifiedState;this.lastNotifiedState=this.state,this.log.debug("state changed",{previousState:t,currentState:this.state});for(let n of this.stateCallbacks)try{n(this.state);}catch(o){this.log.error("state callback error",{error:String(o)});}}onStateChange(t){this.stateCallbacks.add(t);}offStateChange(t){this.stateCallbacks.delete(t);}stopHeartbeat(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null),this.heartbeatTimeoutTimer&&(clearInterval(this.heartbeatTimeoutTimer),this.heartbeatTimeoutTimer=null);}async resubscribeAll(){for(let t of this.subscriptions.keys())try{await this.subscribe(t);}catch(n){this.log.error("failed to resubscribe",{sessionId:t,error:String(n)});}}getHttpUrl(){return this.config.url.replace(/^ws:/,"http:").replace(/^wss:/,"https:").replace(/\/$/,"")}async httpRequest(t,n={}){let o=`${this.getHttpUrl()}${t}`,s=n.method||"GET",{signal:r,...i}=n,c=await Fetch.request(o,{method:s,...i,headers:{"Content-Type":"application/json",...i.headers},...r?{signal:r}:{}});if(!c.ok){let l=c.data,d=typeof l=="object"?JSON.stringify(l):String(l||"Unknown error");throw new Error(`HTTP ${c.status}: ${d}`)}return c.data}async healthCheck(){return this.httpRequest("/health")}async getStatus(){return this.httpRequest("/status")}async listChannels(){return this.httpRequest("/channels")}async listContacts(t,n={}){let o=new URLSearchParams({platform:t,limit:String(n.limit??100),offset:String(n.offset??0)});return this.httpRequest(`/contacts?${o}`)}async getContact(t){return this.httpRequest(`/contacts/${encodeURIComponent(t)}`)}async getSession(t){return this.httpRequest(`/sessions/${encodeURIComponent(t)}`)}async createSession(t){return this.httpRequest("/session",{method:"POST",body:JSON.stringify(t??{})})}async getOrCreateSession(t){if(t.sessionId)try{return await this.getSession(t.sessionId),{sessionId:t.sessionId,created:!1}}catch{this.log.debug("session not found, will create new",{sessionId:t.sessionId});}if(t.platform||t.channel||t.userId){let o=t.chatId??t.userId;try{let i=await this.listSessions({platform:t.platform,channelId:t.channel,userId:t.userId,chatId:o});if(i.sessions.length>0){let c=i.sessions[0];if(c)return this.log.debug("found existing session",{sessionId:c.id,channel:t.channel,userId:t.userId,chatId:o}),{sessionId:c.id,created:!1}}}catch(i){this.log.warn("failed to search sessions",{error:String(i)});}let s={channel:{platform:t.platform,channelId:t.channel,userId:t.userId,chatId:o}},r=await this.createSession(s);return this.log.debug("session created",{sessionId:r.id,params:s}),{sessionId:r.id,created:true}}let n=await this.createSession({channel:{platform:"api",channelId:"default"}});return this.log.debug("session created (default)",{sessionId:n.id}),{sessionId:n.id,created:true}}async listSessions(t={}){let n=new URLSearchParams;return n.set("limit",String(t.limit??100)),n.set("offset",String(t.offset??0)),t.platform&&n.set("platform",t.platform),t.channelId&&n.set("channelId",t.channelId),t.userId&&n.set("userId",t.userId),t.chatId&&n.set("chatId",t.chatId),this.httpRequest(`/sessions?${n}`)}async sendMessage(t,n){return this.httpRequest(`/session/${encodeURIComponent(t)}/prompt`,{method:"POST",body:JSON.stringify(n)})}};var ts;(S=>{let e=a.create({service:"agent-services"});function t(A){switch(A){case "healthy":return "online";case "unhealthy":return "offline";case "offline":return "offline";default:return "unknown"}}class n{constructor(y){b$1(this,"storagePath");b$1(this,"gatewayUrl");b$1(this,"services",new Map);b$1(this,"gatewayClient",null);b$1(this,"gatewayCallbacks",{onAgentListChange:y=>{this.updateFromGateway(y);},onStateChange:y=>{y==="connected"&&this.gatewayClient?.subscribeAgentList(true).catch(()=>{});}});this.storagePath=Ce__default.join(a$1.Path.data,"state","agent-services.json"),this.gatewayUrl=y,e.debug("AgentServiceRegistry created",{storagePath:this.storagePath,gatewayUrl:this.gatewayUrl});}async load(y="",x=false){if(await Promise.all([this.loadFromLocalConfig(),this.loadFromClientsConfig()]),x)for(let b of this.services.keys())b.startsWith("gateway:")&&this.services.delete(b);this.gatewayUrl&&await this.loadFromGateway(y),e.debug("Agent services loaded",{count:this.services.size});}async loadFromClientsConfig(){try{let{getACPClientsConfig:y}=await import('./adapter-loader-ZXPJJRRY.mjs'),x=await y();if(!x?.clients||x.clients.length===0)return;for(let b of x.clients){let w=this.extractBaseUrl(b);if(!w)continue;let C=`clients:${b.id}`;if(this.services.has(C))continue;let k=b.agentId??b.id;this.services.set(C,{id:C,name:b.name??b.id,baseUrl:w,agentId:k,capabilities:b.channel?[b.channel]:[],status:"unknown",metadata:{type:b.type,channel:b.channel,autoConnect:b.autoConnect,priority:b.priority},updatedAt:Date.now()});}e.debug("Loaded services from clients config",{count:x.clients.length});}catch(y){e.warn("Failed to load clients config",{error:String(y)});}}extractBaseUrl(y){if(y.connection?.http?.baseUrl)return y.connection.http.baseUrl;if(y.connection?.ws?.url)return y.connection.ws.url;if(y.connection?.stdio)return "stdio://local"}async loadFromLocalConfig(){try{if(!await Tt__default.access(this.storagePath).then(()=>!0).catch(()=>!1))return;let x=await Tt__default.readFile(this.storagePath,"utf-8"),b=JSON.parse(x);if(b.services)for(let w of b.services)this.services.set(w.id,{...w,updatedAt:w.updatedAt??Date.now()});e.debug("Loaded services from local config",{count:b.services?.length??0});}catch(y){e.warn("Failed to load local config",{error:String(y)});}}async loadFromGateway(y=""){if(!this.gatewayUrl)return;let x=`${y}_agent_services`;this.gatewayClient=new kr({url:this.gatewayUrl,type:"subagent",id:x,heartbeat:{enabled:true,interval:6e4}}),this.gatewayClient.onAgentListChange(this.gatewayCallbacks.onAgentListChange),this.gatewayClient.onStateChange(this.gatewayCallbacks.onStateChange),e.debug("Gateway client initialized, will subscribe on connect");}updateFromGateway(y){for(let x of y){let b=`gateway:${x.id}`;this.services.set(b,{id:b,name:x.name,baseUrl:x.address,agentId:x.id,capabilities:x.capabilities??[],status:t(x.status),metadata:{sourceGatewayId:x.sourceGatewayId,...x.metadata},updatedAt:x.updatedAt});}e.debug("Gateway agent list updated",{count:y.length});}listServices(y){let x=Array.from(this.services.values());return y?.status&&(x=x.filter(b=>b.status===y.status)),y?.capability&&(x=x.filter(b=>b.capabilities.includes(y.capability))),x}getService(y){return this.services.get(y)}getServiceByUrl(y){for(let x of this.services.values())if(x.baseUrl===y)return x}async registerService(y){let x={...y,updatedAt:Date.now()};this.services.set(y.id,x),await this.save();}async unregisterService(y){this.services.delete(y)&&await this.save();}async updateServiceStatus(y,x){let b=this.services.get(y);b&&(b.status=x,b.updatedAt=Date.now(),await this.save());}async save(){let y={version:1,services:Array.from(this.services.values())};try{await Tt__default.mkdir(Ce__default.dirname(this.storagePath),{recursive:!0}),await Tt__default.writeFile(this.storagePath,JSON.stringify(y,null,2),"utf-8"),e.debug("Services saved",{count:this.services.size});}catch(x){e.error("Failed to save services",{error:String(x)}),await this.saveBackup(y);}}async saveBackup(y){try{let x=this.storagePath+".backup";await Tt__default.writeFile(x,JSON.stringify(y,null,2),"utf-8"),e.debug("Services backup saved",{backupPath:x});}catch(x){e.error("Failed to save services backup",{error:String(x)});}}async disconnect(){this.gatewayClient&&(this.gatewayClient.offAgentListChange(this.gatewayCallbacks.onAgentListChange),this.gatewayClient.offStateChange(this.gatewayCallbacks.onStateChange),await this.gatewayClient.subscribeAgentList(false),await this.gatewayClient.disconnect(),this.gatewayClient=null);}}let o=new Map,s="";function r(A){let y=o.get(A);return y||(y=_.state(async()=>{let x;try{let{getGatewayClientUrl:w}=await import('./gateway-loader-OH3VCEUD.mjs');x=await w();}catch(w){e.warn("Failed to get Gateway URL",{error:String(w)});}let b=new n(x);return await b.load(A),e.info("AgentServices initialized",{prefix:A,gatewayUrl:x,servicesCount:b.listServices().length}),{registry:b,gatewayUrl:x,initialized:true}},async x=>{x?.registry&&await x.registry.disconnect();}),o.set(A,y)),y}function i(){return r(s)()}async function c(){return (await i()).registry}S.get=c;async function l(A){return (await c()).listServices(A)}S.listServices=l;async function d(A){return (await c()).getService(A)}S.getService=d;async function m(A){return (await c()).getServiceByUrl(A)}S.getServiceByUrl=m;async function f(A){await(await c()).registerService(A);}S.registerService=f;async function a$2(A){await(await c()).unregisterService(A);}S.unregisterService=a$2;async function p(A,y){await(await c()).updateServiceStatus(A,y);}S.updateServiceStatus=p;async function u(){return (await i()).initialized}S.isInitialized=u;async function g(A){s=A,await r(A)(),e.debug("AgentServices init",{prefix:A});}S.init=g;async function h(){await(await c()).load(s,true);}S.refresh=h;})(ts||(ts={}));function _I(e,t){switch(t){case "websocket":return Dl(e);case "http":return $l(e);case "stdio":return e;default:throw new Error(`Unsupported channel type: ${t}`)}}function MI(e){let t=e.type;switch(t){case "websocket":return Hl(e);case "http":return Gl(e);case "stdio":return Wl(e);default:throw new Error(`Unsupported channel type: ${t}`)}}var Qn;(l=>{async function e(d){let{config:m,sessionId:f}=d,a=m.type,p=m.url,u=m.cwd??process.cwd(),g=MI(m);await g.connect(p);let h=f;if(h?(await g.client.listSessions({cwd:u})).sessions?.find(y=>y.sessionId===h)?await g.client.resumeSession({sessionId:h,cwd:u}):h=(await g.client.newSession({cwd:u,mcpServers:[]})).sessionId:h=(await g.client.newSession({cwd:u,mcpServers:[]})).sessionId,!h)throw new Error("Failed to create remote session");return {baseUrl:p,sessionId:h,channel:a,subscriber:g}}l.connect=e;async function t(d,m,f){await d.client.prompt({sessionId:m,prompt:f});}l.send=t;async function n(d,m){await d.client.cancel({sessionId:m});}l.interrupt=n;async function o(d){let m=await d.client.initialize({protocolVersion:1});return {protocolVersion:m.protocolVersion,agentCapabilities:{modes:[],models:[],...m.agentInfo},authMethods:[]}}l.capabilities=o;async function s(d,m){let a=(await d.client.listSessions({cwd:process.cwd()})).sessions?.find(p=>p.sessionId===m);return a?{status:"active",sessionId:a.sessionId,cwd:a.cwd,title:a.title,exists:true}:{status:"not_found",sessionId:m,exists:false}}l.status=s;async function r(d,m){await d.client.cancel({sessionId:m});}l.releaseSubscription=r;async function i(d){return {sessions:(await d.client.listSessions({cwd:process.cwd()})).sessions??[]}}l.subscriptions=i;function c(d,m){return _I(d,m)}l.getConnectionUrl=c;})(Qn||(Qn={}));function Ym(e,t){let n=btoa(String.fromCharCode(...e));return `data:${t??"application/octet-stream"};base64,${n}`}function Xm(e,t){let n=[];if(t&&n.push(`<system-reminder>
146
+ ${t}
147
+ </system-reminder>`),e)for(let o of e)switch(o.type){case "text":o.text&&n.push(`<text>
148
+ ${o.text}
149
+ </text>`);break;case "image":{let s="";typeof o.image=="string"?s=o.image:o.image instanceof URL?s=o.image.toString():o.image instanceof Uint8Array&&(s=Ym(o.image,o.mime)),n.push(`<image mime="${o.mime??"image/png"}">
150
+ ${s}
151
+ </image>`);break}case "file":{let s="";typeof o.data=="string"?s=o.data:o.data instanceof URL?s=o.data.toString():o.data instanceof Uint8Array&&(s=Ym(o.data,o.mime)),n.push(`<file mime="${o.mime??"application/octet-stream"}">
152
+ ${s}
153
+ </file>`);break}case "command":n.push(o.arguments?`/${o.command} ${o.arguments}`:`/${o.command}`);break}return n.join(`
154
+ `)}var pn=a.create({service:"subagent.acp"}),Ic=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){pn.debug("ACPAgentHandler.start: already connected, reusing",{name:this.config.name});return}let t=this.config.transport==="websocket"?"websocket":this.config.transport==="http"?"http":"stdio",n=this.config.uri??this.buildUrl(this.config);pn.debug("ACPAgentHandler.start",{type:t,url:n,cwd:this.config.cwd??_.directory??process.cwd(),name:this.config.name});try{let o=await Qn.connect({config:{type:t,url:n,cwd:this.config.cwd??_.directory??process.cwd(),timeout:this.config.timeout,env:this.config.env}});this.subscriber=o.subscriber,this.sessionId=o.sessionId,this._isRunning=!0,pn.info("ACPAgentHandler started",{name:this.config.name,type:t,url:n});}catch(o){throw pn.error("ACPAgentHandler.start failed",{name:this.config.name,error:String(o)}),o}}async stop(){if(pn.debug("ACPAgentHandler.stop",{sessionId:this.sessionId,name:this.config?.name}),this.unsubscribeFn&&(this.unsubscribeFn(),this.unsubscribeFn=null),this.subscriber&&this.sessionId)try{await Qn.releaseSubscription(this.subscriber,this.sessionId);}catch(t){pn.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");pn.debug("ACPAgentHandler.execute",{title:t.title,agent:t.agent,partsCount:t.parts?.length??1});let n=this.config?.timeout??300*1e3;this.config?.cwd??process.cwd();let s=this.subscriber.client,r=await new Promise((i,c)=>{let l="",d,m,f=0,a=false,p=setTimeout(()=>{a||(a=true,pn.debug("ACPAgentHandler.execute timeout",{timeout:n,messageCount:f}),i({title:t.title,output:l,metadata:{sessionId:this.sessionId??void 0,agent:t.agent,messageId:d,tokens:m}}));},n);(async()=>{try{let u=this.sessionId;if(!u)throw new Error("No session available. Call start() first.");pn.debug("ACPAgentHandler: using existing session",{sessionId:u}),this.unsubscribeFn=s.subscribeSessionEvents(u,{onMessage:h=>{f++,pn.debug("ACPAgentHandler: message received",{messageCount:f,hasText:!!h.text,textLength:h.text?.length??0}),h.text&&(l=h.text),d=h.metadata.messageId,m=h.metadata.tokens,a||(a=!0,clearTimeout(p),i({title:t.title,output:l,metadata:{sessionId:u,agent:t.agent,messageId:d,tokens:m}}));},onError:h=>{if(h.message?.includes("NotFoundError")){pn.debug("ACPAgentHandler: ignored NotFoundError",{sessionId:u});return}pn.error("ACPAgentHandler: subscription error",{error:h.message});}},{includeThinking:!1,includeToolDetails:!1,includeToolOutput:!1});let g=Xm(t.parts,t.system);await s.prompt({sessionId:u,prompt:[{type:"text",text:g}]}),pn.debug("ACPAgentHandler.execute prompt sent",{title:t.title,sessionId:u});}catch(u){a||(a=true,clearTimeout(p),c(u));}})();});return pn.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&&(pn.debug("ACPAgentHandler.interrupt",{sessionId:this.sessionId}),await Qn.interrupt(this.subscriber,this.sessionId));}isRunning(){return this._isRunning}async checkHealth(){if(!this._isRunning||!this.subscriber)return false;try{if(this.sessionId){let n=(await this.subscriber.client.listSessions({cwd:this.config?.cwd??process.cwd()}))?.sessions;return !n||!Array.isArray(n)?!1:n.some(o=>o.sessionId===this.sessionId)}return !0}catch(t){return pn.debug("ACPAgentHandler.checkHealth failed",{error:String(t)}),false}}buildUrl(t){if(t.uri)return t.uri;let n=t.command??"easbot",o=t.args??["acp","--channel","stdio"];return `${n} ${o.join(" ")}`}};var tt;(c=>{let e;function t(){return e||(e=_.state(async()=>({...process.env}))),e}function n(){return t()()}async function o(l){return (await n())[l]}c.get=o;async function s(){return await n()}c.all=s;async function r(l,d){let m=await n();m[l]=d;}c.set=r;async function i(l){let d=await n();delete d[l];}c.remove=i;})(tt||(tt={}));var vc=a.create({service:"subagent.cli"}),Sc=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,vc.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");vc.debug("CLIAgentHandler.execute",{title:t.title,command:this.config.command});let n=this.buildArgs(t),o=this.config.command,s=this.config.cwd,i={...await tt.all(),...this.config.env},c=this.config.timeout??3e5,l={...process.env,...i};this.abortController=new AbortController;let d=process.platform==="win32"?"cmd":void 0;this.process=Shell.spawn(d,`${o} ${n.join(" ")}`,{cwd:s,env:l,stdout:"pipe",stderr:"pipe",stdin:"null",timeout:c,signal:this.abortController.signal});let m="",f="";this.process.stdout?.on("data",a=>{m+=a.toString("utf-8");}),this.process.stderr?.on("data",a=>{f+=a.toString("utf-8");});try{let a=await this.process.exited;if(a===0)return {title:t.title,output:m.trim(),metadata:{command:o,args:n,exitCode:a}};throw vc.error("CLI exited with error",{code:a,stderr:f}),new Error(`CLI exited with code ${a}: ${f}`)}catch(a){let p=a;throw vc.error("CLI process error",{error:p.message}),a}finally{this.process=null,this._isRunning=false;}}async interrupt(){this.abortController&&this.abortController.abort();}isRunning(){return this._isRunning}async checkHealth(){return this._isRunning?this.process!==null||this._isRunning:false}buildArgs(t){let n=[...this.config?.args??[]],o=t.parts?.filter(s=>s.type==="text").map(s=>s.type==="text"&&"text"in s?s.text:"").filter(Boolean).join(`
155
+ `)||t.title;return n.push("--prompt",o),n}};var xn=a.create({service:"subagent.registry"}),Cc=class{constructor(t){b$1(this,"instances",new Map);b$1(this,"handlers",new Map);b$1(this,"config");b$1(this,"agentCounts",new Map);b$1(this,"idleCleanupTimer",null);this.config=t,this.startIdleCleanup();}startIdleCleanup(){if(this.idleCleanupTimer)return;let t=this.config.idleCheckInterval??300*1e3,n=this.config.idleTimeout??1800*1e3;this.idleCleanupTimer=setInterval(()=>{this.cleanupIdleInstances(n);},t),xn.debug("Idle cleanup timer started",{interval:t,timeout:n});}stopIdleCleanup(){this.idleCleanupTimer&&(clearInterval(this.idleCleanupTimer),this.idleCleanupTimer=null,xn.debug("Idle cleanup timer stopped"));}async cleanupIdleInstances(t){let n=Date.now(),o=[];for(let[s,r]of this.instances){if(r.config.runMode!=="persistent"||r.status!=="idle"&&r.status!=="error")continue;n-r.lastActiveAt>t&&o.push(s);}if(o.length>0){xn.debug("Cleaning up idle instances",{count:o.length,maxIdleTime:t});for(let s of o)try{await this.terminate(s);}catch(r){xn.warn("Failed to cleanup idle instance",{id:s,error:String(r)});}}}async checkInstanceHealth(t){let n=this.handlers.get(t.id);if(!n)return false;try{return "checkHealth"in n&&typeof n.checkHealth=="function"?await n.checkHealth():n.isRunning()}catch{return false}}async spawn(t){let n=Identifier.ascending("subagent"),o={id:n,config:t,status:"starting",createdAt:Date.now(),lastActiveAt:Date.now()},s=this.createHandler(t);this.handlers.set(n,s),this.instances.set(n,o);try{return await s.start(t),o.status="idle",this.agentCounts.set(t.name,(this.agentCounts.get(t.name)??0)+1),xn.debug("Agent spawned",{id:n,name:t.name,status:o.status}),o}catch(r){throw o.status="error",o.error=String(r),this.handlers.delete(n),this.instances.delete(n),xn.error("Failed to spawn agent, cleaned up",{id:n,name:t.name,error:String(r)}),r}}createHandler(t){switch(t.transport){case "stdio":case "http":case "websocket":return new Ic(t);case "cli":return new Sc(t);default:throw new Error(`Unknown transport type: ${t.transport}`)}}async acquire(t){let n=await this.findIdleInstance(t.name);if(!n){let s=this.agentCounts.get(t.name)??0,r=t.maxConcurrent??this.config.maxConcurrent;s<r?n=await this.spawn(t):(xn.debug("Max concurrent reached, waiting for idle instance",{name:t.name,currentCount:s,maxConcurrent:r}),n=await this.waitForIdleInstance(t.name));}n.status="running",n.lastActiveAt=Date.now();let o=this.handlers.get(n.id);if(!o)throw new Error(`Handler not found for instance: ${n.id}`);return {instance:n,execute:async s=>{n.status="busy";try{let r=await o.execute(s);return n.status="idle",n.lastActiveAt=Date.now(),r}catch(r){throw n.status="error",r}},interrupt:()=>o.interrupt()}}async release(t,n){n==="ephemeral"?await this.terminate(t.id):(t.status="idle",xn.debug("Agent released to pool",{id:t.id,name:t.config.name}));}async terminate(t){let n=this.handlers.get(t),o=this.instances.get(t);if(this.handlers.delete(t),n)try{await n.stop();}catch(s){xn.warn("Error stopping agent",{id:t,error:String(s)});}if(o){let s=this.agentCounts.get(o.config.name)??0;s>0&&this.agentCounts.set(o.config.name,s-1),o.status="stopped",this.instances.delete(t);}xn.debug("Agent terminated",{id:t});}async interrupt(t){let n=this.handlers.get(t);if(n)try{await n.interrupt(),xn.debug("Agent interrupted",{id:t});}catch(o){xn.warn("Error interrupting agent",{id:t,error:String(o)});}}async shutdownAll(){this.stopIdleCleanup();let t=Array.from(this.instances.keys());await Promise.all(t.map(n=>this.terminate(n))),xn.debug("All agents shut down",{count:t.length});}list(){return Array.from(this.instances.values())}get(t){return this.instances.get(t)}async findIdleInstance(t){let n=[];for(let[o,s]of this.instances){if(s.config.name!==t||s.status!=="idle")continue;if(!await this.checkInstanceHealth(s)){xn.warn("Found unhealthy idle instance, marking for cleanup",{id:o,name:t,lastActiveAt:s.lastActiveAt}),n.push(o);continue}return s}for(let o of n)try{await this.terminate(o);}catch(s){xn.warn("Failed to terminate unhealthy instance",{id:o,error:String(s)});}}async waitForIdleInstance(t,n=6e4){let o=Date.now();for(;Date.now()-o<n;){let s=await this.findIdleInstance(t);if(s)return s;await new Promise(r=>setTimeout(r,1e3));}throw new Error(`Timeout waiting for idle ${t} agent`)}};var tn=a.create({service:"subagent"});function Vl(e,t){return t?{...e,...t}:e}var As;(A=>{let e,t;function n(){return e||(e=_.state(async()=>{try{let y=await o();if(!y.enabled)return tn.debug("SubAgent system disabled"),{registry:null,config:y,initialized:!0};let x=new Cc(y),b=y.agents.filter(w=>w.runMode==="persistent");for(let w of b)try{await x.spawn(w),tn.debug("Persistent agent spawned",{name:w.name});}catch(C){tn.error("Failed to spawn persistent agent",{name:w.name,error:String(C)});}return tn.info("SubAgent system initialized",{totalAgents:y.agents.length,persistentAgents:b.length}),{registry:x,config:y,initialized:!0}}catch(y){return t=y instanceof Error?y:new Error(String(y)),tn.error("SubAgent system initialization failed, continuing without SubAgent",{error:t.message}),{registry:null,config:{enabled:false,defaultRunMode:"ephemeral",timeout:3e5,maxConcurrent:5,agents:[],idleTimeout:1800*1e3,idleCheckInterval:300*1e3},initialized:false,initError:t}}},async y=>{y?.registry&&await y.registry.shutdownAll();})),e}async function o(){let y=await fr();if(!y.enabled)return {enabled:false,defaultRunMode:"ephemeral",timeout:3e5,maxConcurrent:5,idleTimeout:1800*1e3,idleCheckInterval:300*1e3,agents:[]};let b=y.defaultRunMode==="persistent"?"persistent":"ephemeral",w=y.timeout,C=y.maxConcurrent,k=y.idleTimeout??1800*1e3,P=y.idleCheckInterval??300*1e3,E=y.agents.map(O=>({...O,transport:O.transport,runMode:O.runMode}));return {enabled:true,defaultRunMode:b,timeout:w,maxConcurrent:C,idleTimeout:k,idleCheckInterval:P,agents:E}}function s(){return n()()}A.state=s;async function r(){return (await s()).config?.enabled??false}A.isEnabled=r;async function i(){return (await s()).initialized}A.isInitialized=i;function c(){return t}A.getInitError=c;async function l(y){let x=await s();if(!x.config?.enabled)throw new Error("SubAgent system is disabled");let b=x.config.agents.find(k=>k.name===y.agent);if(!b)throw new Error(`Unknown agent: ${y.agent}`);let w=Vl(b,y.config);if(tn.debug("SubAgent.run started",{title:y.title,agent:y.agent,runMode:w.runMode,transport:w.transport}),!x.registry)throw new Error("SubAgent registry not initialized");let C=await x.registry.acquire(w);try{return await C.execute(y)}catch(k){if(tn.error("SubAgent.run failed",{title:y.title,agent:y.agent,runMode:w.runMode,error:String(k)}),w.runMode==="persistent"){tn.warn("Persistent agent failed, terminating instance",{id:C.instance.id,name:y.agent});try{await x.registry.terminate(C.instance.id);}catch(P){tn.warn("Failed to terminate persistent agent",{id:C.instance.id,error:String(P)});}}throw k}finally{if(w.runMode==="ephemeral")try{await x.registry.release(C.instance,"ephemeral");}catch(k){tn.warn("Failed to release ephemeral agent",{id:C.instance.id,error:String(k)});}}}A.run=l;async function d(y,x){let b=await s();if(!b.config?.enabled)throw new Error("SubAgent system is disabled");let w=b.config.agents.find(E=>E.name===y.agent);if(!w)throw new Error(`Unknown agent: ${y.agent}`);let C=Vl(w,y.config);if(tn.debug("SubAgent.runAsync started",{title:y.title,agent:y.agent,runMode:C.runMode,transport:C.transport}),!b.registry)throw new Error("SubAgent registry not initialized");let k=b.registry,P=await k.acquire(C);return (async()=>{try{let E=await P.execute(y);try{await x(E);}finally{await k.release(P.instance,C.runMode);}}catch(E){tn.error("SubAgent.runAsync failed",{title:y.title,agent:y.agent,error:String(E)});try{await x({title:y.title,output:`Error: ${E}`,metadata:{error:String(E)}});}finally{await k.release(P.instance,C.runMode);}}})(),P.instance.id}A.runAsync=d;function m(y){return (async()=>{let x=await s();if(!x.config?.enabled)throw new Error("SubAgent system is disabled");let b=x.config.agents.find(P=>P.name===y.agent);if(!b)throw new Error(`Unknown agent: ${y.agent}`);let w=Vl(b,y.config);if(tn.debug("SubAgent.runPromise started",{title:y.title,agent:y.agent,runMode:w.runMode,transport:w.transport}),!x.registry)throw new Error("SubAgent registry not initialized");let C=x.registry,k=await C.acquire(w);try{return {...await k.execute(y),instanceId:k.instance.id}}catch(P){throw tn.error("SubAgent.runPromise failed",{title:y.title,agent:y.agent,error:String(P)}),P}finally{await C.release(k.instance,w.runMode);}})()}A.runPromise=m;async function f(){return (await s()).registry?.list()??[]}A.list=f;async function a(y){return (await s()).registry?.get(y)}A.get=a;async function p(y){let x=await s();x.registry&&await x.registry.terminate(y);}A.close=p;async function u(){let y=await s();y.registry&&await y.registry.shutdownAll();}A.closeAll=u;async function g(y){let x=await s();x.registry&&x.registry.get(y)&&await x.registry.interrupt(y);}A.interrupt=g;async function h(y){let x=await s();if(x.config){if(x.config.agents.find(w=>w.name===y.name)){tn.warn("Agent already registered",{name:y.name});return}if(x.config.agents.push(y),y.runMode==="persistent"&&x.registry)try{await x.registry.spawn(y);}catch(w){tn.error("Failed to spawn persistent agent after register",{name:y.name,error:String(w)});}tn.info("Agent registered",{name:y.name});}}A.register=h;async function S(y){let x=await s();if(x.config){let b=x.config.agents.findIndex(w=>w.name===y);b!==-1&&(x.config.agents.splice(b,1),tn.info("Agent unregistered",{name:y}));}}A.unregister=S;})(As||(As={}));var Kl=class extends Error{constructor(n,o){super(`Too many concurrent tasks: ${n} running, limit is ${o}`);b$1(this,"running");b$1(this,"limit");this.name="TaskConcurrencyError",this.running=n,this.limit=o;}},jt;(x=>{let e=a.create({service:"task"});x.MAX_CONCURRENT_TASKS=5;async function n(b){let w=await o(b);if(w>=x.MAX_CONCURRENT_TASKS)throw new Kl(w,x.MAX_CONCURRENT_TASKS)}async function o(b){return (await h(b)).filter(C=>C.status==="running").length}x.getRunningCount=o;let s;async function r(){return Filesystem.normalize(Ce__default.join(a$1.Path.data,"task"))}async function i(b){let w=await r();return Filesystem.normalize(Ce__default.join(w,`${b}.json`))}async function c(b){let w=await i(b);try{let C=await Filesystem.readText(w);return C?JSON.parse(C):[]}catch{return []}}async function l(b,w){let C=await i(b);try{await Filesystem.write(C,JSON.stringify(w,null,2)),e.debug("Session tasks saved",{sessionId:b,count:w.length});}catch(k){e.error("Failed to save session tasks",{sessionId:b,error:String(k)});}}async function d(){let b=await r(),w=new Map;try{let C=await readdir(b);for(let k of C){if(!k.endsWith(".json"))continue;let P=k.replace(".json",""),E=await c(P);for(let O of E)w.set(O.taskId,O);}}catch(C){e.debug("Task directory not found or empty",{error:String(C)});}return w}function m(){return s||(s=_.state(async()=>{let b=await d();return e.debug("Task state initialized",{taskCount:b.size}),{tasks:b,initialized:true}},async()=>{})),s}function f(){return m()()}x.state=f;async function a$2(b){return (await f()).tasks.get(b)}x.get=a$2;async function p(b){await n(b.sessionId);let w=await f(),C=Date.now(),k={taskId:b.taskId,sessionId:b.sessionId,description:b.description,prompt:b.prompt,agentType:b.agentType,source:b.source||"tool",status:"pending",createdAt:C,updatedAt:C,metadata:b.metadata};w.tasks.set(b.taskId,k);let P=await c(b.sessionId);return P.push(k),await l(b.sessionId,P),e.debug("Task created",{taskId:b.taskId,sessionId:b.sessionId}),k}x.create=p;async function u(b,w){let C=await f(),k=C.tasks.get(b);if(!k){e.warn("Task not found for update",{taskId:b});return}w.status!==void 0&&(k.status=w.status),w.result!==void 0&&(k.result=w.result),w.error!==void 0&&(k.error=w.error),w.duration!==void 0&&(k.duration=w.duration),w.metadata!==void 0&&(k.metadata={...k.metadata,...w.metadata}),k.updatedAt=Date.now(),C.tasks.set(b,k);let P=await c(k.sessionId),E=P.findIndex(O=>O.taskId===b);E>=0?P[E]=k:P.push(k),await l(k.sessionId,P),e.debug("Task updated",{taskId:b,status:k.status});}x.update=u;async function g(b){let w=await f(),C=w.tasks.get(b);if(!C){e.warn("Task not found for remove",{taskId:b});return}let k=C.sessionId;w.tasks.delete(b);let E=(await c(k)).filter(O=>O.taskId!==b);await l(k,E),e.debug("Task removed",{taskId:b,sessionId:k});}x.remove=g;async function h(b){return c(b)}x.list=h;async function S(b){return (await h(b)).filter(C=>C.status==="running"||C.status==="pending")}x.active=S;async function A(b){let w=await h(b);return {total:w.length,pending:w.filter(C=>C.status==="pending").length,running:w.filter(C=>C.status==="running").length,completed:w.filter(C=>C.status==="completed").length,error:w.filter(C=>C.status==="error").length}}x.stats=A;async function y(b=10080*60*1e3){let w=await f(),C=Date.now(),k=0;for(let[P,E]of w.tasks)(E.status==="completed"||E.status==="error")&&C-E.updatedAt>b&&(w.tasks.delete(P),k++);if(k>0){let P=new Map;for(let E of w.tasks.values()){let O=P.get(E.sessionId)||[];O.push(E),P.set(E.sessionId,O);}for(let[E,O]of P)await l(E,O);e.debug("Cleaned up old tasks",{count:k});}return k}x.cleanup=y;})(jt||(jt={}));a.create({service:"tool.task"});var FI=loadTextFile("./task.txt",import.meta.url),NI=FI(),$i={create:F.object({operation:F.literal("create").describe("Create a new async subtask"),description:F.string().describe("Task description, brief summary of task goal"),prompt:F.string().describe("Task prompt, detailed description of work to execute"),subagent_type:F.string().describe("Agent type, specifies the Agent role for executing the task")}),query:F.object({operation:F.literal("query").describe("Query task status or list"),taskId:F.string().optional().describe("Task ID, omit to list all tasks")}),continue:F.object({operation:F.literal("continue").describe("Continue executing a task"),taskId:F.string().describe("Task ID, the task to continue executing")}),delete:F.object({operation:F.literal("delete").describe("Delete task record"),taskId:F.string().describe("Task ID, the task to delete")}),agents:F.object({operation:F.literal("agents").describe("Get list of available Agent types")})},UI=F.discriminatedUnion("operation",[$i.create,$i.query,$i.continue,$i.delete,$i.agents]),Fi=De.define("task",{description:NI,parameters:UI,formatValidationError(e){return `Task tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(e.operation==="create")return zI(e,t);if(e.operation==="query")return qI(e,t);if(e.operation==="continue")return HI(e,t);if(e.operation==="delete")return BI(e);if(e.operation==="agents")return WI();throw new Error(`Unknown operation: ${e.operation}`)}});async function zI(e,t){if(!t.messageId)throw new Error("messageId is required");if((await ve.get({sessionId:t.sessionId,messageId:t.messageId}))?.info.role!=="assistant")throw new Error("Not an assistant message");let o=await jt.getRunningCount(t.sessionId);if(o>=jt.MAX_CONCURRENT_TASKS)throw new Error(`Too many concurrent tasks: ${o} running, max is ${jt.MAX_CONCURRENT_TASKS}`);t.extra?.bypassAgentCheck||await t.ask({permission:"task",patterns:[e.subagent_type],always:["*"],metadata:{description:e.description,subagent_type:e.subagent_type}});let s=Identifier.ascending("task"),r=Date.now();await Le.triggerEvent(HookEvent.TaskStart,{taskId:s,sessionId:t.sessionId,source:"tool",agentType:e.subagent_type,description:e.description,prompt:e.prompt}),t.metadata({title:e.description,metadata:{taskId:s}});let i=[{type:"text",text:e.prompt}],c=await Ue.get(e.subagent_type);return 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}
156
+
157
+ Task started, results will be injected when complete`,title:e.description,metadata:{operation:"create",taskId:s}}}async function qI(e,t){if(e.taskId){let s=await jt.get(e.taskId);if(!s)return {output:`<task>
158
+ Task not found: ${e.taskId}
159
+ </task>`,title:"Task Query",metadata:{operation:"query",found:false,taskId:e.taskId}};let r=[`<task taskId="${s.taskId}" status="${s.status}">`];return s.description&&r.push(` description: ${s.description}`),s.agentType&&r.push(` agent: ${s.agentType}`),s.result&&r.push(` result: ${s.result}`),s.error&&r.push(` error: ${s.error}`),s.duration&&r.push(` duration: ${s.duration}ms`),r.push(` created: ${new Date(s.createdAt).toISOString()}`),r.push(` updated: ${new Date(s.updatedAt).toISOString()}`),r.push("</task>"),{output:r.join(`
160
+ `),title:`Task: ${s.description}`,metadata:{operation:"query",found:true,taskId:e.taskId,status:s.status}}}let n=await jt.list(t.sessionId);if(n.length===0)return {output:`<tasks>
161
+ No tasks found
162
+ </tasks>`,title:"Task Query",metadata:{operation:"query",total:0}};let o=[`<tasks total="${n.length}">`];for(let s of n)o.push(`[task_id="${s.taskId}"]`),o.push(` status: ${s.status}`),s.description&&o.push(` description: ${s.description}`),s.agentType&&o.push(` agent: ${s.agentType}`),o.push("");return o.push("</tasks>"),{output:o.join(`
163
+ `),title:`Tasks: ${n.length}`,metadata:{operation:"query",total:n.length}}}async function HI(e,t){let n=await jt.get(e.taskId);if(!n)return {output:`<task>
164
+ Task not found: ${e.taskId}
165
+ </task>`,title:"Task Continue",metadata:{operation:"continue",found:false,taskId:e.taskId}};if(n.status==="completed"||n.status==="running")return {output:`<task>
166
+ Task ${e.taskId} is already ${n.status}. Cannot restart.
167
+ </task>`,title:"Task Continue",metadata:{operation:"continue",taskId:e.taskId,status:n.status}};await jt.update(e.taskId,{status:"running"});let o=Date.now();t.metadata({title:n.description,metadata:{taskId:e.taskId}});let s=[{type:"text",text:n.prompt}],r=await Ue.get(n.agentType);return As.runAsync({source:t.sessionId,title:n.description,agent:"task_general",system:r?.prompt??"",parts:s,config:{runMode:"ephemeral",transport:"stdio"}},async i=>{let c=Date.now()-o;await jt.update(e.taskId,{status:"completed",result:i.output,duration:c}),await Le.triggerEvent(HookEvent.TaskComplete,{taskId:e.taskId,sessionId:t.sessionId,source:"tool",result:i.output,duration:c,agentType:n.agentType});}),{output:`taskId: ${e.taskId}
168
+
169
+ Task continued, results will be injected when complete`,title:n.description,metadata:{operation:"continue",taskId:e.taskId}}}async function BI(e,t){return await jt.get(e.taskId)?(await jt.remove(e.taskId),{output:`<task>
170
+ Task ${e.taskId} deleted successfully.
171
+ </task>`,title:"Task Delete",metadata:{operation:"delete",found:true,taskId:e.taskId}}):{output:`<task>
172
+ Task not found: ${e.taskId}
173
+ </task>`,title:"Task Delete",metadata:{operation:"delete",found:false,taskId:e.taskId}}}async function GI(){return (await Ue.list()).filter(t=>t.mode==="subagent").filter(t=>t.hidden!==true).map(t=>({name:t.name,description:t.description}))}async function WI(){let e=await GI(),t=[`<agents total="${e.length}">`];for(let n of e)t.push(`- ${n.name}: ${n.description??"No description"}`);return t.push("</agents>"),{output:t.join(`
174
+ `),title:`Agents: ${e.length}`,metadata:{operation:"agents",total:e.length}}}var KI=loadTextFile("./init.txt",import.meta.url),Jl=f("init",{description:"create/update AGENTS.md",source:"command",commandType:"prompt",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=KI(),o=e$1(n,e);return {title:"Initialize",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var YI=loadTextFile("./review.txt",import.meta.url),Yl=f("review",{description:"review changes [commit|branch|pr], defaults to uncommitted",source:"command",commandType:"prompt",subtask:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=YI(),o=e$1(n,e);return {title:"Code Review",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var QI=loadTextFile("./vuln.txt",import.meta.url),Xl=f("vuln",{description:"analyze code for security vulnerabilities",source:"command",commandType:"prompt",subtask:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=QI(),o=e$1(n,e);return {title:"Security Vulnerability Analysis",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var ev=loadTextFile("./arch.txt",import.meta.url),Ql=f("arch",{description:"review code architecture and design patterns",source:"command",commandType:"prompt",subtask:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=ev(),o=e$1(n,e);return {title:"Architecture Review",metadata:{sessionId:t.sessionId},output:o,parts:[{type:"text",text:o}],success:true}},init:async()=>({})});var tv="Never use question tool (question)",Zl=f("btw",{description:"ask a side question without interrupting current task",source:"command",commandType:"local",agent:"btw",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let{Provider:n}=await import('./provider-RGQTLMFK.mjs'),o;t.model?o=n.parseModel(t.model):o=await Zo(t.sessionId);let s=typeof e=="string"?e:JSON.stringify(e),r=await Pr.run({source:t.sessionId,title:"BTW Response",agent:t.agent,model:{providerId:o.providerId,modelId:o.modelId},parts:[{type:"text",text:s}],system:tv,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 ov(e){return typeof e=="string"?e:JSON.stringify(e)}var eu=f("shell",{description:"execute shell command locally",source:"command",commandType:"local",subtask:false,hidden:true,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=ov(e).trim();if(!n)return {title:"Shell Command",metadata:{sessionId:t.sessionId},output:"No command provided",success:true};try{let o=await Shell.run(void 0,n,{cwd:_.directory});if(o.code!==0){let r=o.stderr||o.stdout||`Exit code: ${o.code}`;throw new Error(`Command failed (${o.code}): ${r}`)}let s=o.stdout||o.stderr;return {title:"Shell Command",metadata:{sessionId:t.sessionId,command:n},output:s||"(empty output)",success:!0}}catch(o){return {title:"Shell Command",metadata:{sessionId:t.sessionId,command:n,error:o instanceof Error?o.message:String(o)},output:`Error: ${o instanceof Error?o.message:String(o)}`,success:false}}},init:async()=>({})});var Ni=a.create({service:"scheduler.task-store"}),rv="scheduler",iv="tasks.json",ef=1,qe;(C=>{let e={heartbeats:[],scheduled:[],commands:[],version:ef},t=false;function n(){return Ce__default.join(a$1.Path.data,rv)}function o(){let k=n();return Ce__default.join(k,iv)}async function s(){let k=n();await Filesystem.exists(k)||await mkdir(k,{recursive:true});}async function r(){let k=o();if(!await Filesystem.exists(k)){Ni.debug("Task store file not found, using empty store");return}try{let P=await Filesystem.readText(k),E=JSON.parse(P);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:ef,Ni.info("Task store loaded",{heartbeats:e.heartbeats.length,scheduled:e.scheduled.length,commands:e.commands.length});}catch(P){Ni.error("Failed to load task store",{error:P});}}async function i(){if(!t)return;await s();let k=o();try{let P=JSON.stringify(e,null,2);await Filesystem.write(k,P),t=!1,Ni.debug("Task store saved");}catch(P){throw Ni.error("Failed to save task store",{error:P}),P}}async function c(){await r();}C.init=c;async function l(){return [...e.heartbeats]}C.getHeartbeats=l;async function d(){return [...e.scheduled]}C.getScheduled=d;async function m(k){return e.heartbeats.find(P=>P.id===k)}C.getHeartbeat=m;async function f(k){return e.scheduled.find(P=>P.id===k)}C.getScheduledTask=f;async function a(k){let P=e.heartbeats.findIndex(E=>E.id===k.id);P>=0?e.heartbeats[P]=k:e.heartbeats.push(k),t=true,await i();}C.saveHeartbeat=a;async function p(k){let P=e.scheduled.findIndex(E=>E.id===k.id);P>=0?e.scheduled[P]=k:e.scheduled.push(k),t=true,await i();}C.saveScheduled=p;async function u(k){e.heartbeats=e.heartbeats.filter(P=>P.id!==k),t=true,await i();}C.deleteHeartbeat=u;async function g(k){e.scheduled=e.scheduled.filter(P=>P.id!==k),t=true,await i();}C.deleteScheduled=g;async function h(k,P){let E=e.heartbeats.findIndex(L=>L.id===k);if(E<0)throw new Error(`Heartbeat task not found: ${k}`);let O=e.heartbeats[E],N={id:k,name:P.name??O.name,cron:P.cron??O.cron,type:"heartbeat",enabled:P.enabled??O.enabled,parts:P.parts??O.parts,config:P.config??O.config,recurring:true,createdAt:O.createdAt,updatedAt:Date.now(),lastFiredAt:P.lastFiredAt??O.lastFiredAt,nextFireAt:P.nextFireAt??O.nextFireAt};e.heartbeats[E]=N,t=true,await i();}C.updateHeartbeat=h;async function S(k,P){let E=e.scheduled.findIndex(L=>L.id===k);if(E<0)throw new Error(`Scheduled task not found: ${k}`);let O=e.scheduled[E],N={id:k,name:P.name??O.name,cron:P.cron??O.cron,type:"scheduled",enabled:P.enabled??O.enabled,parts:P.parts??O.parts,agentType:P.agentType??O.agentType,transport:P.transport??O.transport,agentConfig:P.agentConfig??O.agentConfig,recurring:P.recurring??O.recurring,durable:P.durable??O.durable,permanent:P.permanent??O.permanent,createdAt:O.createdAt,updatedAt:Date.now(),lastFiredAt:P.lastFiredAt??O.lastFiredAt,nextFireAt:P.nextFireAt??O.nextFireAt};e.scheduled[E]=N,t=true,await i();}C.updateScheduled=S;async function A(){return [...e.commands]}C.getCommands=A;async function y(k){return e.commands.find(P=>P.id===k)}C.getCommand=y;async function x(k){let P=e.commands.findIndex(E=>E.id===k.id);P>=0?e.commands[P]=k:e.commands.push(k),t=true,await i();}C.saveCommand=x;async function b(k){e.commands=e.commands.filter(P=>P.id!==k),t=true,await i();}C.deleteCommand=b;async function w(k,P){let E=e.commands.findIndex(L=>L.id===k);if(E<0)throw new Error(`Command task not found: ${k}`);let O=e.commands[E],N={id:k,name:P.name??O.name,cron:P.cron??O.cron,type:"command",enabled:P.enabled??O.enabled,config:P.config??O.config,recurring:P.recurring??O.recurring,durable:P.durable??O.durable,createdAt:O.createdAt,updatedAt:Date.now(),lastFiredAt:P.lastFiredAt??O.lastFiredAt,nextFireAt:P.nextFireAt??O.nextFireAt};e.commands[E]=N,t=true,await i();}C.updateCommand=w;})(qe||(qe={}));var tu;(h=>{async function e(){return qe.init()}h.init=e;async function t(){return qe.getHeartbeats()}h.getHeartbeats=t;async function n(){return qe.getScheduled()}h.getScheduled=n;async function o(S){return qe.getHeartbeat(S)}h.getHeartbeat=o;async function s(S){return qe.getScheduledTask(S)}h.getScheduledTask=s;async function r(S){return qe.saveHeartbeat(S)}h.saveHeartbeat=r;async function i(S){return qe.saveScheduled(S)}h.saveScheduled=i;async function c(S){return qe.deleteHeartbeat(S)}h.deleteHeartbeat=c;async function l(S){return qe.deleteScheduled(S)}h.deleteScheduled=l;async function d(S,A){return qe.updateHeartbeat(S,A)}h.updateHeartbeat=d;async function m(S,A){return qe.updateScheduled(S,A)}h.updateScheduled=m;async function f(){return qe.getCommands()}h.getCommands=f;async function a(S){return qe.getCommand(S)}h.getCommand=a;async function p(S){return qe.saveCommand(S)}h.saveCommand=p;async function u(S){return qe.deleteCommand(S)}h.deleteCommand=u;async function g(S,A){return qe.updateCommand(S,A)}h.updateCommand=g;})(tu||(tu={}));function Ui(e,t,n){if(e==="*"){let r=[];for(let i=t;i<=n;i++)r.push(i);return r}let o=new Set,s=e.split(",");for(let r of s)if(r.includes("/")){let[i,c]=r.split("/"),l=tf(i??"*",t,n),d=parseInt(c??"1",10);for(let m=0;m<l.length;m+=d)m<l.length&&o.add(l[m]);}else if(r.includes("-")){let i=tf(r,t,n);for(let c of i)o.add(c);}else {let i=parseInt(r,10);!Number.isNaN(i)&&i>=t&&i<=n&&o.add(i);}return Array.from(o).sort((r,i)=>r-i)}function tf(e,t,n){if(e==="*"){let l=[];for(let d=t;d<=n;d++)l.push(d);return l}let[o,s]=e.split("-"),r=o?parseInt(o,10):t,i=s?parseInt(s,10):n,c=[];for(let l=r;l<=i;l++)l>=t&&l<=n&&c.push(l);return c}function Tr(e){if(!e||typeof e!="string")return null;let n=e.trim().split(/\s+/);if(n.length!==5)return null;try{let[o,s,r,i,c]=n;return {minutes:Ui(o??"*",0,59),hours:Ui(s??"*",0,23),days:Ui(r??"*",1,31),months:Ui(i??"*",1,12),weekdays:Ui(c??"*",0,6)}}catch{return null}}function ns(e){return Tr(e)!==null}function Ac(e,t=new Date){let n=new Date(t);n.setSeconds(0,0);for(let o=0;o<366*24*60;o++){n.setMinutes(n.getMinutes()+1);let s=n.getMinutes(),r=n.getHours(),i=n.getDate(),c=n.getMonth()+1,l=n.getDay();if(e.minutes.includes(s)&&e.hours.includes(r)&&e.days.includes(i)&&e.months.includes(c)&&e.weekdays.includes(l))return new Date(n)}return new Date(n.getTime()+1440*60*1e3*366)}function av(e){let t=(n,o,s)=>{if(n.length===s-o+1)return "*";if(n.length===1)return n[0].toString();let r=[...n],i=[],c=r[0],l=r[0];for(let d=1;d<r.length;d++)r[d]!==l+1&&(i.push(c===l?`${c}`:`${c}-${l}`),c=r[d]),l=r[d];return i.push(c===l?`${c}`:`${c}-${l}`),i.join(",")};return [t(e.minutes,0,59),t(e.hours,0,23),t(e.days,1,31),t(e.months,1,12),t(e.weekdays,0,6)].join(" ")}function cv(e){if(!Tr(e))return null;let n=e.trim().split(/\s+/);return n.length!==5?null:{minute:n[0]??"",hour:n[1]??"",day:n[2]??"",month:n[3]??"",weekday:n[4]??""}}function nf(e){let t=cv(e);if(!t)return "Invalid cron expression";let n=[],o=s=>s.includes("-")?`from ${s.replace("-"," to ")}`:s.includes(",")?`at ${s}`:`at ${s}`;if(t.minute==="*")n.push("every minute");else if(t.minute.startsWith("*/")){let s=t.minute.slice(2);n.push(`every ${s} minutes`);}else n.push(o(t.minute));if(t.hour!=="*")if(t.hour.startsWith("*/")){let s=t.hour.slice(2);n.push(`every ${s} hours`);}else n.push(o(t.hour));if(t.day!=="*")if(t.day.startsWith("*/")){let s=t.day.slice(2);n.push(`every ${s} days`);}else n.push(`on day ${t.day}`);if(t.month!=="*"){let s={1:"January",2:"February",3:"March",4:"April",5:"May",6:"June",7:"July",8:"August",9:"September",10:"October",11:"November",12:"December"},i=t.month.split(",").map(c=>{let l=parseInt(c.split("-")[0],10);return !Number.isNaN(l)&&l>=1&&l<=12&&s[l]||c});n.push(`in ${i.join(", ")}`);}if(t.weekday!=="*"){let s={0:"Sunday",1:"Monday",2:"Tuesday",3:"Wednesday",4:"Thursday",5:"Friday",6:"Saturday"},i=t.weekday.split(",").map(c=>{let l=parseInt(c.split("-")[0],10);return !Number.isNaN(l)&&l>=0&&l<=6&&s[l]||c});n.push(`on ${i.join(", ")}`);}return n.join(" ")}var uv=loadTextFile("./heartbeat.txt",import.meta.url),pv=loadTextFile("./scheduled.txt",import.meta.url),lf=uv(),uf=pv(),af=a.create({service:"scheduler.history"}),mv=/\{\{([A-Z_]+)\}\}/g,ou;(s=>{function e(r,i){return r.replace(mv,(c,l)=>t(l,i)??c)}s.render=e;function t(r,i){switch(r){case "TASK_ID":return i.taskId;case "TASK_NAME":return i.taskName;case "TASK_TYPE":return i.taskType;case "SESSION":return i.session;case "AGENT":return i.agent;case "MODEL":return i.model;case "TIME":return new Date().toISOString();case "TIME_LOCAL":return new Date().toLocaleString();case "TIMESTAMP":return String(Date.now());default:return}}s.resolveVariable=t;function n(r){let i={taskId:r.id,taskName:r.name,taskType:"heartbeat",session:r.session,agent:r.agent,model:r.model,timestamp:Date.now()};return s.render(lf,i)}s.buildHeartbeatPrompt=n;function o(r,i){let c={taskId:r.id,taskName:r.name,taskType:"scheduled",agent:r.agentType,model:r.model,timestamp:Date.now()};return `${s.render(uf,c)}
175
+
176
+ ## User Request
177
+
178
+ ${i}`}s.buildScheduledPrompt=o;})(ou||(ou={}));var fv="scheduler/history",cf=100;function _c(){return Ce__default.join(a$1.Path.data,fv)}function nu(e){let t=_c(),n=e.replace(/[^a-zA-Z0-9_-]/g,"_");return Ce__default.join(t,`${n}.json`)}async function Ar(e){try{return await access(e),!0}catch{return false}}async function gv(){let e=_c();await Ar(e)||await mkdir(e,{recursive:true});}var Mc;(i=>{async function e(c){await gv();let l=nu(c.taskId),d=[];if(await Ar(l))try{let f=await readFile(l,"utf-8");d=JSON.parse(f);}catch{d=[];}d.unshift(c),d.length>cf&&(d=d.slice(0,cf)),await writeFile(l,JSON.stringify(d,null,2)),af.debug("Task history record added",{taskId:c.taskId,success:c.success});}i.add=e;async function t(c,l){let d=nu(c);if(!await Ar(d))return [];try{let f=await readFile(d,"utf-8"),a=JSON.parse(f);return l?a.slice(0,l):a}catch{return []}}i.get=t;async function n(c){let l=nu(c);await Ar(l)&&await unlink(l);}i.clear=n;async function o(c){let l=_c(),d=0,m=c?Date.now()-c:Date.now()-720*60*60*1e3;if(!await Ar(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 g=await readFile(u,"utf-8"),h=JSON.parse(g),S=h.filter(A=>A.endTime>m);S.length!==h.length&&(S.length===0?await unlink(u):await writeFile(u,JSON.stringify(S,null,2)),d+=h.length-S.length);}catch{}}return af.info("Task history pruned",{prunedCount:d}),d}i.prune=o;async function s(){let c=_c(),l=0,d=0;if(!await Ar(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"),g=JSON.parse(u);l+=g.length,d+=g.filter(h=>h.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;})(Mc||(Mc={}));function hv(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,8);return `hist_${e}_${t}`}async function os(e,t,n,o,s){let r={id:hv(),taskId:e,taskType:t,sessionId:n,startTime:o,endTime:Date.now(),success:s.success,output:s.output,error:s.error};await Mc.add(r);}var nt=a.create({service:"scheduler"});function Lo(e,t){let n=Tr(e);return n?Ac(n,new Date(t??Date.now())).getTime():(nt.warn("Invalid cron expression",{cron:e}),0)}var Lt;(D=>{let e,t=false;function n(){return e||(e=_.state(async()=>(await qe.init(),{status:"stopped",timers:new Map,listeners:new Map,initialized:true}),async M=>{if(M){for(let v of M.timers.values())clearTimeout(v);M.timers.clear(),M.listeners.clear();}})),e}async function o(){await s(),await c(),nt.debug("Scheduler initialized and started");}D.init=o;function s(){return n()()}D.state=s;async function r(){return (await s()).status}D.getStatus=r;async function i(){return nt.debug("isInitialized check",{_started:t}),t}D.isInitialized=i;async function c(){if(t){nt.debug("Scheduler already started, skipping");return}let I=await s();if(I.status==="running"){nt.warn("Scheduler already running");return}nt.info("Starting scheduler"),I.status="running",t=true;let M=await qe.getHeartbeats();for(let R of M)R.enabled&&O(I,R);let v=await qe.getScheduled();for(let R of v)R.enabled&&N(I,R);let T=await qe.getCommands();for(let R of T)R.enabled&&Q(I,R);nt.info("Scheduler started",{heartbeats:M.length,scheduled:v.length,commands:T.length});}D.start=c;async function l(){let I=await s();if(I.status==="running"){nt.info("Stopping scheduler");for(let M of I.timers.values())clearTimeout(M);I.timers.clear(),I.status="stopped",nt.info("Scheduler stopped");}}D.stop=l;function d(I,M){return s().then(v=>{v.listeners.has(I)||v.listeners.set(I,new Set),v.listeners.get(I).add(M);}),()=>{s().then(v=>{v.listeners.get(I)?.delete(M);});}}D.onTaskComplete=d;async function m(I){if(!ns(I.cron))throw new Error(`Invalid cron expression: ${I.cron}`);let v={id:I.id??Identifier.ascending("heartbeat"),name:I.name,cron:I.cron,type:"heartbeat",enabled:true,parts:I.parts,config:{session:I.session,mode:I.mode??"session",agentId:I.agentId,transport:I.transport,agentConfig:I.agentConfig},recurring:true,createdAt:Date.now(),updatedAt:Date.now(),nextFireAt:Lo(I.cron,Date.now())};await qe.saveHeartbeat(v);let T=await s();return T.status==="running"&&v.enabled&&O(T,v),nt.info("Heartbeat task created",{id:v.id,name:v.name}),v}D.createHeartbeat=m;async function f(I){if(!ns(I.cron))throw new Error(`Invalid cron expression: ${I.cron}`);let M=I.id??Identifier.ascending("task"),v=Date.now(),T={id:M,name:I.name,cron:I.cron,type:"scheduled",enabled:true,parts:I.parts,agentType:I.agentType??"default",transport:I.transport??"stdio",agentConfig:I.agentConfig,recurring:I.recurring??true,durable:I.durable??true,createdAt:v,updatedAt:v,nextFireAt:Lo(I.cron,v)};await qe.saveScheduled(T);let R=await s();return R.status==="running"&&T.enabled&&N(R,T),nt.info("Scheduled task created",{id:T.id,name:T.name}),T}D.createScheduled=f;async function a(I){if(!ns(I.cron))throw new Error(`Invalid cron expression: ${I.cron}`);let M=I.id??Identifier.ascending("command"),v=Date.now(),T={id:M,name:I.name,cron:I.cron,type:"command",enabled:true,config:{command:I.command,arguments:I.arguments,session:I.session,durable:I.durable},recurring:I.recurring??true,durable:I.durable??true,createdAt:v,updatedAt:v,nextFireAt:Lo(I.cron,v)};await qe.saveCommand(T);let R=await s();return R.status==="running"&&T.enabled&&Q(R,T),nt.debug("Command task created",{id:T.id,name:T.name,command:T.config.command}),T}D.createCommand=a;async function p(){return qe.getHeartbeats()}D.listHeartbeats=p;async function u(){return qe.getScheduled()}D.listScheduled=u;async function g(){return qe.getCommands()}D.listCommands=g;async function h(I){return qe.getHeartbeat(I)}D.getHeartbeat=h;async function S(I){return qe.getScheduledTask(I)}D.getScheduled=S;async function A(I){let M=await s();E(M,I),await qe.deleteHeartbeat(I),nt.info("Heartbeat task deleted",{id:I});}D.deleteHeartbeat=A;async function y(I){let M=await s();E(M,I),await qe.deleteScheduled(I),nt.info("Scheduled task deleted",{id:I});}D.deleteScheduled=y;async function x(I){let M=await qe.getHeartbeat(I);if(!M)throw new Error(`Heartbeat task not found: ${I}`);await qe.updateHeartbeat(I,{enabled:true});let v=await s();O(v,{...M,enabled:true}),nt.debug("Heartbeat task enabled",{id:I});}D.enableHeartbeat=x;async function b(I){let M=await s();E(M,I),await qe.updateHeartbeat(I,{enabled:false}),nt.info("Heartbeat task disabled",{id:I});}D.disableHeartbeat=b;async function w(I){let M=await qe.getScheduledTask(I);if(!M)throw new Error(`Scheduled task not found: ${I}`);await qe.updateScheduled(I,{enabled:true});let v=await s();N(v,{...M,enabled:true}),nt.info("Scheduled task enabled",{id:I});}D.enableScheduled=w;async function C(I){let M=await s();E(M,I),await qe.updateScheduled(I,{enabled:false}),nt.info("Scheduled task disabled",{id:I});}D.disableScheduled=C;async function k(I){let M=await qe.getHeartbeat(I);if(!M)throw new Error(`Heartbeat task not found: ${I}`);return L(M)}D.triggerHeartbeat=k;async function P(I){let M=await qe.getScheduledTask(I);if(!M)throw new Error(`Scheduled task not found: ${I}`);return K(M)}D.triggerScheduled=P;function E(I,M){let v=I.timers.get(M);v&&(clearTimeout(v),I.timers.delete(M));}function O(I,M){E(I,M.id);let v=(M.nextFireAt??Lo(M.cron))-Date.now(),T=Math.max(0,v);nt.info("Scheduling heartbeat",{id:M.id,nextFireAt:M.nextFireAt,delay:T});let R=setTimeout(async()=>{let j=M.id;try{let U=await L(M),Y=I.listeners.get(j);if(Y)for(let ee of Y)try{ee(U);}catch(se){nt.error("Task listener error",{taskId:j,error:se instanceof Error?se.message:String(se)});}let J=await qe.getHeartbeat(j);if(J?.enabled&&J.recurring){let ee=Lo(J.cron);await qe.updateHeartbeat(j,{lastFiredAt:Date.now(),nextFireAt:ee});let se=await qe.getHeartbeat(j);se&&O(I,{...se,nextFireAt:ee});}}catch(U){nt.error("Heartbeat execution failed",{id:j,error:U});}},T);R.unref(),I.timers.set(M.id,R);}function N(I,M){E(I,M.id);let v=(M.nextFireAt??Lo(M.cron))-Date.now(),T=Math.max(0,v);nt.info("Scheduling task",{id:M.id,nextFireAt:M.nextFireAt,delay:T});let R=setTimeout(async()=>{let j=M.id;try{let U=await K(M),Y=I.listeners.get(j);if(Y)for(let ee of Y)try{ee(U);}catch(se){nt.error("Task listener error",{taskId:j,error:se instanceof Error?se.message:String(se)});}let J=await qe.getScheduledTask(j);if(J?.enabled&&(J.recurring??!0)){let ee=Lo(J.cron);await qe.updateScheduled(j,{lastFiredAt:Date.now(),nextFireAt:ee});let se=await qe.getScheduledTask(j);se&&N(I,{...se,nextFireAt:ee});}}catch(U){nt.error("Scheduled task execution failed",{id:j,error:U});}},T);R.unref(),I.timers.set(M.id,R);}async function L(I){let M=Date.now(),v=I.config.session;v||(v=(await X.create({title:`Heartbeat - ${I.name}`})).id);let T={type:"heartbeat",parts:I.parts,system:I.config.agentConfig?.system,config:{session:v,mode:I.config.mode,agent:I.config.agentId,model:I.config.agentConfig?.model,tools:I.config.agentConfig?.tools}},R={sessionId:v,agent:I.config.agentId,model:I.config.agentConfig?.model},j={taskId:I.id,taskName:I.name,sessionId:v,mode:I.config.mode,definition:T,context:R};try{nt.debug("Executing heartbeat",{id:I.id,mode:I.config.mode});let J=(await Le.triggerEvent(HookEvent.HeartbeatTrigger,j,R)).output?.execution;if(!J)throw new Error(`No heartbeat hook handled event: ${HookEvent.HeartbeatTrigger}`);let ee={success:J.success,output:J.output!==void 0?typeof J.output=="string"?J.output:JSON.stringify(J.output):void 0,error:J.error};return await os(I.id,"heartbeat",v,M,ee),await Le.triggerEvent(HookEvent.HeartbeatComplete,{taskId:I.id,taskName:I.name,success:J.success,output:J.output,error:J.error,duration:Date.now()-M},R),{taskId:I.id,sessionId:v,success:J.success,output:ee.output,error:J.error,executedAt:M,duration:Date.now()-M}}catch(U){nt.error("Heartbeat execution error",{id:I.id,error:U});let Y={success:false,error:U instanceof Error?U.message:String(U)};return await os(I.id,"heartbeat",v,M,Y),await Le.triggerEvent(HookEvent.HeartbeatComplete,{taskId:I.id,taskName:I.name,success:false,error:U instanceof Error?U.message:String(U),duration:Date.now()-M},R),{taskId:I.id,sessionId:v,success:false,error:U instanceof Error?U.message:String(U),executedAt:M,duration:Date.now()-M}}}async function K(I){let M=Date.now(),v={type:"scheduler",parts:I.parts,system:I.agentConfig?.system,config:{agentType:I.agentType,transport:I.transport,model:I.agentConfig?.model,tools:I.agentConfig?.tools}},T={agent:I.agentType,model:I.agentConfig?.model},R={taskId:I.id,taskName:I.name,agentType:I.agentType,transport:I.transport,definition:v,context:T};try{nt.debug("Executing scheduled task",{id:I.id,agentType:I.agentType});let Y=(await Le.triggerEvent(HookEvent.ScheduledTaskTrigger,R,T)).output?.execution;if(!Y)throw new Error(`No scheduler hook handled event: ${HookEvent.ScheduledTaskTrigger}`);let J={success:Y.success,output:Y.output!==void 0?typeof Y.output=="string"?Y.output:JSON.stringify(Y.output):void 0,error:Y.error},ee=Y.sessionId??"scheduler";return await os(I.id,"scheduled",ee,M,J),await Le.triggerEvent(HookEvent.ScheduledTaskComplete,{taskId:I.id,taskName:I.name,success:Y.success,output:Y.output,error:Y.error,duration:Date.now()-M},T),{taskId:I.id,sessionId:ee,success:Y.success,output:J.output,error:Y.error,executedAt:M,duration:Date.now()-M}}catch(j){nt.error("Scheduled task execution error",{id:I.id,error:j});let U={success:false,error:j instanceof Error?j.message:String(j)};return await os(I.id,"scheduled","scheduler",M,U),await Le.triggerEvent(HookEvent.ScheduledTaskComplete,{taskId:I.id,taskName:I.name,success:false,error:j instanceof Error?j.message:String(j),duration:Date.now()-M},T),{taskId:I.id,sessionId:"scheduler",success:false,error:j instanceof Error?j.message:String(j),executedAt:M,duration:Date.now()-M}}}function Q(I,M){E(I,M.id);let v=(M.nextFireAt??Lo(M.cron))-Date.now(),T=Math.max(0,v);nt.debug("Scheduling command task",{id:M.id,nextFireAt:M.nextFireAt,delay:T});let R=setTimeout(async()=>{let j=M.id;try{let U=await ue(M),Y=I.listeners.get(j);if(Y)for(let ee of Y)try{ee(U);}catch(se){nt.error("Task listener error",{taskId:j,error:se instanceof Error?se.message:String(se)});}let J=await qe.getCommand(j);if(J?.enabled&&(J.recurring??!0)){let ee=Lo(J.cron);await qe.updateCommand(j,{lastFiredAt:Date.now(),nextFireAt:ee});let se=await qe.getCommand(j);se&&Q(I,{...se,nextFireAt:ee});}}catch(U){nt.error("Command task execution failed",{id:j,error:U});}},T);R.unref(),I.timers.set(M.id,R);}async function ue(I){let M=Date.now(),v=I.config.session;v||(v=(await X.create({title:`Command - ${I.name}`})).id);let T={type:"command",config:{command:I.config.command,arguments:I.config.arguments,session:v}},R={sessionId:v},j={taskId:I.id,taskName:I.name,command:I.config.command,arguments:I.config.arguments,sessionId:v,timestamp:M,definition:T,context:R};try{nt.debug("Executing command task",{id:I.id,command:I.config.command});let J=(await Le.triggerEvent(HookEvent.CommandTrigger,j,R)).output?.execution;if(!J)throw new Error(`No command hook handled event: ${HookEvent.CommandTrigger}`);let ee={success:J.success,output:J.output!==void 0?typeof J.output=="string"?J.output:JSON.stringify(J.output):void 0,error:J.error};return await os(I.id,"command",v,M,ee),await Le.triggerEvent(HookEvent.CommandComplete,{taskId:I.id,success:J.success,output:ee.output,error:J.error,duration:Date.now()-M,timestamp:Date.now()},R),{taskId:I.id,sessionId:v,success:J.success,output:ee.output,error:J.error,executedAt:M,duration:Date.now()-M}}catch(U){nt.error("Command task execution error",{id:I.id,error:U});let Y={success:false,error:U instanceof Error?U.message:String(U)};return await os(I.id,"command",v,M,Y),{taskId:I.id,sessionId:v,success:false,error:U instanceof Error?U.message:String(U),executedAt:M,duration:Date.now()-M}}}})(Lt||(Lt={}));function yv(e){let t={};if(typeof e=="string"){let n=e.trim(),o=[],s="",r=null;for(let i=0;i<n.length;i++){let c=n[i];(c==='"'||c==="'")&&!r?r=c:c===r?r=null:c===" "&&!r?s&&(o.push(s),s=""):s+=c;}s&&o.push(s),o.length>0&&(t.subcommand=o[0],t.name=o[1]);for(let i=2;i<o.length;i++){let c=o[i];if(c==="--cron"&&i+1<o.length)t.cron=o[++i];else if(c==="--type"&&i+1<o.length)t.type=o[++i];else if(c==="--session"&&i+1<o.length)t.session=o[++i];else if(c==="--mode"&&i+1<o.length)t.mode=o[++i];else if(c==="--prompt"&&i+1<o.length){let l=[];for(let d=i+1;d<o.length&&!o[d].startsWith("--");d++)l.push(o[++i]);t.prompt=l.join(" ");}else c==="--agent-type"&&i+1<o.length?t.agentType=o[++i]:c==="--transport"&&i+1<o.length?t.transport=o[++i]:c==="--recurring"?t.recurring=true:c==="--durable"&&(t.durable=true);}}return t}function pf(e,t){let n=["Tasks:"];if(e.length>0){n.push(`
179
+ Heartbeats:`),n.push("ID | Name | Cron | Session | Mode | Enabled"),n.push("------------------|---------------|---------------|---------|---------|--------");for(let o of e){let s=o.config.session??"(auto)";n.push(`${o.id.padEnd(17)}| ${o.name.padEnd(12)}| ${o.cron.padEnd(12)}| ${s.padEnd(7)}| ${o.config.mode.padEnd(7)}| ${o.enabled}`);}}else n.push(`
180
+ Heartbeats: (none)`);if(t.length>0){n.push(`
181
+ Scheduled:`),n.push("ID | Name | Cron | Agent Type | Recurring | Durable"),n.push("------------------|---------------|---------------|------------|-----------|--------");for(let o of t)n.push(`${o.id.padEnd(17)}| ${o.name.padEnd(12)}| ${o.cron.padEnd(12)}| ${(o.agentType||"default").padEnd(11)}| ${(o.recurring?"yes":"no").padEnd(7)}| ${o.durable?"yes":"no"}`);}else n.push(`
182
+ Scheduled: (none)`);return n.join(`
183
+ `)}var ru=f("loop",{description:"Create and manage scheduled tasks and heartbeats",source:"command",commandType:"local",subtask:false,hints:["{{ARGUMENTS}}"],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=yv(e);if(!n.subcommand)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:Er(),success:true,parts:[{type:"text",text:Er()}]};switch(n.subcommand){case "create":return bv(n,t);case "list":return wv(t);case "delete":return xv(n,t);case "enable":return Iv(n,t);case "disable":return vv(n,t);case "trigger":return Sv(n,t);case "help":return {title:"Loop Command Help",metadata:{sessionId:t.sessionId},output:Er(),success:true,parts:[{type:"text",text:Er()}]};default:return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Unknown subcommand: ${n.subcommand}
184
+
185
+ ${Er()}`,success:true,parts:[{type:"text",text:Er()}]}}},init:async()=>({})});async function bv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task name is required
186
+
187
+ Usage: /loop create <name> --cron <expression> [options]`,success:false,parts:[{type:"text",text:"Error: Task name is required"}]};if(!e.cron)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Cron expression is required
188
+
189
+ Usage: /loop create <name> --cron <expression> [options]`,success:false,parts:[{type:"text",text:"Error: Cron expression is required"}]};if(!ns(e.cron))return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Invalid cron expression: ${e.cron}`,success:false,parts:[{type:"text",text:`Error: Invalid cron expression: ${e.cron}`}]};if((e.type??"heartbeat")==="heartbeat"){if(!e.session)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Session is required for heartbeat tasks
190
+
191
+ Usage: /loop create <name> --cron <expression> --session <session-name> --type heartbeat`,success:false,parts:[{type:"text",text:"Error: Session is required for heartbeat tasks"}]};try{let o=await Lt.createHeartbeat({name:e.name,cron:e.cron,session:e.session,mode:e.mode,agentId:e.agentType,transport:e.transport,parts:[{type:"text",text:e.prompt??`Heartbeat: ${e.name}`}]});return {title:"Heartbeat Created",metadata:{sessionId:t.sessionId},output:`Heartbeat task created successfully!
192
+
193
+ ID: ${o.id}
194
+ Name: ${o.name}
195
+ Cron: ${o.cron}
196
+ Session: ${o.config.session}
197
+ Mode: ${o.config.mode}
198
+ Next Fire: ${new Date(o.nextFireAt).toLocaleString()}`,success:!0,parts:[{type:"text",text:`Heartbeat task created: ${o.id}`}]}}catch(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error creating heartbeat: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}if(!e.prompt)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Prompt is required for scheduled tasks
199
+
200
+ Usage: /loop create <name> --cron <expression> --prompt <text> --type scheduled`,success:false,parts:[{type:"text",text:"Error: Prompt is required for scheduled tasks"}]};try{let o=await Lt.createScheduled({name:e.name,cron:e.cron,parts:[{type:"text",text:e.prompt}],agentType:e.agentType??"default",transport:e.transport??"stdio",recurring:e.recurring??!0,durable:e.durable??!0});return {title:"Scheduled Task Created",metadata:{sessionId:t.sessionId},output:`Scheduled task created successfully!
201
+
202
+ ID: ${o.id}
203
+ Name: ${o.name}
204
+ Cron: ${o.cron}
205
+ Agent Type: ${o.agentType}
206
+ Recurring: ${o.recurring}
207
+ Next Fire: ${new Date(o.nextFireAt).toLocaleString()}`,success:!0,parts:[{type:"text",text:`Scheduled task created: ${o.id}`}]}}catch(o){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error creating scheduled task: ${o instanceof Error?o.message:String(o)}`,success:false,parts:[{type:"text",text:`Error: ${o instanceof Error?o.message:String(o)}`}]}}}async function wv(e){try{let t=await Lt.listHeartbeats(),n=await Lt.listScheduled();return {title:"Task List",metadata:{sessionId:e.sessionId},output:pf(t,n),success:!0,parts:[{type:"text",text:pf(t,n)}]}}catch(t){return {title:"Loop Command",metadata:{sessionId:e.sessionId},output:`Error listing tasks: ${t instanceof Error?t.message:String(t)}`,success:false,parts:[{type:"text",text:`Error: ${t instanceof Error?t.message:String(t)}`}]}}}async function xv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
208
+
209
+ Usage: /loop delete <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await Lt.deleteHeartbeat(e.name).catch(()=>Lt.deleteScheduled(e.name)),{title:"Task Deleted",metadata:{sessionId:t.sessionId},output:`Task deleted: ${e.name}`,success:!0,parts:[{type:"text",text:`Task deleted: ${e.name}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error deleting task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function Iv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
210
+
211
+ Usage: /loop enable <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await Lt.enableHeartbeat(e.name).catch(()=>Lt.enableScheduled(e.name)),{title:"Task Enabled",metadata:{sessionId:t.sessionId},output:`Task enabled: ${e.name}`,success:!0,parts:[{type:"text",text:`Task enabled: ${e.name}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error enabling task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function vv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
212
+
213
+ Usage: /loop disable <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{return await Lt.disableHeartbeat(e.name).catch(()=>Lt.disableScheduled(e.name)),{title:"Task Disabled",metadata:{sessionId:t.sessionId},output:`Task disabled: ${e.name}`,success:!0,parts:[{type:"text",text:`Task disabled: ${e.name}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error disabling task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}async function Sv(e,t){if(!e.name)return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error: Task ID is required
214
+
215
+ Usage: /loop trigger <id>`,success:false,parts:[{type:"text",text:"Error: Task ID is required"}]};try{let n=await Lt.triggerHeartbeat(e.name).catch(()=>Lt.triggerScheduled(e.name));return {title:"Task Triggered",metadata:{sessionId:t.sessionId},output:n.success?`Task triggered successfully!
216
+
217
+ Output: ${n.output||"(no output)"}`:`Task failed: ${n.error}`,success:n.success,parts:[{type:"text",text:n.success?`Task executed: ${n.output||"(no output)"}`:`Task failed: ${n.error}`}]}}catch(n){return {title:"Loop Command",metadata:{sessionId:t.sessionId},output:`Error triggering task: ${n instanceof Error?n.message:String(n)}`,success:false,parts:[{type:"text",text:`Error: ${n instanceof Error?n.message:String(n)}`}]}}}function Er(){return `Loop Command - Create and manage scheduled tasks and heartbeats
218
+
219
+ Usage:
220
+ /loop <subcommand> [options]
221
+
222
+ Subcommands:
223
+ create <name> --cron <expression> [options]
224
+ Create a scheduled task or heartbeat
225
+
226
+ list
227
+ List all tasks
228
+
229
+ delete <id>
230
+ Delete a task
231
+
232
+ enable <id>
233
+ Enable a task
234
+
235
+ disable <id>
236
+ Disable a task
237
+
238
+ trigger <id>
239
+ Manually trigger a task
240
+
241
+ help
242
+ Show this help message
243
+
244
+ Options:
245
+ --cron <expr> Cron expression (required)
246
+ --type <type> Task type: heartbeat (default) | scheduled
247
+ --session <name> Session name (heartbeat required)
248
+ --mode <mode> Mode: session (default) | fork
249
+ --prompt <text> Prompt (scheduled required)
250
+ --agent-type <type> Agent type (default: default)
251
+ --transport <type> Transport: stdio (default) | http | websocket | cli
252
+ --recurring Recurring execution
253
+ --durable Persistent storage
254
+
255
+ Cron Expression Format:
256
+ \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 minute (0-59)
257
+ \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 hour (0-23)
258
+ \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 day (1-31)
259
+ \u2502 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 month (1-12)
260
+ \u2502 \u2502 \u2502 \u2502 \u250C\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500 weekday (0-6, 0=Sun)
261
+ \u2502 \u2502 \u2502 \u2502 \u2502
262
+ * * * * *
263
+
264
+ Examples:
265
+ /loop create main-heartbeat --cron "*/5 * * * *" --session main --type heartbeat
266
+ /loop create hourly-sync --cron "0 * * * *" --prompt "Sync data" --type scheduled
267
+ /loop list
268
+ /loop delete hb_xxx
269
+ /loop enable st_xxx
270
+ /loop trigger hb_xxx
271
+ `}var iu=f("cleanup",{description:"Internal cleanup command for truncating old files",source:"command",commandType:"local",subtask:false,hidden:true,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=[],o=[];if(typeof e=="string"&&e.includes("truncation"))try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(r){o.push(`Truncation cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("snapshot"))try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(r){o.push(`Snapshot cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("context"))try{await TruncateContent.cleanup(),n.push("Context cleanup completed");}catch(r){o.push(`Context cleanup failed: ${r instanceof Error?r.message:String(r)}`);}if(typeof e=="string"&&e.includes("all")){try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(r){o.push(`Truncation cleanup failed: ${r instanceof Error?r.message:String(r)}`);}try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(r){o.push(`Snapshot cleanup failed: ${r instanceof Error?r.message:String(r)}`);}try{await TruncateContent.cleanup(),n.push("Context cleanup completed");}catch(r){o.push(`Context cleanup failed: ${r instanceof Error?r.message:String(r)}`);}}if(typeof e=="object"&&e!==null){let r=e;if(r.type==="truncation"||r.target==="truncation")try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(i){o.push(`Truncation cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(r.type==="snapshot"||r.target==="snapshot")try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(i){o.push(`Snapshot cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(r.type==="context"||r.target==="context")try{await TruncateContent.cleanup(),n.push("Context cleanup completed");}catch(i){o.push(`Context cleanup failed: ${i instanceof Error?i.message:String(i)}`);}if(!r.type&&!r.target){try{await Ve.cleanup(),n.push("Truncation cleanup completed");}catch(i){o.push(`Truncation cleanup failed: ${i instanceof Error?i.message:String(i)}`);}try{await yt.cleanup(),n.push("Snapshot cleanup completed");}catch(i){o.push(`Snapshot cleanup failed: ${i instanceof Error?i.message:String(i)}`);}try{await TruncateContent.cleanup(),n.push("Context cleanup completed");}catch(i){o.push(`Context cleanup failed: ${i instanceof Error?i.message:String(i)}`);}}}let s=[...n,...o].join(`
272
+ `);return {title:"Cleanup Command",metadata:{sessionId:t.sessionId,success:o.length===0,cleaned:n.length,errors:o.length},output:s,success:o.length===0,parts:[{type:"text",text:s}]}},init:async()=>({})});var In;(f=>{let e=a.create({service:"knowledge.memory"}),t;async function n(a){let p=await he.get(),u=a?.embedding?.model||p.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:g,model:h}=parseModelId(u),S=g||"easbot-local",A=h||"bge-base-zh-v1.5",y=await xe.getEmbedding(S,A),x=a?.graph?.model||p.graph_model,b,w;if(x){let{provider:k,model:P}=parseModelId(x);b=k||"easbot-local",w=P||x;}else {let k=await xe.defaultModel();b=k.providerId,w=k.modelId;}let C;try{let k=await xe.getModel(b,w);C=await xe.getLanguage(k);}catch(k){e.error("memory loadModels graphLlm failed",{graphProvider:b,graphModel:w,error:String(k)});}return {embeddingLlm:y,graphLlm:C}}function o(){return t||(t=_.state(async()=>{let a$1=await ar();if(!a$1||a$1.enabled===false)return {system:null,config:null,rootDir:"",initialized:true};let{Global:p}=await import('./global-HVRSDT3G.mjs'),u=_.directory,g=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")),h=Filesystem.normalize(a$1?.database?Ce__default.isAbsolute(a$1.database)?a$1.database:Ce__default.resolve(u,a$1.database):Ce__default.join(_.worktree,".easbot","db","memory.db")),{embeddingLlm:S,graphLlm:A}=await n(a$1);return await initLog({logDir:p.Path.log,logFile:"memory.log",level:a.getLevel(),print:false}),{system:await createMemorySystem({workspaceDir:g,database:{path:h,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:S,graphLlm:A}),config:a$1??null,rootDir:g,initialized:true}},async a=>{a.system&&await a?.system?.close().catch(()=>{});})),t}function s(){return o()()}f.state=s;async function r(){return (await s()).system}f.get=r;async function i(){return (await s()).rootDir}f.rootDir=i;async function c(){return (await s()).system!==null}f.isEnabled=c;async function l(){return (await s()).config}f.config=l;async function d(){return (await s()).initialized}f.isInitialized=d;async function m(){(await r())?.sync().catch(p=>e.warn("memory sync failed",{error:String(p)}));}f.sync=m;})(In||(In={}));var Do;(p=>{let e=a.create({service:"knowledge.codebase"}),t;async function n(u){let g=await he.get(),h=u?.embedding?.model||g.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:S,model:A}=parseModelId(h),y=S||"easbot-local",x=A||"bge-base-zh-v1.5";try{return await xe.getEmbedding(y,x)}catch(b){return e.warn("failed to load embedding model, using easbot-local/bge-base-zh-v1.5",{error:b}),xe.getEmbedding("easbot-local","bge-base-zh-v1.5")}}function o(){return t||(t=_.state(async()=>{let u=await ir();if(!u||u.enabled===false)return {codebase:null,config:null,rootDir:"",initialized:true};let{Global:g}=await import('./global-HVRSDT3G.mjs'),h=Filesystem.normalize(_.worktree??_.directory),S=Filesystem.normalize(u.database?Ce__default.isAbsolute(u.database)?u.database:Ce__default.resolve(h,u.database):Ce__default.join(_.worktree,".easbot","db","codebase.db")),A=await n(u);await initLog$1({logDir:g.Path.log,logFile:"codebase.log",level:a.getLevel(),print:false});let y=await createCodebase({workspaceDir:h,database:{path:S,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(_.worktree,".gitignore"))).filter(x=>!x.includes(".easbot"))],incremental:u.indexer?.incremental??true},sync:u.sync,embeddingLlm:A});return u.sync?.onBoot&&await y.sync().catch(x=>e.warn("codebase sync on boot failed",{error:String(x)})),{codebase:y,config:u,rootDir:h,initialized:true}},async u=>{u.codebase&&await u?.codebase?.close().catch(()=>{});})),t}function s(){return o()()}p.state=s;async function r(){return (await s()).codebase}p.get=r;async function i(){return (await s()).rootDir}p.rootDir=i;async function c(){return (await s()).codebase!==null}p.isEnabled=c;async function l(){return (await s()).config}p.config=l;async function d(){return (await s()).initialized}p.isInitialized=d;async function m(){let u=await r();u&&u.sync().catch(g=>e.warn("codebase sync failed",{error:String(g)}));}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 g=await u.healthCheck();return {healthy:g.healthy,issues:g.issues}}p.healthCheck=a$1;})(Do||(Do={}));async function Ev(e){let t,n;switch(e){case "note":t=await Xt.isEnabled(),n=()=>Xt.sync();break;case "codebase":t=await Do.isEnabled(),n=()=>Do.sync();break;case "memory":t=await In.isEnabled(),n=()=>In.sync();break}return t?(n().catch(o=>{console.error(`${e} sync failed:`,o);}),{target:e,started:true,message:`${e} sync started`}):{target:e,started:false,message:`${e} not enabled`}}function Rv(e){return typeof e!="string"?[]:e.split(",").map(t=>t.trim().toLowerCase()).filter(t=>["note","codebase","memory"].includes(t))}var au=f("sync",{description:"Sync knowledge bases (note, codebase, memory)",source:"command",commandType:"local",subtask:false,hidden:false,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=Rv(e),o=n.length>0?n:["note","codebase","memory"],s=await Promise.all(o.map(d=>Ev(d))),r=s.filter(d=>d.started),i=s.filter(d=>!d.started),c=[];r.length>0&&c.push(`\u2713 Started: ${r.map(d=>d.target).join(", ")}`),i.length>0&&c.push(`\u2298 Skipped: ${i.map(d=>d.target).join(", ")}`);let l=c.join(`
273
+ `);return {title:"Knowledge Base Sync",metadata:{sessionId:t.sessionId,success:i.length===0,started:r.length,skipped:i.length},output:l,success:i.length===0,parts:[{type:"text",text:l}]}},init:async()=>({})});var Fv=["BOOT.md","IDENTITY.md","SOUL.md","USER.md","AGENTS.md","TOOLS.md","CONTEXT.md","CODER.md"];function yf(){let e=new Date,t=e.getFullYear(),n=String(e.getMonth()+1).padStart(2,"0"),o=String(e.getDate()).padStart(2,"0");return `${t}-${n}-${o}`}async function bf(e){try{return await access(e,constants.F_OK),!0}catch{return false}}async function Nv(e,t,n){let o={backedUpFiles:[],cleanedOldBackups:0},s=yf(),r=join(t,s);await mkdir(r,{recursive:true});for(let i of Fv){let c=join(e,i),l=join(r,i);await bf(c)&&(await copyFile(c,l),o.backedUpFiles.push(i));}if(n>0){let i=new Date;i.setDate(i.getDate()-n);try{let c=await readdir(t);for(let l of c){if(l===s)continue;let d=join(t,l),m=await stat(d);m.isDirectory()&&m.mtime<i&&(await rm$1(d,{recursive:!0,force:!0}),o.cleanedOldBackups++);}}catch{}}return o}var cu=f("backup",{description:"Backup agent configuration files to Global.Path.data/backup/yyyy-mm-dd/",source:"command",commandType:"local",subtask:false,hidden:true,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let n=[],o=[],s=".easbot",r=30;if(typeof e=="string"){let c=e.split(" ");for(let l of c)if(l.startsWith("config-path=")){let d=l.split("=")[1];d&&(s=d);}else if(l.startsWith("retention-days=")){let d=l.split("=")[1];d&&(r=parseInt(d,10)||30);}}else if(typeof e=="object"&&e!==null){let c=e;s=c.configPath||s,r=c.retentionDays||r;}try{await a$1.init();let c=join(a$1.Path.data,"backup");if(!await bf(s))n.push(`Config directory not found: ${s}`);else {let d=await Nv(s,c,r);n.push(`Backup completed to: ${join(c,yf())}`),n.push(`Backed up files: ${d.backedUpFiles.length}`),d.backedUpFiles.length>0&&n.push(`Files: ${d.backedUpFiles.join(", ")}`),d.cleanedOldBackups>0&&n.push(`Cleaned old backups: ${d.cleanedOldBackups}`);}}catch(c){o.push(`Backup failed: ${c instanceof Error?c.message:String(c)}`);}let i=[...n,...o].join(`
274
+ `);return {title:"Backup Command",metadata:{sessionId:t.sessionId,success:o.length===0,backedUpFiles:n.filter(c=>c.includes("Backed up files:")).length,errors:o.length},output:i,success:o.length===0,parts:[{type:"text",text:i}]}},init:async()=>({})});var wf=a.create({service:"command-abort"});function du(e,t,n,o={}){let s={title:"Abort",metadata:{sessionId:e,...o},output:n,parts:[{type:"text",text:n}],success:t};return t?s:{...s,error:n}}var lu=f("abort",{description:"Abort the currently running agent task",source:"command",commandType:"local",subtask:false,hidden:false,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let{sessionId:n}=t;wf.debug("Abort command executed",{sessionId:n});try{return (await Mt.get(n))?.type!=="busy"?du(n,!0,"\u2298 No active task to abort",{aborted:!1,reason:"no_active_task"}):(await nn.abortSession(n),du(n,!0,`\u2713 Abort signal sent
275
+
276
+ The agent will stop after completing its current action.`,{aborted:!0}))}catch(o){let s=o instanceof Error?o.message:String(o);return wf.error("Failed to abort session",{sessionId:n,error:s}),du(n,false,`\u2298 Failed to abort: ${s}`,{error:s})}},init:async()=>({})});var nn={};a$7(nn,{abort:()=>Qv,abortSession:()=>Cf,create:()=>Yv,createSession:()=>vf,deleteSession:()=>Uv,fork:()=>Xv,forkSession:()=>Sf,formatSessionJSON:()=>Vv,formatSessionTable:()=>Wv,get:()=>Jv,getSession:()=>If,getSessionChildren:()=>qv,getSessionContextMode:()=>Bv,getSessionStatus:()=>eS,initSession:()=>Hv,list:()=>Kv,listSessionStatuses:()=>tS,listSessions:()=>xf,setSessionContextMode:()=>Gv,summarize:()=>Zv,summarizeSession:()=>Lc,updateSession:()=>zv});async function xf(e){let t=[];for await(let o of X.list())!o.parentId&&(!e?.directory||o.directory===e.directory)&&t.push(o);t.sort((o,s)=>s.time.updated-o.time.updated);let n=e?.limit;return !n||n<=0?t:t.slice(0,n)}async function If(e){return X.get(e)}async function vf(e){return X.create(e)}async function Sf(e,t,n){return X.fork({sessionId:e,messageId:t,directory:n})}async function Uv(e){await X.remove(e);}async function Cf(e){let{SessionPrompt:t}=await import('./prompt-7M7NMDG4.mjs');await t.cancel(e);}async function Lc(e){let[{SessionPrompt:t},{Compaction:n},{SessionRevert:o}]=await Promise.all([import('./prompt-7M7NMDG4.mjs'),import('./compaction-OCFEYJC4.mjs'),import('./revert-FOMRGDW5.mjs')]),s=e.sessionId,r=await X.get(s);if(!r)throw new Error("session not found");await o.cleanup(r);let i;return e.providerId&&e.modelId&&(i={providerId:e.providerId,modelId:e.modelId}),await n.create({sessionId:s,model:i,agent:e.agent??"compaction",auto:e.auto??false}),await t.loop({sessionId:s}),true}async function zv(e,t){let n=await X.get(e);if(!n)throw new Error("session not found");t.title&&(n.title=t.title),t.time?.archived&&(n.time.archived=t.time.archived);let{Storage:o}=await import('./storage-23DKEFPY.mjs'),{Instance:s}=await import('./instance-5OB47GH5.mjs');return await o.write(["session",s.project.id,e],n),n}async function qv(e){return X.children(e)}async function Hv(e){return true}async function Bv(e){return X.getContextMode(e)}async function Gv(e,t){await X.setContextMode(e,t);}function Wv(e,t=20,n=25){let o=[],s=Math.max(t,...e.map(c=>c.id.length)),r=Math.max(n,...e.map(c=>c.title.length)),i=`Session ID${" ".repeat(s-10)} Title${" ".repeat(r-5)} Updated`;o.push(i),o.push("\u2500".repeat(i.length));for(let c of e){let l=c.title.length>r?c.title.slice(0,r-3)+"...":c.title,d=new Date(c.time.updated).toLocaleString(),m=`${c.id.padEnd(s)} ${l.padEnd(r)} ${d}`;o.push(m);}return o.join(`
277
+ `)}function Vv(e){let t=e.map(n=>({id:n.id,title:n.title,updated:n.time.updated,created:n.time.created,projectId:n.providerId,directory:n.directory}));return JSON.stringify(t,null,2)}var Kv=xf,Jv=If,Yv=vf,Xv=Sf,Qv=Cf,Zv=Lc;async function eS(e){return Mt.get(e)}async function tS(){return Mt.list()}var kf=a.create({service:"command-compact"});function Pf(e,t,n,o={}){let s={title:"Compact",metadata:{sessionId:e,...o},output:n,parts:[{type:"text",text:n}],success:t};return t?s:{...s,error:n}}var uu=f("compact",{description:"Compact context by summarizing old messages",source:"command",commandType:"local",agent:"compaction",subtask:false,hidden:false,hints:[],isEnabled:()=>Promise.resolve(true),execute:async(e,t)=>{let{sessionId:n}=t;kf.debug("Compact command executed",{sessionId:n});try{return await Lc({sessionId:n,agent:"compaction"}),Pf(n,!0,`\u2713 Context compaction started
278
+
279
+ Summarization is running in the background.`)}catch(o){let s=o instanceof Error?o.message:String(o);return kf.error("Failed to start compact",{sessionId:n,error:s}),Pf(n,false,`\u2298 Failed to start compaction: ${s}`,{error:s})}},init:async()=>({})});var Tf=[Jl,Yl,Xl,Ql,Zl,eu,ru,iu,au,cu,lu,uu];var Rf=a.create({service:"command.registry"}),vn;(A=>{A.Info=F.object({name:F.string(),description:F.string().optional(),agent:F.string().optional(),model:F.string().optional(),source:F.enum(["command","mcp","skill"]).optional(),subtask:F.boolean().optional(),hints:F.array(F.string()).optional(),commandType:F.enum(["prompt","local"]).optional(),isHidden:F.boolean().optional(),isEnabled:F.any().optional(),execute:F.any()}).meta({ref:"Command"}),A.Default={INIT:"init",REVIEW:"review",BTW:"btw"},A.Event={Executed:a$5.define("command.executed",F.object({name:F.string(),sessionId:Identifier.schema("session"),arguments:F.union([F.string(),F.record(F.string(),F.unknown())]),messageId:Identifier.schema("message")}))},A.define=f;let s,r;async function i(y){let x={};return y.init&&await y.init(x),{name:y.name,description:y.description,agent:y.agent,model:y.model,source:y.source,subtask:y.subtask,hints:y.hints,commandType:y.commandType,isEnabled:y.isEnabled,scope:y.scope??"all",hidden:y.hidden,execute:y.execute}}async function c(y){let{glob:x}=await import('glob'),b={};if(!await Filesystem.isDir(y))return b;let w=await x("*.md",{cwd:y,absolute:true,nodir:true,follow:false,dot:false});for(let C of w)try{let{ConfigMarkdown:k}=await import('./markdown-Z6UXVBNP.mjs'),P=await k.parse(C),{CommandMetadataSchema:E}=await import('@easbot/plugin'),O=E.parse(P.data),N=c$3(O,P.content,"command");b[N.name]=N;}catch(k){Rf.error("Failed to load command file",{file:C,error:k});}return b}function l(){return s||(s=_.state(async()=>{let y=await he.get(),x={};for(let b of Tf){let w=await i(b);x[b.name]=w;}for(let[b,w]of Object.entries(y.command??{})){let C=typeof w.template=="string"?w.template:"";x[b]={name:b,agent:w.agent,model:w.model,scope:w.scope??"all",description:w.description,source:"command",subtask:w.subtask,hints:/\{\{ARGUMENTS\}\}/i.test(C)?["{{ARGUMENTS}}"]:[],commandType:"prompt",isEnabled:()=>true,execute:async(k,P)=>{let{replaceTemplateVars:E}=await import('./command-34YNL5HZ.mjs'),O=E(C,k);return {title:b,metadata:{sessionId:P.sessionId},output:O,success:true,parts:[{type:"text",text:O}]}}};}for(let[b,w]of Object.entries(await ze.prompts()))x[b]={name:b,source:"mcp",scope:w.scope??"all",description:w.description,commandType:"prompt",hints:w.arguments?.map((C,k)=>`$${k+1}`)??[],isEnabled:()=>true,execute:async C=>{if(typeof C=="string"){let O=(C.match(/(?:\[Image\s+\d+\]|"[^"]*"|'[^']*'|[^\s"']+)/gi)??[]).map(Q=>Q.replace(/^["']|["']$/g,"")),N=w.arguments?Object.fromEntries(w.arguments.map((Q,ue)=>[Q.name,O[ue]??""])):{},K=(await ze.getPrompt(w.client,w.name,N))?.messages.map(Q=>Q.content.type==="text"?Q.content.text:"").join(`
280
+ `)||"";return {title:b,metadata:{},output:K,success:true,parts:[{type:"text",text:K}]}}let P=(await ze.getPrompt(w.client,w.name,C))?.messages.map(E=>E.content.type==="text"?E.content.text:"").join(`
281
+ `)||"";return {title:b,metadata:{},output:P,success:true,parts:[{type:"text",text:P}]}}};for(let b of await Jt.all())x[b.name]={name:b.name,description:b.description,source:"skill",commandType:"prompt",hints:[],scope:b.scope??"all",isEnabled:()=>true,execute:async(w,C)=>({title:b.name,metadata:{sessionId:C.sessionId},output:b.content,success:true,parts:[{type:"text",text:b.content}]})};if(r)for(let[b,w]of Object.entries(r))x[b]=w;for await(let b of Filesystem.up({targets:[".easbot/commands"],start:_.directory,stop:_.worktree})){let w=await c(b);for(let[C,k]of Object.entries(w))x[C]||(x[C]=k);}return x})),s}async function d(){return l()()}A.state=d;async function m(){return d()}A.all=m;async function f$1(y){return d().then(x=>x[y])}A.get=f$1;async function a(y){let x=await d(),b=y??"general",w=[];for(let C of Object.values(x)){let k=C.scope??"all";k!=="all"&&k!==b||C.isEnabled&&!await C.isEnabled()||w.push(C);}return w}A.list=a;async function p(y,x){r||(r=await d()),r[y]=x,g();}A.register=p;async function u(y){return r?.[y]?(delete r[y],g(),true):false}A.unregister=u;function g(){s=void 0;}async function h(){r=void 0,g(),await d();}A.refresh=h;async function S(){await d(),Rf.debug("command registry initialized");}A.init=S;})(vn||(vn={}));var pu=vn;var jf=a$5.define("command.executed",F.object({name:F.string(),sessionId:F.string(),arguments:F.union([F.string(),F.record(F.string(),F.unknown())]),messageId:F.string().optional()})),Lf=a.create({service:"command.executor"});F.object({sessionId:Identifier.schema("session"),agent:F.string(),model:F.object({providerId:F.string(),modelId:F.string()}).optional(),command:F.string()});F.object({messageId:Identifier.schema("message").optional(),sessionId:Identifier.schema("session"),agent:F.string().optional(),model:F.string().optional(),arguments:F.union([F.string(),F.record(F.string(),F.unknown())]),command:F.string(),variant:F.string().optional(),parts:F.array(F.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 iS=/!`([^`]+)`/g;async function Dc(e){let t=await Zo(e);return await xe.getModel(t.providerId,t.modelId)}async function aS(e){let t=[{type:"text",text:e}],n=a$9.files(e),o=new Set;for(let s of n){let r=s[1];if(!r||o.has(r))continue;o.add(r);let i=_.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 zi;(n=>{async function e(o){let s=Je.start(o.sessionId);if(!s)throw new X.BusyError(o.sessionId);let r=async()=>{(Je.state()[o.sessionId]?.callbacks??[]).length===0?await Je.cancel(o.sessionId):Je.loop({sessionId:o.sessionId,resume_existing:true}).catch(c=>{Lf.error("session loop failed to resume after shell command",{sessionId:o.sessionId,error:c});});};try{let i=await X.get(o.sessionId);i.revert&&await ao.cleanup(i);let c=await Ue.get(o.agent);if(!c)throw new Error(`Agent not found: ${o.agent}`);let l;o.model?l=await xe.getModel(o.model.providerId,o.model.modelId):c.model?l=await xe.getModel(c.model.providerId,c.model.modelId):l=await Dc(o.sessionId);let d={id:Identifier.ascending("message"),sessionId:o.sessionId,time:{created:Date.now()},role:"user",agent:o.agent,model:{providerId:l.providerId,modelId:l.id}};await X.updateMessage(d);let m={type:"text",id:Identifier.ascending("part"),messageId:d.id,sessionId:o.sessionId,text:"The following tool was executed by the user",synthetic:!0};await X.updatePart(m);let f={id:Identifier.ascending("message"),sessionId:o.sessionId,parentId:d.id,mode:o.agent,agent:o.agent,cost:0,path:{cwd:_.directory,root:_.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 X.updateMessage(f);let a={type:"tool",id:Identifier.ascending("part"),messageId:f.id,sessionId:o.sessionId,tool:"bash",callId:ulid(),state:{status:"running",time:{start:Date.now()},input:{command:o.command}}};await X.updatePart(a);let p=Shell.acceptable(),u=await Promise.resolve(p),g=(process.platform==="win32"?Ce__default.win32.basename(u??"",".exe"):Ce__default.basename(u??"")).toLowerCase(),h={nu:{args:["-c",o.command]},fish:{args:["-c",o.command]},zsh:{args:["-c","-l",`
282
+ [[ -f ~/.zshenv ]] && source ~/.zshenv >/dev/null 2>&1 || true
283
+ [[ -f "\${ZDOTDIR:-$HOME}/.zshrc" ]] && source "\${ZDOTDIR:-$HOME}/.zshrc" >/dev/null 2>&1 || true
284
+ eval ${JSON.stringify(o.command)}
285
+ `]},bash:{args:["-c","-l",`
286
+ shopt -s expand_aliases
287
+ [[ -f ~/.bashrc ]] && source ~/.bashrc >/dev/null 2>&1 || true
288
+ eval ${JSON.stringify(o.command)}
289
+ `]},cmd:{args:["/c",o.command]},powershell:{args:["-NoProfile","-Command",o.command]},pwsh:{args:["-NoProfile","-Command",o.command]},"":{args:["-c",`${o.command}`]}},A=(h[g]??h[""])?.args??[];process.platform==="win32"&&(g==="cmd"?A=["/c",`chcp 65001 >nul 2>&1 && ${o.command}`]:(g==="powershell"||g==="pwsh")&&(A=["-NoProfile","-Command",`[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; ${o.command}`]));let y=_.directory,b=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:y},{cwd:y})).output?.env??{},w=spawn(u??"sh",A,{cwd:y,detached:process.platform!=="win32",stdio:["ignore","pipe","pipe"],env:{...process.env,...b,TERM:"dumb",LANG:"en_US.UTF-8",LC_ALL:"en_US.UTF-8"}}),C="";w.stdout?.on("data",N=>{C+=N.toString("utf-8"),a.state.status==="running"&&(a.state.metadata={output:C,description:""},X.updatePart(a));}),w.stderr?.on("data",N=>{C+=N.toString("utf-8"),a.state.status==="running"&&(a.state.metadata={output:C,description:""},X.updatePart(a));});let k=!1,P=!1,E=()=>Shell.killTree(w,{exited:()=>P});s.aborted&&(k=!0,await E());let O=()=>{k=!0,E();};return s.addEventListener("abort",O,{once:!0}),await new Promise(N=>{w.on("close",()=>{P=!0,s.removeEventListener("abort",O),N();});}),k&&(C+=`
290
+
291
+ `+["<metadata>","User aborted the command","</metadata>"].join(`
292
+ `)),f.time={...f.time,completed:Date.now()},await X.updateMessage(f),a.state.status==="running"&&(a.state={status:"completed",time:{...a.state.time,end:Date.now()},input:a.state.input,title:"",metadata:{output:C,description:""},output:C},await X.updatePart(a)),{info:f,parts:[a],title:"Shell Command",metadata:{command:o.command},output:C,success:!k}}finally{await r();}}n.shell=e;async function t(o){Lf.debug("command",o);let s=await vn.get(o.command);if(!s)throw new Error(`Command not found: ${o.command}`);if(await Le.triggerEvent(HookEvent.CommandBefore,{command:o.command,sessionId:o.sessionId,arguments:o.arguments},{sessionId:o.sessionId}),s.commandType==="local"){let w={sessionId:o.sessionId,directory:_.worktree,model:o.model,agent:s.agent??o.agent??await Ue.defaultAgent(),arguments:o.arguments},C=await s.execute(o.arguments,w);C.metadata.commandType="local";let k={...C,success:C.success,error:C.metadata?.error};return await pe.publish(jf,{name:o.command,sessionId:o.sessionId,arguments:o.arguments}),await Le.triggerEvent(HookEvent.CommandAfter,{command:o.command,sessionId:o.sessionId,arguments:o.arguments,result:k},{sessionId:o.sessionId}),k}let r=s.agent??o.agent??await Ue.defaultAgent(),i={sessionId:o.sessionId,directory:_.worktree,model:o.model,agent:r,arguments:o.arguments},l=(await s.execute(o.arguments,i)).output,d=l,m=a$9.shell(d);if(m.length>0){let w=await Promise.all(m.map(async([,k])=>{try{return await $`${{raw:k}}`.quiet().nothrow().text()}catch(P){return `Error executing command: ${P instanceof Error?P.message:String(P)}`}})),C=0;d=d.replace(iS,()=>w[C++]??"");}d=d.trim();let a=await(async()=>{if(s.model)return xe.parseModel(s.model);if(s.agent){let C=await Ue.get(s.agent);if(C?.model)return C.model}if(o.model)return xe.parseModel(o.model);let w=await Dc(o.sessionId);return {providerId:w.providerId,modelId:w.id}})();try{await xe.getModel(a.providerId,a.modelId);}catch(w){if(xe.ModelNotFoundError.isInstance(w)){let{providerId:C,modelId:k,suggestions:P}=w.data,E=P&&P.length>0?` Did you mean: ${P.join(", ")}?`:"";await pe.publish(X.Event.Error,{sessionId:o.sessionId,error:new NamedError.Unknown({message:`Model not found: ${C}/${k}.${E}`}).toObject()});}throw w}let p=await Ue.get(r);if(!p){let w=await Ue.list().then(P=>P.filter(E=>!E.hidden).map(E=>E.name)),C=w.length>0?` Available agents: ${w.join(", ")}`:"",k=new NamedError.Unknown({message:`Agent not found: "${r}".${C}`});throw await pe.publish(X.Event.Error,{sessionId:o.sessionId,error:k.toObject()}),k}let u=await aS(d),g=[],h=s.subtask===true,S=Identifier.ascending("task"),A=h?[{type:"subtask",taskId:S,agent:p.name,description:s.description??"",command:o.command,model:{providerId:a.providerId,modelId:a.modelId},prompt:[...u??[],...g].find(w=>w.type==="text")?.text??""}]:[...u??[],...g,...o.parts??[]],y=h?o.agent??await Ue.defaultAgent():r,x=h?o.model?xe.parseModel(o.model):{providerId:(await Dc(o.sessionId)).providerId,modelId:(await Dc(o.sessionId)).id}:a,b=await Je.prompt({sessionId:o.sessionId,messageId:o.messageId,model:x,agent:y,parts:A,variant:o.variant});return await pe.publish(jf,{name:o.command,sessionId:o.sessionId,arguments:o.arguments,messageId:b.info.id}),await Le.triggerEvent(HookEvent.CommandAfter,{command:o.command,sessionId:o.sessionId,arguments:o.arguments,result:{info:b.info,parts:b.parts,success:true}},{sessionId:o.sessionId}),{info:b.info,parts:b.parts,title:o.command,metadata:{command:o.command,arguments:o.arguments,commandType:"prompt"},output:l,success:true}}n.execute=t;})(zi||(zi={}));var fu=new Set(["powershell","pwsh"]),gu=new Set(["cmd"]);function dS(e){return e==="pwsh"?"pwsh":e==="powershell"?"powershell":e==="cmd"?"cmd":e==="bash"?"bash":e==="zsh"?"zsh":e}function mu(e){return fu.has(e)?`Brief description of this command (5-10 words). Examples:
293
+ Input: Get-ChildItem -LiteralPath "."
294
+ Output: Lists current directory
295
+
296
+ Input: git status
297
+ Output: Shows working tree status
298
+
299
+ Input: npm install
300
+ Output: Installs package dependencies
301
+
302
+ Input: New-Item -ItemType Directory -Path "tmp"
303
+ Output: Creates directory tmp`:gu.has(e)?`Brief description of this command (5-10 words). Examples:
304
+ Input: dir
305
+ Output: Lists current directory
306
+
307
+ Input: if exist "package.json" type "package.json"
308
+ Output: Prints package.json when it exists
309
+
310
+ Input: mkdir tmp
311
+ Output: Creates directory tmp`:`Brief description of this command (5-10 words). Examples:
312
+ Input: ls
313
+ Output: Lists files in current directory
314
+
315
+ Input: git status
316
+ Output: Shows working tree status
317
+
318
+ Input: npm install
319
+ Output: Installs package dependencies
320
+
321
+ Input: mkdir foo
322
+ Output: Creates directory 'foo'`}function lS(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 uS(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.":fu.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.":gu.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 pS(e,t){return `Before executing the command, please follow these steps:
323
+
324
+ 1. Directory Verification:
325
+ - If the command will create new directories or files, first use \`ls\` to verify the parent directory exists and is the correct location
326
+ - For example, before running "mkdir foo/bar", first use \`ls foo\` to check that "foo" exists and is the intended parent directory
327
+
328
+ 2. Command Execution:
329
+ - Always quote file paths that contain spaces with double quotes (e.g., rm "path with spaces/file.txt")
330
+ - Examples of proper quoting:
331
+ - mkdir "/Users/name/My Documents" (correct)
332
+ - mkdir /Users/name/My Documents (incorrect - will fail)
333
+ - python "/path/with spaces/script.py" (correct)
334
+ - python /path/with spaces/script.py (incorrect - will fail)
335
+ - After ensuring proper quoting, execute the command.
336
+ - Capture the output of the command.
337
+
338
+ Usage notes:
339
+ - The command argument is required.
340
+ - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
341
+ - Provide a brief description of what this command does (5-10 words).
342
+ - If the output exceeds ${t.maxLines} lines or ${t.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Because of this, you do NOT need to use \`head\`, \`tail\`, or other truncation commands to limit output - just run the command directly.
343
+
344
+ - Avoid using Bash with the \`find\`, \`grep\`, \`cat\`, \`head\`, \`tail\`, \`sed\`, \`awk\`, or \`echo\` commands, unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
345
+ - File search: Use Glob (NOT find or ls)
346
+ - Content search: Use Grep (NOT grep or rg)
347
+ - Read files: Use Read (NOT cat/head/tail)
348
+ - Edit files: Use Edit (NOT sed/awk)
349
+ - Write files: Use Write (NOT echo >/cat <<EOF)
350
+ - Communication: Output text directly (NOT echo/printf)
351
+ - When issuing multiple commands:
352
+ - If the commands are independent and can run in parallel, make multiple Bash tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Bash tool calls in parallel.
353
+ - ${e}
354
+ - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
355
+ - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
356
+ - AVOID using \`cd <directory> && <command>\`. Use the \`workdir\` parameter to change directories instead.
357
+ <good-example>
358
+ Use workdir="/foo/bar" with command: pytest tests
359
+ </good-example>
360
+ <bad-example>
361
+ cd /foo/bar && pytest tests
362
+ </bad-example>`}function mS(e,t,n){let o=process.platform==="win32"?"\\":"/";return `${lS(e)}
363
+
364
+ Before executing the command, please follow these steps:
365
+
366
+ 1. Directory Verification:
367
+ - If the command will create new directories or files, first use \`Test-Path -LiteralPath <parent>\` to verify the parent directory exists and is the correct location
368
+ - For example, before creating \`foo${o}bar\`, first use \`Test-Path -LiteralPath "foo"\` to check that \`foo\` exists and is the intended parent directory
369
+
370
+ 2. Command Execution:
371
+ - Always quote file paths that contain spaces with double quotes (e.g., Remove-Item -LiteralPath "path with spaces${o}file.txt")
372
+ - Examples of proper quoting:
373
+ - New-Item -ItemType Directory -Path "My Documents" (correct)
374
+ - New-Item -ItemType Directory -Path My Documents (incorrect - path is split)
375
+ - & "path with spaces${o}script.ps1" (correct)
376
+ - path with spaces${o}script.ps1 (incorrect - path is split and not invoked)
377
+ - After ensuring proper quoting, execute the command.
378
+ - Capture the output of the command.
379
+
380
+ Usage notes:
381
+ - The command argument is required.
382
+ - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
383
+ - Provide a brief description of what this command does (5-10 words).
384
+ - If the output exceeds ${n.maxLines} lines or ${n.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Because of this, you do NOT need to use \`Select-Object -First\`, \`Select-Object -Last\`, or other truncation commands to limit output - just run the command directly.
385
+
386
+ - Avoid using Shell with PowerShell file/content cmdlets unless explicitly instructed or when these cmdlets are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
387
+ - File search: Use Glob (NOT Get-ChildItem)
388
+ - Content search: Use Grep (NOT Select-String)
389
+ - Read files: Use Read (NOT Get-Content)
390
+ - Edit files: Use Edit (NOT Set-Content)
391
+ - Write files: Use Write (NOT Set-Content/Out-File or here-strings)
392
+ - Communication: Output text directly (NOT Write-Output/Write-Host)
393
+ - When issuing multiple commands:
394
+ - If the commands are independent and can run in parallel, make multiple Shell tool calls in a single message. For example, if you need to run "git status" and "git diff", send a single message with two Shell tool calls in parallel.
395
+ - ${t}
396
+ - Use ';' only when you need to run commands sequentially but don't care if earlier commands fail
397
+ - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
398
+ - AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
399
+ <good-example>
400
+ Use workdir="project${o}subdir" with command: pytest tests
401
+ </good-example>
402
+ <bad-example>
403
+ ${e==="powershell"?`Set-Location -LiteralPath "project${o}subdir"; if ($?) { pytest tests }`:`Set-Location -LiteralPath "project${o}subdir" && pytest tests`}
404
+ </bad-example>`}function fS(e,t){return `# cmd.exe shell notes
405
+ - Use double quotes for paths with spaces.
406
+ - Use %VAR% for environment variables.
407
+ - Use \`if exist\` for existence checks.
408
+ - Use \`call\` when invoking batch files from another batch-style command.
409
+
410
+ Before executing the command, please follow these steps:
411
+
412
+ 1. Directory Verification:
413
+ - If the command will create new directories or files, first use \`if exist\` to verify the parent directory exists and is the correct location
414
+ - For example, before creating \`foo\\bar\`, first use \`if exist "foo\\" dir "foo"\` to check that \`foo\` exists and is the intended parent directory
415
+
416
+ 2. Command Execution:
417
+ - Always quote file paths that contain spaces with double quotes (e.g., del "path with spaces\\file.txt")
418
+ - Examples of proper quoting:
419
+ - mkdir "My Documents" (correct)
420
+ - mkdir My Documents (incorrect - path is split)
421
+ - call "path with spaces\\script.bat" (correct)
422
+ - path with spaces\\script.bat (incorrect - path is split and not invoked correctly)
423
+ - After ensuring proper quoting, execute the command.
424
+ - Capture the output of the command.
425
+
426
+ Usage notes:
427
+ - The command argument is required.
428
+ - You can specify an optional timeout in milliseconds. If not specified, commands will time out after 120000ms (2 minutes).
429
+ - Provide a brief description of what this command does (5-10 words).
430
+ - If the output exceeds ${t.maxLines} lines or ${t.maxBytes} bytes, it will be truncated and the full output will be written to a file. You can use Read with offset/limit to read specific sections or Grep to search the full content. Because of this, you do NOT need to use \`more\` or other pagination commands to limit output - just run the command directly.
431
+
432
+ - Avoid using Shell with cmd.exe file/content commands unless explicitly instructed or when these commands are truly necessary for the task. Instead, always prefer using the dedicated tools for these commands:
433
+ - File search: Use Glob (NOT dir /s)
434
+ - Content search: Use Grep (NOT findstr)
435
+ - Read files: Use Read (NOT type)
436
+ - Edit files: Use Edit (NOT copy)
437
+ - Write files: Use Write (NOT echo > file)
438
+ - Communication: Output text directly (NOT echo)
439
+ - When issuing multiple commands:
440
+ - If the commands are independent and can run in parallel, make multiple Shell tool calls in a single message. For example, if you need to run "dir" and "where cmd", send a single message with two Shell tool calls in parallel.
441
+ - ${e}
442
+ - Use '&' only when you need to run commands sequentially but don't care if earlier commands fail
443
+ - DO NOT use newlines to separate commands (newlines are ok in quoted strings)
444
+ - AVOID changing directories inside the command. Use the \`workdir\` parameter to change directories instead.
445
+ <good-example>
446
+ Use workdir="project\\subdir" with command: dir
447
+ </good-example>
448
+ <bad-example>
449
+ cd /d "project\\subdir" && dir
450
+ </bad-example>`}function gS(e,t){let n=fu.has(e),o=gu.has(e),s=dS(e),r=uS(e);return o?{intro:`Executes a given ${s} command with optional timeout, ensuring proper handling and security measures.`,workdirSection:"All commands run in {{directory}} by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.",commandSection:fS(r,t),gitSection:`# Committing changes with git
451
+
452
+ Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
453
+
454
+ Git Safety Protocol:
455
+ - NEVER update the git config
456
+ - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
457
+ - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
458
+ - NEVER run force push to main/master, warn the user if they request it
459
+ - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
460
+ (1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
461
+ (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
462
+ (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
463
+ - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
464
+ - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
465
+ - NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
466
+
467
+ 1. You can call multiple tools in a single response. When multiple independent pieces of information are requested and all commands are likely to succeed, run the following bash commands in parallel:
468
+ - Run \`git status\` to see all untracked files
469
+ - Run \`git diff\` to see both staged and unstaged changes that will be committed
470
+ - Run \`git log --oneline -10\` to see recent commit messages
471
+
472
+ 2. Analyze all staged changes and draft a commit message:
473
+ - Summarize the nature of the changes
474
+ - Draft a concise (1-2 sentences) commit message
475
+ - Do not commit files that likely contain secrets (.env, etc.)
476
+
477
+ 3. Create the commit using a temporary body file so cmd.exe quoting stays simple:
478
+ \`(
479
+ echo ## Summary
480
+ echo ^<1-3 bullet points^>
481
+ ) ^> pr-body.txt
482
+ gh pr create --title "the pr title" --body-file pr-body.txt\`
483
+
484
+ 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
485
+
486
+ # Creating pull requests
487
+
488
+ Use the gh command via the Shell tool for ALL GitHub-related tasks including PRs and issues. Create PR using a temporary body file so cmd.exe quoting stays simple.`,createPrSection:`IMPORTANT: When creating a PR with gh, use a temporary body file for correct cmd.exe quoting:
489
+ \`(
490
+ echo ## Summary
491
+ echo - ^<1-3 bullet points^>
492
+ ) ^> pr-body.txt
493
+ gh pr create --title "the pr title" --body-file pr-body.txt\``,parameterDescription:mu(e)}:n?{intro:`Executes a given ${s} command with optional timeout, ensuring proper handling and security measures.`,workdirSection:"All commands run in {{directory}} by default. Use the `workdir` parameter if you need to run a command in a different directory. AVOID using `cd <directory> && <command>` patterns - use `workdir` instead.",commandSection:mS(e,r,t),gitSection:`# Committing changes with git
494
+
495
+ Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
496
+
497
+ Git Safety Protocol:
498
+ - NEVER update the git config
499
+ - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
500
+ - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
501
+ - NEVER run force push to main/master, warn the user if they request it
502
+ - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
503
+ (1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
504
+ (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
505
+ (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
506
+ - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
507
+ - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
508
+ - NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
509
+
510
+ 1. Run these commands in parallel:
511
+ - Run \`git status\` to see all untracked files
512
+ - Run \`git diff\` to see both staged and unstaged changes
513
+ - Run \`git log --oneline -10\` to see recent commit messages
514
+
515
+ 2. Analyze all staged changes and draft a commit message
516
+
517
+ 3. Create the commit:
518
+ - Add relevant untracked files to the staging area
519
+ - Create the commit with a message
520
+ - Run git status after the commit completes
521
+
522
+ 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
523
+
524
+ # Creating pull requests
525
+
526
+ Use the gh command via the Shell tool for ALL GitHub-related tasks. Create PR using gh pr create with a PowerShell here-string to pass the body correctly:
527
+ \`\`\`powershell
528
+ gh pr create --title "the pr title" --body @'
529
+ ## Summary
530
+ - <1-3 bullet points>
531
+ '@
532
+ \`\`\``,createPrSection:`IMPORTANT: When creating a PR with gh, use a PowerShell here-string for correct body formatting:
533
+ \`gh pr create --title "the pr title" --body @'
534
+ ## Summary
535
+ - <1-3 bullet points>
536
+ '@`,parameterDescription:mu(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:pS(r,t),gitSection:`# Committing changes with git
537
+
538
+ Only create commits when requested by the user. If unclear, ask first. When the user asks you to create a new git commit, follow these steps carefully:
539
+
540
+ Git Safety Protocol:
541
+ - NEVER update the git config
542
+ - NEVER run destructive/irreversible git commands (like push --force, hard reset, etc) unless the user explicitly requests them
543
+ - NEVER skip hooks (--no-verify, --no-gpg-sign, etc) unless the user explicitly requests it
544
+ - NEVER run force push to main/master, warn the user if they request it
545
+ - Avoid git commit --amend. ONLY use --amend when ALL conditions are met:
546
+ (1) User explicitly requested amend, OR commit SUCCEEDED but pre-commit hook auto-modified files that need including
547
+ (2) HEAD commit was created by you in this conversation (verify: git log -1 --format='%an %ae')
548
+ (3) Commit has NOT been pushed to remote (verify: git status shows "Your branch is ahead")
549
+ - CRITICAL: If commit FAILED or was REJECTED by hook, NEVER amend - fix the issue and create a NEW commit
550
+ - CRITICAL: If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)
551
+ - NEVER commit changes unless the user explicitly asks you to. It is VERY IMPORTANT to only commit when explicitly asked, otherwise the user will feel that you are being too proactive.
552
+
553
+ 1. Run these commands in parallel:
554
+ - Run \`git status\` to see all untracked files
555
+ - Run \`git diff\` to see both staged and unstaged changes
556
+ - Run \`git log --oneline -10\` to see recent commit messages
557
+
558
+ 2. Analyze all staged changes and draft a commit message
559
+
560
+ 3. Create the commit:
561
+ - Add relevant untracked files to the staging area
562
+ - Create the commit with a message
563
+ - Run git status after the commit completes
564
+
565
+ 4. If the commit fails due to pre-commit hook, fix the issue and create a NEW commit (see amend rules above)
566
+
567
+ # Creating pull requests
568
+
569
+ Use the gh command via the Shell tool for ALL GitHub-related tasks including PRs and issues. Use gh pr create with the format below. Use a HEREDOC to pass the body:
570
+ \`\`\`bash
571
+ gh pr create --title "the pr title" --body "$(cat <<'EOF'
572
+ ## Summary
573
+ <1-3 bullet points>
574
+ EOF
575
+ )"
576
+ \`\`\``,createPrSection:`IMPORTANT: When creating a PR with gh, use a HEREDOC to pass the body:
577
+ \`gh pr create --title "the pr title" --body "$(cat <<'EOF'
578
+ ## Summary
579
+ <1-3 bullet points>
580
+ EOF
581
+ )"\``,parameterDescription:mu(e)}}function Df(e){let t={maxLines:Ve.MAX_LINES,maxBytes:Ve.MAX_BYTES},n=Shell.name(e),o=gS(n,t);return {description:`${o.intro}
582
+
583
+ ${o.workdirSection}
584
+
585
+ ${o.commandSection}
586
+
587
+ ${o.gitSection}
588
+
589
+ ${o.createPrSection}`,parameterDescription:o.parameterDescription}}var Fc=3e4,wS=a$2.EASBOT_BASH_DEFAULT_TIMEOUT_MS||120*1e3,Nc=a.create({service:"tool.bash"});function xS(e){let t=[];function n(o){if(o){if(o.type==="Command"){let s=o.name?.text||"",r=[],i=o.text||"";if(o.suffix)for(let c of o.suffix)c.text&&r.push(c.text);s&&t.push({command:s,args:r,fullText:i});}if(o.commands)for(let s of o.commands)n(s);o.left&&n(o.left),o.right&&n(o.right),o.then&&n(o.then),o.else&&n(o.else);}}return n(e),t}var Ff=De.define("bash",async()=>{let e=Shell.acceptable()??"/bin/bash";Nc.debug("bash tool using shell",{shell:e});let{description:t,parameterDescription:n}=Df(e);return {description:t.replaceAll("{{directory}}",_.directory).replaceAll("{{maxLines}}",String(Ve.MAX_LINES)).replaceAll("{{maxBytes}}",String(Ve.MAX_BYTES)),parameters:F.object({command:F.string().describe("The command to execute"),timeout:F.number().describe("Optional timeout in milliseconds").optional(),workdir:F.string().describe(`The working directory to run the command in. Defaults to ${_.directory}. Use this instead of 'cd' commands.`).optional(),description:F.string().describe(n)}),async execute(o,s){let r=o.workdir||_.directory;if(o.timeout!==void 0&&o.timeout<0)throw new Error(`Invalid timeout value: ${o.timeout}. Timeout must be a positive number.`);let i=o.timeout??wS,c;try{c=yS(o.command);}catch(h){Nc.warn("Failed to parse command, requesting full bash permission",{command:o.command,error:h instanceof Error?h.message:String(h)}),await s.ask({permission:"bash",patterns:[o.command],always:[],metadata:{unparseable:true,reason:"Command syntax too complex to analyze"}}),c=null;}if(c){let h=new Set;_.containsPath(r)||h.add(r);let S=new Set,A=new Set,y=xS(c);for(let{command:x,args:b,fullText:w}of y){if(["cd","rm","cp","mv","mkdir","touch","chmod","chown","cat"].includes(x))for(let C of b){if(C.startsWith("-")||x==="chmod"&&C.startsWith("+"))continue;let k=await realpath(Ce__default.resolve(r,C)).catch(()=>null);if(Nc.debug("resolved path",{arg:C,resolved:k}),k){let P=process.platform==="win32"&&k.match(/^\/[a-z]\//)?k.replace(/^\/([a-z])\//,(E,O)=>`${O.toUpperCase()}:\\`).replace(/\//g,"\\"):k;if(!_.containsPath(P)){let E=await Filesystem.isDir(P)?P:Filesystem.dirname(P);h.add(E);}}}x&&x!=="cd"&&(S.add(w),A.add(`${x} *`));}if(h.size>0){let x=Array.from(h).map(b=>Filesystem.join(b,"*"));await s.ask({permission:"external_directory",patterns:x,always:x,metadata:{}});}S.size>0&&await s.ask({permission:"bash",patterns:Array.from(S),always:Array.from(A),metadata:{}});}Nc.debug("Executing bash command",{command:o.command,cwd:r,shell:e});let d=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:r})).output?.env??{},m=Shell.spawn(e,o.command,{cwd:r,env:{...process.env,...d},stdin:"null",stdout:"pipe",stderr:"pipe",signal:s.abort}),f="";s.metadata({metadata:{output:"",description:o.description}});let a=h=>{f+=h.toString("utf-8"),s.metadata({metadata:{output:f.length>Fc?f.slice(0,Fc)+`
590
+
591
+ ...`:f,description:o.description}});};m.stdout.on("data",a),m.stderr.on("data",a);let p=false,u=false,g=setTimeout(()=>{p=true,m.kill();},i+100);try{let h=await m.exited;clearTimeout(g),m.stdout.destroy(),m.stderr.destroy(),s.abort.aborted&&(u=!0);let S=[];return p&&S.push(`bash tool terminated command after exceeding timeout ${i} ms`),u&&S.push("User aborted the command"),S.length>0&&(f+=`
592
+
593
+ <bash_metadata>
594
+ `+S.join(`
595
+ `)+`
596
+ </bash_metadata>`),{title:o.description,metadata:{output:f.length>Fc?f.slice(0,Fc)+`
597
+
598
+ ...`:f,exit:h,description:o.description},output:f}}catch(h){throw clearTimeout(g),h}}}});var Uc;(r=>{let e=new Set(["node_modules","bower_components",".pnpm-store","vendor",".npm","dist","build","out",".next","target","bin","obj",".git",".svn",".hg",".vscode",".idea",".turbo",".output","desktop",".sst",".cache",".webkit-cache","__pycache__",".pytest_cache","mypy_cache",".history",".gradle"]),t=["**/*.swp","**/*.swo","**/*.pyc","**/.DS_Store","**/Thumbs.db","**/logs/**","**/tmp/**","**/temp/**","**/*.log","**/coverage/**","**/.nyc_output/**"],n=t.map(i=>new PKG.Glob(i));r.PATTERNS=[...t,...e];function s(i,c){for(let m of c?.whitelist||[])if(m.match(i))return false;let l=i.split(sep);for(let m=0;m<l.length;m++){let f=l[m];if(f&&e.has(f))return true}let d=c?.extra||[];for(let m of [...n,...d])if(m.match(i))return true;return false}r.match=s;})(Uc||(Uc={}));createRequire(import.meta.url);var zf=1e4,Nn;(f=>{let e=a.create({service:"file.watcher"});f.Event={Updated:a$5.define("file.watcher.updated",F.object({file:F.string(),event:F.union([F.literal("add"),F.literal("change"),F.literal("unlink")])}))};function n(){let a=process.platform==="linux"?`-${EASBOT_LIBC||"glibc"}`:"";return `@parcel/watcher-${process.platform}-${process.arch}${a}`}async function o(a){try{let p=process.env.EASBOT_CACHE_PATH||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=n(),p=await o(a),u;if(p){let A=process.env.EASBOT_CACHE_PATH||Ce__default.join(".easbot","cache");u=Ce__default.join(A,"node_modules",a);}else {let A="latest";e.info("Parcel watcher binding not found, attempting to install",{binding:a}),u=await s(a,A);}e.info("Loading Parcel watcher binding",{binding:a,modulePath:u});let{createWrapper:g}=await import('@parcel/watcher/wrapper.js'),S=createRequire(Ce__default.join(u,"package.json"))(a);return g(S)}catch(a){e.error("failed to load watcher binding",{error:a});return}});async function i(){if(_.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 g=_.directory,h=(b,w)=>{_.provide({directory:g,init:void 0,fn:()=>pe.publish(f.Event.Updated,{file:b,event:w})});},S=(b,w)=>{if(!b)for(let C of w){let k=C;k.type==="create"&&h(k.path,"add"),k.type==="update"&&h(k.path,"change"),k.type==="delete"&&h(k.path,"unlink");}},A=[],y=a.watcher?.ignore??[];if(a$2.EASBOT_FILEWATCHER){let b=u.subscribe(_.directory,S,{ignore:[...Uc.PATTERNS,...y],backend:p}),w=await withTimeout(b,zf).catch(C=>{e.error("failed to subscribe to Instance.directory",{error:C}),b.then(k=>k.unsubscribe()).catch(()=>{});});w&&A.push(w);}let x=await $`git rev-parse --git-dir`.quiet().nothrow().cwd(_.worktree).text().then(b=>Filesystem.resolve(Filesystem.join(_.worktree,b.trim()))).catch(()=>{});if(x&&!y.includes(".git")&&!y.includes(x)){let w=(await readdir(x).catch(()=>[])).filter(P=>P!=="HEAD"),C=u.subscribe(x,S,{ignore:w,backend:p}),k=await withTimeout(C,zf).catch(P=>{e.error("failed to subscribe to vcsDir",{error:P}),C.then(E=>E.unsubscribe()).catch(()=>{});});k&&A.push(k);}return {subs:A}}let c;function l(){return c||(c=_.state(i,async a=>{a.subs&&await Promise.all(a.subs.map(p=>p?.unsubscribe()));})),c}async function d(){return l()()}async function m(){a$2.EASBOT_FILEWATCHER&&d();}f.init=m;})(Nn||(Nn={}));var Or=class e extends Error{constructor(n,o,s){let r=o||`Operation '${n}' was aborted`;super(r);b$1(this,"name","AbortError");b$1(this,"operation");b$1(this,"cause");this.operation=n,this.cause=s,Object.setPrototypeOf(this,e.prototype);}static isAbortError(n){return n instanceof e}};var Rt;(o=>{function e(s,r){if(s?.aborted)throw new Or(r,`Operation '${r}' was aborted`)}o.check=e;function t(s,r){let i=new AbortController,{signal:c}=i,l=setTimeout(()=>{i.abort(new Error(`Operation timed out after ${s}ms`));},s);if(r){let d=()=>{clearTimeout(l),i.abort(r.reason);};r.aborted?(clearTimeout(l),i.abort(r.reason)):(r.addEventListener("abort",d,{once:true}),c.addEventListener("abort",()=>{clearTimeout(l),r.removeEventListener("abort",d);},{once:true}));}else c.addEventListener("abort",()=>clearTimeout(l),{once:true});return {signal:c,controller:i}}o.withTimeout=t;async function n(s,r,i){if(e(r,s),!r)return await i(void 0);let c=new Promise((l,d)=>{if(r.aborted)d(new Or(s,`Operation '${s}' was aborted`,r.reason));else {let m=()=>{d(new Or(s,`Operation '${s}' was aborted`,r.reason));};r.addEventListener("abort",m,{once:true});}});return await Promise.race([i(r),c])}o.wrap=n;})(Rt||(Rt={}));var RS=loadTextFile("./edit.txt",import.meta.url),_S=RS(),wu=20;function zc(e){return e.replaceAll(`\r
599
+ `,`
600
+ `)}var qc=De.define("edit",{description:_S,parameters:F.object({filePath:F.string().describe("The absolute path to the file to modify"),oldString:F.string().describe("The text to replace"),newString:F.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:F.boolean().optional().describe("Replace all occurrences of oldString (default false)")}),async execute(e,t){if(Rt.check(t.abort,"edit"),!e.filePath)throw new Error("filePath is required");if(e.oldString===e.newString)throw new Error("No changes to apply: oldString and newString are identical.");let n=Filesystem.normalize(Ce.isAbsolute(e.filePath)?e.filePath:Filesystem.join(_.directory,e.filePath));await Yt(t,n,{tool:"edit"});let o="",s="",r="";await An.withLock(n,async()=>{if(e.oldString===""){let m=await PKG.file(n).exists();r=e.newString,o=$o(createTwoFilesPatch(n,n,s,r)),await t.ask({permission:"edit",patterns:[Ce.posix.relative(_.worktree,n)],always:["*"],metadata:{filepath:n,diff:o}}),Rt.check(t.abort,"edit"),await PKG.write(n,e.newString),await pe.publish(bt.Event.Edited,{file:n}),await pe.publish(Nn.Event.Updated,{file:n,event:m?"change":"add"}),An.read(t.sessionId,n);return}let d=await Tt.stat(n).catch(()=>null);if(!d)throw new Error(`File ${n} not found`);if(d.isDirectory())throw new Error(`Path is a directory, not a file: ${n}`);await An.assert(t.sessionId,n),s=await Tt.readFile(n,"utf-8"),r=qS(s,e.oldString,e.newString,e.replaceAll),o=$o(createTwoFilesPatch(n,n,zc(s),zc(r))),await t.ask({permission:"edit",patterns:[Ce.posix.relative(_.worktree,n)],always:["*"],metadata:{filepath:n,diff:o}}),Rt.check(t.abort,"edit"),await Tt.writeFile(n,r),await pe.publish(bt.Event.Edited,{file:n}),await pe.publish(Nn.Event.Updated,{file:n,event:"change"}),r=await Tt.readFile(n,"utf-8"),o=$o(createTwoFilesPatch(n,n,zc(s),zc(r))),An.read(t.sessionId,n);});let i={file:n,before:s,after:r,additions:0,deletions:0};for(let d of diffLines(s,r))d.added&&(i.additions+=d.count||0),d.removed&&(i.deletions+=d.count||0);t.metadata({metadata:{diff:o,filediff:i,diagnostics:{}}});let c="Edit applied successfully.";Rt.check(t.abort,"edit");let l=[];if(await We.isAvailable(t.sessionId)){await We.touchFile(n,true);let d=await We.getFileDiagnostics(n);l.push(...d);let m=d.filter(f=>f.severity===1);if(m.length>0){let f=m.slice(0,wu),a=m.length>wu?`
601
+ ... and ${m.length-wu} more`:"",p=f.map(u=>We.Diagnostic.pretty(u));c+=`
602
+
603
+ LSP errors detected in this file, please fix:
604
+ <diagnostics file="${n}">
605
+ ${p.join(`
606
+ `)}${a}
607
+ </diagnostics>`;}}return {metadata:{filepath:n,diagnostics:{[Filesystem.normalize(n)]:l},diff:o,filediff:i},title:`${Ce.posix.relative(_.worktree,n)}`,output:c}}}),Bf=0,MS=.3;function Gf(e,t){if(e===""||t==="")return Math.max(e.length,t.length);let n=Array.from({length:e.length+1},(o,s)=>Array.from({length:t.length+1},(r,i)=>s===0?i:i===0?s:0));for(let o=1;o<=e.length;o++)for(let s=1;s<=t.length;s++){let r=e[o-1]===t[s-1]?0:1,i=n[o],c=n[o-1];i[s]=Math.min((c[s]??0)+1,(i[s-1]??0)+1,(c[s-1]??0)+r);}return n[e.length]?.[t.length]??0}var OS=function*(e,t){yield t;},jS=function*(e,t){let n=e.split(`
608
+ `),o=t.split(`
609
+ `);o[o.length-1]===""&&o.pop();for(let s=0;s<=n.length-o.length;s++){let r=true;for(let i=0;i<o.length;i++){let c=n[s+i],l=o[i];if(c===void 0||l===void 0){r=false;break}let d=c.trim(),m=l.trim();if(d!==m){r=false;break}}if(r){let i=0;for(let l=0;l<s;l++){let d=n[l];d!==void 0&&(i+=d.length+1);}let c=i;for(let l=0;l<o.length;l++){let d=n[s+l];d!==void 0&&(c+=d.length,l<o.length-1&&(c+=1));}yield e.substring(i,c);}}},LS=function*(e,t){let n=e.split(`
610
+ `),o=t.split(`
611
+ `);if(o.length<3)return;o[o.length-1]===""&&o.pop();let s=o[0]?.trim()??"",r=o[o.length-1]?.trim()??"",i=o.length,c=[];for(let m=0;m<n.length;m++){let f=n[m];if(f!==void 0&&f.trim()===s)for(let a=m+2;a<n.length;a++){let p=n[a];if(p!==void 0&&p.trim()===r){c.push({startLine:m,endLine:a});break}}}if(c.length===0)return;if(c.length===1&&c[0]){let{startLine:m,endLine:f}=c[0],a=f-m+1,p=0,u=Math.min(i-2,a-2);if(u>0)for(let g=1;g<i-1&&g<a-1;g++){let h=n[m+g],S=o[g];if(!h||!S)continue;let A=h.trim(),y=S.trim(),x=Math.max(A.length,y.length);if(x===0)continue;let b=Gf(A,y);if(p+=(1-b/x)/u,p>=Bf)break}else p=1;if(p>=Bf){let g=0;for(let S=0;S<m;S++){let A=n[S];A!==void 0&&(g+=A.length+1);}let h=g;for(let S=m;S<=f;S++){let A=n[S];A!==void 0&&(h+=A.length,S<f&&(h+=1));}yield e.substring(g,h);}return}let l=null,d=-1;for(let m of c){let{startLine:f,endLine:a}=m,p=a-f+1,u=0,g=Math.min(i-2,p-2);if(g>0){for(let h=1;h<i-1&&h<p-1;h++){let S=n[f+h],A=o[h];if(!S||!A)continue;let y=S.trim(),x=A.trim(),b=Math.max(y.length,x.length);if(b===0)continue;let w=Gf(y,x);u+=1-w/b;}u/=g;}else u=1;u>d&&(d=u,l=m);}if(d>=MS&&l){let{startLine:m,endLine:f}=l,a=0;for(let u=0;u<m;u++){let g=n[u];g&&(a+=g.length+1);}let p=a;for(let u=m;u<=f;u++){let g=n[u];g&&(p+=g.length,u<f&&(p+=1));}yield e.substring(a,p);}},DS=function*(e,t){let n=i=>i.replace(/\s+/g," ").trim(),o=n(t),s=e.split(`
612
+ `);for(let i=0;i<s.length;i++){let c=s[i];if(n(c)===o)yield c;else if(n(c).includes(o)){let d=t.trim().split(/\s+/);if(d.length>0&&d[0]){let m=d.map(f=>f.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("\\s+");try{let f=new RegExp(m),a=c.match(f);a?.[0]&&(yield a[0]);}catch{}}}}let r=t.split(`
613
+ `);if(r.length>1)for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length);n(c.join(`
614
+ `))===o&&(yield c.join(`
615
+ `));}},$S=function*(e,t){let n=i=>{let c=i.split(`
616
+ `),l=c.filter(m=>m.trim().length>0);if(l.length===0)return i;let d=Math.min(...l.map(m=>m.match(/^(\s*)/)?.[1]?.length??0));return c.map(m=>m.trim().length===0?m:m.slice(d)).join(`
617
+ `)},o=n(t),s=e.split(`
618
+ `),r=t.split(`
619
+ `);for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length).join(`
620
+ `);n(c)===o&&(yield c);}},FS=function*(e,t){let n=i=>i.replace(/\\(n|t|r|'|"|`|\\|\n|\$)/g,(c,l)=>{switch(l){case "n":return `
621
+ `;case "t":return " ";case "r":return "\r";case "'":return "'";case '"':return '"';case "`":return "`";case "\\":return "\\";case `
622
+ `:return `
623
+ `;case "$":return "$";default:return c}}),o=n(t);e.includes(o)&&(yield o);let s=e.split(`
624
+ `),r=o.split(`
625
+ `);for(let i=0;i<=s.length-r.length;i++){let c=s.slice(i,i+r.length).join(`
626
+ `);n(c)===o&&(yield c);}},NS=function*(e,t){let n=0;for(;;){let o=e.indexOf(t,n);if(o===-1)break;yield t,n=o+t.length;}},US=function*(e,t){let n=t.trim();if(n===t)return;e.includes(n)&&(yield n);let o=e.split(`
627
+ `),s=t.split(`
628
+ `);for(let r=0;r<=o.length-s.length;r++){let i=o.slice(r,r+s.length).join(`
629
+ `);i.trim()===n&&(yield i);}},zS=function*(e,t){let n=t.split(`
630
+ `);if(n.length<3)return;n[n.length-1]===""&&n.pop();let o=e.split(`
631
+ `),s=n[0]?.trim(),r=n[n.length-1]?.trim();if(!(!s||!r))for(let i=0;i<o.length;i++){let c=o[i];if(!(!c||c.trim()!==s))for(let l=i+2;l<o.length;l++){let d=o[l];if(!d||d.trim()!==r)continue;let m=o.slice(i,l+1),f=m.join(`
632
+ `);if(m.length===n.length){let a=0,p=0;for(let u=1;u<m.length-1;u++){let g=m[u],h=n[u];if(!g||!h)continue;let S=g.trim(),A=h.trim();(S.length>0||A.length>0)&&(p++,S===A&&a++);}if(p===0||a/p>=.5){yield f;break}}break}}};function $o(e){let t=e.split(`
633
+ `),n=t.filter(r=>(r.startsWith("+")||r.startsWith("-")||r.startsWith(" "))&&!r.startsWith("---")&&!r.startsWith("+++"));if(n.length===0)return e;let o=1/0;for(let r of n){let i=r.slice(1);if(i.trim().length>0){let c=i.match(/^(\s*)/);c?.[1]&&(o=Math.min(o,c[1].length));}}return o===1/0||o===0?e:t.map(r=>{let i=r[0];if(!i)return r;if((r.startsWith("+")||r.startsWith("-")||r.startsWith(" "))&&!r.startsWith("---")&&!r.startsWith("+++")){let c=r.slice(1);return i+c.slice(o)}return r}).join(`
634
+ `)}function qS(e,t,n,o=false){if(t===n)throw new Error("No changes to apply: oldString and newString are identical.");let s=true;for(let r of [OS,jS,LS,DS,$S,FS,US,zS,NS])for(let i of r(e,t)){let c=e.indexOf(i);if(c===-1)continue;if(s=false,o)return e.replaceAll(i,n);let l=e.lastIndexOf(i);if(c===l)return e.substring(0,c)+n+e.substring(c+i.length)}throw s?new Error("Could not find oldString in the file. It must match exactly, including whitespace, indentation, and line endings."):new Error("Found multiple matches for oldString. Provide more surrounding context to make the match unique.")}var GS=loadTextFile("./glob.txt",import.meta.url),WS=GS(),Vf=De.define("glob",{description:WS,parameters:F.object({pattern:F.string().describe("The glob pattern to match files against"),path:F.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:F.number().optional().default(100).describe("Maximum number of results to return (default: 100)")}),async execute(e,t){await t.ask({permission:"glob",patterns:[e.pattern],always:["*"],metadata:{pattern:e.pattern,path:e.path}});let n=e.path??_.directory;n=Filesystem.normalize(Ce__default.isAbsolute(n)?n:Ce__default.resolve(_.directory,n)),await Yt(t,n,{kind:"directory",tool:"glob"});let o=e.limit??100,s=[],r=false;for await(let c of a$8.files({cwd:n,glob:[e.pattern],signal:t.abort})){if(s.length>=o){r=true;break}let l=Filesystem.join(n,c),d=await PKG.file(l).stat().then(m=>m.mtime.getTime()).catch(()=>0);s.push({path:l,mtime:d});}s.sort((c,l)=>l.mtime-c.mtime);let i=[];return s.length===0&&i.push("No files found"),s.length>0&&(i.push(...s.map(c=>c.path)),r&&(i.push(""),i.push(`[${o} results limit reached. Use limit=${o*2} for more, or refine pattern]`))),{title:Ce__default.posix.relative(_.worktree,n),metadata:{pattern:e.pattern,path:n,count:s.length,truncated:r,resultLimitReached:r?o:void 0},output:i.join(`
635
+ `)}}});var YS=loadTextFile("./grep.txt",import.meta.url),XS=YS(),Yf=2e3,Qf=De.define("grep",{description:XS,parameters:F.object({pattern:F.string().describe("The regex pattern to search for in file contents"),path:F.string().optional().describe("The directory to search in. Defaults to the current working directory."),include:F.string().optional().describe('File pattern to include in the search (e.g. "*.js", "*.{ts,tsx}")')}),async execute(e,t){if(!e.pattern)throw new Error("pattern is required");await t.ask({permission:"grep",patterns:[e.pattern],always:["*"],metadata:{pattern:e.pattern,path:e.path,include:e.include}});let n=e.path??_.directory;n=Filesystem.normalize(Ce__default.isAbsolute(n)?n:Ce__default.resolve(_.directory,n)),await Yt(t,n,{kind:"directory",tool:"grep"});let o=await a$8.filepath(),s=100,r=["--json","--line-number","--color=never","--hidden","--no-messages","--regexp",e.pattern];e.include&&r.push("--glob",e.include),r.push(n);let i=PKG.spawn([o,...r],{stdin:"null",stdout:"pipe",stderr:"pipe"}),c=createInterface({input:i.stdout}),l="",d=0,m=false,f=[];i.stderr?.on("data",S=>{l+=S.toString("utf-8");}),c.on("line",S=>{if(!S.trim()||d>=s)return;let A;try{A=JSON.parse(S);}catch{return}if(A.type==="match"){let y=Filesystem.toUnixPath(A.data?.path?.text),x=A.data?.line_number,b=A.data?.lines?.text;y&&typeof x=="number"&&b&&Tt.stat(y).then(w=>{d++,f.push({path:y,lineNum:x,lineText:b.replace(/\r?\n$/,""),modTime:w.mtime.getTime()}),d>=s&&(m=true,i.kill()||i.kill("SIGTERM"));}).catch(()=>{});}});let a=await i.exited;if(f.length===0){if(a!==0&&a!==1&&a!==2){let S=l.trim()||`ripgrep exited with code ${a}`;throw new Error(S)}return {title:e.pattern,metadata:{matches:0,truncated:false},output:"No files found"}}f.sort((S,A)=>A.modTime-S.modTime);let p=m,u=[`Found ${f.length} matches`],g="";for(let S of f){g!==S.path&&(g!==""&&u.push(""),g=S.path,u.push(`${S.path}:`));let A=S.lineText.length>Yf?S.lineText.substring(0,Yf)+"...":S.lineText;u.push(` Line ${S.lineNum}: ${A}`);}return p&&(u.push(""),u.push("(Results are truncated. Consider using a more specific path or pattern.)")),a===2&&(u.push(""),u.push("(Some paths were inaccessible and skipped)")),{title:e.pattern,metadata:{pattern:e.pattern,path:n,matches:f.length,truncated:p},output:u.join(`
636
+ `)}}});var ZS=loadTextFile("./batch.txt",import.meta.url),eC=ZS(),Iu=new Set(["batch"]),tC=new Set(["invalid","patch",...Iu]),Zf=De.define("batch",async()=>{let e=await he.get();return {isEnabled:async()=>e.experimental?.batch_tool===true,description:eC,parameters:F.object({tool_calls:F.array(F.object({tool:F.string().describe("The name of the tool to execute"),parameters:F.object({}).loose().describe("Parameters for the tool")})).min(1,"Provide at least one tool call").describe("Array of tool calls to execute in parallel")}),formatValidationError(t){return `Invalid parameters for tool 'batch':
637
+ ${t.issues.map(o=>` - ${o.path.length>0?o.path.join("."):"root"}: ${o.message}`).join(`
638
+ `)}
639
+
640
+ Expected payload format:
641
+ [{"tool": "tool_name", "parameters": {...}}, {...}]`},async execute(t,n){let{Session:o}=await import('./session-FQ5O5XZY.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-AA7CYXUC.mjs'),l=await c.tools({modelId:"",providerId:""}),d=new Map(l.map(h=>[h.id,h])),m=async h=>{let S=Date.now(),A=s.ascending("part");try{if(Iu.has(h.tool))throw new Error(`Tool '${h.tool}' is not allowed in batch. Disallowed tools: ${Array.from(Iu).join(", ")}`);let y=d.get(h.tool);if(!y){let C=Array.from(d.keys()).filter(k=>!tC.has(k));throw new Error(`Tool '${h.tool}' not in registry. External tools (MCP, environment) cannot be batched - call them directly. Available tools: ${C.join(", ")}`)}let x=y.parameters.parse(h.parameters);await o.updatePart({id:A,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:h.tool,callId:A,state:{status:"running",input:h.parameters,time:{start:S}}});let b=await y.execute(x,{...n,callId:A}),w;return b.attachments&&b.attachments.length>0&&(w=b.attachments.map(C=>({...C,id:C.id??s.ascending("part"),sessionId:C.sessionId??n.sessionId,messageId:C.messageId??n.messageId}))),await o.updatePart({id:A,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:h.tool,callId:A,state:{status:"completed",input:h.parameters,output:b.output,title:b.title,metadata:b.metadata,attachments:w,time:{start:S,end:Date.now()}}}),{success:!0,tool:h.tool,result:b}}catch(y){return await o.updatePart({id:A,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:h.tool,callId:A,state:{status:"error",input:h.parameters,error:y instanceof Error?y.message:String(y),time:{start:S,end:Date.now()}}}),{success:false,tool:h.tool,error:y}}},f=await Promise.all(r.map(h=>m(h))),a=Date.now();for(let h of i){let S=s.ascending("part");await o.updatePart({id:S,messageId:n.messageId,sessionId:n.sessionId,type:"tool",tool:h.tool,callId:S,state:{status:"error",input:h.parameters,error:"Maximum of 25 tools allowed in batch",time:{start:a,end:a}}}),f.push({success:false,tool:h.tool,error:new Error("Maximum of 25 tools allowed in batch")});}let p=f.filter(h=>h.success).length,u=f.length-p,g=u>0?`Executed ${p}/${f.length} tools successfully. ${u} failed.`:`All ${p} tools executed successfully.
642
+
643
+ Keep using the batch tool for optimal performance in your next response!`;return {title:`Batch execution (${p}/${f.length} successful)`,output:g,attachments:f.filter(h=>h.success).flatMap(h=>h.result.attachments??[]),metadata:{totalCalls:f.length,successful:p,failed:u,tools:t.tool_calls.map(h=>h.tool),details:f.map(h=>({tool:h.tool,success:h.success}))}}}}});var po;(s=>{s.Info=F.object({content:F.string().describe("Brief description of the task"),status:F.string().describe("Current status of the task: pending, in_progress, completed, cancelled"),priority:F.string().describe("Priority level of the task: high, medium, low"),id:F.string().describe("Unique identifier for the todo item")}).meta({ref:"Todo"}),s.Event={Updated:a$5.define("todo.updated",F.object({sessionId:F.string(),todos:F.array(s.Info)}))};async function n(r){await a$6.write(["todo",r.sessionId],r.todos),await pe.publish(s.Event.Updated,r);}s.update=n;async function o(r){return a$6.read(["todo",r]).then(i=>i||[]).catch(()=>[])}s.get=o;})(po||(po={}));var oC=loadTextFile("./todo.txt",import.meta.url),sC=oC(),eg={write:F.object({operation:F.literal("write").describe("Write or update TODO list"),todos:F.union([F.array(po.Info),F.string()]).describe("The updated todo list")}),read:F.object({operation:F.literal("read").describe("Read current TODO list")})},rC=F.discriminatedUnion("operation",[eg.write,eg.read]),tg=De.define("todo",{description:sC,parameters:rC,formatValidationError(e){return `Todo tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(Rt.check(t.abort,"todo"),e.operation==="write")return iC(e,t);if(e.operation==="read")return aC(e,t);throw new Error(`Unknown operation: ${e.operation}`)}});async function iC(e,t){await t.ask({permission:"todo",patterns:["*"],always:["*"],metadata:{}});let n=[];if(typeof e.todos=="string")try{n=JSON.parse(e.todos);}catch{throw new Error("Invalid todos format: expected JSON array or array")}else n=e.todos;await po.update({sessionId:t.sessionId,todos:n});let o=n.filter(s=>s.status!=="completed").length;return {title:`${o} todos`,output:JSON.stringify(n,null,2),metadata:{operation:"write",total:n.length,active:o,todos:n}}}async function aC(e,t){await t.ask({permission:"todo",patterns:["*"],always:["*"],metadata:{}});let n=await po.get(t.sessionId),o=n.filter(s=>s.status!=="completed").length;return {title:`${o} todos`,metadata:{operation:"read",total:n.length,active:o,todos:n},output:JSON.stringify(n,null,2)}}var pC=loadTextFile("./webfetch.txt",import.meta.url),mC=pC(),og=5*1024*1024,sg=2*1024*1024,fC=30*1e3,gC=120*1e3,rg=De.define("webfetch",{description:mC,parameters:F.object({url:F.string().describe("The URL to fetch content from"),format:F.enum(["text","markdown","html"]).default("markdown").describe("The format to return the content in (text, markdown, or html). Defaults to markdown."),timeout:F.number().describe("Optional timeout in seconds (max 120)").optional()}),formatValidationError(e){return `WebFetch tool validation error:
644
+ ${e.issues.map(n=>n.path.includes("format")?`Invalid format parameter: "${"received"in n?n.received:"unknown"}". Must be one of: "text", "markdown", or "html". Defaults to "markdown" if not specified.`:n.path.includes("url")?`Invalid URL: ${n.message}. URL must start with http:// or https://.`:n.path.includes("timeout")?`Invalid timeout: ${n.message}. Timeout must be a number (max 120 seconds).`:n.message).join(`
645
+ `)}`},async execute(e,t){if(!e.url.startsWith("http://")&&!e.url.startsWith("https://"))throw new Error("URL must start with http:// or https://");await t.ask({permission:"webfetch",patterns:[e.url],always:["*"],metadata:{url:e.url,format:e.format,timeout:e.timeout}});let n=Math.min((e.timeout??fC/1e3)*1e3,gC),{signal:o,clearTimeout:s}=abortAfterAny(n,t.abort),r="*/*";switch(e.format){case "markdown":r="text/markdown;q=1.0, text/x-markdown;q=0.9, text/plain;q=0.8, text/html;q=0.7, */*;q=0.1";break;case "text":r="text/plain;q=1.0, text/markdown;q=0.9, text/html;q=0.8, */*;q=0.1";break;case "html":r="text/html;q=1.0, application/xhtml+xml;q=0.9, text/plain;q=0.8, text/markdown;q=0.7, */*;q=0.1";break;default:r="text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8";}let i={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36",Accept:r,"Accept-Language":"en-US,en;q=0.9"},c;try{let S=await Fetch.get(e.url,{signal:o,headers:i,responseType:"arrayBuffer"});c={ok:S.ok,status:S.status,statusText:S.statusText,headers:S.headers,arrayBuffer:async()=>Promise.resolve(S.data)};}catch(S){if(s(),S instanceof Error){if(S.name==="AbortError")throw new Error(`Request timed out after ${n/1e3} seconds. Try increasing the timeout parameter.`);if(S.message.includes("fetch failed"))throw new Error(`Failed to fetch URL: ${e.url}. The server may be unreachable or blocking requests. Original error: ${S.message}`)}throw S}let l=c.status===403&&c.headers.get("cf-mitigated")==="challenge"?await(async()=>{let S=await Fetch.get(e.url,{signal:o,headers:{...i,"User-Agent":"easbot"},responseType:"arrayBuffer"});return {ok:S.ok,status:S.status,statusText:S.statusText,headers:S.headers,arrayBuffer:async()=>Promise.resolve(S.data)}})():c;if(s(),!l.ok){let S=l.statusText||"Unknown error";throw new Error(`Request failed with status ${l.status} (${S}). The server may be blocking requests or the URL may be incorrect.`)}let d=l.headers.get("content-length");if(d&&parseInt(d,10)>og)throw new Error("Response too large (exceeds 5MB limit)");let m=await l.arrayBuffer();if(m.byteLength>og)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>sg)return {title:p,output:`Image fetched successfully but too large to display (${(m.byteLength/1024/1024).toFixed(2)}MB, max ${sg/1024/1024}MB). Image URL: ${e.url}`,metadata:{size:m.byteLength,mime:a,url:e.url}};try{let S=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,${S}`}]}}catch(S){return {title:p,output:`Image fetched but failed to convert to base64: ${S instanceof Error?S.message:"Unknown error"}. Image URL: ${e.url}`,metadata:{size:m.byteLength,mime:a,url:e.url}}}}let g=new TextDecoder().decode(m),h=m.byteLength;switch(e.format){case "markdown":return f.includes("text/html")?{output:yC(g),title:p,metadata:{size:h,mime:a,url:e.url}}:{output:g,title:p,metadata:{size:h,mime:a,url:e.url}};case "text":return f.includes("text/html")?{output:await hC(g),title:p,metadata:{size:h,mime:a,url:e.url}}:{output:g,title:p,metadata:{size:h,mime:a,url:e.url}};case "html":return {output:g,title:p,metadata:{size:h,mime:a,url:e.url}};default:return {output:g,title:p,metadata:{size:h,mime:a,url:e.url}}}}});async function hC(e){try{let t=parse(e),n=["script","style","noscript","iframe","object","embed","svg","head"];for(let r of n){let i=t.querySelectorAll(r);for(let c of i)c.remove();}let o=t.querySelector("body"),s=o?o.textContent||o.text||"":t.textContent||t.text||"";return s=s.replace(/<[^>]+>/g," "),s=s.replace(/\s+/g," ").trim(),s}catch{let n=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<style\b[^<]*(?:(?!<\/style>)<[^<]*)*<\/style>/gi,"").replace(/<noscript\b[^<]*(?:(?!<\/noscript>)<[^<]*)*<\/noscript>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/<object\b[^<]*(?:(?!<\/object>)<[^<]*)*<\/object>/gi,"").replace(/<embed\b[^<]*(?:(?!<\/embed>)<[^<]*)*<\/embed>/gi,"");return n=n.replace(/<[^>]+>/g," "),n=n.replace(/\s+/g," ").trim(),n}}function yC(e){let t=new lC({headingStyle:"atx",hr:"---",bulletListMarker:"-",codeBlockStyle:"fenced",emDelimiter:"*"});return t.remove(["script","style","meta","link"]),t.turndown(e)}var xC=loadTextFile("./write.txt",import.meta.url),IC=xC(),Cu=20;var ag=De.define("write",{description:IC,parameters:F.object({content:F.string().describe("The content to write to the file"),filePath:F.string().describe("The absolute path to the file to write (must be absolute, not relative)")}),async execute(e,t){Rt.check(t.abort,"write");let n=Filesystem.normalize(Ce.isAbsolute(e.filePath)?e.filePath:Filesystem.join(_.directory,e.filePath));await Yt(t,n,{tool:"write"});let o=PKG.file(n),s=await o.exists(),r=s?await o.text():"";s&&await An.assert(t.sessionId,n);let i=$o(createTwoFilesPatch(n,n,r,e.content));await t.ask({permission:"edit",patterns:[Ce.posix.relative(_.worktree,n)],always:["*"],metadata:{filepath:n,diff:i}}),Rt.check(t.abort,"write"),await PKG.write(n,e.content),await pe.publish(bt.Event.Edited,{file:n}),await pe.publish(Nn.Event.Updated,{file:n,event:s?"change":"add"}),An.read(t.sessionId,n);let c="Wrote file successfully.";Rt.check(t.abort,"write");let l=[];if(await We.isAvailable(t.sessionId)){await We.touchFile(n,true);let d=await We.getFileDiagnostics(n);l.push(...d);let m=d.filter(f=>f.severity===1);if(m.length>0){let f=m.slice(0,Cu),a=m.length>Cu?`
646
+ ... and ${m.length-Cu} more`:"",p=f.map(u=>We.Diagnostic.pretty(u));c+=`
647
+
648
+ LSP errors detected in this file, please fix:
649
+ <diagnostics file="${n}">
650
+ ${p.join(`
651
+ `)}${a}
652
+ </diagnostics>`;}}return {title:Ce.posix.relative(_.worktree,n),metadata:{diagnostics:{[Filesystem.normalize(n)]:l},filepath:n,exists:s},output:c}}});var cg=De.define("invalid",{description:"Do not use",parameters:F.object({tool:F.string(),error:F.string()}),async execute(e){return {title:"Invalid Tool",output:`The arguments provided to the tool are invalid: ${e.error}`,metadata:{}}}});var ug=De.define("skill",async()=>{let e=["Load a specialized skill that provides domain-specific instructions and workflows.","","When you recognize that a task matches one of the available skills, use this tool to load the full skill instructions.","","The skill will inject detailed instructions, workflows, and access to bundled resources (scripts, references, templates) into the conversation context.","",'Tool output includes a `<skill_content name="...">` block with the loaded content.'].join(`
653
+ `),t=F.object({name:F.string().describe("The name of the skill to load")});return {description:e,parameters:t,async execute(n,o){let s=await X.getContextMode(o.sessionId),r=await Ue.get(o.agent),i=await Jt.available(r,s),c=await Jt.get(n.name);if(!c){let p=i.length>0?i.map(u=>u.name).join(", "):"none";throw new Error(`Skill "${n.name}" not found. Available skills: ${p}`)}if(!i.some(p=>p.name===n.name)){let p=i.length>0?i.map(u=>u.name).join(", "):"none";throw new Error(`Skill "${n.name}" is not available. Available skills: ${p}`)}await o.ask({permission:"skill",patterns:[n.name],always:[n.name],metadata:{}});let d=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:o.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(`
654
+ `));return {title:`Loaded skill: ${c.name}`,output:[`<skill_content name="${c.name}">`,`# Skill: ${c.name}`,"",c.content.trim(),"",`Base directory for this skill: ${m}`,"Relative paths in this skill (e.g., scripts/, references/) are relative to this base directory.","If you need to load references or scripts files, use the Read tool with paths relative to this base directory.","Note: file list is sampled.","","<skill_files>",a,"</skill_files>","</skill_content>"].join(`
655
+ `),metadata:{name:c.name,dir:d}}}}});var st;(k=>{let e=a.create({service:"pty"}),t=1024*1024*2,n=64*1024,o=new TextEncoder,s=P=>{let E=JSON.stringify({cursor:P}),O=o.encode(E),N=new Uint8Array(O.length+1);return N[0]=0,N.set(O,1),N},r=lazy(async()=>CC);k.Info=F.object({id:Identifier.schema("pty"),title:F.string(),command:F.string(),args:F.array(F.string()),cwd:F.string(),status:F.enum(["running","exited"]),pid:F.number()}).meta({ref:"Pty"}),k.CreateInput=F.object({command:F.string().optional(),args:F.array(F.string()).optional(),cwd:F.string().optional(),title:F.string().optional(),env:F.record(F.string(),F.string()).optional(),persistent:F.boolean().optional().default(true)}),k.UpdateInput=F.object({title:F.string().optional(),size:F.object({rows:F.number(),cols:F.number()}).optional()}),k.Event={Created:a$5.define("pty.created",F.object({info:k.Info})),Updated:a$5.define("pty.updated",F.object({info:k.Info})),Exited:a$5.define("pty.exited",F.object({id:Identifier.schema("pty"),exitCode:F.number()})),Deleted:a$5.define("pty.deleted",F.object({id:Identifier.schema("pty")}))};let m;function f(){return m||(m=_.state(()=>new Map,async P=>{for(let E of P.values()){try{E.process.kill();}catch{}for(let O of E.subscribers)O.close();}P.clear();})),m}function a$1(){return f()()}let p=new Map;async function u(){let P=a$1();return Array.from(P.values()).map(E=>E.info)}k.list=u;async function g(P){return a$1().get(P)?.info}k.get=g;async function h(P){let E=Identifier.create("pty",false),O=P.persistent??true,N=process.platform==="win32"?"cmd":Shell.acceptable(),L=P.command||N,K=P.args||[],Q=P.cwd||_.directory,D=(await Le.triggerEvent(HookEvent.ShellEnv,{cwd:Q})).output?.env??{},I={...process.env,...P.env,...D,TERM:"xterm-256color",EASBOT_TERMINAL:"1"};process.platform==="win32"&&(I.LANG="en_US.UTF-8",I.LC_ALL="en_US.UTF-8",I.LC_CTYPE="en_US.UTF-8");let M=L;if(process.platform==="win32"){let{PKG:se}=await import('@easbot/utils'),ae=await se.which(M);if(ae)e.debug("resolved command path",{original:M,resolved:ae});else {e.warn("command not found in PATH, trying PKG.which() fallback",{command:M});let we=M?.toLowerCase(),ie=null;if(we==="cmd.exe"||we==="cmd"?ie="cmd":we==="powershell.exe"||we==="powershell"?ie="powershell":we==="pwsh.exe"||we==="pwsh"?ie="pwsh":we==="wsl.exe"||we==="wsl"?ie="wsl":ie=Shell.acceptable(we)??"",ie){let Z=await se.which(ie);Z?(e.debug("found command via PKG.which()",{original:M,resolved:Z})):(e.warn("command not found, using original",{command:M}),M);}else e.warn("unknown command type, using original",{command:M});}}let T=L??"",R=[...K];T.endsWith("sh")&&R.push("-l"),e.debug("creating PTY session",{id:E,cmd:T,args:R,cwd:Q,platform:process.platform});let j=await r(),U;try{U=j.spawn(T,R,{name:"xterm-256color",cwd:Q,env:I}),e.debug("PTY process spawned successfully",{id:E,pid:U.pid});}catch(se){let ae=se instanceof Error?se.message:String(se);e.error("Failed to spawn PTY process",{command:T,args:R,cwd:Q,platform:process.platform,error:ae,stack:se instanceof Error?se.stack:void 0});let we="";throw ae.includes("ENOENT")||ae.includes("not found")?we=`
656
+
657
+ \u{1F4A1} Hint: The command "${T}" was not found. Please ensure:
658
+ - The command is installed and available in PATH
659
+ - On Windows, use full path like "cmd.exe" or "powershell.exe"
660
+ - On Unix, use full path like "/bin/bash" or "/usr/bin/ssh"`:ae.includes("permission")&&(we=`
661
+
662
+ \u{1F4A1} Hint: Permission denied. Please check file permissions.`),new Error(`Failed to create PTY session: ${ae}${we}`)}let Y={id:E,title:P.title||`Terminal ${E.slice(-4)}`,command:L,args:R,cwd:Q,status:"running",pid:U.pid},J={info:Y,process:U,buffer:"",bufferCursor:0,cursor:0,subscribers:new Set};return a$1().set(E,J),U.onData(se=>{J.cursor+=se.length;for(let we of J.subscribers){if(we.readyState!==1){J.subscribers.delete(we);continue}we.send(se);}if(J.buffer+=se,J.buffer.length<=t)return;let ae=J.buffer.length-t;J.buffer=J.buffer.slice(ae),J.bufferCursor+=ae;}),U.onExit(async({exitCode:se})=>{e.debug("session exited",{id:E,exitCode:se,persistent:O}),J.info.status="exited";for(let ae of J.subscribers)ae.close();J.subscribers.clear(),await pe.publish(k.Event.Exited,{id:E,exitCode:se}),O?e.debug("persistent session, keeping for reconnection",{id:E,exitCode:se}):(e.debug("non-persistent session, deleting",{id:E,exitCode:se}),p.set(E,se),a$1().delete(E));}),await pe.publish(k.Event.Created,{info:Y}),Y}k.create=h;async function S(P,E){let N=a$1().get(P);if(!N)throw new Error(`Session ${P} not found`);if(E.title&&(N.info.title=E.title),(E?.size?.cols??0)>0&&(E?.size?.rows??0)>0){if(N.info.status==="exited")throw new Error(`Session ${P} has exited (PID: ${N.info.pid}). Cannot resize. Use 'remove' to delete and create a new session.`);N.process.resize(E?.size?.cols??0,E?.size?.rows??0);}return await pe.publish(k.Event.Updated,{info:N.info}),N.info}k.update=S;async function A(P){let E=a$1(),O=E.get(P);if(!O)throw new Error(`Session ${P} not found`);e.debug("removing session",{id:P,pid:O.info.pid,status:O.info.status});try{O.process.kill();}catch{}for(let N of O.subscribers)N.close();E.delete(P),p.delete(P),await pe.publish(k.Event.Deleted,{id:P});}k.remove=A;async function y(P,E,O){let L=a$1().get(P);if(!L)throw new Error(`Session ${P} not found`);if(L.info.status==="exited")throw e.warn("cannot resize exited session",{id:P}),new Error(`Session ${P} has exited (PID: ${L.info.pid}). Use 'remove' to delete it and create a new session.`);L.process.resize(E,O);}k.resize=y;async function x(P,E){let N=a$1().get(P);if(!N)throw new Error(`Session ${P} not found`);if(N.info.status==="exited")throw e.warn("cannot write to exited session",{id:P}),new Error(`Session ${P} has exited (PID: ${N.info.pid}). Use 'remove' to delete it and create a new session.`);N.process.write(E);}k.write=x;async function b(P,E,O){let L=a$1().get(P);if(!L)return e.warn("cannot connect to non-existent session",{id:P}),E.close(),{onMessage:()=>{},onClose:()=>{}};e.debug("client connected to session",{id:P,status:L.info.status});let K=L.bufferCursor,Q=L.cursor,ue=O===-1?Q:typeof O=="number"&&Number.isSafeInteger(O)?Math.max(0,O):0,D=(()=>{if(!L.buffer||ue>=Q)return "";let I=Math.max(0,ue-K);return I>=L.buffer.length?"":L.buffer.slice(I)})();if(D)try{for(let I=0;I<D.length;I+=n)E.send(D.slice(I,I+n));}catch{E.close();return}try{E.send(s(Q));}catch{E.close();return}return L.subscribers.add(E),{onMessage:I=>{L.process.write(String(I));},onClose:()=>{e.debug("client disconnected from session",{id:P}),L.subscribers.delete(E);}}}k.connect=b;async function w(P){let O=a$1().get(P);if(O)return {buffer:O.buffer,cursor:O.cursor,bufferCursor:O.bufferCursor}}k.getBuffer=w;async function C(P,E){let N=a$1().get(P);if(!N){let Q=p.get(P);if(Q!==void 0)return e.debug("subscribing to exited session",{id:P,exitCode:Q}),E.onExit&&E.onExit(Q),()=>{};throw e.warn("session not found for subscription",{id:P}),new Error(`Session ${P} not found`)}let L={readyState:1,send:Q=>{typeof Q=="string"&&E.onData&&E.onData(Q);},close:()=>{}};N.subscribers.add(L);let K;return E.onExit&&(K=pe.subscribe(k.Event.Exited,Q=>{Q.properties.id===P&&E.onExit&&E.onExit(Q.properties.exitCode);})),()=>{N.subscribers.delete(L),K&&K();}}k.subscribe=C;})(st||(st={}));var PC=loadTextFile("./pty_session.txt",import.meta.url),TC=loadTextFile("./pty_manage.txt",import.meta.url),AC=PC(),EC=TC(),mg=a.create({service:"tool.pty"}),Lr={BUFFER_SIZE_LIMIT:8*1024,MAX_LINES:200,DEFAULT_COLS:120,DEFAULT_ROWS:30},RC=F.object({action:F.enum(["list","get","resize","write","close"]).describe("Management action to perform"),sessionId:F.string().optional().describe("Session ID for get/resize/write/close actions"),cols:F.number().optional().describe("New columns for resize action"),rows:F.number().optional().describe("New rows for resize action"),data:F.string().optional().describe("Data to write to session")}),gg=De.define("pty_manage",{description:EC,parameters:RC,async execute(e,t){if(await t.ask({permission:"pty_manage",patterns:[e.action],always:["*"],metadata:{action:e.action,sessionId:e.sessionId}}),t.abort.aborted)throw new Error("Operation aborted");switch(e.action){case "list":{let n=await st.list(),o=n.length===0?"No active PTY sessions":`Active PTY Sessions (${n.length}):
663
+ ${n.map(s=>`- ${s.id}: ${s.title} (PID: ${s.pid}, Status: ${s.status})`).join(`
664
+ `)}`;return {title:"PTY Sessions",metadata:{action:"list",sessionCount:n.length,sessions:n.map(s=>({id:s.id,title:s.title,command:s.command,pid:s.pid,status:s.status}))},output:o}}case "get":{if(!e.sessionId)throw new Error("sessionId is required for get action");let n=await st.get(e.sessionId);if(!n)return {title:"Session Not Found",metadata:{action:"get",found:false,sessionCount:0,sessions:[]},output:`No session found with ID: ${e.sessionId}`};let o=await st.getBuffer(e.sessionId),s=o?.buffer||"";return {title:`Session ${e.sessionId}`,metadata:{action:"get",found:true,sessionCount:1,sessions:[{id:n.id,title:n.title,command:n.command,pid:n.pid,status:n.status}],session:{id:n.id,title:n.title,command:n.command,cwd:n.cwd,pid:n.pid,status:n.status},bufferSize:s.length,cursor:o?.cursor,bufferCursor:o?.bufferCursor},output:`Session Details:
665
+ ID: ${n.id}
666
+ Title: ${n.title}
667
+ Command: ${n.command}
668
+ PID: ${n.pid}
669
+ Status: ${n.status}
670
+ CWD: ${n.cwd}
671
+
672
+ Output Buffer (${s.length} characters):
673
+ ${s||"(no output yet)"}`}}case "resize":{if(!e.sessionId||e.cols===void 0||e.rows===void 0)throw new Error("sessionId, cols, and rows are required for resize action");return await st.resize(e.sessionId,e.cols,e.rows),{title:"Session Resized",metadata:{action:"resize",sessionId:e.sessionId,cols:e.cols,rows:e.rows,sessionCount:1,sessions:[]},output:`Session ${e.sessionId} resized to ${e.cols}x${e.rows}`}}case "write":{if(!e.sessionId||e.data===void 0)throw new Error("sessionId and data are required for write action");let n=process.platform==="win32"?e.data.replace(/\n/g,`\r
674
+ `):e.data;return await st.write(e.sessionId,n),{title:"Data Written",metadata:{action:"write",sessionId:e.sessionId,dataLength:n.length,sessionCount:1,sessions:[]},output:`Wrote ${n.length} characters to session ${e.sessionId}`}}case "close":{if(!e.sessionId)throw new Error("sessionId is required for close action");return await st.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}`)}}}),hg=De.define("pty_session",{description:AC,parameters:F.object({command:F.string().describe("Initial command to run in session"),args:F.array(F.string()).optional().describe("Command arguments"),cwd:F.string().optional().describe("Working directory (defaults to project directory)"),env:F.record(F.string(),F.string()).optional().describe("Environment variables"),sessionName:F.string().optional().describe("Session name for identification"),cols:F.number().min(10).max(500).optional().default(Lr.DEFAULT_COLS).describe("Terminal columns (default: 120)"),rows:F.number().min(5).max(200).optional().default(Lr.DEFAULT_ROWS).describe("Terminal rows (default: 30)"),truncateMode:F.enum(["head","tail"]).optional().default("tail").describe("Truncation mode: head (keep beginning) or tail (keep end, default for PTY sessions)"),persistent:F.boolean().optional().default(true).describe("Keep session running after initial command completes (default: true, for SSH/long-running connections)")}),async execute(e,t){let n=e.command,o=e.args||[];await t.ask({permission:"pty_session",patterns:[e.command],always:[`${e.command} *`],metadata:{command:e.command,args:e.args,cwd:e.cwd||_.directory,sessionName:e.sessionName}});let s=e.cwd||_.directory,r=e.cols??Lr.DEFAULT_COLS,i=e.rows??Lr.DEFAULT_ROWS;try{if(t.abort.aborted)throw new Error("Operation aborted");let c=await st.create({command:n,args:o,cwd:s,env:e.env,title:e.sessionName||`Interactive Session: ${e.command}`,persistent:e.persistent??!0});return r&&i&&await st.resize(c.id,r,i),mg.debug("PTY session created successfully",{sessionId:c.id,command:c.command,pid:c.pid,status:c.status}),{title:`PTY Session Created: ${e.sessionName||e.command}`,metadata:{sessionId:c.id,sessionName:e.sessionName||c.title,command:c.command,pid:c.pid,status:c.status,truncateMode:e.truncateMode,persistent:e.persistent,websocketSupport:!0},output:`PTY session created successfully.
675
+
676
+ Session ID: ${c.id}
677
+ Session Name: ${e.sessionName||c.title}
678
+ Command: ${c.command}
679
+ PID: ${c.pid}
680
+ Status: ${c.status}
681
+ Output Limit: ${Lr.BUFFER_SIZE_LIMIT/1024}KB / ${Lr.MAX_LINES} lines
682
+ Truncate Mode: ${e.truncateMode||"tail"} (${e.truncateMode==="head"?"keeps beginning of output":"keeps latest output for interactive use"})
683
+
684
+ \u26A0\uFE0F IMPORTANT: This session will run in the background until explicitly closed.
685
+ Use pty_manage tool to interact with this session:
686
+ - Send input: pty_manage { "action": "write", "sessionId": "${c.id}", "data": "your command\\n" }
687
+ - Check status: pty_manage { "action": "get", "sessionId": "${c.id}" }
688
+ - Close session: pty_manage { "action": "close", "sessionId": "${c.id}" }
689
+
690
+ \u26A0\uFE0F RESOURCE WARNING: Remember to close unused sessions to prevent resource exhaustion!`}}catch(c){let l=c instanceof Error?c.message:String(c),d=c instanceof Error?c.stack:void 0;throw mg.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 jC=loadTextFile("./websearch.txt",import.meta.url),LC=jC(),Pu={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{SEARCH:"/mcp"},DEFAULT_NUM_RESULTS:8},yg=De.define("websearch",async()=>({get description(){return LC.replace("{{year}}",new Date().getFullYear().toString())},parameters:F.object({query:F.string().describe("Websearch query"),numResults:F.number().optional().describe("Number of search results to return (default: 8)"),livecrawl:F.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:F.enum(["auto","fast","deep"]).optional().describe("Search type - 'auto': balanced search (default), 'fast': quick results, 'deep': comprehensive search"),contextMaxCharacters:F.number().optional().describe("Maximum characters for context string optimized for LLMs (default: 10000)")}),async execute(e,t){await t.ask({permission:"websearch",patterns:[e.query],always:["*"],metadata:{query:e.query,numResults:e.numResults,livecrawl:e.livecrawl,type:e.type,contextMaxCharacters:e.contextMaxCharacters}});let n={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"web_search_exa",arguments:{query:e.query,type:e.type||"auto",numResults:e.numResults||Pu.DEFAULT_NUM_RESULTS,livecrawl:e.livecrawl||"fallback",contextMaxCharacters:e.contextMaxCharacters}}},{signal:o,clearTimeout:s}=abortAfterAny(25e3,t.abort);try{let r={accept:"application/json, text/event-stream","content-type":"application/json"},i=await Fetch.post(`${Pu.BASE_URL}${Pu.ENDPOINTS.SEARCH}`,n,{headers:r,responseType:"text",signal:o});if(s(),!i.ok)throw new Error(`Search error (${i.status}): ${i.data||"Unknown error"}`);let l=i.data.split(`
691
+ `);for(let d of l)if(d.startsWith("data: ")){let m=JSON.parse(d.substring(6));if(m.result?.content&&m.result.content.length>0){let f=m.result.content[0]?.text;if(f)return {output:f,title:`Web search: ${e.query}`,metadata:{query:e.query}}}}return {output:"No search results found. Please try a different query.",title:`Web search: ${e.query}`,metadata:{query:e.query}}}catch(r){throw s(),r instanceof Error&&r.name==="AbortError"?new Error("Search request timed out"):r}}}));var NC=loadTextFile("./codesearch.txt",import.meta.url),UC=NC(),bg={BASE_URL:"https://mcp.exa.ai",ENDPOINTS:{CONTEXT:"/mcp"}},wg=De.define("codesearch",{scope:g.Coder,description:UC,parameters:F.object({query:F.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:F.number().min(1e3).max(5e4).default(5e3).describe("Number of tokens to return (1000-50000). Default is 5000 tokens. Adjust this value based on how much context you need - use lower values for focused queries and higher values for comprehensive documentation.")}),async execute(e,t){await t.ask({permission:"codesearch",patterns:[e.query],always:["*"],metadata:{query:e.query,tokensNum:e.tokensNum}});let n={jsonrpc:"2.0",id:1,method:"tools/call",params:{name:"get_code_context_exa",arguments:{query:e.query,tokensNum:e.tokensNum||5e3}}},{signal:o,clearTimeout:s}=abortAfterAny(3e4,t.abort);try{let r={accept:"application/json, text/event-stream","content-type":"application/json"},i=await Fetch.post(`${bg.BASE_URL}${bg.ENDPOINTS.CONTEXT}`,n,{headers:r,responseType:"text",signal:o});if(s(),!i.ok)throw new Error(`Code search error (${i.status}): ${i.data||"Unknown error"}`);let l=i.data.split(`
692
+ `);for(let d of l)if(d.startsWith("data: ")){let m=JSON.parse(d.substring(6));if(m.result?.content&&m.result.content.length>0){let f=m.result.content[0]?.text;if(f)return {output:f,title:`Code search: ${e.query}`,metadata:{}}}}return {output:"No code snippets or documentation found. Please try a different query, be more specific about the library or programming concept, or check the spelling of framework names.",title:`Code search: ${e.query}`,metadata:{}}}catch(r){throw s(),r instanceof Error&&r.name==="AbortError"?new Error("Code search request timed out"):r}}});var Au=a.create({service:"tool.note"}),qC=loadTextFile("./note.txt",import.meta.url),HC=qC(),BC=10,GC=800,xg=30,Ig=1500,WC=10,VC=500,KC=F.discriminatedUnion("operation",[F.object({operation:F.literal("search"),query:F.string().optional().describe("Search query for note content"),maxResults:F.number().optional().default(10).describe("Maximum number of results to return"),minScore:F.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)")}),F.object({operation:F.literal("queryEdges"),nodeId:F.number().describe("Node ID to query relations"),maxDepth:F.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")})]);async function JC(e,t){if(e.length===0)return `<note_context>
693
+ No note context found.
694
+ </note_context>`;let n=[];n.push(`<note_context total="${e.length}">`);for(let o=0;o<e.length;o++){let s=e[o],r=await Ve.output(s.snippet,{maxLines:BC,maxBytes:GC,contentType:"list",toolName:"note_snippet"},t);if(n.push(`[${o+1}]`),n.push(` document: ${s.document.path}`),n.push(` lines: ${s.chunk.startLine}-${s.chunk.endLine}`),n.push(` score: ${s.score.toFixed(4)}`),n.push(` source: ${s.source}`),n.push(` snippet: ${r.content}`),r.truncated&&n.push(` (snippet: ${r.outputPath})`),s.nodes&&s.nodes.length>0){let i=s.nodes.map(l=>{let d=[` - node: id=${l.id} type=${l.type} name=${l.name}`];if(l.edges&&l.edges.length>0)for(let m of l.edges){let f=m.source===l.id?"out":"in";m.targetNode?d.push(` \u2192 [${f}] ${m.relation} \u2192 ${m.targetNode.type}:${m.targetNode.name} (id=${m.target})`):d.push(` \u2192 [${f}] ${m.relation} \u2192 id=${m.target} (node not found)`);}return d.join(`
695
+ `)}).join(`
696
+ `),c=await Ve.output(i,{maxLines:xg,maxBytes:Ig,contentType:"list",toolName:"note_nodes"},t);n.push(` nodes (${s.nodes.length}):`),n.push(c.content),c.truncated&&n.push(` (nodes: ${c.outputPath})`);}n.push("");}return n.push("</note_context>"),n.join(`
697
+ `)}var vg=De.define("note",{description:HC,parameters:KC,async execute(e,t){if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");let n={directory:t.extra.directory},o=await Xt.config(),s=n.directory;Au.debug("note tool execute",{operation:e.operation,...e.operation==="search"&&{query:e.query},directory:s,noteConfigLoaded:!!o,noteConfig:o?{search:o.search,sync:o.sync}:null}),await t.ask({permission:"note",patterns:[e.operation],always:["*"],metadata:{operation:e.operation,...e.operation==="search"&&{query:e.query},...e.operation==="queryEdges"&&{nodeId:e.nodeId},workspaceDir:s,noteConfigLoaded:!!o}});let r=await Xt.get();if(!r)return Au.warn("note kb not available"),{output:`<note_context>
698
+ Note knowledge base is not enabled or not properly configured.
699
+ </note_context>`,title:`Note: ${e.operation}`,metadata:{available:false,count:0,enabled:false}};if(e.operation==="search"){let i=o?.search?.minScore??.3,c=e.minScore!==void 0&&e.minScore!==null?Number(e.minScore):i,l=o?.search?.maxResults??10;Au.debug("note search params",{query:e.query,minScore:c,defaultMinScore:i,maxResults:e.maxResults??l,noteMinScore:o?.search?.minScore}),o?.sync?.onSearch&&r.sync().catch(()=>{});let d=await r.search(e.query??"",{maxResults:e.maxResults??l,minScore:c,includeEdges:true,enableEmbedding:true,enableFts:true});return {output:await JC(d,t.extra?.agent),title:`Note search: ${e.query??""}`,metadata:{available:true,operation:"search",total:d.length,query:e.query,enabled:true}}}if(e.operation==="queryEdges"){let i=typeof e.nodeId=="string"?parseInt(e.nodeId,10):e.nodeId,c=await r.queryNodes({ids:[i]});if(!c||c.length===0)return {output:`<note_queryEdges>
700
+ Node with id ${e.nodeId} not found.
701
+ </note_queryEdges>`,title:`Note queryEdges: ${e.nodeId}`,metadata:{available:true,operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:0}};let l=c[0],d=typeof e.maxDepth=="string"?parseInt(e.maxDepth,10):e.maxDepth??2,m=Math.min(d||2,3),f=await r.queryNeighbors(i,{limit:20,maxDepth:m}),a=20,p=f.edges.slice(0,a),u=f.nodes.map(y=>`[id=${y.id}] type=${y.type} name=${y.name}`).join(`
702
+ `),g=await Ve.output(u,{maxLines:xg,maxBytes:Ig,contentType:"list",toolName:"note_neighbors"},t.extra?.agent),h=p.map(y=>{let x=y.source===i?"out":"in";return y.targetNode?` \u2192 [${x}] ${y.relation} \u2192 ${y.targetNode.type}:${y.targetNode.name} (id=${y.target})`:` \u2192 [${x}] ${y.relation} \u2192 id=${y.target} (node not found)`}).join(`
703
+ `);if(f.edges.length>a){let y=f.edges.length-a,x=p.length>0?`
704
+ `:"";h=h+x+` ... and ${y} more relations`;}let S=await Ve.output(h,{maxLines:WC,maxBytes:VC,contentType:"list",toolName:"note_edges"},t.extra?.agent),A=[];return A.push(`<note_queryEdges node_id="${e.nodeId}" name="${l.name}" type="${l.type}">`),A.push(`neighbors (${f.nodes.length}):`),A.push(g.content),g.truncated&&A.push(` (neighbors: ${g.outputPath})`),A.push(""),A.push(`relations (${f.edges.length}):`),A.push(S.content),S.truncated&&A.push(` (relations: ${S.outputPath})`),A.push("</note_queryEdges>"),{output:A.join(`
705
+ `),title:`Note queryEdges: ${e.nodeId}`,metadata:{available:true,operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:f.nodes.length}}}throw new Error(`Unknown operation: ${e.operation}`)}});var QC=loadTextFile("./memory.txt",import.meta.url),ZC=QC()||"Access and manage memory system for agent operations",ek=10,tk=800,nk=30,ok=1500;async function sk(e,t){if(e.length===0)return `<memory_context>
706
+ No memories found.
707
+ </memory_context>`;let n=[];n.push(`<memory_context total="${e.length}">`);for(let o=0;o<e.length;o++){let s=e[o],r=new Date(s.createdAt),i=formatLocalISOCompact(r),c=Intl.DateTimeFormat().resolvedOptions().timeZone,l=await Ve.output(s.snippet,{maxLines:ek,maxBytes:tk,contentType:"list",toolName:"memory_snippet"},t);if(n.push(`[${o+1}]`),n.push(` id: ${s.memoryId}`),n.push(` [${s.category}] importance=${s.importance}`),n.push(` score: ${s.score.toFixed(4)}`),n.push(` created: ${i} (${c})`),n.push(` agent: ${s.agentId}`),n.push(` source: ${s.source}`),n.push(` snippet: ${l.content}`),l.truncated&&n.push(` (snippet: ${l.outputPath})`),s.filePath){let d=Filesystem.normalize(s.filePath);n.push(` file: ${d}`);}if(s.nodes&&s.nodes.length>0){let d=s.nodes.map(f=>{let a=[` - node: id=${f.id} type=${f.type} name=${f.name}`];if(f.edges&&f.edges.length>0)for(let p of f.edges){let u=p.source===f.id?"out":"in";p.targetNode?a.push(` \u2192 [${u}] ${p.relation} \u2192 ${p.targetNode.type}:${p.targetNode.name} (id=${p.target})`):a.push(` \u2192 [${u}] ${p.relation} \u2192 id=${p.target} (node not found)`);}return a.join(`
708
+ `)}).join(`
709
+ `),m=await Ve.output(d,{maxLines:nk,maxBytes:ok,contentType:"list",toolName:"memory_nodes"},t);n.push(` nodes (${s.nodes.length}):`),n.push(m.content),m.truncated&&n.push(` (nodes: ${m.outputPath})`);}n.push("");}return n.push("</memory_context>"),n.join(`
710
+ `)}function Sg(e){if(e?.trim())return e.split(",").map(t=>t.trim()).filter(Boolean)}function Cg(e){if(e)try{let t=new Date(e);return Number.isNaN(t.getTime())?void 0:t.toISOString()}catch{return}}var Eu=F.enum(["user_preference","task_context","technical_fact","decision","relationship","reminder","error_pattern","workflow","exploration_finding","experience_summary","tool_usage","skill_creation","test","other"]),rk=F.discriminatedUnion("operation",[F.object({operation:F.literal("remember"),content:F.string().describe("Memory content to store"),category:Eu.describe("Memory category"),importance:F.coerce.number().min(1).max(10).describe("Importance score 1-10"),tags:F.string().optional().describe('Optional tags, comma-separated (e.g. "typescript, testing, api")')}),F.object({operation:F.literal("recall"),query:F.string().describe("Search query"),maxResults:F.coerce.number().optional().default(10).describe("Maximum number of results to return (default 10)"),minScore:F.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)"),category:Eu.optional().describe("Filter by memory category"),fromTime:F.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:F.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')}),F.object({operation:F.literal("queryEdges"),nodeId:F.coerce.number().describe("Node ID to query relations"),maxDepth:F.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")}),F.object({operation:F.literal("forget"),memoryId:F.string().describe("Memory ID to delete")}),F.object({operation:F.literal("update"),memoryId:F.string().describe("Memory ID to update"),content:F.string().optional().describe("Updated memory content"),importance:F.coerce.number().min(1).max(10).optional().describe("Updated importance score 1-10"),tags:F.string().optional().describe('Updated tags, comma-separated (e.g. "typescript, testing, api")')}),F.object({operation:F.literal("list"),maxResults:F.coerce.number().min(1).max(100).optional().default(20).describe("Maximum number of memories to list (default 20, max 100)"),category:Eu.optional().describe("Filter by memory category"),fromTime:F.string().optional().describe('Start time filter in local time (e.g. "2024-01-01 00:00:00")'),toTime:F.string().optional().describe('End time filter in local time (e.g. "2024-12-31 23:59:59")')})]),Pg=De.define("memory",{description:ZC,parameters:rk,formatValidationError(e){return `Memory tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){let n=t.extra?.directory??"unknown";await t.ask({permission:"memory",patterns:e.operation==="recall"?[e.query]:["*"],always:["*"],metadata:{operation:e.operation,workspaceDir:n}});let o=await In.get();if(!o)return {output:`<memory_context>
711
+ Memory system is not enabled or not properly configured.
712
+ </memory_context>`,title:`Memory: ${e.operation}`,metadata:{enabled:false,operation:e.operation,truncated:false}};let s=t.protocolMetadata?.agentId??t.agent;if(e.operation==="remember"){if(!e.category||e.importance==null)throw new Error("remember requires category and importance");let r;if(t.messageId){let c=await ve.get({sessionId:t.sessionId,messageId:t.messageId});c?.info.role==="assistant"&&(r=c.info.parentId);}let i=await o.remember({agentId:s,content:e.content,category:e.category,importance:e.importance,source:"session_self_write",tags:Sg(e.tags),sessionId:t.sessionId,msgId:t.messageId,parentMsgId:r});return {output:`<memory_result>
713
+ Memory saved successfully.
714
+ id: ${i.id}
715
+ category: ${i.category}
716
+ importance: ${i.importance}
717
+ </memory_result>`,title:"Memory saved",metadata:{operation:"remember",enabled:true,memoryId:i.id,category:i.category,importance:i.importance,truncated:false}}}if(e.operation==="recall"){let i=(await In.config())?.search?.minScore??.3,c=await o.query(e.query,{agentId:s,maxResults:e.maxResults??10,minScore:e.minScore??i,category:e.category,fromTime:Cg(e.fromTime),toTime:Cg(e.toTime)}),l=t.extra?.agent;return {output:await sk(c,l),title:`Memory recall: ${e.query}`,metadata:{operation:"recall",enabled:true,total:c.length,query:e.query}}}if(e.operation==="queryEdges"){if(e.nodeId===void 0)throw new Error("nodeId is required for queryEdges operation");let r=typeof e.nodeId=="string"?parseInt(e.nodeId,10):e.nodeId,i=typeof e.maxDepth=="string"?parseInt(e.maxDepth,10):e.maxDepth??2,c=Math.min(i||2,3),l=await o.queryEdgesByNodeId(r,{maxDepth:c});if(!l.node)return {output:`<memory_queryEdges node_id="${e.nodeId}">
718
+ Node ${e.nodeId} not found.
719
+ </memory_queryEdges>`,title:`Memory queryEdges: ${e.nodeId}`,metadata:{operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:0}};let d=[];d.push(`<memory_queryEdges node_id="${e.nodeId}" name="${l.node.name}" type="${l.node.type}">`),d.push(`neighbors (${l.nodes.length}):`);for(let a of l.nodes)d.push(` [id=${a.id}] type=${a.type} name=${a.name}`);let m=20,f=l.edges.slice(0,m);d.push(`relations (${l.edges.length}):`);for(let a of f){let p=a.source===r?"out":"in";a.targetNode?d.push(` \u2192 [${p}] ${a.relation} \u2192 ${a.targetNode.type}:${a.targetNode.name} (id=${a.target})`):d.push(` \u2192 [${p}] ${a.relation} \u2192 id=${a.target} (node not found)`);}return l.edges.length>m&&d.push(` ... and ${l.edges.length-m} more relations`),d.push("</memory_queryEdges>"),{output:d.join(`
720
+ `),title:`Memory queryEdges: ${e.nodeId}`,metadata:{operation:"queryEdges",nodeId:e.nodeId,enabled:true,total:l.edges.length}}}if(e.operation==="forget")try{return await o.forget(s,e.memoryId),{output:`<memory_result>
721
+ Memory ${e.memoryId} deleted successfully.
722
+ </memory_result>`,title:"Memory deleted",metadata:{operation:"forget",enabled:!0,memoryId:e.memoryId,truncated:!1}}}catch(r){if(r?.message?.includes("not found")||r?.name==="MemoryNotFoundError")return {output:`<memory_result>
723
+ Memory ${e.memoryId} not found or already deleted.
724
+ </memory_result>`,title:"Memory forget",metadata:{operation:"forget",enabled:true,memoryId:e.memoryId,truncated:false}};throw r}if(e.operation==="update")try{let r=await o.update(s,e.memoryId,{content:e.content,importance:e.importance,tags:Sg(e.tags)});return {output:`<memory_result>
725
+ Memory ${r.id} updated successfully.
726
+ category: ${r.category}
727
+ importance: ${r.importance}
728
+ </memory_result>`,title:"Memory updated",metadata:{operation:"update",enabled:!0,memoryId:r.id,category:r.category,truncated:!1}}}catch(r){if(r?.name==="MemoryNotFoundError")return {output:`<memory_result>
729
+ Memory ${e.memoryId} not found. Please use 'list' to see available memory IDs.
730
+ </memory_result>`,title:"Memory update failed",metadata:{operation:"update",enabled:true,memoryId:e.memoryId,truncated:false}};throw r}if(e.operation==="list"){let r=await o.queryForSummary(s,{limit:e.maxResults??20,category:e.category,fromTime:e.fromTime,toTime:e.toTime});if(r.length===0)return {output:`<memory_context>
731
+ No memories found${e.category||e.fromTime||e.toTime?" with given filters":""}.
732
+ </memory_context>`,title:"Memory list",metadata:{operation:"list",enabled:true,total:0,truncated:false}};let i=[];i.push(`<memory_context total="${r.length}">`);for(let c=0;c<r.length;c++){let l=r[c],d=new Date(l.createdAt),m=formatLocalISOCompact(d);i.push(`[${c+1}] id=${l.id} [${l.category}] importance=${l.importance} created=${m}`),i.push(` ${l.content.slice(0,100)}${l.content.length>100?"...":""}`),l.tags&&l.tags.length>0&&i.push(` tags: ${l.tags.join(", ")}`);}return i.push("</memory_context>"),{output:i.join(`
733
+ `),title:`Memory list (${r.length})`,metadata:{operation:"list",enabled:true,total:r.length,truncated:false}}}throw new Error(`Unknown operation: ${e.operation}`)}});var ak=loadTextFile("./codebase.txt",import.meta.url),ck=ak()||"Access and analyze codebase knowledge graph for agent operations",dk=10,lk=1e3,Vc=20,Kc=2e3,uk=F.discriminatedUnion("operation",[F.object({operation:F.literal("search"),query:F.string().optional().describe("Search query for codebase content"),maxResults:F.number().optional().default(10).describe("Maximum number of results to return"),astType:F.string().optional().describe("Filter by AST type (e.g., class_declaration, function_declaration)"),language:F.string().optional().describe("Filter by programming language"),minScore:F.coerce.number().optional().describe("Minimum score threshold (default 0.3, higher = more precise)")}),F.object({operation:F.literal("queryEdges"),nodeId:F.string().describe("Node ID to query relations"),direction:F.enum(["in","out","both"]).optional().default("both").describe("Edge direction: in (incoming), out (outgoing), both"),maxDepth:F.coerce.number().optional().default(2).describe("Maximum depth of relations to query (default 2)")})]);async function pk(e,t){if(e.length===0)return `<codebase_context>
734
+ No codebase results found.
735
+ </codebase_context>`;let n=[];n.push(`<codebase_context total="${e.length}">`);for(let o=0;o<e.length;o++){let s=e[o],r=await Ve.output(s.text,{maxLines:dk,maxBytes:lk,contentType:"output",toolName:"codebase_code"},t),i=s.edges?.map(l=>` \u2192 ${l.relation} \u2192 node:${l.target}`).join(`
736
+ `)||"";s.edges&&s.edges.length>0?await Ve.output(i,{maxLines:Vc,maxBytes:Kc,contentType:"list",toolName:"codebase_edges"},t):null;if(n.push(`[${o+1}]`),n.push(` node id=${s.id}`),n.push(` type: ${s.ast_type}`),n.push(` language: ${s.language}`),n.push(` name: ${s.name}`),n.push(` location: ${s.file_path}:${s.start_line}`),n.push(` code: ${r.content.replace(/\s+/g," ")}`),s.edges&&s.edges.length>0){let l=new Map(e.map(f=>[f.id,f])),d=s.edges.map(f=>{let a=f.source===s.id?"out":"in",p=l.get(f.target),u=p?.ast_type||"unknown",g=p?.name||String(f.target);return ` \u2192 [${a}] ${f.relation} \u2192 target=${u}:${g} (id=${f.target})`}).join(`
737
+ `),m=await Ve.output(d,{maxLines:Vc,maxBytes:Kc,contentType:"list",toolName:"codebase_edges"},t);n.push(` edges (${s.edges.length}):`),n.push(m.content);}n.push("");}return n.push("</codebase_context>"),n.join(`
738
+ `)}var Tg=De.define("codebase",{scope:g.Coder,description:ck,parameters:uk,formatValidationError(e){return `Codebase tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");await t.ask({permission:"codebase",patterns:[e.operation==="search"?e.query??"*":"*"],always:["*"],metadata:{operation:e.operation,...e.operation==="search"&&{query:e.query},...e.operation==="queryEdges"&&{nodeId:e.nodeId},workspaceDir:t.extra.directory}});let n=await Do.get();if(!n)return {output:`<codebase_context>
739
+ Codebase knowledge base is not enabled or not properly configured.
740
+ </codebase_context>`,title:`Codebase ${e.operation}`,metadata:{count:0,enabled:false,operation:e.operation}};if(e.operation==="search"){let s=(await Do.config())?.search?.minScore??.3,r=await n.search(e.query??"",{maxResults:e.maxResults??10,enableEmbedding:true,enableFts:true,astType:e.astType,minScore:e.minScore??s,language:e.language,includeEdges:true}),i=await pk(r,t.extra?.agent);return r.length===0&&e.astType&&(i+=`
741
+
742
+ <i>Tip: astType filter was applied but returned no results. Try without astType or use different astType value.</i>`),{output:i,title:`Codebase search: ${e.query??""}`,metadata:{count:r.length,query:e.query,enabled:true,operation:"search",astType:e.astType,language:e.language}}}if(e.operation==="queryEdges"){let o={in:"incoming",out:"outgoing",both:"both"},s=String(e.nodeId),r=await n.getNode(s),i=Math.min(e.maxDepth??2,3),{nodes:c,edges:l}=await n.queryNeighbors(s,{limit:50,maxDepth:i,direction:o[e.direction??"both"]});if((!l||l.length===0)&&!r)return {output:`<codebase_queryEdges node_id="${e.nodeId}">
743
+ Node ${e.nodeId} not found or has no relations.
744
+ </codebase_queryEdges>`,title:`Codebase queryEdges: ${e.nodeId}`,metadata:{count:0,nodeId:e.nodeId,direction:e.direction,enabled:true,operation:"queryEdges"}};let d=[];if(d.push(`<codebase_queryEdges node_id="${s}" name="${r?.name}" type="${r?.ast_type}" language="${r?.language}" location="${r?.file_path}:${r?.start_line}" direction="${e.direction??"both"}">`),d.push(`neighbors (${c.length}):`),c.length>0){let a=c.map(u=>`[id=${u.id}] type=${u.ast_type} name=${u.name} location=${u.file_path}:${u.start_line}`).join(`
745
+ `),p=await Ve.output(a,{maxLines:Vc,maxBytes:Kc,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(h=>[h.id,h])),p=[];for(let h of f){let S=h.source===s?"out":"in",A=a.get(h.target),y=A?.ast_type||"unknown",x=A?.name||String(h.target);p.push(` \u2192 [${S}] ${h.relation} \u2192 target=${y}:${x} (id=${h.target})`);}l.length>m&&p.push(` ... and ${l.length-m} more relations`);let u=p.join(`
746
+ `),g=await Ve.output(u,{maxLines:Vc,maxBytes:Kc,contentType:"list",toolName:"codebase_edges"},t.extra?.agent);d.push(g.content);}return d.push("</codebase_queryEdges>"),{output:d.join(`
747
+ `),title:`Codebase queryEdges: ${s}`,metadata:{count:l.length,nodeId:s,direction:e.direction,enabled:true,operation:"queryEdges"}}}throw new Error(`Unknown operation: ${e.operation}`)}});var hk=loadTextFile("./lsp.txt",import.meta.url),yk=hk(),bk=200,wk=5*1024,xk=["goToDefinition","findReferences","hover","documentSymbol","workspaceSymbol","goToImplementation","prepareCallHierarchy","incomingCalls","outgoingCalls"],Ag=De.define("lsp",{scope:g.Coder,isEnabled:()=>a$2.EASBOT_LSP_TOOL,description:yk,parameters:F.object({operation:F.enum(xk).describe("The LSP operation to perform"),filePath:F.string().describe("The absolute or relative path to the file"),line:F.number().int().min(1).describe("The line number (1-based, as shown in editors)"),character:F.number().int().min(1).describe("The character offset (1-based, as shown in editors)"),query:F.string().optional().describe("Search query for workspaceSymbol. Empty string requests all symbols.")}),formatValidationError(e){return `LSP tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},execute:async(e,t)=>{Rt.check(t.abort,"lsp");let n=Filesystem.normalize(Ce__default.isAbsolute(e.filePath)?e.filePath:Ce__default.join(_.directory,e.filePath));await Yt(t,n,{tool:"lsp"});let o=e.operation==="workspaceSymbol"?{operation:e.operation}:e.operation==="documentSymbol"?{operation:e.operation,filePath:n}:{operation:e.operation,filePath:n,line:e.line,character:e.character};await t.ask({permission:"lsp",patterns:["*"],always:["*"],metadata:o});let s={file:n,line:e.line-1,character:e.character-1},r=Ce__default.posix.relative(_.worktree,n),i=e.operation==="workspaceSymbol"?"":e.operation==="documentSymbol"?r:`${r}:${e.line}:${e.character}`,c=i?`${e.operation} ${i}`:e.operation;if(!await Tt__default.access(n).then(()=>true).catch(()=>false))throw new Error(`File not found: ${n}`);if(!await We.hasClients(n))throw new Error("No LSP server available for this file type.");await We.touchFile(n,true);let m=await Rt.wrap("lsp",t.abort,async()=>{switch(e.operation){case "goToDefinition":return We.definition(s);case "findReferences":return We.references(s);case "hover":return We.hover(s);case "documentSymbol":return We.documentSymbol({file:n});case "workspaceSymbol":return We.workspaceSymbol(e.query??"");case "goToImplementation":return We.implementation(s);case "prepareCallHierarchy":return We.prepareCallHierarchy(s);case "incomingCalls":return We.incomingCalls(s);case "outgoingCalls":return We.outgoingCalls(s)}}),f=m.length===0?`No results found for ${e.operation}`:JSON.stringify(m,null,2),a=await Ve.output(f,{maxLines:bk,maxBytes:wk,contentType:"output",toolName:"lsp"});return {title:c,metadata:{filepath:n,truncated:a.truncated,...a.truncated&&{outputPath:a.outputPath}},output:a.content}}});var vk=loadTextFile("./plan.txt",import.meta.url),Sk=vk();async function _g(e){for await(let t of ve.stream(e))if(t.info.role==="user"&&t.info.model)return t.info.model;return xe.defaultModel()}var Eg={enter:F.object({operation:F.literal("enter").describe("Enter plan mode for research and planning")}),exit:F.object({operation:F.literal("exit").describe("Exit plan mode and switch to build mode")})},Ck=F.discriminatedUnion("operation",[Eg.enter,Eg.exit]),Mg=De.define("plan",{description:Sk,parameters:Ck,formatValidationError(e){return `Plan tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){if(e.operation==="enter")return kk(t);if(e.operation==="exit")return Pk(t);throw new Error(`Unknown operation: ${e.operation}`)}});async function kk(e){let t=await X.get(e.sessionId),n=Ce__default.posix.relative(_.worktree,X.plan(t));if((await Ot.ask({sessionId:e.sessionId,questions:[{question:`Would you like to switch to the plan agent and create a plan saved to ${n}?`,header:"Plan Mode",custom:false,options:[{label:"Yes",description:"Switch to plan agent for research and planning"},{label:"No",description:"Stay with build agent to continue making changes"}]}],tool:e.callId?{messageId:e.messageId,callId:e.callId}:void 0}))[0]?.[0]==="No")throw new Ot.RejectedError;let r=await _g(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 X.updateMessage(c),await X.updatePart({id:Identifier.ascending("part"),messageId:c.id,sessionId:e.sessionId,type:"text",text:"User has requested to enter plan mode. Switch to plan mode and begin planning.",synthetic:true}),{title:"Switching to plan agent",output:`User confirmed to switch to plan mode. A new message has been created to switch you to plan mode. The plan file will be at ${n}. Begin planning.`,metadata:{operation:"enter"}}}async function Pk(e){let t=await X.get(e.sessionId),n=Ce__default.posix.relative(_.worktree,X.plan(t));if((await Ot.ask({sessionId:e.sessionId,questions:[{question:`Plan at ${n} is complete. Would you like to switch to the build agent and start implementing?`,header:"Build Agent",custom:false,options:[{label:"Yes",description:"Switch to build agent and start implementing the plan"},{label:"No",description:"Stay with plan agent to continue refining the plan"}]}],tool:e.callId?{messageId:e.messageId,callId:e.callId}:void 0}))[0]?.[0]==="No")throw new Ot.RejectedError;let r=await _g(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 X.updateMessage(c),await X.updatePart({id:Identifier.ascending("part"),messageId:c.id,sessionId:e.sessionId,type:"text",text:`The plan at ${n} has been approved, you can now edit files. Execute the plan`,synthetic:true}),{title:"Switching to build agent",output:"User approved switching to build agent. Wait for further instructions.",metadata:{operation:"exit"}}}var Ki;(b=>{let e=a.create({service:"patch"});b.PatchSchema=F.object({patchText:F.string().describe("The full patch text that describes all changes to be made")});(E=>(E.ParseError="ParseError",E.IoError="IoError",E.ComputeReplacements="ComputeReplacements",E.ImplicitInvocation="ImplicitInvocation"))(b.ApplyPatchError||(b.ApplyPatchError={}));(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.PatchParseError="PatchParseError",E.NotApplyPatch="NotApplyPatch"))(b.MaybeApplyPatch||(b.MaybeApplyPatch={}));(E=>(E.Body="Body",E.ShellParseError="ShellParseError",E.CorrectnessError="CorrectnessError",E.NotApplyPatch="NotApplyPatch"))(b.MaybeApplyPatchVerified||(b.MaybeApplyPatchVerified={}));function r(w,C){let k=w[C];if(!k)return null;let P=E=>{let O=E.indexOf(":");if(O!==-1)return E.substring(O+1).trim()||void 0};if(k.startsWith("*** Add File:")){let E=P(k);return E?{filePath:E,nextIdx:C+1}:null}if(k.startsWith("*** Delete File:")){let E=P(k);return E?{filePath:E,nextIdx:C+1}:null}if(k.startsWith("*** Update File:")){let E=P(k),O,N=C+1;if(N<w.length&&w[N]?.startsWith("*** Move to:")){let L=w[N];L&&(O=P(L)),N++;}return E?{filePath:E,movePath:O,nextIdx:N}:null}return null}function i(w,C){let k=[],P=C;for(;P<w.length&&!w[P]?.startsWith("***");){let E=w[P];if(!E){P++;continue}if(E.startsWith("@@")){let O=E.indexOf("@@",2),N=O!==-1?E.substring(O+2).trim():"";P++;let L=[],K=[],Q=false;for(;P<w.length&&!w[P]?.startsWith("@@")&&!w[P]?.startsWith("***");){let ue=w[P];if(!ue){P++;continue}if(ue==="*** End of File"){Q=true,P++;break}if(ue.startsWith(" ")){let D=ue.substring(1);L.push(D),K.push(D);}else ue.startsWith("-")?L.push(ue.substring(1)):ue.startsWith("+")&&K.push(ue.substring(1));P++;}k.push({old_lines:L,new_lines:K,change_context:N||void 0,is_end_of_file:Q||void 0});}else P++;}return {chunks:k,nextIdx:P}}function c(w,C){let k="",P=C;for(;P<w.length&&!w[P]?.startsWith("***");){let E=w[P];if(!E){P++;continue}E.startsWith("+")&&(k+=E.substring(1)+`
748
+ `),P++;}return k.endsWith(`
749
+ `)&&(k=k.slice(0,-1)),{content:k,nextIdx:P}}function l(w){let C=w.match(/^(?:cat\s+)?<<['"]?(\w+)['"]?\s*\n([\s\S]*?)\n\1\s*$/);return C?.[2]?C[2]:w}function d(w){let k=l(w.trim()).split(`
750
+ `),P=[],E=0,O="*** Begin Patch",N="*** End Patch",L=k.findIndex(Q=>Q.trim()===O),K=k.findIndex(Q=>Q.trim()===N);if(L===-1||K===-1||L>=K)throw new Error("Invalid patch format: missing Begin/End markers");for(E=L+1;E<K;){let Q=r(k,E);if(!Q){E++;continue}if(k[E]?.startsWith("*** Add File:")){let{content:ue,nextIdx:D}=c(k,Q.nextIdx);P.push({type:"add",path:Q.filePath,contents:ue}),E=D;}else if(k[E]?.startsWith("*** Delete File:"))P.push({type:"delete",path:Q.filePath}),E=Q.nextIdx;else if(k[E]?.startsWith("*** Update File:")){let{chunks:ue,nextIdx:D}=i(k,Q.nextIdx);P.push({type:"update",path:Q.filePath,move_path:Q.movePath,chunks:ue}),E=D;}else E++;}return {hunks:P}}b.parsePatch=d;function m(w){let C=["apply_patch","applypatch"];if(w.length===2&&C.includes(w[0]))try{let k=w[1];if(!k)return {type:"PatchParseError",error:new Error("Missing patch argument")};let{hunks:P}=d(k);return {type:"Body",args:{patch:k,hunks:P}}}catch(k){return {type:"PatchParseError",error:k}}if(w.length===3&&w[0]==="bash"&&w[1]==="-lc"){let k=w[2];if(!k)return {type:"NotApplyPatch"};let P=k.match(/apply_patch\s*<<['"](\w+)['"]\s*\n([\s\S]*?)\n\1/);if(P?.[2]){let E=P[2];try{let{hunks:O}=d(E);return {type:"Body",args:{patch:E,hunks:O}}}catch(O){return {type:"PatchParseError",error:O}}}}return {type:"NotApplyPatch"}}b.maybeParseApplyPatch=m;function f(w,C){let k;try{k=readFileSync(w,"utf-8");}catch(K){throw new Error(`Failed to read file ${w}: ${K}`)}let P=k.split(`
751
+ `);P.length>0&&P[P.length-1]===""&&P.pop();let E=a$1(P,w,C),O=p(P,E);(O.length===0||O[O.length-1]!=="")&&O.push("");let N=O.join(`
752
+ `);return {unified_diff:S(k,N),content:N}}b.deriveNewContentsFromChunks=f;function a$1(w,C,k){let P=[],E=0;for(let O of k){if(O.change_context){let Q=h(w,[O.change_context],E);if(Q===-1)throw new Error(`Failed to find context '${O.change_context}' in ${C}`);E=Q+1;}if(O.old_lines.length===0){let Q=w.length>0&&w[w.length-1]===""?w.length-1:w.length;P.push([Q,0,O.new_lines]);continue}let N=O.old_lines,L=O.new_lines,K=h(w,N,E,O.is_end_of_file);if(K===-1&&N.length>0&&N[N.length-1]===""&&(N=N.slice(0,-1),L.length>0&&L[L.length-1]===""&&(L=L.slice(0,-1)),K=h(w,N,E,O.is_end_of_file)),K!==-1){let Q=[K,N.length,L];P.push(Q),E=K+N.length;}else throw new Error(`Failed to find expected lines in ${C}:
753
+ ${O.old_lines.join(`
754
+ `)}`)}return P.sort((O,N)=>O[0]-N[0]),P}function p(w,C){let k=[...w];for(let P=C.length-1;P>=0;P--){let E=C[P];if(!E)continue;let[O,N,L]=E;k.splice(O,N);for(let K=0;K<L.length;K++){let Q=L[K];Q!==void 0&&k.splice(O+K,0,Q);}}return k}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 g(w,C,k,P,E){if(E){let O=w.length-C.length;if(O>=k){let N=true;for(let L=0;L<C.length;L++){let K=w[O+L],Q=C[L];if(!K||!Q||!P(K,Q)){N=false;break}}if(N)return O}}for(let O=k;O<=w.length-C.length;O++){let N=true;for(let L=0;L<C.length;L++){let K=w[O+L],Q=C[L];if(!K||!Q||!P(K,Q)){N=false;break}}if(N)return O}return -1}function h(w,C,k,P=false){if(C.length===0)return -1;let E=g(w,C,k,(K,Q)=>K===Q,P);if(E!==-1)return E;let O=g(w,C,k,(K,Q)=>K.trimEnd()===Q.trimEnd(),P);if(O!==-1)return O;let N=g(w,C,k,(K,Q)=>K.trim()===Q.trim(),P);return N!==-1?N:g(w,C,k,(K,Q)=>u(K.trim())===u(Q.trim()),P)}function S(w,C){let k=w.split(`
755
+ `),P=C.split(`
756
+ `),E=`@@ -1 +1 @@
757
+ `,O=Math.max(k.length,P.length),N=false;for(let L=0;L<O;L++){let K=k[L]||"",Q=P[L]||"";K!==Q?(K&&(E+=`-${K}
758
+ `),Q&&(E+=`+${Q}
759
+ `),N=true):K&&(E+=` ${K}
760
+ `);}return N?E:""}async function A(w){if(w.length===0)throw new Error("No files were modified.");let C=[],k=[],P=[];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"),C.push(E.path),e.info(`Added file: ${E.path}`);break}case "delete":await Tt.unlink(E.path),P.push(E.path),e.info(`Deleted file: ${E.path}`);break;case "update":{let O=f(E.path,E.chunks);if(E.move_path){let N=Ce.dirname(E.move_path);N!=="."&&N!=="/"&&await Tt.mkdir(N,{recursive:true}),await Tt.writeFile(E.move_path,O.content,"utf-8"),await Tt.unlink(E.path),k.push(E.move_path),e.info(`Moved file: ${E.path} -> ${E.move_path}`);}else await Tt.writeFile(E.path,O.content,"utf-8"),k.push(E.path),e.info(`Updated file: ${E.path}`);break}}return {added:C,modified:k,deleted:P}}b.applyHunksToFiles=A;async function y(w){let{hunks:C}=d(w);return A(C)}b.applyPatch=y;async function x(w,C){if(w.length===1){let P=w[0];if(!P)return {type:"NotApplyPatch"};try{return d(P),{type:"CorrectnessError",error:new Error("ImplicitInvocation")}}catch{}}let k=m(w);switch(k.type){case "Body":{let{args:P}=k,E=P.workdir?Ce.resolve(C,P.workdir):C,O=new Map;for(let N of P.hunks){let L=Ce.resolve(E,N.type==="update"&&N.move_path?N.move_path:N.path);switch(N.type){case "add":O.set(L,{type:"add",content:N.contents});break;case "delete":{let K=Ce.resolve(E,N.path);try{let Q=await Tt.readFile(K,"utf-8");O.set(L,{type:"delete",content:Q});}catch{return {type:"CorrectnessError",error:new Error(`Failed to read file for deletion: ${K}`)}}break}case "update":{let K=Ce.resolve(E,N.path);try{let Q=f(K,N.chunks);O.set(L,{type:"update",unified_diff:Q.unified_diff,move_path:N.move_path?Ce.resolve(E,N.move_path):void 0,new_content:Q.content});}catch(Q){return {type:"CorrectnessError",error:Q}}break}}}return {type:"Body",action:{changes:O,patch:P.patch,cwd:E}}}case "PatchParseError":return {type:"CorrectnessError",error:k.error};case "NotApplyPatch":return {type:"NotApplyPatch"}}}b.maybeParseApplyPatchVerified=x;})(Ki||(Ki={}));var Ek=loadTextFile("./apply_patch.txt",import.meta.url),Rk=Ek(),_k=F.object({patchText:F.string().describe("The full patch text that describes all changes to be made")}),Dg=De.define("apply_patch",{scope:g.Coder,description:Rk,parameters:_k,async execute(e,t){if(Rt.check(t.abort,"apply_patch"),!e.patchText)throw new Error("patchText is required");let n;try{n=Ki.parsePatch(e.patchText).hunks;}catch(a){throw new Error(`apply_patch verification failed: ${a}`)}if(n.length===0)throw e.patchText.replace(/\r\n/g,`
761
+ `).replace(/\r/g,`
762
+ `).trim()===`*** Begin Patch
763
+ *** End Patch`?new Error("patch rejected: empty patch"):new Error("apply_patch verification failed: no hunks found");let o=[],s="";for(let a of n){let p=Filesystem.normalize(Ce.resolve(_.directory,a.path));switch(await Yt(t,p,{tool:"patch"}),a.type){case "add":{let g=a.contents.length===0||a.contents.endsWith(`
764
+ `)?a.contents:`${a.contents}
765
+ `,h=$o(createTwoFilesPatch(p,p,"",g)),S=0,A=0;for(let y of diffLines("",g))y.added&&(S+=y.count||0),y.removed&&(A+=y.count||0);o.push({filePath:p,oldContent:"",newContent:g,type:"add",diff:h,additions:S,deletions:A}),s+=h+`
766
+ `;break}case "update":{let u=await Tt.stat(p).catch(()=>null);if(!u||u.isDirectory())throw new Error(`apply_patch verification failed: Failed to read file to update: ${p}`);let g=await Tt.readFile(p,"utf-8"),h=g;try{h=Ki.deriveNewContentsFromChunks(p,a.chunks).content;}catch(b){throw new Error(`apply_patch verification failed: ${b}`)}let S=$o(createTwoFilesPatch(p,p,g,h)),A=0,y=0;for(let b of diffLines(g,h))b.added&&(A+=b.count||0),b.removed&&(y+=b.count||0);let x=a.move_path?Filesystem.normalize(Ce.resolve(_.directory,a.move_path)):void 0;await Yt(t,x,{tool:"patch"}),o.push({filePath:p,oldContent:g,newContent:h,type:a.move_path?"move":"update",movePath:x,diff:S,additions:A,deletions:y}),s+=S+`
767
+ `;break}case "delete":{let u=await Tt.stat(p).catch(()=>null);if(!u||u.isDirectory())throw new Error(`apply_patch verification failed: File not found: ${p}`);let g=await Tt.readFile(p,"utf-8"),h=$o(createTwoFilesPatch(p,p,g,"")),S=g.split(`
768
+ `).length;o.push({filePath:p,oldContent:g,newContent:"",type:"delete",diff:h,additions:0,deletions:S}),s+=h+`
769
+ `;break}}}let r=o.map(a=>({filePath:a.filePath,relativePath:Ce.posix.relative(_.worktree,a.movePath??a.filePath),type:a.type,diff:a.diff,before:a.oldContent,after:a.newContent,additions:a.additions,deletions:a.deletions,movePath:a.movePath})),i=o.map(a=>Ce.posix.relative(_.worktree,a.filePath));await t.ask({permission:"edit",patterns:i,always:["*"],metadata:{filepath:i.join(", "),diff:s,files:r}}),Rt.check(t.abort,"apply_patch");let c=[];for(let a of o){let p=a.type==="delete"?void 0:a.movePath??a.filePath;switch(a.type){case "add":await Tt.mkdir(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 pe.publish(bt.Event.Edited,{file:p});}for(let a of c)await pe.publish(Nn.Event.Updated,a);Rt.check(t.abort,"apply_patch");for(let a of o){if(a.type==="delete")continue;let p=a.movePath??a.filePath;await We.touchFile(p,true);}let l=await We.diagnostics(),m=`Success. Updated the following files:
770
+ ${o.map(a=>{if(a.type==="add")return `A ${Ce.posix.relative(_.worktree,a.filePath)}`;if(a.type==="delete")return `D ${Ce.posix.relative(_.worktree,a.filePath)}`;let p=a.movePath??a.filePath;return `M ${Ce.posix.relative(_.worktree,p)}`}).join(`
771
+ `)}`,f=20;for(let a of o){if(a.type==="delete")continue;let p=a.movePath??a.filePath,u=Filesystem.normalize(p),h=(l[u]??[]).filter(S=>S.severity===1);if(h.length>0){let S=h.slice(0,f),A=h.length>f?`
772
+ ... and ${h.length-f} more`:"";m+=`
773
+
774
+ LSP errors detected in ${Ce.posix.relative(_.worktree,p)}, please fix:
775
+ <diagnostics file="${p}">
776
+ ${S.map(We.Diagnostic.pretty).join(`
777
+ `)}${A}
778
+ </diagnostics>`;}}return {title:m,metadata:{diff:s,files:r,diagnostics:l},output:m}}});var Ok=loadTextFile("./multiedit.txt",import.meta.url),jk=Ok(),Dk=F.object({edits:F.array(F.object({filePath:F.string().describe("The absolute path to the file to modify"),oldString:F.string().describe("The text to replace"),newString:F.string().describe("The text to replace it with (must be different from oldString)"),replaceAll:F.boolean().optional().describe("Replace all occurrences of oldString (default false)")})).min(1).describe("Array of edit operations to perform sequentially"),continueOnError:F.boolean().optional().default(false).describe("Continue processing remaining edits if one fails (default false)")});function $k(e){return "filePath"in e&&"edits"in e?(console.warn('[multiedit] Deprecated parameter format detected. The top-level "filePath" field is no longer needed. Please update to new format where each edit contains its own filePath.'),{edits:e.edits.map(n=>({filePath:n.filePath||e.filePath,oldString:n.oldString,newString:n.newString,replaceAll:n.replaceAll})),continueOnError:e.continueOnError??false}):e}var $g=De.define("multiedit",{description:jk,parameters:Dk,async execute(e,t){let n=$k(e);Rt.check(t.abort,"multiedit");let o=await qc.init(),s=[],r=[],i=new Map;for(let a of n.edits)i.has(a.filePath)||i.set(a.filePath,[]),i.get(a.filePath).push(a);for(let[a,p]of i.entries()){Rt.check(t.abort,"multiedit");try{for(let u of p){let g=await o.execute({filePath:u.filePath,oldString:u.oldString,newString:u.newString,replaceAll:u.replaceAll},t);s.push({success:!0,filePath:u.filePath,result:g});}}catch(u){if(r.push({filePath:a,error:u}),s.push({success:false,filePath:a,error:u}),!n.continueOnError)throw u}}let c=s.filter(a=>a.success).length,l=s.filter(a=>!a.success).length,d=n.edits.length,m=s.filter(a=>a.success).at(-1),f="";if(l===0?f=`Successfully applied ${d} edit(s) across ${i.size} file(s)`:c===0?f=`Failed to apply all ${d} edit(s)`:f=`Applied ${c}/${d} edit(s) successfully, ${l} failed`,r.length>0){f+=`
779
+
780
+ Errors:
781
+ `;for(let{filePath:a,error:p}of r)f+=`- ${Ce__default.posix.relative(_.worktree,a)}: ${p.message}
782
+ `;}return m?.result&&(f+=`
783
+
784
+ Last successful edit:
785
+ `,f+=m.result.output),{title:`Multiedit: ${c}/${d} successful`,metadata:{totalEdits:d,successCount:c,failureCount:l,filesModified:i.size,files:s.map(a=>({success:a.success,filePath:a.filePath,metadata:a.result?.metadata,error:a.error?.message}))},output:f}}});var Ji=a.create({service:"connection-registry"}),fn;(a=>{let e=null;async function t(){return e||(e=await Yc.create()),e}async function n(p){e=await Yc.create(p),Ji.info("AcpConnectionRegistry initialized");}a.init=n;async function o(p){return (await t()).connect(p.baseUrl,p.localAgentId,p.remoteAgentId,p.remoteSessionId,p.localSessionId)}a.connect=o;async function s(p){return (await t()).resolve(p)}a.resolve=s;function r(p){if(e)return e.resolve(p)}a.resolveSync=r;async function i(p){(await t()).closeConnection(p);}a.close=i;async function c(p,u){(await t()).markDegraded(p,u);}a.markDegraded=c;async function l(p){return (await t()).getConnectionsByAgent(p)}a.getConnectionsByLocalAgent=l;async function d(p){return (await t()).getConnectionsByService(p)}a.getConnectionsByService=d;async function m(){return (await t()).getAllActiveConnections()}a.getAllActiveConnections=m;async function f(p,u){(await t()).updateLastSeenMessageId(p,u);}a.updateLastSeenMessageId=f;})(fn||(fn={}));var Yc=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",Ji.debug("connection registry created",{defaultHistoryScope:this.defaultHistoryScope});}static create(t){return new e(t)}connect(t,n,o,s,r){let i=this.agentIndex.get(n);if(i)for(let m of i){let f=this.connections.get(m);if(f&&f.baseUrl===t&&f.status!=="closed")return s&&f.sessionId!==s&&(f.sessionId=s,f.sessionSequence=f.sessionSequence??[],f.sessionSequence.includes(s)||f.sessionSequence.push(s)),r&&(f.localSessionId=r),f.updatedAt=Date.now(),{connectionId:f.connectionId,sessionId:f.sessionId,localAgentId:f.localAgentId,remoteAgentId:f.remoteAgentId,baseUrl:f.baseUrl}}let c=this.generateConnectionId(),l=s??`session-${this.generateShortId()}`,d={localAgentId:n,remoteAgentId:o,connectionId:c,sessionId:l,...r?{localSessionId:r}:{},baseUrl:t,historyScope:this.defaultHistoryScope,historyWindowSize:this.defaultHistoryWindowSize,degradePolicy:this.defaultDegradePolicy,updatedAt:Date.now(),status:"active"};return this.connections.set(c,d),this.agentIndex.has(n)||this.agentIndex.set(n,new Set),this.agentIndex.get(n).add(c),this.serviceIndex.has(t)||this.serviceIndex.set(t,new Set),this.serviceIndex.get(t).add(c),{connectionId:c,sessionId:l,localAgentId:n,remoteAgentId:o,baseUrl:t}}resolve(t,n=false){let o=this.connections.get(t);if(o)return o;let s=this.agentIndex.get(t);if(s&&s.size>0)for(let r of s){let i=this.connections.get(r);if(i&&i.status!=="closed")return i}for(let r of this.connections.values())if(r.status!=="closed"&&(r.sessionId===t||r.localSessionId===t))return r;if(n){let c=this.connect("http://localhost","system-local","system-remote",t);return this.connections.get(c.connectionId)}}closeConnection(t){let n=this.connections.get(t);if(!n)return;this.connections.delete(t);let o=this.agentIndex.get(n.localAgentId);o&&(o.delete(t),o.size===0&&this.agentIndex.delete(n.localAgentId));let s=this.serviceIndex.get(n.baseUrl);s&&(s.delete(t),s.size===0&&this.serviceIndex.delete(n.baseUrl)),Ji.debug("connection closed and removed",{connectionId:t,localAgentId:n.localAgentId,remoteAgentId:n.remoteAgentId});}markDegraded(t,n){let o=this.connections.get(t);o&&(o.status="degraded",o.updatedAt=Date.now(),Ji.debug("connection marked degraded",{connectionId:t,reason:n}));}getConnectionsByAgent(t){let n=this.agentIndex.get(t);return n?Array.from(n).map(o=>this.connections.get(o)).filter(o=>o!==void 0&&o.status!=="closed"):[]}getConnectionsByService(t){let n=this.serviceIndex.get(t);return n?Array.from(n).map(o=>this.connections.get(o)).filter(o=>o!==void 0&&o.status!=="closed"):[]}getAllActiveConnections(){return Array.from(this.connections.values()).filter(t=>t.status!=="closed")}updateLastSeenMessageId(t,n){let o=this.connections.get(t);o&&(o.lastSeenMessageId=n,o.updatedAt=Date.now());}generateConnectionId(){return `conn-${this.generateShortId()}`}generateShortId(){return createHash("sha256").update(`${Date.now()}-${Math.random()}`).digest("hex").substring(0,8)}async close(){this.connections.clear(),this.agentIndex.clear(),this.serviceIndex.clear(),Ji.info("connection registry closed");}};var No=a.create({service:"session-router"});var Fr=class extends Error{constructor(n,o,s){super(o);b$1(this,"code",n);b$1(this,"context",s);this.name="RoutingError";}},Ou=class e{static create(){return new e}constructor(){No.info("session router created");}route(t){if(!this.isValidContext(t))return {success:false,error:"routing context is empty or invalid"};try{return t.connectionId?this.routeByConnectionId(t.connectionId):t.localAgentId&&t.baseUrl?this.routeByPeerAndBaseUrl(t.localAgentId,t.baseUrl):t.baseUrl&&t.sessionId?this.routeByBaseUrlAndSessionId(t.baseUrl,t.sessionId):{success:!1,error:"insufficient routing parameters: need connectionId, or localAgentId+baseUrl, or baseUrl+sessionId"}}catch(n){let o=n instanceof Error?n.message:String(n);return No.error("routing failed",{context:t,error:o}),{success:false,error:o}}}routeOrThrow(t){let n=this.route(t);if(!n.success)throw new Fr(this.getErrorCode(n.error),n.error??"routing failed",t);if(!n.connectionId)throw new Fr("NOT_FOUND","connection not found",t);let o=this.getConnectionState(n.connectionId);if(!o)throw new Fr("NOT_FOUND","connection state not found",t);if(o.status==="closed")throw new Fr("CONNECTION_CLOSED","connection is closed",t);return o}registerConnection(t){return !t.connectionId||!t.localAgentId||!t.remoteAgentId||!t.baseUrl||!t.sessionId?{success:false,error:"invalid connection state: missing required fields"}:(No.debug("connection registered",{connectionId:t.connectionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl}),{success:true,connectionId:t.connectionId,sessionId:t.sessionId,localAgentId:t.localAgentId,remoteAgentId:t.remoteAgentId,baseUrl:t.baseUrl})}unregisterConnection(t){let n=this.getConnectionState(t);return n?(No.debug("connection unregistered",{connectionId:t,localAgentId:n.localAgentId,remoteAgentId:n.remoteAgentId,baseUrl:n.baseUrl}),true):(No.debug("connection not found for unregister",{connectionId:t}),false)}isValidContext(t){return !!(t.connectionId||t.remoteAgentId||t.baseUrl||t.sessionId)}routeByConnectionId(t){let n=this.getConnectionState(t);return n?n.status==="closed"?{success:false,error:`connection is closed: ${t}`}:{success:true,connectionId:n.connectionId,sessionId:n.sessionId,localAgentId:n.localAgentId,remoteAgentId:n.remoteAgentId,baseUrl:n.baseUrl}:{success:false,error:`connection not found: ${t}`}}routeByPeerAndBaseUrl(t,n){let s=this.getConnectionsByPeer(t).filter(i=>i.baseUrl===n&&i.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for localAgentId=${t}, baseUrl=${n}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for localAgentId=${t}, baseUrl=${n}`};let r=s[0];return {success:true,connectionId:r.connectionId,sessionId:r.sessionId,localAgentId:r.localAgentId,remoteAgentId:r.remoteAgentId,baseUrl:r.baseUrl}}routeByBaseUrlAndSessionId(t,n){let s=this.getConnectionsByService(t).filter(i=>i.sessionId===n&&i.status!=="closed");if(s.length===0)return {success:false,error:`no connection found for baseUrl=${t}, sessionId=${n}`};if(s.length>1)return {success:false,error:`ambiguous route: multiple connections found for baseUrl=${t}, sessionId=${n}`};let r=s[0];return {success:true,connectionId:r.connectionId,sessionId:r.sessionId,localAgentId:r.localAgentId,remoteAgentId:r.remoteAgentId,baseUrl:r.baseUrl}}getConnectionState(t){No.warn("getConnectionState not implemented, returning undefined",{connectionId:t});}getConnectionsByPeer(t){return No.warn("getConnectionsByPeer not implemented, returning empty array",{agentId:t}),[]}getConnectionsByService(t){return No.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"}},Fg=class e extends Ou{constructor(n){super();b$1(this,"registry");this.registry=n,No.info("registry session router created");}static fromRegistry(n){return new e(n)}getConnectionState(n){return this.registry.resolve(n)}getConnectionsByPeer(n){return this.registry.getConnectionsByPeer(n)}getConnectionsByService(n){return this.registry.getConnectionsByService(n)}};var mo=a.create({service:"agent-client-api"});function Nk(e){return e==="stdio"||e==="http"||e==="websocket"?e:"http"}async function Uk(e){return (await Se(()=>Co.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",e||{directory:_.directory}).catch(()=>{}))?.acp?.server?.agentId??""}var an;(S=>{async function e(A,y){mo.debug("connect called",{args:A,context:y});let x=await Se(()=>Co.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",y||{directory:_.directory}).catch(()=>{}),b=x?.acp?.server?.agentId,w=A.agentId;w||(w=(await ts.getServiceByUrl(A.baseUrl))?.agentId);let C;if(A.baseUrl.startsWith("ws://")||A.baseUrl.startsWith("wss://")?C="websocket":A.baseUrl.startsWith("http://")||A.baseUrl.startsWith("https://")?C="http":C=Nk(x?.acp?.server?.channel),mo.debug("connect resolved",{baseUrl:A.baseUrl,resolvedChannel:C,localAgentId:b,remoteAgentId:w}),b){let Q=(await fn.getConnectionsByLocalAgent(b)).find(ue=>ue.baseUrl===A.baseUrl);if(Q){if(mo.debug("connect: found existing connection by agent"),Q.channel&&Q.channel!==C)throw new Error(`Channel mismatch for agent ${b}: ${Q.channel} != ${C}`);return {reused:true,...Q,channel:Q.channel??C}}}let k=await fn.getConnectionsByService(A.baseUrl);if(k.length>0){let K=k[0];if(mo.debug("connect: found existing connection by service",{existing:K}),K.channel&&K.channel!==C)throw new Error(`Channel mismatch for service ${A.baseUrl}: ${K.channel} != ${C}`);return {reused:true,connectionId:K.connectionId,sessionId:K.sessionId,remoteAgentId:K.remoteAgentId,baseUrl:K.baseUrl,channel:K.channel??C}}let P=b??"local-unknown",E=w??`remote-${Buffer.from(A.baseUrl).toString("base64").slice(0,16)}`;mo.debug("connect: using effective agent IDs",{effectiveLocalAgentId:P,effectiveRemoteAgentId:E}),mo.debug("connect: calling AgentClientService.connect",{baseUrl:A.baseUrl,channel:C});let O;try{O=await Qn.connect({config:{type:C,url:A.baseUrl,cwd:y.directory}}),mo.debug("connect: AgentClientService.connect succeeded",{remote:O});}catch(K){throw mo.error("connect: AgentClientService.connect failed",{error:K.message,stack:K.stack}),K}mo.debug("connect: creating connection in registry",{baseUrl:O.baseUrl,localAgentId:P,remoteAgentId:E,sessionId:O.sessionId});let N=await fn.connect({baseUrl:O.baseUrl,localAgentId:P,remoteAgentId:E,remoteSessionId:O.sessionId}),L=await fn.resolve(N.connectionId);return L&&(L.channel=O.channel??C,L.subscriber=O.subscriber),mo.debug("connect: completed",{result:N}),{created:true,connectionId:N.connectionId,sessionId:N.sessionId,remoteAgentId:N.remoteAgentId,baseUrl:N.baseUrl,channel:O.channel??C}}S.connect=e;async function t(A,y){let x=A.agentId??await Uk(y);return (await fn.getConnectionsByLocalAgent(x)).filter(w=>!A.baseUrl||w.baseUrl===A.baseUrl)}S.list=t;async function n(A,y,x){let b=await fn.resolve(A);if(!b)throw new Error("Connection not found");let w=b.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");await Qn.send(w,b.sessionId,y.parts),b.updatedAt=Date.now();}S.send=n;async function o(A,y){let x=await fn.resolve(A);if(!x)throw new Error("Connection not found");let b=x.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");return Qn.capabilities(b)}S.capabilities=o;async function s(A,y){await fn.close(A);}S.close=s;async function r(A,y){let x=await fn.resolve(A);return x?{connectionId:x.connectionId,remoteAgentId:x.remoteAgentId,baseUrl:x.baseUrl,sessionId:x.sessionId,status:x.status,updatedAt:x.updatedAt}:{connectionId:A,status:"unknown"}}S.status=r;async function i(A){let y=await Se(()=>Co.getConfig(),"AGENT_CLIENT_CONFIG_ERROR",A).catch(()=>{}),x=await fn.getAllActiveConnections();return {config:y?.acp,managedConnections:x.length}}S.config=i;async function c(A){return ts.listServices(A)}S.listServices=c;async function l(A){return ts.getService(A)}S.getService=l;async function d(A){return ts.registerService(A)}S.registerService=d;async function m(A,y,x,b){let w=await fn.resolve(A);if(!w)throw new Error("Connection not found");let C={...En,...b},k=w.channel??"http";switch(k){case "websocket":return f(w,C,y);case "http":return a(w,C,y);case "stdio":return p(w,C,y);default:throw new Error(`Unsupported channel type: ${k}`)}}S.subscribe=m;async function f(A,y,x){let b=A.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");return b.subscribe(A.sessionId,x)}async function a(A,y,x,b){let w=A.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");return w.subscribe(A.sessionId,x,b)}async function p(A,y,x,b){let w=A.subscriber;if(!w)throw new Error("Connection not initialized with subscriber");return w.subscribe(A.sessionId,x,b)}async function u(A,y){let x=await fn.resolve(A);if(!x)throw new Error("Connection not found");let b=x.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");await Qn.interrupt(b,x.sessionId);}S.interrupt=u;async function g(A,y,x,b,w){return await n(A,y),m(A,x,b,w)}S.exchangeSubscribe=g;async function h(A,y){let x=await fn.resolve(A);if(!x){mo.warn("Connection not found for releaseSubscription",{connectionId:A});return}let b=x.subscriber;if(!b)throw new Error("Connection not initialized with subscriber");await Qn.releaseSubscription(b,x.sessionId);}S.releaseSubscription=h;})(an||(an={}));var ju=a.create({service:"api"}),Xc=class extends Error{constructor(n,o,s){super(n);b$1(this,"code",o);b$1(this,"details",s);this.name="ApiError";}};async function Se(e,t,n){try{n&&ju.debug(`API call started: ${JSON.stringify(n)}`,{errorCode:t});let o=await _.provide({directory:n?.directory??_.directory,init:void 0,fn:e});return n&&ju.debug(`API call completed: ${JSON.stringify(n)}`,{errorCode:t}),o}catch(o){let s=o instanceof Error?o.message:String(o),r=o instanceof Error?o.name:"Error",i=o instanceof Error?o.stack:void 0;throw ju.error(`API call failed: ${n||t}`,{errorCode:t,errorName:r,error:s,stack:i}),o instanceof Xc?o:new Xc(s,t,o)}}var ko=a.create({service:"tool.agent-client"}),qk=loadTextFile("./agent-client.txt",import.meta.url),Hk=10,Rs=new Map,Ng=De.define("agent_client",{description:qk(),parameters:F.object({operation:F.enum(["connect","list","discover","capabilities","send","status","interrupt","close"]).default("connect").describe("Operation: connect | list | discover | capabilities | send | status | interrupt | close"),baseUrl:F.string().optional().describe("Target easbot service base URL (required for connect operation, e.g. http://127.0.0.1:3000)"),connectionId:F.string().optional().describe("Connection ID from a previous connect operation (auto-resolved if not provided)"),prompt:F.string().optional().describe("Message to send to remote agent (required for send operation)")}),formatValidationError(e){return `Agent client chat tool validation error: ${e.issues.map(n=>n.message).join("; ")}`},async execute(e,t){let n=e.operation??"connect",o=new Set(["connect","capabilities","send","interrupt"]);if(!t.extra?.directory)throw new Error("Directory context is required in ctx.extra.directory");let s={directory:t.extra.directory};if(o.has(n)&&e.baseUrl&&await t.ask({permission:"agent_client",patterns:[e.baseUrl],always:["*"],metadata:{operation:n,baseUrl:e.baseUrl}}),n==="list"){let r=await an.list({baseUrl:e.baseUrl},s);if(r.length===0)return {title:"Connection List",metadata:{count:0},output:`<connections>
786
+ No active connections
787
+ </connections>`};let i=[`<connections total="${r.length}">`];for(let c of r)i.push(`[connection_id="${c.connectionId}"]`),i.push(` baseUrl: ${c.baseUrl}`),i.push(` channel: ${c.channel}`),c.sessionId&&i.push(` sessionId: ${c.sessionId}`),i.push("");return i.push("</connections>"),{title:"Connection List",metadata:{count:r.length},output:i.join(`
788
+ `)}}if(n==="connect"){if(!e.baseUrl)throw new Error("baseUrl required for connect");let r=await an.connect({baseUrl:e.baseUrl},s),i=["<connection>"];return i.push(` connectionId: ${r.connectionId}`),i.push(` baseUrl: ${r.baseUrl}`),i.push(` channel: ${r.channel}`),i.push(` sessionId: ${r.sessionId}`),i.push("</connection>"),{title:"Connection established",metadata:{count:0},output:i.join(`
789
+ `)}}if(n==="discover"){let r=await an.listServices();if(r.length===0)return {title:"Discoverable Services",metadata:{count:0},output:`<services>
790
+ No services discovered
791
+ </services>`};let i=[`<services total="${r.length}">`];for(let c of r)i.push(`- ${c.name} (${c.status}): ${c.baseUrl}`);return i.push("</services>"),{title:"Discoverable Services",metadata:{count:r.length},output:i.join(`
792
+ `)}}if(!e.connectionId){let i=(await an.list({baseUrl:e.baseUrl},s)).at(0);if(i)e.connectionId=i.connectionId;else throw new Error("No active connection found. Please connect first or provide connectionId.")}if(!e.connectionId)throw new Error("connectionId is required");if(n==="close"){await an.interrupt(e.connectionId,s).catch(i=>{ko.warn("interrupt during close failed (connection may already be closed)",{error:i});});let r=Rs.get(e.connectionId);return r&&(r.unsubscribe?.(),Rs.delete(e.connectionId)),await an.close(e.connectionId,s),{title:"Connection closed",metadata:{count:0},output:`<connection>
793
+ connectionId: ${e.connectionId}
794
+ status: closed
795
+ </connection>`}}if(n==="interrupt"){await an.interrupt(e.connectionId,s);let r=Rs.get(e.connectionId);return r&&(r.unsubscribe?.(),Rs.delete(e.connectionId)),{title:"Session Interrupted",metadata:{count:0},output:`<connection>
796
+ connectionId: ${e.connectionId}
797
+ status: interrupted
798
+ </connection>`}}if(n==="capabilities"){let r=await an.capabilities(e.connectionId,s);return {title:"Remote Agent Capabilities",metadata:{count:1},output:JSON.stringify(r,null,2)}}if(n==="status"){let r=await an.status(e.connectionId,s),i=["<connection>"];return i.push(` connectionId: ${e.connectionId}`),r.baseUrl&&i.push(` baseUrl: ${r.baseUrl}`),r.sessionId&&i.push(` sessionId: ${r.sessionId}`),i.push(` status: ${r.status}`),i.push("</connection>"),{title:"Connection Status",metadata:{count:0},output:i.join(`
799
+ `)}}if(n==="send"){if(!e.prompt)throw new Error("prompt required");let r=e.connectionId,i=Rs.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 an.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()},ko.debug("Establishing subscription for Agent-to-Agent interaction",{connectionId:r,sessionId:t.sessionId,remoteSessionId:l.sessionId});let d=await an.subscribe(r,async m=>{if(ko.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,ko.debug("Remote response received, building prompt for local LLM",{connectionId:r,currentRound:i.currentRound,textPreview:m.text?.substring(0,100)??"",error:m.metadata.error});let f=(await Mt.get(t.sessionId)).type==="idle";if(await Je.prompt({sessionId:t.sessionId,parts:[{type:"subtask-result",taskId:i.connectionId,source:"agent-client",agent:"remote-agent",status:m.metadata.error?"error":"completed",result:m.text??"",error:m.metadata.error,rounds:{current:i.currentRound,max:i.maxRounds},thinking:m.thinking,tools:await Promise.all((m.tools??[]).map(async a=>{let p=typeof a.output=="string"?a.output:"",u=await Ve.output(p,{contentType:"output",toolName:a.name});return {name:a.name,status:a.status,output:u.content||void 0}})),metadata:{originalPrompt:i.originalPrompt,remoteAgentId:i.remoteAgentId,baseUrl:i.baseUrl,remoteSessionId:m.metadata.sessionId,connectionId:i.connectionId,tool:"agent_client"},time:{start:i.startedAt,end:Date.now()}}],noReply:!f}),ko.debug("Round completed, keeping connection alive for next round",{connectionId:r,currentRound:i.currentRound,remainingRounds:i.maxRounds-i.currentRound}),i.currentRound>=i.maxRounds){ko.debug("Max rounds reached, closing connection",{connectionId:r,currentRound:i.currentRound,maxRounds:i.maxRounds});try{await an.releaseSubscription(r,s);}catch(a){ko.warn("Failed to release server subscription",{connectionId:r,error:a instanceof Error?a.message:String(a)});}Rs.delete(r);}}},s,{includeThinking:false,includeToolDetails:false,includeToolOutput:false});i.unsubscribe=d,Rs.set(r,i);}ko.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 an.send(r,{sessionId:i.sessionId,parts:[{type:"text",text:`${e.prompt}
800
+
801
+ [async] Agent Client message`}]},s);}catch(l){throw i.hasPendingResponse=false,l}ko.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 ko.debug("Tool execute returning, subscription should trigger callback on remote response",{connectionId:r,pendingRound:c,maxRounds:i.maxRounds}),{title:"Message sent to remote agent",metadata:{count:0,connectionId:r,completedRounds:i.currentRound,pendingRound:c,maxRounds:i.maxRounds},output:`<agent_message>
802
+ connectionId: ${r}
803
+ round: ${i.currentRound}/${i.maxRounds}
804
+ status: Remote agent is processing, response will be injected automatically
805
+ </agent_message>`}}throw new Error(`Unknown operation: ${n}`)}});var fo=a.create({service:"tool.gateway"}),Wk=loadTextFile("./gateway.txt",import.meta.url),Vk=Wk(),Xi=null;async function Kk(){if(Xi)return Xi;try{let e=await c$1(),t=e.path||"",n=t.endsWith("/")?t.slice(0,-1):t,o=`ws://${e.hostname}:${e.port}${n}`;Xi=new kr({url:o,type:"api"});let s=new Promise(i=>{Xi.onStateChange(c=>{c==="connected"?(fo.debug("gateway client connected",{url:o}),i(c)):c==="disconnected"&&i(c);});}),r=await Promise.race([s,new Promise(i=>setTimeout(()=>i("timeout"),1e4))]);return r==="connected"?Xi:(fo.error("failed to connect to gateway",{state:r}),null)}catch(e){return fo.error("failed to connect to gateway",{error:String(e)}),null}}var Jk=F.discriminatedUnion("operation",[F.object({operation:F.literal("status")}),F.object({operation:F.literal("channels")}),F.object({operation:F.literal("sessions"),limit:F.number().optional(),offset:F.number().optional(),type:F.enum(["private","group","all"]).optional().default("all").describe("Filter by chat type: private, group, or all")}),F.object({operation:F.literal("contacts"),platform:F.string().describe("Platform to list contacts (e.g., telegram, discord)"),limit:F.number().optional(),offset:F.number().optional()}),F.object({operation:F.literal("send"),contactUid:F.string().optional().describe('Full Contact UID like "telegram:123456789" (recommended)'),sessionId:F.string().optional().describe("Session ID to use"),content:F.string(),messageType:F.enum(["text","image","file"]).default("text")})]),qg=De.define("gateway",async()=>({description:Vk,parameters:Jk,async execute(e,t){let n=await Kk();if(!n)return {title:"Gateway Not Available",metadata:{available:false},output:"**Error**: Cannot connect to Gateway server"};if(e.operation==="status"){let o=await n.getStatus(),s=o.agents?`
806
+ - **Registered Agents**: ${o.agents.total} (healthy: ${o.agents.healthy}, unhealthy: ${o.agents.unhealthy})`:"";return {title:"Gateway Status",metadata:{connections:o.connections,sessions:o.sessions,messageSubscriptions:o.messageSubscriptions,agentSubscriptions:o.agentSubscriptions,...o.agents?{agents:o.agents}:{}},output:`## Gateway Status
807
+
808
+ - **Status**: ${o.status}
809
+ - **Connections**: ${o.connections}
810
+ - **Sessions**: ${o.sessions}
811
+ - **Message Subscriptions**: ${o.messageSubscriptions}
812
+ - **Agent Subscriptions**: ${o.agentSubscriptions}${s}
813
+ - **Uptime**: ${Yk(o.uptime)}
814
+ - **Version**: ${o.version}`}}if(e.operation==="channels"){let o=await n.listChannels();if(o.channels.length===0)return {title:"Channels",metadata:{count:0},output:"**No channels connected**"};let s=["## Connected Channels"];for(let r of o.channels)s.push(`### ${r.name} (${r.platform})`),s.push(`- ID: ${r.id}`),r.version&&s.push(`- Version: ${r.version}`);return {title:"Channels",metadata:{count:o.channels.length},output:s.join(`
815
+ `)}}if(e.operation==="sessions"){let o=e.limit??50,s=e.offset??0,r=e.type??"all",i=await n.listSessions({limit:o,offset:s}),c=i.sessions.filter(d=>r==="all"?true:r==="private"?d.chatType==="private":r==="group"?d.chatType==="supergroup"||d.chatType==="group":true);if(c.length===0)return {title:"Sessions",metadata:{count:0},output:`**No ${r==="all"?"":r+" "}sessions**`};let l=[`## ${r==="all"?"Active":r.charAt(0).toUpperCase()+r.slice(1)} Sessions (${c.length})`];for(let d of c)l.push(`### ${d.id}`),l.push(`- **Type**: ${d.chatType||"unknown"}`),d.chatTitle&&l.push(`- **Title**: ${d.chatTitle}`),d.platform&&d.userId&&l.push(`- **UID**: ${d.platform}:${d.userId}`),d.channelId&&l.push(`- **Channel**: ${d.channelId}`),l.push(`- **State**: ${d.state}`),l.push(`- **Last Active**: ${Ug(d.lastActiveAt)}`);return i.hasMore&&l.push(`
816
+ *Showing ${c.length} of ${i.total}*`),{title:"Sessions",metadata:{count:i.sessions.length,total:i.total},output:l.join(`
817
+ `)}}if(e.operation==="contacts"){let o=e.platform,s=e.limit??50,r=e.offset??0,i=await n.listContacts(o,{limit:s,offset:r});if(i.contacts.length===0)return {title:"Contacts",metadata:{count:0},output:`**No contacts found on ${o}**`};let c=[`## Contacts on ${o} (${i.total})`];for(let l of i.contacts){let d=l.profile.displayName||l.profile.username||l.stableId;c.push(`### ${d}`),l.profile.username&&c.push(`- **@**: ${l.profile.username}`),c.push(`- **UID**: ${l.uid}`),c.push(`- **Last Seen**: ${Ug(l.lastSeenAt)}`);}return i.hasMore&&c.push(`
818
+ *Showing ${i.contacts.length} of ${i.total}*`),{title:"Contacts",metadata:{count:i.contacts.length,total:i.total,platform:o},output:c.join(`
819
+ `)}}if(e.operation==="send"){if(!e.content)return {title:"Send Message",metadata:{success:false},output:"**Error**: content is required"};if(e.messageType==="image"||e.messageType==="file"){let l=await Qk(t,e.content,e.messageType);if(!l.valid)return {title:"Send Failed",metadata:{success:false},output:`**Error**: ${l.error}`}}let o,s,r,i,c;if(e.contactUid){let[l,d]=e.contactUid.split(":");l&&d&&(r=l,o=d,s=d,i=`${r}-main`,c=`${r}_${i}_${s}_${o}`,fo.debug("built session from contactUid",{contactUid:e.contactUid,sessionId:c}));}else if(e.sessionId){c=e.sessionId;let l=c.split("_");l.length>=3&&(r=l[0],i=l[1],s=l[2],o=l.length>=4?l[3]:s,fo.debug("extracted params from sessionId",{sessionId:c,platform:r,channelId:i,chatId:s,userId:o}));}if(!c||!s)return {title:"Send Failed",metadata:{success:false},output:"**Error**: sessionId or contactUid is required"};if(!i)try{let l=await n.listChannels();l.channels.length>0&&(i=l.channels[0]?.id,r=l.channels[0]?.platform,fo.debug("using first available channel",{channelId:i,platform:r}));}catch(l){fo.warn("failed to get channels",{error:String(l)});}if(!i)return {title:"Send Failed",metadata:{success:false},output:"**Error**: no channel available"};try{let l=await n.getOrCreateSession({sessionId:c,platform:r,channel:i,userId:o,chatId:s});c=l.sessionId,fo.debug("session ensured",{sessionId:c,created:l.created});}catch(l){return fo.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(_.directory,f);return pathToFileURL(a).href}catch{return f}},d=e.messageType==="text"?[{type:"text",text:e.content}]:e.messageType==="image"?[{type:"image",image:l(e.content)}]:[{type:"file",data:l(e.content)}],m=await n.sendMessage(c,{content:d,channel:i,userId:o,chatId:s,processorId:"gateway",agent:t?.agent??"gateway"});return fo.debug("message sent via HTTP API",{messageId:m.messageId,sessionId:c}),{title:"Message Sent",metadata:{success:!0,messageId:m.messageId,sessionId:c},output:`## Message Sent
820
+
821
+ - **Message ID**: ${m.messageId}
822
+ - **Session ID**: ${c}
823
+ ${r&&o?`- **Contact UID**: ${r}:${o}`:""}
824
+ - **Content**: ${l(e.content).length>100?l(e.content).slice(0,100)+"...":l(e.content)}`}}catch(l){return fo.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 Yk(e){let t=Math.floor(e/1e3),n=Math.floor(t/60),o=Math.floor(n/60),s=Math.floor(o/24);return s>0?`${s}d ${o%24}h ${n%60}m`:o>0?`${o}h ${n%60}m`:n>0?`${n}m ${t%60}s`:`${t}s`}function Ug(e){let t=new Date(e),o=new Date().getTime()-t.getTime();return o<6e4?"just now":o<36e5?`${Math.floor(o/6e4)}m ago`:o<864e5?`${Math.floor(o/36e5)}h ago`:t.toISOString().replace("T"," ").slice(0,19)}function Xk(e){let t=e.trim();if(t.startsWith("file://")&&(t=t.slice(7)),Filesystem.isAbsolute(t))return Filesystem.normalize(t);let n=Ce__default.resolve(_.directory,t);return Filesystem.normalize(n)}async function Qk(e,t,n){let o=Xk(t),s=Filesystem.stat(o);if(!s){let i=Filesystem.dirname(o),c=Filesystem.basename(o),l=await Tt.readdir(i).then(d=>d.filter(m=>m.toLowerCase().includes(c.toLowerCase())||c.toLowerCase().includes(m.toLowerCase())).map(m=>Filesystem.join(i,m)).slice(0,3)).catch(()=>[]);return l.length>0?{valid:false,error:`File not found: ${o}
825
+
826
+ Did you mean one of these?
827
+ ${l.join(`
828
+ `)}`}:{valid:false,error:`File not found: ${o}`}}if(s.isDirectory())return {valid:false,error:`Path is a directory, not a file: ${o}`};await Yt(e,o,{bypass:!!e.extra?.bypassCwdCheck,kind:"file",tool:"gateway"});let r=Ce__default.posix.relative(_.worktree,o);return await e.ask({permission:"read",patterns:[r],always:["*"],metadata:{}}),{valid:true,filePath:o}}var eP=loadTextFile("./question.txt",import.meta.url),tP=eP(),Bg=De.define("question",{isEnabled:()=>["app","cli","desktop"].includes(a$2.EASBOT_CLIENT)||a$2.EASBOT_ENABLE_QUESTION_TOOL,description:tP,parameters:F.object({questions:F.array(Ot.Info).describe("Questions to ask")}),async execute(e,t){let n=await Ot.ask({sessionId:t.sessionId,questions:e.questions,tool:t.callId?{messageId:t.messageId,callId:t.callId}:void 0});function o(r){return !r||r.length===0?"Unanswered":r.join(", ")}let s=e.questions.map((r,i)=>`"${r.question}"="${o(n[i])}"`).join(", ");return {title:`Asked ${e.questions.length} question${e.questions.length>1?"s":""}`,output:`User has answered your questions: ${s}. You can now continue with the user's answers in mind.`,metadata:{answers:n}}}});var Gg=a.create({service:"tool.registry"}),nP=[cg,Bg,Ff,hg,gg,yc,Vf,bc,Qf,qc,ag,$g,Fi,rg,tg,yg,wg,vg,Pg,Tg,Ng,qg,ug,Dg,Ag,Zf,Mg],zn;(p=>{let e,t;async function n(){let u={},{Filesystem:g}=await import('@easbot/utils'),{glob:h}=await import('glob');for await(let S of g.up({targets:[".easbot/tools"],start:_.directory,stop:_.worktree})){if(!await g.isDir(S))continue;let A=await h("*.{ts,js}",{cwd:S,absolute:true,nodir:true,follow:false,dot:false});for(let y of A)try{let x=g.extname(y),b=g.basename(y,x),{pathToFileURL:w}=await import('url'),C=await import(w(y).href);for(let[k,P]of Object.entries(C)){let E=k==="default"?b:`${b}_${k}`;u[E]={...P,id:E,source:"custom"};}}catch(x){Gg.error("Failed to load tool file",{file:y,error:x});}}return u}function o(){return e||(e=_.state(async()=>{let u={};for(let h of nP)h.isEnabled&&!await h.isEnabled()||(u[h.id]={...h,source:"builtin"});let g=await n();for(let[h,S]of Object.entries(g))u[h]||(u[h]=S);if(t)for(let[h,S]of Object.entries(t))u[h]=S;return u})),e}async function s(){return o()()}p.state=s;async function r(){return s().then(u=>Object.values(u))}p.all=r;async function i(){return s().then(u=>Object.keys(u))}p.ids=i;async function c(u,g){let h=await r();return (await Promise.all(h.map(async A=>{let x=(await Le.triggerEvent(HookEvent.ToolDefinition,A)).output;if(x.isEnabled&&!await x.isEnabled())return null;let b=await x.init({agent:g});return {id:x.id,init:x.init,scope:x.scope,isEnabled:x.isEnabled,...b}}))).filter(A=>A!==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(),Gg.debug("tool registry initialized");}p.init=a;})(zn||(zn={}));var Zc=a.create({service:"tool.builder"}),ed;(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 X.updatePart({...m,state:{title:d.title,metadata:d.metadata,status:"running",input:c,time:{start:Date.now()}}});},ask:async d=>{await Me.ask({...d,sessionId:i.sessionId,tool:{messageId:i.processor?.message.id??"",callId:l.toolCallId??""},ruleset:Me.merge(i.agent.permission,i.session.permission??[])});}})}async function t(i$1){var P=[];try{let{agent:c$1,session:l,model:d,userTools:m,messages:f,userMessageId:a,processor:p,bypassAgentCheck:u,protocolMetadata:g,includeMCP:h=!0,includeBuiltIn:S=!0,toolFilter:A}=i$1;let y=c(P,Zc.time("buildTools"));let x=l.id;let b=l.contextMode??f$1;let w=e({sessionId:x,session:l,agent:c$1,model:d,agentName:c$1.name,messages:f??[],protocolMetadata:g,bypassAgentCheck:u,processor:p,userMessageId:a});let C={};if(S){let L=await zn.tools({providerId:d.providerId,modelId:d.api.id},c$1);for(let K of L){if(A&&!A(K.id))continue;let Q=K.scope??i;if(Q!=="all"&&Q!==b)continue;let ue=wt.schema(d,rP.toJSONSchema(K.parameters));C[K.id]=tool({description:K.description,inputSchema:jsonSchema(ue),async execute(D,I){let M=w(D,I);await Le.triggerEvent(HookEvent.ToolBefore,{tool:K.id,sessionId:M.sessionId,userMessageId:a,callId:M.callId??""},{sessionId:M.sessionId});let v=await K.execute(D,M);return await Le.triggerEvent(HookEvent.ToolAfter,{tool:K.id,sessionId:M.sessionId,userMessageId:a,callId:M.callId??"",args:D},{sessionId:M.sessionId}),v}});}}if(h)try{let L=await ze.tools(),K=await ze.configInfo();for(let[Q,ue]of Object.entries(L)){if(A&&!A(Q))continue;let D=Q.split("_")[0];if(D){let v=K[D];if(v){let T=v.scope??i;if(T!=="all"&&T!==b)continue}}let I=ue.execute;if(!I)continue;let M=wt.schema(d,await asSchema(ue.inputSchema).jsonSchema);ue.inputSchema=jsonSchema(M),ue.execute=async(v,T)=>{let R=w(v,T);await Le.triggerEvent(HookEvent.ToolBefore,{tool:Q,sessionId:R.sessionId,userMessageId:a,callId:T.toolCallId},{sessionId:R.sessionId}),await R.ask({permission:Q,metadata:{},patterns:["*"],always:["*"]});let j=await I(v,T);await Le.triggerEvent(HookEvent.ToolAfter,{tool:Q,sessionId:R.sessionId,userMessageId:a,callId:T.toolCallId,args:v},{sessionId:R.sessionId});let U=[],Y=[];for(let se of j.content)if(se.type==="text")U.push(se.text);else if(se.type==="image")Y.push({id:Identifier.ascending("part"),sessionId:x,messageId:p?.message.id??"",type:"file",mime:se.mimeType,url:`data:${se.mimeType};base64,${se.data}`});else if(se.type==="resource"){let{resource:ae}=se;ae.text&&U.push(ae.text),ae.blob&&Y.push({id:Identifier.ascending("part"),sessionId:x,messageId:p?.message.id??"",type:"file",mime:ae.mimeType??"application/octet-stream",url:`data:${ae.mimeType??"application/octet-stream"};base64,${ae.blob}`,filename:ae.uri});}let J=await Ve.output(U.join(`
829
+
830
+ `),{},c$1);return {title:"",metadata:{...j.metadata??{},truncated:J.truncated,...J.truncated&&{outputPath:J.outputPath}},output:J.content,attachments:Y,content:j.content}},C[Q]=ue;}}catch(L){Zc.error("Failed to load MCP tools",{error:L});}let k=n(C,c$1,m);Zc.debug("built tools",{count:Object.keys(k).length,includeBuiltIn:S,includeMCP:h,contextMode:b,userToolsDisabled:Object.entries(m??{}).filter(([,L])=>L===!1).map(([L])=>L)});return k}catch(E){var O=E,N=true;}finally{d(P,O,N);}}r.buildTools=t;function n(i,c,l){let d=Me.disabled(Object.keys(i),c.permission),m={...i};for(let f of Object.keys(m))(l?.[f]===false||d.has(f))&&delete m[f];return m}async function o(i={}){let{includeMCP:c=true,includeBuiltIn:l=true,toolFilter:d}=i,m=[];if(l){let f=await zn.ids();for(let a of f)d&&!d(a)||m.push(a);}if(c)try{let f=await ze.tools();for(let a of Object.keys(f))d&&!d(a)||m.includes(a)||m.push(a);}catch(f){Zc.error("Failed to load MCP tools",{error:f});}return m}r.listTools=o;async function s(i){let c=await zn.ids();if(Array.isArray(c)&&c.includes(i))return true;try{let l=await ze.tools();return i in l}catch{return false}}r.hasTool=s;})(ed||(ed={}));globalThis.AI_SDK_LOG_WARNINGS=false;var Je;(y=>{let e$1=a.create({service:"session.prompt"}),t;function n(){return t||(t=_.state(()=>({}),async x=>{for(let b of Object.values(x))b.abort.abort();})),t}function o(){return n()()}y.state=o;function s(x){if(o()[x])throw new X.BusyError(x)}y.assertNotBusy=s,y.PromptInput=F.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message").optional(),model:F.object({providerId:F.string(),modelId:F.string()}).optional(),agent:F.string().optional(),contextMode:F.enum(e).optional(),noReply:F.boolean().optional(),tools:F.record(F.string(),F.boolean()).optional().describe("@deprecated tools and permissions have been merged, you can set permissions on the session itself now"),system:F.string().optional(),variant:F.string().optional(),parts:F.array(F.discriminatedUnion("type",[ve.TextPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"TextPartInput"}),ve.FilePart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"FilePartInput"}),ve.AgentPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"AgentPartInput"}),ve.SubtaskPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"SubtaskPartInput"}),ve.SubtaskResultPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"SubtaskResultPartInput"}),ve.MemoryPart.omit({messageId:true,sessionId:true}).partial({id:true}).meta({ref:"MemoryPartInput"})]))}),y.prompt=fn$1(y.PromptInput,async x=>{let b=await X.get(x.sessionId);await ao.cleanup(b),x.contextMode&&(await X.update(b.id,k=>{k.contextMode=x.contextMode;}),b.contextMode=x.contextMode);let w=await p(x);await X.touch(x.sessionId);let C=[];for(let[k,P]of Object.entries(x.tools??{}))C.push({permission:k,action:P?"allow":"deny",pattern:"*"});return C.length>0&&(b.permission=C,await X.update(b.id,k=>{k.permission=C;})),x.noReply===true?w:(0, y.loop)({sessionId:x.sessionId})});async function c$1(x){let b=[{type:"text",text:x}],w=a$9.files(x),C=new Set;return await Promise.all(w.map(async k=>{let P=k[1];if(!P||C.has(P))return;C.add(P);let E=P.startsWith("~/")?Ce__default.join(sc.homedir(),P.slice(2)):Ce__default.resolve(_.worktree,P),O=await Tt__default.stat(E).catch(()=>{});if(O){if(O.isDirectory()){b.push({type:"file",url:pathToFileURL(E).href,filename:P,mime:"application/x-directory"});return}b.push({type:"file",url:pathToFileURL(E).href,filename:P,mime:"text/plain"});}})),b}y.resolvePromptParts=c$1;function l(x){let b=o();if(b[x])return;let w=new AbortController;return b[x]={abort:w,callbacks:[]},w.signal}y.start=l;function d$1(x){let b=o();if(b[x])return b[x].abort.signal}y.resume=d$1;async function m(x){e$1.debug("cancel",{sessionId:x});let b=o(),w=b[x];if(!w){await Mt.set(x,{type:"idle"});return}for(let C of w.callbacks)C.reject(new Error("Session aborted"));w.callbacks=[],w.abort.abort(),delete b[x],await Mt.set(x,{type:"idle"});}y.cancel=m,y.LoopInput=F.object({sessionId:Identifier.schema("session"),resume_existing:F.boolean().optional()}),y.loop=fn$1(y.LoopInput,async x=>{var ue=[];try{let{sessionId:b,resume_existing:w}=x;let C=w?d$1(b):l(b);if(!C)return new Promise((T,R)=>{let j=o()[b]?.callbacks;if(!j){let U=o()[b]?.callbacks;U&&U.push({resolve:T,reject:R});return}j.push({resolve:T,reject:R});});let k=c(ue,defer(async()=>await m(b)),!0);let P=0;let E=await X.get(b);for(;;){var O=[];try{await Mt.set(b,{type:"busy"});e$1.debug("loop",{step:P,sessionId:b});if(C.aborted)break;let T=await Le.triggerEvent(HookEvent.LoopStart,{sessionId:b,step:P,lastUserId:"",result:"start"},{sessionId:b});if(T.modified&&T.output?.result==="stop"){e$1.debug("exiting loop due to hook",{sessionId:b});break}let R=await ve.filterCompacted(ve.stream(b));let j;let U;let Y;let J;let ee=[];for(let ce=R.length-1;ce>=0;ce--){let ye=R[ce];if(!ye)continue;if(!j&&ye.info.role==="user"&&(j=ye.info,U=ye),!Y&&ye.info.role==="assistant"&&(Y=ye.info),!J&&ye.info.role==="assistant"&&ye.info.finish&&(J=ye),j&&J)break;let je=ye.parts.filter(Ie=>Ie.type==="compaction"||Ie.type==="subtask");je.length>0&&!J&&ee.push(...je);}if(!j)throw new Error("No user message found in stream. This should never happen.");if(Y?.finish&&!["tool-calls","unknown"].includes(Y.finish)&&j.id<Y.id){e$1.debug("exiting loop",{sessionId:b});break}P++;P===1&&await A({session:E,modelId:j.model.modelId,providerId:j.model.providerId,history:R});let se=await xe.getModel(j.model.providerId,j.model.modelId).catch(async ce=>{if(xe.ModelNotFoundError.isInstance(ce)){let ye=ce.data.suggestions&&ce.data.suggestions.length>0?` Did you mean: ${ce.data.suggestions.join(", ")}?`:"";await pe.publish(X.Event.Error,{sessionId:b,error:new NamedError.Unknown({message:`Model not found: ${ce.data.providerId}/${ce.data.modelId}.${ye}`}).toObject()});}throw ce});let ae=ee.pop();if(ae?.type==="subtask"){let ce=await Fi.init(),ye=ae.model?await xe.getModel(ae.model.providerId,ae.model.modelId):se,je=await X.updateMessage({id:Identifier.ascending("message"),role:"assistant",parentId:j.id,sessionId:b,mode:ae.agent,agent:ae.agent,variant:j.variant,path:{cwd:_.directory,root:_.worktree},cost:0,tokens:{input:0,output:0,reasoning:0,cache:{read:0,write:0}},modelId:ye.id,providerId:ye.providerId,time:{created:Date.now()}}),Ie=await X.updatePart({id:Identifier.ascending("part"),messageId:je.id,sessionId:je.sessionId,type:"tool",callId:ulid(),tool:Fi.id,state:{status:"running",input:{prompt:ae.prompt,description:ae.description,subagent_type:ae.agent,command:ae.command},time:{start:Date.now()}}}),ke={operation:"create",prompt:ae.prompt,description:ae.description,subagent_type:ae.agent};await Le.triggerEvent(HookEvent.ToolBefore,{tool:"task",sessionId:b,userMessageId:je.parentId,callId:Ie.id},{sessionId:b});let re,$e=await Ue.get(ae.agent);if(!$e)throw new Error(`Task agent not found: ${ae.agent}`);let Ae={agent:ae.agent,messageId:je.id,sessionId:b,abort:C,callId:Ie.callId,extra:{bypassAgentCheck:!0},messages:R,async metadata(Ct){await X.updatePart({...Ie,type:"tool",state:{...Ie.state,...Ct}});},async ask(Ct){await Me.ask({...Ct,sessionId:b,ruleset:Me.merge($e.permission,E.permission??[])});}},pt=await ce.execute(ke,Ae).catch(Ct=>{re=Ct,e$1.error("subtask execution failed",{error:Ct,agent:ae.agent,description:ae.description});});if(await Le.triggerEvent(HookEvent.ToolAfter,{tool:"task",sessionId:b,userMessageId:je.parentId,callId:Ie.id,args:ke},{sessionId:b}),je.finish="tool-calls",je.time.completed=Date.now(),await X.updateMessage(je),pt&&Ie.state.status==="running"){let Ct;pt.attachments&&pt.attachments.length>0&&(Ct=pt.attachments.map(dn=>({...dn,id:dn.id??Identifier.ascending("part"),sessionId:dn.sessionId??Ie.sessionId,messageId:dn.messageId??Ie.messageId}))),await X.updatePart({...Ie,state:{status:"completed",input:Ie.state.input,title:pt.title,metadata:pt.metadata,output:pt.output,attachments:Ct,time:{...Ie.state.time,end:Date.now()}}});}if(pt||await X.updatePart({...Ie,state:{status:"error",error:re?`Tool execution failed: ${re.message}`:"Tool execution failed",time:{start:Ie.state.status==="running"?Ie.state.time.start:Date.now(),end:Date.now()},metadata:Ie.metadata,input:Ie.state.input}}),ae.command){let Ct={id:Identifier.ascending("message"),sessionId:b,role:"user",time:{created:Date.now()},agent:j.agent,model:j.model};await X.updateMessage(Ct),await X.updatePart({id:Identifier.ascending("part"),messageId:Ct.id,sessionId:b,type:"text",text:"Summarize the task tool output above and continue with your task.",synthetic:!0});}continue}if(ae?.type==="compaction"){if(await sn.compactConversation({messages:R,parentId:j.id,abort:C,sessionId:b,auto:ae.auto})==="stop")break;continue}let we=await Ue.get(j.agent);if(!we)throw new Error(`Agent not found: ${j.agent}`);let ie=we.steps??1/0;let Z=P>=ie;let H=vr.create({assistantMessage:await X.updateMessage({id:Identifier.ascending("message"),parentId:j.id,role:"assistant",mode:we.name,agent:we.name,variant:j.variant,path:{cwd:_.directory,root:_.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:C});let $=c(O,defer(()=>ks.clear(H.message.id)),!0);let te=R.findLast(ce=>ce.info.role==="user");let W=te?.parts.some(ce=>ce.type==="agent")??!1;let V=await go.getProtocolMetadata(we);let oe=await ed.buildTools({agent:we,session:E,model:se,userTools:j.tools,processor:{message:{id:H.message.id,parentId:H.message.parentId},partFromToolCall:ce=>H.partFromToolCall(ce)},bypassAgentCheck:W,messages:R,protocolMetadata:V,userMessageId:H.message.parentId});let de=await go.build({sessionId:b,userMessage:U,user:j,messages:R,model:se,agent:we,session:E,tools:oe,isLastStep:Z,step:P,lastFinished:J,maxMessages:100,mode:E.contextMode});if(de.metadata.needsCompaction){await sn.create({sessionId:b,agent:"compaction",model:j.model,auto:!0});continue}let me=await H.process({user:j,agent:we,abort:C,sessionId:b,system:de.system,messages:de.messages,tools:oe,model:se,mode:de.metadata.mode});if(me==="stop"){let ce=await Le.triggerEvent(HookEvent.LoopEnd,{sessionId:b,step:P,lastUserId:j.id,result:"stop"},{sessionId:b});if(ce.modified&&ce.output.result==="continue")continue;break}me==="compact"&&await sn.create({sessionId:b,agent:"compaction",model:j.model,auto:!0});}catch(N){var L=N,K=!0;}finally{var Q=d(O,L,K);Q&&await Q;}}await sn.prune({sessionId:b});for await(let T of ve.stream(b)){if(T.info.role==="user")continue;let R=o()[b]?.callbacks??[];for(let j of R)j.resolve(T);return T}throw new Error("Impossible")}catch(D){var I=D,M=true;}finally{var v=d(ue,I,M);v&&await v;}});async function p(x){var N=[];try{let b=await Ue.get(x.agent??await Ue.defaultAgent());if(!b)throw new Error(`Agent not found: ${x.agent}`);let w=x.model??b.model??await Zo(x.sessionId);let C=!x.variant&&b.variant&&w.providerId?await xe.getModel(w.providerId,w.modelId).catch(()=>{}):void 0;let k=x.variant??(b.variant&&C?.variants?.[b.variant]?b.variant:void 0);let P={id:x.messageId??Identifier.ascending("message"),role:"user",sessionId:x.sessionId,time:{created:Date.now()},tools:x.tools,agent:b.name,model:{providerId:w.providerId,modelId:w.modelId},system:x.system,variant:k};let E=c(N,defer(()=>ks.clear(P.id)),!0);let O=await Promise.all(x.parts.map(async D=>{if(D.type==="file"){if(D.source?.type==="resource"){let{clientName:M,uri:v}=D.source;e$1.debug("mcp resource",{clientName:M,uri:v,mime:D.mime});let T=[{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Reading MCP resource: ${D.filename} (${v})`}];try{let R=await ze.readResource(M,v);if(!R)throw new Error(`Resource not found: ${M}/${v}`);let j=Array.isArray(R.contents)?R.contents:[R.contents];for(let U of j)if("text"in U&&U.text)T.push({id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:U.text});else if("blob"in U&&U.blob){let Y="mimeType"in U?U.mimeType:D.mime;T.push({id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`[Binary content: ${Y}]`});}T.push({...D,id:D.id??Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId});}catch(R){e$1.error("failed to read MCP resource",{error:R,clientName:M,uri:v});let j=R instanceof Error?R.message:String(R);T.push({id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Failed to read MCP resource ${D.filename}: ${j}`});}return T}let I=new URL(D.url);switch(I.protocol){case "data:":if(D.mime==="text/plain")return [{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify({filePath:D.filename})}`},{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:Buffer.from(D.url,"base64url").toString()},{...D,id:D.id??Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId}];break;case "file:":{e$1.debug("file",{mime:D.mime});let M=fileURLToPath(D.url),v;try{v=await Tt__default.stat(M);}catch{v=void 0;}if(v?.isDirectory()&&(D.mime="application/x-directory"),D.mime==="text/plain"){let T,R,j={start:I.searchParams.get("start"),end:I.searchParams.get("end")};if(j.start!=null){let J=D.url.split("?")[0]??"",ee=parseInt(j.start,10),se=j.end?parseInt(j.end,10):void 0;if(ee===se){let ae=fileURLToPath(J),we=await We.documentSymbol({file:ae}).catch(()=>[]);for(let ie of we){let Z;if("range"in ie?Z=ie.range:"location"in ie&&(Z=ie.location.range),Z?.start?.line&&Z?.start?.line===ee){ee=Z.start.line,se=Z?.end?.line??ee;break}}}T=Math.max(ee-1,0),se&&(R=se-T);}let U={filePath:M,offset:T,limit:R},Y=[{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Called the Read tool with the following input: ${JSON.stringify(U)}`}];return await yc.init().then(async J=>{let ee=await xe.getModel(P.model.providerId,P.model.modelId),se={sessionId:x.sessionId,abort:new AbortController().signal,agent:x.agent,messageId:P.id,extra:{bypassCwdCheck:!0,model:ee},messages:[],metadata:async()=>{},ask:async()=>{}},ae=await J.execute(U,se);Y.push({id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:ae.output}),ae.attachments&&ae.attachments.length>0?Y.push(...ae.attachments.map(we=>({...we,id:we.id??Identifier.ascending("part"),synthetic:!0,filename:we.filename??D.filename,messageId:P.id,sessionId:x.sessionId}))):Y.push({...D,id:D.id??Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId});}).catch(async J=>{e$1.error("failed to read file",{error:J});let ee=J instanceof Error?J.message:J.toString();await pe.publish(X.Event.Error,{sessionId:x.sessionId,error:new NamedError.Unknown({message:ee}).toObject()}),Y.push({id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Read tool failed to read ${M} with the following error: ${ee}`});}),Y}if(D.mime==="application/x-directory"){let T={path:M,limit:100},R={sessionId:x.sessionId,abort:new AbortController().signal,agent:x.agent,messageId:P.id,extra:{bypassCwdCheck:!0},messages:[],metadata:async()=>{},ask:async()=>{}},j=await bc.init().then(U=>U.execute(T,R));return [{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:`Called the list tool with the following input: ${JSON.stringify(T)}`},{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:j.output},{...D,id:D.id??Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId}]}else {let T=await Tt__default.readFile(M);return An.read(x.sessionId,M),[{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",text:`Called the Read tool with the following input: {"filePath":"${M}"}`,synthetic:!0},{id:D.id??Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"file",url:`data:${D.mime};base64,`+Buffer.from(T).toString("base64"),mime:D.mime,filename:D.filename,source:D.source}]}}}}if(D.type==="agent"){let M=Me.evaluate("task",D.name,b.permission).action==="deny"?" . Invoked by user; guaranteed to exist.":"";return [{id:Identifier.ascending("part"),...D,messageId:P.id,sessionId:x.sessionId},{id:Identifier.ascending("part"),messageId:P.id,sessionId:x.sessionId,type:"text",synthetic:!0,text:" Use the above message and context to generate a prompt and call the task tool with subagent: "+D.name+M}]}return [{id:Identifier.ascending("part"),...D,messageId:P.id,sessionId:x.sessionId}]})).then(D=>D.flat());await Le.triggerEvent(HookEvent.MessageReceive,{sessionId:x.sessionId,agent:x.agent,model:x.model,userMessageId:P.id,messageId:x.messageId,variant:x.variant});await X.updateMessage(P);for(let D of O)await X.updatePart(D);return {info:P,parts:O}}catch(L){var K=L,Q=true;}finally{var ue=d(N,K,Q);ue&&await ue;}}y.ShellInput=F.object({sessionId:Identifier.schema("session"),agent:F.string(),model:F.object({providerId:F.string(),modelId:F.string()}).optional(),command:F.string()});async function g(x){return zi.shell(x)}y.shell=g,y.CommandInput=F.object({messageId:Identifier.schema("message").optional(),sessionId:Identifier.schema("session"),agent:F.string().optional(),model:F.string().optional(),contextMode:F.enum(e).optional(),arguments:F.union([F.string(),F.record(F.string(),F.unknown())]),command:F.string(),variant:F.string().optional(),parts:F.array(F.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 S(x){return x.contextMode&&await X.update(x.sessionId,b=>{b.contextMode=x.contextMode;}),zi.execute(x)}y.command=S;async function A(x){if(x.session.parentId||!X.isDefaultTitle(x.session.title))return;let b=x.history.findIndex(Q=>Q.info.role==="user"&&!Q.parts.every(ue=>"synthetic"in ue&&ue.synthetic));if(b===-1||!(x.history.filter(Q=>Q.info.role==="user"&&!Q.parts.every(ue=>"synthetic"in ue&&ue.synthetic)).length===1))return;let C=x.history.slice(0,b+1),k=C[b];if(!k)return;let P=k.parts.filter(Q=>Q.type==="subtask"),E=P.length>0&&k.parts.every(Q=>Q.type==="subtask"),O=await Ue.get("title");if(!O)return;let N=await iife(async()=>O.model?await xe.getModel(O.model.providerId,O.model.modelId):await xe.getSmallModel(x.providerId)??await xe.getModel(x.providerId,x.modelId)),L=await Xo.stream({agent:O,user:k.info,system:[O.prompt??""],small:true,tools:{},model:N,abort:new AbortController().signal,sessionId:x.session.id,retries:2,messages:[{role:"user",content:`Generate a title for this conversation:
831
+ `},...E?[{role:"user",content:P.map(Q=>Q.prompt).join(`
832
+ `)}]:await ve.toModelMessages(C,N)]}),K=await Promise.resolve(L.text).catch(Q=>{e$1.error("failed to generate title",{error:Q});});if(K)return X.update(x.session.id,Q=>{let ue=K.replace(/<think>[\s\S]*?<\/think>\s*/g,"").split(`
833
+ `).map(I=>I.trim()).find(I=>I.length>0);if(!ue)return;let D=ue.length>100?ue.substring(0,97)+"...":ue;Q.title=D;},{touch:false})}})(Je||(Je={}));var Qi=a.create({service:"forked-agent"}),Pr;(n=>{async function e(o){let{source:s,title:r,agent:i,parts:c,model:l,system:d,tools:m,syncMessages:f,metadata:a}=o,p=await X.fork({sessionId:s});try{let u=await Lm(s),g=i??u?.agent??await Ue.defaultAgent(),h;if(l?.providerId&&l.modelId?h={providerId:l.providerId,modelId:l.modelId}:h=(await Ue.get(g))?.model,!l){let{Provider:x}=await import('./provider-RGQTLMFK.mjs');h=u?.model??await x.defaultModel();}Qi.debug("forked started and session created",{sessionId:p.id,source:s,title:r,agent:g,model:h}),await Je.prompt({sessionId:p.id,system:d,tools:m,agent:g,model:h,parts:c??[]}),Qi.debug("forked agent prompt sent",{sessionId:p.id,agent:g});let S=await ve.getLastMessages(p.id,{filterByText:!0}),A="";S.lastAssistantWithText&&(A=S.lastAssistantWithText.parts.filter(x=>x.type==="text").map(x=>x.text).join(""));let y={title:r,output:A,metadata:{...a,sessionId:p.id,source:s,agent:g,userMessage:S.lastUser,assistantMessage:S.lastAssistant}};if(f&&S.lastUser&&S.lastFinished){let x=await t(p.id,s,S,g);y.metadata.userMessage=x.userMessage,y.metadata.assistantMessage=x.assistantMessage;}return Qi.debug("forked agent completed",{sessionId:p.id,source:s,title:r,agent:g,contentLength:A.length,hasText:A.length>0,lastUser:S.lastUser?.id,lastAssistant:S.lastAssistant?.id,lastFinished:S.lastFinished?.info?.id}),y}finally{await X.remove(p.id),Qi.debug("forked session removed",{sessionId:p.id});}}n.run=e;async function t(o,s,r,i){if(!r.lastUser||!r.lastFinished)throw new Error("Messages not found in forked session");let c=i??r.lastUser.agent??await Ue.defaultAgent(),l=Identifier.ascending("message"),d={...r.lastUser,id:l,agent:c,sessionId:s};await X.updateMessage(d);for(let a of r.lastUserMessage.parts)await X.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 X.updateMessage(f);for(let a of r.lastFinished.parts)await X.updatePart({...a,id:Identifier.ascending("part"),messageId:m,sessionId:s});return Qi.debug("messages synced",{fromSessionID:o,toSessionID:s,userMessageId:l,assistantMessageId:m}),{userMessage:d,assistantMessage:f}}n.syncMessagesToParent=t;})(Pr||(Pr={}));var cs=a.create({service:"hook.builtin.memory"}),eh=2e3,$u=new Map;function th(e,t){return `${e}:${t??"default"}`}async function pP(e,t,n){let o=[];if(t){let r=t.parts.filter(i=>i.type==="text").map(i=>i.text).join("");r&&o.push({role:"user",content:r});}let s=await ve.get({sessionId:e,messageId:n});if(s){let r=s.parts.filter(i=>i.type==="text").map(i=>i.text).join("");r&&o.push({role:"assistant",content:r});}return o}async function mP(e){if(e.length===0)return "";let t=`### Our Conversation
834
+
835
+ `;for(let n of e.slice(-4)){let o=Token.estimate(n.content),s=n.content,r=false;if(o>eh){s=n.content.slice(-8e3),r=true;}r?t+=`**${n.role==="user"?"User":"Me"}**: ${s}
836
+
837
+ [Content truncated from ${o} tokens]
838
+
839
+ `:t+=`**${n.role==="user"?"User":"Me"}**: ${s||"(empty)"}
840
+
841
+ `;}return t}function fP(){return `### My Reflection
842
+
843
+ After reading this conversation, I ask myself:
844
+
845
+ **Mistakes & Corrections:**
846
+ - Did I make any mistakes the user corrected?
847
+ - What errors should I avoid next time?
848
+ - Is there a pattern I keep getting wrong?
849
+
850
+ **Better Approaches:**
851
+ - Was there a smarter way to solve this?
852
+ - What approach would be more efficient?
853
+ - Any workflow improvements I discovered?
854
+
855
+ **Knowledge & Context:**
856
+ - What new insights did I gain?
857
+ - What preferences did the user show?
858
+ - What context is important for future work?
859
+
860
+ **Evolution:**
861
+ - How can I do better next time?
862
+ - What should I remember to improve my effectiveness?
863
+
864
+ If nothing special happened, don't save anything.
865
+
866
+ Importance 1-10, skip 1-3`}var Fu=zt("memory",{async init(){return await In.isEnabled()?{isEnabled:()=>true,handlers:[{name:HookEvent.StepStart,handler:(t,n)=>{let o=t;if(!o.userMessageId)return {modified:false,input:t};let s=th(o.sessionId,o.userMessageId);return $u.set(s,{startTime:Date.now()}),cs.debug("step start recorded",{key:s}),{modified:false,input:t}}},{name:HookEvent.StepFinish,handler:async(t,n)=>{let o=t;if(!o.userMessageId)return cs.debug("step.finish: no userMessageId, skip"),{modified:false,input:t};let s=th(o.sessionId,o.userMessageId);cs.debug("step.finish: memory extract started",{convKey:s,finishReason:o.finishReason,messageId:o.messageId});let r=await ve.get({sessionId:o.sessionId,messageId:o.userMessageId});if(r?.parts.some(u=>u.type==="memory"))return cs.debug("step.finish: skip memory extract, already processing"),{modified:false,input:t};let i=Identifier.ascending("part"),c=Date.now(),l={id:i,sessionId:o.sessionId,messageId:o.userMessageId,type:"memory",status:"processing",time:{start:c}};await X.updatePart(l);let d=$u.get(s);$u.delete(s);let m="";d&&(m=`Step Duration: ${((Date.now()-d.startTime)/1e3).toFixed(1)}s`);let f=await pP(o.sessionId,r,o.messageId);if(!f.some(u=>u.role==="assistant"&&u.content))return cs.debug("step.finish: skip memory extract, no assistant text content",{convKey:s,finishReason:o.finishReason,messageId:o.messageId}),await X.updatePart({...l,status:"skipped",time:{start:c,end:Date.now()},reason:`No assistant text content (finish: ${o.finishReason})`}),{modified:false,input:t};let p=`## Conversation Reflection
867
+
868
+ Local Time: ${formatLocalISOCompact(new Date)}
869
+ Finish Reason: ${o.finishReason}
870
+ ${m?`${m}
871
+ `:""}${o.tokens?`Tokens Used: ${o.tokens.total??0}
872
+ `:""}}
873
+
874
+ ${await mP(f)}
875
+
876
+ ${fP()}`;return Pr.run({source:o.sessionId,title:"memory-extract",agent:"memory",syncMessages:false,parts:[{type:"memory",status:"processing",time:{start:c}},{type:"text",text:p}]}).then(async u=>{cs.debug("memory extract completed",{outputLength:u.output.length}),await X.updatePart({...l,status:"completed",time:{start:c,end:Date.now()},result:u.output});}).catch(async u=>{cs.error("memory extract failed",{error:u.message}),await X.updatePart({...l,status:"failed",time:{start:c,end:Date.now()},error:u.message});}),{modified:false,input:t}}}]}:(cs.debug("memory hook disabled, skipping"),{isEnabled:()=>false,handlers:[]})}});var oh=a.create({service:"hook.builtin.compaction"}),Nu=zt("compaction",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.SessionStart,handler:async(e,t)=>{let n=e;return oh.debug("session.start hook triggered, resetting compaction failure counter",{sessionId:n.sessionId,agent:n.agent}),await sn.resetSessionFailures(n.sessionId),{modified:false,input:e}}},{name:HookEvent.StepFinish,handler:async(e,t)=>{let n=e;return oh.debug("step.finish hook triggered, resetting compaction failure counter",{sessionId:n.sessionId,agent:n.agent,finishReason:n.finishReason}),await sn.resetSessionFailures(n.sessionId),{modified:false,input:e}}}]}}});var Ms=a.create({service:"hook.builtin.coder"}),Uu=new Map,zu=zt("coder",{async init(){return {scope:g.Coder,isEnabled:()=>true,handlers:[{name:HookEvent.StepStart,handler:async(e,t)=>{let n=e;try{Ms.debug("coder.step-start hook triggered",{sessionId:n.sessionId,messageId:n.messageId});let o=await yt.track();Uu.set(n.sessionId,o);let r=(await ve.parts(n.messageId)).find(i=>i.type==="step-start");r&&o&&await X.updatePart({...r,snapshot:o}),Ms.debug("coder.step-start hook completed",{sessionId:n.sessionId,hasSnapshot:!!o});}catch(o){Ms.error("coder.step-start hook error",{sessionId:n.sessionId,error:String(o)});}return {modified:false,input:e}}},{name:HookEvent.StepFinish,handler:async(e,t)=>{let n=e;try{Ms.debug("coder.step-finish hook triggered",{sessionId:n.sessionId,messageId:n.messageId,finishReason:n.finishReason});let o=Uu.get(n.sessionId);if(o){let r=(await ve.parts(n.messageId)).find(c=>c.type==="step-finish");r&&await X.updatePart({...r,snapshot:o});let i=await yt.patch(o);i.files.length>0&&(await X.updatePart({id:Identifier.ascending("part"),messageId:n.messageId,sessionId:n.sessionId,type:"patch",hash:i.hash,files:i.files}),Ms.debug("coder.step-finish patch generated",{sessionId:n.sessionId,hash:i.hash,fileCount:i.files.length})),Uu.delete(n.sessionId);}Ms.debug("coder.step-finish hook completed",{sessionId:n.sessionId});}catch(o){Ms.error("coder.step-finish hook error",{sessionId:n.sessionId,error:String(o)});}return {modified:false,input:e}}}]}}});var Sn=a.create({service:"hook.builtin.gateway"}),qu=new Map,Hu=zt("gateway",{async init(){return {handlers:[{name:HookEvent.GatewayMessageReceive,handler:async(e,t)=>{let n=e,o=t.messageStore;return o?n?.id?(await o.store(n),Sn.debug("gateway message stored",{id:n.id,sessionId:n.sessionId,type:n.type}),{modified:false,input:e}):(Sn.warn("gateway message receive: missing id",{input:e}),{modified:false,input:e}):(Sn.debug("messageStore not available in context"),{modified:false,input:e})}},{name:HookEvent.GatewayMessageProcess,handler:async(e,t)=>{let n=e,o=n.id,s=t.messageStore;return s?o?(qu.set(o,n.timestamp??Date.now()),await s.updateStatus(o,"processing",{processorId:n.processorId,processType:n.processType,agent:n.agent}),Sn.debug("gateway message processing",{id:o}),{modified:false,input:e}):(Sn.warn("gateway message process: missing id",{input:e}),{modified:false,input:e}):(Sn.debug("messageStore not available in context"),{modified:false,input:e})}},{name:HookEvent.GatewayMessageComplete,handler:async(e,t)=>{let n=e,o=n.id,s=t.messageStore;if(!s)return Sn.debug("messageStore not available in context"),{modified:false,input:e};if(!o)return Sn.warn("gateway message complete: missing id",{input:e}),{modified:false,input:e};let r=qu.get(o);return qu.delete(o),await s.updateStatus(o,n.status??"completed",{error:n.error,responseMessageId:n.responseMessageId,tokens:n.tokens,duration:n.duration??(r?Date.now()-r:void 0),processedBy:n.processorId??n.agent}),Sn.debug("gateway message completed",{id:o,status:n.status}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageSend,handler:async(e,t)=>{let n=e,o=t.messageStore;if(!n?.id)return Sn.warn("gateway message send: missing id",{input:e}),{modified:false,input:e};if(o){let s=n.processorId||n.agent||"gateway";await o.store({id:n.id,sessionId:n.sessionId,type:n.type,content:n.content||[],channel:n.channel,replyToMessageId:n.replyToMessageId,proactive:n.proactive??!n.replyToMessageId,timestamp:n.timestamp,processorId:n.processorId,agent:n.agent},"completed"),n.replyToMessageId&&await o.updateStatus(n.replyToMessageId,"completed",{processedBy:s});}return Sn.debug("gateway message sent",{id:n.id,proactive:n.proactive}),{modified:false,input:e}}},{name:HookEvent.GatewayMessageDelivered,handler:async(e,t)=>{let n=e,o=t.messageStore;return n?.id?(o&&await o.updateStatus(n.id,"delivered",{deliveredAt:n.timestamp}),Sn.debug("gateway message delivered",{id:n.id}),{modified:false,input:e}):(Sn.warn("gateway message delivered: missing id",{input:e}),{modified:false,input:e})}},{name:HookEvent.GatewayMessageRead,handler:async(e,t)=>{let n=e,o=t.messageStore;return n?.id?(o&&await o.updateStatus(n.id,"read",{readAt:n.timestamp}),Sn.debug("gateway message read",{id:n.id}),{modified:false,input:e}):(Sn.warn("gateway message read: missing id",{input:e}),{modified:false,input:e})}}]}}});var Bu=a.create({service:"hook.executor.prompt"}),Os=class Os{constructor(){b$1(this,"type","prompt");}static getInstance(){return Os._instance||(Os._instance=new Os),Os._instance}canExecute(t){return t?.type==="prompt"}async execute(t,n,o){let s=Date.now(),r=t.runMode??"session";try{return Bu.debug("Execute Prompt Hook",{partsCount:t.parts?.length,model:t.model,runMode:r,context:o?.sessionId}),r==="fork"?await this.executeInFork(t,n,o,s):await this.executeInSession(t,n,o,s)}catch(i){return Bu.error("Prompt Hook execution failed",{error:i?.message,stack:i?.stack}),{success:false,modified:false,error:i?.message??String(i),duration:Date.now()-s}}}async executeInSession(t,n,o,s){let r=s??Date.now(),i=o?.sessionId??"",c=Identifier.ascending("message"),l=t.model?(()=>{let f=parseModelId(t.model);return {providerId:f.provider||"default",modelId:f.model}})():void 0,m=(await Je.prompt({messageId:c,sessionId:i,model:l,system:t.system,parts:t.parts})).parts.findLast(f=>f.type==="text")?.text??"";return {success:true,modified:n.modified,input:n.input,output:m,duration:Date.now()-r}}async executeInFork(t,n,o,s){let r=s??Date.now(),i=o?.sessionId??"";if(!i)return {success:false,modified:false,error:"Fork mode requires sessionId in context",duration:Date.now()-r};Bu.debug("Fork session for Prompt Hook",{sourceSessionID:i});let c=await X.fork({sessionId:i});try{let l=Identifier.ascending("message"),d=t.model?(()=>{let a=parseModelId(t.model);return {providerId:a.provider||"default",modelId:a.model}})():void 0,f=(await Je.prompt({messageId:l,sessionId:c.id,model:d,system:t.system,agent:o?.agent,parts:t.parts})).parts.findLast(a=>a.type==="text")?.text??"";return {success:!0,modified:n.modified,input:n.input,output:f,duration:Date.now()-r}}finally{await X.remove(c.id);}}};b$1(Os,"_instance");var Ur=Os;var Gu=a.create({service:"hook.builtin.heartbeat"}),ds=class ds{static getExecutor(){return ds._executor||(ds._executor=Ur.getInstance()),ds._executor}static async execute(t,n){let o=t.config?.mode??"session";try{let s={type:"prompt",model:t.config?.model,runMode:o,system:t.system,parts:t.parts??[]},r={sessionId:t.config?.session??n?.sessionId??"",agent:t.config?.agent,model:t.config?.model,cwd:n?.cwd},i=await ds.getExecutor().execute(s,{modified:!1,input:void 0},r),c=i.output!==void 0?typeof i.output=="string"?i.output:JSON.stringify(i.output):void 0;return {success:i.success??!1,output:c,error:i.error}}catch(s){return Gu.error("Heartbeat execution failed",{error:s}),{success:false,error:s instanceof Error?s.message:String(s)}}}};b$1(ds,"TYPE","heartbeat"),b$1(ds,"_executor");var nd=ds,Wu=zt("heartbeat.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.HeartbeatTrigger,handler:async(e,t)=>{let n=e;if(Gu.debug("Heartbeat trigger event received",{timestamp:n.timestamp,name:n.name}),n.definition){let o=await nd.execute(n.definition,n.context??t);return {modified:false,input:e,output:{execution:o}}}return {modified:false,input:e}}},{name:HookEvent.HeartbeatComplete,handler:(e,t)=>{let n=e;return Gu.debug("Heartbeat complete event received",{timestamp:n.timestamp,duration:n.duration}),{modified:false,input:e}}}]}}});var js=class js{constructor(){b$1(this,"type","function");}static getInstance(){return js._instance||(js._instance=new js),js._instance}canExecute(t){return t?.type==="function"}async execute(t,n,o){try{let s=t.handler,r=await s(n.input,o??{});return {success:!0,modified:r.modified,input:r.input}}catch(s){return {success:false,modified:false,error:s instanceof Error?s.message:String(s)}}}};b$1(js,"_instance");var od=js;var ch=a.create({service:"hook.executor.command"}),Ls=class Ls{constructor(){b$1(this,"type","command");}static getInstance(){return Ls._instance||(Ls._instance=new Ls),Ls._instance}canExecute(t){return t?.type==="command"}async execute(t,n,o){let s=Date.now();try{ch.debug("Execute Command Hook",{command:t.command,context:o});let i=await createPkgShell({cwd:o?.cwd,env:{...process.env,...n.input}})`${t.command}`.nothrow();return i.exitCode===0?{success:!0,modified:n.modified,input:n.input,stdout:i.text(),stderr:i.stderr.toString(),duration:Date.now()-s}:{success:!1,modified:n.modified,input:n.input,stdout:i.text(),stderr:i.stderr.toString(),exitCode:i.exitCode,duration:Date.now()-s}}catch(r){return ch.error("Command Hook execution failed",{error:r?.message}),{success:false,modified:false,error:r?.message??String(r),duration:Date.now()-s}}}};b$1(Ls,"_instance");var sd=Ls;var dh=a.create({service:"hook.executor.http"}),Ds=class Ds{constructor(){b$1(this,"type","http");}static getInstance(){return Ds._instance||(Ds._instance=new Ds),Ds._instance}canExecute(t){return t?.type==="http"}async execute(t,n,o){let s=Date.now(),r=t.timeout??3e4,i=t.method??"GET";try{dh.debug("Execute HTTP Hook",{url:t.url,method:i,context:o});let c={"Content-Type":"application/json",...t.headers};if(t.allowedEnvVars&&t.allowedEnvVars.length>0)for(let p of t.allowedEnvVars)process.env[p]&&(c[p]=process.env[p]);let l=new AbortController,d=setTimeout(()=>l.abort(),r),m=await Fetch.request(t.url,{method:i,headers:c,body:i!=="GET"?JSON.stringify(n.input):void 0,responseType:"text",signal:l.signal});clearTimeout(d);let f=m.data,a;try{a=JSON.parse(f);}catch{a=f;}return {success:m.ok,modified:n.modified,input:n.input,output:a,stdout:f,exitCode:m.ok?0:m.status,duration:Date.now()-s}}catch(c){return dh.error("HTTP Hook execution failed",{error:c?.message}),{success:false,modified:false,error:c?.message??String(c),duration:Date.now()-s}}}};b$1(Ds,"_instance");var rd=Ds;var lh=a.create({service:"hook.executor.agent"}),$s=class $s{constructor(){b$1(this,"type","agent");}static getInstance(){return $s._instance||($s._instance=new $s),$s._instance}canExecute(t){return !t||typeof t!="object"?false:t.type==="agent"}async execute(t,n,o){let s=Date.now();try{let r=t.agent??o?.agent??"task_general",i=t.model?(()=>{let l=parseModelId(t.model);return {providerId:l.provider||"default",modelId:l.model}})():void 0;lh.debug("Execute Agent Hook",{type:t.type,agent:r,model:t.model,timeout:t.timeout,context:o?.sessionId});let c=await As.run({source:o?.sessionId??"",title:this.extractTitle(t.parts),agent:r,system:t.system,parts:t.parts,model:i,syncMessages:!1});return {success:!0,modified:n.modified,input:n.input,output:c.output,duration:Date.now()-s}}catch(r){return lh.error("Agent Hook execution failed",{error:r?.message,stack:r?.stack}),{success:false,modified:false,error:r?.message??String(r),duration:Date.now()-s}}}extractTitle(t){if(!t||t.length===0)return "Agent Task";let n=t.find(o=>typeof o=="object"&&o!==null&&o.type==="text");return n&&typeof n.text=="string"?n.text.slice(0,50):"Agent Task"}};b$1($s,"_instance");var zr=$s;var ls=class ls{constructor(){b$1(this,"executors",[]);}static getInstance(){return ls._instance||(ls._instance=new ls,ls._instance.registerDefaultExecutors()),ls._instance}registerDefaultExecutors(){this.register(od.getInstance()),this.register(sd.getInstance()),this.register(Ur.getInstance()),this.register(rd.getInstance()),this.register(zr.getInstance());}register(t){this.executors.push(t);}getExecutor(t){return this.executors.find(n=>n.canExecute(t))}async execute(t,n,o){let s=this.getExecutor(t);return s?s.execute(t,n,o):{success:false,modified:false,error:`No executor found for hook type: ${t.type}`}}};b$1(ls,"_instance");var Zi=ls;var Vu=a.create({service:"hook.builtin.scheduler"}),us=class us{static getExecutor(){return us._executor||(us._executor=zr.getInstance()),us._executor}static async execute(t,n){let{agentType:o,model:s}=t.config??{};try{let r={type:"agent",model:s,system:t.system,parts:t.parts},i=await us.getExecutor().execute(r,{modified:!1,input:void 0},{sessionId:n?.sessionId??"scheduler",agent:o}),c=i.output!==void 0?typeof i.output=="string"?i.output:JSON.stringify(i.output):void 0;return {success:i.success??!1,output:c,error:i.error}}catch(r){return Vu.error("Scheduled task execution failed",{error:r}),{success:false,error:r instanceof Error?r.message:String(r)}}}};b$1(us,"TYPE","scheduler"),b$1(us,"_executor");var id=us,Ku=zt("scheduler.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.ScheduledTaskTrigger,handler:async(e,t)=>{let n=e;if(Vu.debug("Scheduled task trigger event received",{taskID:n.taskID,taskName:n.taskName,timestamp:n.timestamp}),n.definition){let o=await id.execute(n.definition,n.context??t);return {modified:false,input:e,output:{execution:o}}}return {modified:false,input:e}}},{name:HookEvent.ScheduledTaskComplete,handler:(e,t)=>{let n=e;return Vu.debug("Scheduled task complete event received",{taskID:n.taskID,timestamp:n.timestamp,success:n.success}),{modified:false,input:e}}}]}}});var ad=a.create({service:"hook.builtin.command"}),ea=class{static async execute(t){let{command:n,arguments:o,session:s}=t.config;try{ad.debug("Executing command",{command:n,session:s});let r=await Je.command({sessionId:s??"scheduler",command:n,arguments:o??""});return {success:!r.error,output:r.output,error:r.error}}catch(r){return ad.error("Command execution failed",{command:n,error:r}),{success:false,error:r instanceof Error?r.message:String(r)}}}};b$1(ea,"TYPE","command");var Ju=zt("command.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.CommandTrigger,handler:async(e,t)=>{let n=e;if(ad.debug("Command trigger event received",{taskId:n.taskId,taskName:n.taskName,command:n.command,timestamp:n.timestamp}),n.definition){let o=await ea.execute(n.definition);return {modified:false,input:e,output:{execution:o}}}return {modified:false,input:e}}},{name:HookEvent.CommandComplete,handler:(e,t)=>{let n=e;return ad.debug("Command complete event received",{taskId:n.taskId,timestamp:n.timestamp,success:n.success,duration:n.duration}),{modified:false,input:e}}}]}}});var fh=a.create({service:"hook.builtin.context"}),Yu=zt("context.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.ContextBuildBefore,handler:(e,t)=>{let n=e;return fh.debug("context.build.before hook triggered",{sessionId:n.sessionId,mode:n.mode}),{modified:false,input:e}}},{name:HookEvent.ContextBuildAfter,handler:(e,t)=>{let n=e;return fh.debug("context.build.after hook triggered",{sessionId:n.context.metadata.sessionId}),{modified:false,input:e}}}]}}});var gn=a.create({service:"hook.builtin.task"});async function wP(e){try{return (await Mt.get(e)).type==="idle"}catch{return false}}async function xP(e){let{taskId:t,duration:n,error:o}=e;e.source==="scheduler"&&gn.debug("Scheduled task completed",{taskId:t,duration:n,success:!o});}async function IP(e){let{taskId:t,error:n}=e;e.source==="cli"&&(n?gn.error("CLI task error",{taskId:t,error:n}):gn.debug("CLI task completed",{taskId:t}));}async function vP(e){let{taskId:t,result:n,error:o}=e;e.source==="api"&&gn.debug("API task event",{taskId:t,hasError:!!o,hasResult:!!n});}var SP={tool:async()=>gn.debug("Tool task completed"),scheduler:xP,cli:IP,api:vP};async function CP(e){try{await jt.create({taskId:e.taskId,sessionId:e.sessionId,description:e.description||"",prompt:e.prompt||"",agentType:e.agentType||"unknown",source:e.source,metadata:{agentType:e.agentType}});}catch(t){gn.error("Failed to create task",{taskId:e.taskId,error:String(t)});return}gn.debug("Task created (pending)",{taskId:e.taskId,sessionId:e.sessionId,source:e.source,agentType:e.agentType});}async function kP(e){await jt.update(e.taskId,{status:"running"}),gn.debug("Task running",{taskId:e.taskId,sessionId:e.sessionId});}async function PP(e){if(!await jt.get(e.taskId)){gn.warn("Task progress for unknown task",{taskId:e.taskId});return}gn.debug("Task progress",{taskId:e.taskId,step:e.step,totalSteps:e.totalSteps});}async function TP(e){let t=await jt.get(e.taskId);if(!t){gn.warn("Task complete for unknown task",{taskId:e.taskId});return}await jt.update(e.taskId,{status:e.error?"error":"completed",result:e.result,error:e.error,duration:e.duration,metadata:e.metadata}),gn.debug("Task completed (persisted)",{taskId:e.taskId,sessionId:t.sessionId,source:e.source,duration:e.duration,hasError:!!e.error}),await SP[e.source](e),t.sessionId&&e.source==="tool"&&(e.result||e.error?await AP(t,e):gn.debug("Task completed without result, skip injection",{taskId:e.taskId,sessionId:t.sessionId}));}async function AP(e,t){if(e?.sessionId)try{let n=await wP(e.sessionId);await Je.prompt({sessionId:e.sessionId,parts:[{type:"subtask-result",taskId:e.taskId,source:e.source,agent:t.agentType??e.agentType,status:t.error?"error":"completed",result:t.result,error:t.error,duration:t.duration,time:{start:e.createdAt,end:Date.now()},metadata:t.metadata}],noReply:!n}),n?gn.debug("Injected result to parent session (agent idle, will trigger LLM)",{taskId:e.taskId,sessionId:e.sessionId}):gn.debug("Injected result to parent session (agent busy, queued for next turn)",{taskId:e.taskId,sessionId:e.sessionId});}catch(n){gn.error("Failed to inject result to parent session",{taskId:e.taskId,sessionId:e.sessionId,error:n instanceof Error?n.message:String(n)});}}var Xu=zt("task.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.TaskStart,handler:async e=>(await CP(e),{modified:false,input:e})},{name:HookEvent.TaskRunning,handler:async e=>(await kP(e),{modified:false,input:e})},{name:HookEvent.TaskProgress,handler:async e=>(await PP(e),{modified:false,input:e})},{name:HookEvent.TaskComplete,handler:async e=>(await TP(e),{modified:false,input:e})}]}}});var dd=a.create({service:"hook.builtin.loop"});async function EP(e,t){let n=await ve.getLastMessages(e);return !n.lastUser||n.lastUser.id===t?false:n.lastFinished?n.lastFinished.info.role==="assistant"&&n.lastFinished.info.parentId!==n.lastUser.id?(dd.debug("Latest assistant message does not respond to latest user message, should continue loop",{lastUserId:n.lastUser.id,assistantParentId:n.lastFinished.info.parentId}),true):false:(dd.debug("Found new user message without assistant response, should continue loop",{lastUserId:n.lastUser.id,expectedParentId:n.lastUser.id}),true)}var Qu=zt("loop.builtin",{async init(){return {isEnabled:()=>true,handlers:[{name:HookEvent.LoopStart,handler:async e=>{let t=e;return dd.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 EP(t.sessionId,t.lastUserId)?(dd.debug("Loop should continue for pending messages"),{modified:true,input:{...t,result:"continue"}}):{modified:false,input:e}}}]}}});var hh=a.create({service:"hook.matcher"}),Fs=class Fs{static getInstance(){return Fs._instance||(Fs._instance=new Fs),Fs._instance}match(t,n,o){return t.event!==n?{matched:false}:t.matcher&&!this.evaluateCondition(t.matcher,o)?(hh.debug("Hook matcher condition not met",{matcher:t.matcher,context:o}),{matched:false}):{matched:true}}matchHook(t,n,o){return !("if"in t)||!t.if?true:this.evaluateCondition(t.if,o)}getHookName(t){switch(t.type){case "function":return "function";case "command":return t.command.split(" ")[0]||"command";case "prompt":return "prompt";case "http":try{return new URL(t.url).hostname}catch{return "http"}case "agent":return "agent";default:return "unknown"}}evaluateCondition(t,n){try{let o={...process.env,SESSION_ID:n?.sessionId,AGENT:n?.agent,MODEL:n?.model,CWD:n?.cwd};for(let[i,c]of Object.entries(n??{}))typeof c=="string"&&(o[i.toUpperCase()]=c);let s=t.replace(/\$\{(\w+)\}/g,(i,c)=>{let l=o[c];return typeof l=="string"?`"${l.replace(/"/g,'\\"')}"`:"undefined"});return !!new Function(`return ${s}`)()}catch(o){return hh.error("Failed to evaluate condition",{condition:t,error:o?.message}),false}}};b$1(Fs,"_instance");var ta=Fs;var RP=a.create({service:"hook.registry"}),yh=[Fu,Nu,zu,Wu,Ku,Ju,Yu,Xu,Qu,Hu],Le;(m=>{let e;function t(){return e||(e=_.state(async()=>({matchers:[],executorRegistry:Zi.getInstance(),hookMatcher:ta.getInstance()}))),e}function n(){return t()()}m.state=n;function o(){return [...yh]}m.all=o;async function s(){await n();let a=[];for(let p of yh){let u=await p.init();if(u.isEnabled){let g=u.isEnabled();if(g instanceof Promise){if(!await g)continue}else if(!g)continue}for(let g of u.handlers){let h=await r({event:g.name,scope:u.scope,hooks:[{type:"function",handler:g.handler}],hookName:p.name});a.push(h);}}return a}m.init=s;async function r(f){let a={...f,scope:f.scope,hookName:f.hookName};return (await n()).matchers.push(a),()=>{n().then(u=>{let g=u.matchers.indexOf(a);g>-1&&u.matchers.splice(g,1);});}}m.registerMatcher=r;async function i(f){try{let p=await X.get(f);if(p.contextMode)return p.contextMode}catch{}return (await he.get()).context?.mode??g.General}async function c(f,a,p){let u=await n(),g$1=Date.now(),h={success:true,output:a,modified:false,aborted:false,details:[],errors:[],duration:0},S=p?.sessionId,A=S?await i(S):g.General,y=u.matchers.filter(w=>{if(!u.hookMatcher.match(w,f,p).matched)return false;let C=w.scope??g.All;return !(C!==g.All&&C!==A)}),x=[];for(let w of y)for(let C=0;C<w.hooks.length;C++){let k=w.hooks[C];k&&u.hookMatcher.matchHook(k,a,p)&&x.push({hook:k,hookIndex:C});}let b=a;for(let w=0;w<x.length;w++){if(p?.abort?.aborted){h.aborted=true,h.errors.push({index:w,hookName:"system",error:String(p.abort.reason??"Aborted")});break}let C=x[w];if(!C)continue;let{hook:k}=C,P={index:w,hookType:k.type,hookName:`${f}:${u.hookMatcher.getHookName(k)}`,matched:true,skipped:false,success:false,modified:false,duration:0},E=Date.now();try{let O={modified:!1,input:b},N=await u.executorRegistry.execute(k,O,p);if(p?.abort?.aborted){h.aborted=!0,h.errors.push({index:w,hookName:P.hookName,error:String(p.abort.reason??"Aborted by hook")});break}N.modified&&N.input!==void 0&&(b=N.input,P.modified=!0,h.modified=!0),P.success=N.success!==!1,P.output=N.output,P.duration=Date.now()-E,h.details.push(P);}catch(O){let N=O;if(N?.name==="AbortError"){h.aborted=true,h.errors.push({index:w,hookName:P.hookName,error:String(p?.abort?.reason??"Aborted")});break}h.errors.push({index:w,hookName:P.hookName,error:N?.message??String(O),stack:N?.stack}),RP.error("Hook execution error",{hook:P.hookName,error:N?.message,stack:N?.stack}),P.duration=Date.now()-E,h.details.push(P);}}return h.output=b,h.duration=Date.now()-g$1,h.success=h.errors.length===0&&!h.aborted,h}m.triggerEvent=c;async function l(){e=void 0;}m.clear=l;async function d(){return (await n()).matchers.length}m.matcherCount=d;})(Le||(Le={}));var OP=loadTextFile("./generate.txt",import.meta.url),jP=OP(),LP=loadTextFile("./prompt/compaction.txt",import.meta.url),DP=LP(),$P=loadTextFile("./prompt/explore.txt",import.meta.url),FP=$P(),NP=loadTextFile("./prompt/summary.txt",import.meta.url),UP=NP(),zP=loadTextFile("./prompt/title.txt",import.meta.url),qP=zP(),HP=loadTextFile("./prompt/btw.txt",import.meta.url),BP=HP(),GP=loadTextFile("./prompt/memory.txt",import.meta.url),WP=GP(),Ue;(d=>{d.Info=F.object({name:F.string(),description:F.string().optional(),mode:F.enum(["subagent","primary","all"]),native:F.boolean().optional(),hidden:F.boolean().optional(),topP:F.number().optional(),temperature:F.number().optional(),color:F.string().optional(),permission:F.lazy(()=>Me.Ruleset),scope:F.enum(h).optional(),model:F.object({modelId:F.string(),providerId:F.string()}).optional(),variant:F.string().optional(),prompt:F.string().optional(),options:F.record(F.string(),F.any()),steps:F.number().int().positive().optional()}).meta({ref:"Agent"});async function t(){let m=await he.get(),f=await Jt.dirs(),a=Me.fromConfig({"*":"allow",doom_loop:"ask",external_directory:{"*":"ask",[Ve.GLOB]:"allow",...Object.fromEntries(f.map(g=>[Ce__default.join(g,"*"),"allow"]))},question:"deny",plan:"deny",read:{"*":"allow","*.env":"ask","*.env.*":"ask","*.env.example":"allow"}}),p=Me.fromConfig(m.permission??{}),u={build:{name:"build",description:"The default agent. Executes tools based on configured permissions.",options:{},permission:Me.merge(a,Me.fromConfig({question:"allow",plan:"allow"}),p),mode:"primary",native:true},plan:{name:"plan",description:"Plan mode. Disallows all edit tools.",options:{},permission:Me.merge(a,Me.fromConfig({question:"allow",plan_exit:"allow",external_directory:{[Ce__default.join(a$1.Path.data,"plans","*")]:"allow"},edit:{"*":"deny",[Ce__default.posix.join(".easbot","plans","*.md")]:"allow",[Ce__default.posix.relative(_.worktree,Ce__default.posix.join(a$1.Path.data,Ce__default.posix.join("plans","*.md")))]:"allow"}}),p),mode:"primary",native:true},btw:{name:"btw",description:"Act like a professional in the relevant domain",mode:"primary",options:{},native:true,permission:Me.merge(a,Me.fromConfig({"*":"deny",grep:"allow",glob:"allow",list:"allow",bash:"allow",webfetch:"allow",websearch:"allow",codesearch:"allow",read:"allow",question:"allow",plan:"allow",external_directory:{[Ve.GLOB]:"allow"}}),p),prompt:BP},general:{name:"general",description:"General-purpose agent for researching complex questions and executing multi-step tasks. Use this agent to execute multiple units of work in parallel.",permission:Me.merge(a,Me.fromConfig({todo:"deny"}),p),options:{},mode:"subagent",native:true},explore:{name:"explore",permission:Me.merge(a,Me.fromConfig({"*":"deny",grep:"allow",glob:"allow",list:"allow",bash:"allow",webfetch:"allow",websearch:"allow",codesearch:"allow",read:"allow",external_directory:{[Ve.GLOB]:"allow"}}),p),description:'Fast agent specialized for exploring codebases. Use this when you need to quickly find files by patterns (eg. "src/components/**/*.tsx"), search code for keywords (eg. "API endpoints"), or answer questions about the codebase (eg. "how do API endpoints work?"). When calling this agent, specify the desired thoroughness level: "quick" for basic searches, "medium" for moderate exploration, or "very thorough" for comprehensive analysis across multiple locations and naming conventions.',prompt:FP,options:{},mode:"subagent",native:true},compaction:{name:"compaction",description:"Compresses conversation context when session becomes too long.",mode:"subagent",native:true,hidden:true,prompt:DP,permission:Me.merge(a,Me.fromConfig({"*":"deny"}),p),options:{}},title:{name:"title",description:"Generates a concise title for the conversation.",mode:"subagent",options:{},native:true,hidden:true,temperature:.5,permission:Me.merge(a,Me.fromConfig({"*":"deny"}),p),prompt:qP},summary:{name:"summary",description:"Generates a summary of the conversation.",mode:"subagent",options:{},native:true,hidden:true,permission:Me.merge(a,Me.fromConfig({"*":"deny"}),p),prompt:UP},memory:{name:"memory",description:"Manages memory operations and searches relevant memories.",mode:"subagent",options:{},native:true,hidden:true,permission:Me.merge(a,Me.fromConfig({"*":"deny",memory:"allow",read:{"*":"allow","*.env":"deny","*.env.*":"deny","*.env.example":"allow"},list:"allow",glob:"allow",grep:"allow",webfetch:"allow",websearch:"allow",external_directory:{[Ve.GLOB]:"allow",...Object.fromEntries(f.map(g=>[Ce__default.join(g,"*"),"allow"]))}}),p),prompt:WP}};for(let[g,h]of Object.entries(m.agent??{})){if(h.disable){delete u[g];continue}let S=u[g];if(S||(S=u[g]={name:g,mode:"all",permission:Me.merge(a,p),options:{},native:false}),h.model){let A=xe.parseModel(h.model);S.model={providerId:A.providerId,modelId:A.modelId};}S.variant=h.variant??S.variant,S.prompt=h.prompt??S.prompt,S.description=h.description??S.description,S.temperature=h.temperature??S.temperature,S.topP=h.top_p??S.topP,S.mode=h.mode??S.mode,S.color=h.color??S.color,S.hidden=h.hidden??S.hidden,S.name=h.name??S.name,S.steps=h.steps??S.steps,S.options=mergeDeep(S.options,h.options??{}),S.permission=Me.merge(S.permission,Me.fromConfig(h.permission??{}));}for(let g in u){if(!Object.hasOwn(u,g))continue;let h=u[g];!h||h.permission.some(A=>A.permission!=="external_directory"||A.action!=="deny"?false:A.pattern===Ve.GLOB)||!u[g]||(u[g].permission=Me.merge(u[g].permission,Me.fromConfig({external_directory:{[Ve.GLOB]:"allow"}})));}return u}let n;function o(){return n||(n=_.state(t)),n}function s(){return o()()}async function r(m){return (await s())[m]}d.get=r;async function i(m){let f=await he.get(),a=m??"general";return pipe(await s(),values(),sortBy([u=>f.default_agent?u.name===f.default_agent:u.name==="build","desc"])).filter(u=>{let g=u.scope??"all";return !(g!=="all"&&g!==a)})}d.list=i;async function c(){let m=await he.get(),f=await s();if(m.default_agent){let p=f[m.default_agent];if(!p)throw new Error(`default agent "${m.default_agent}" not found`);if(p.mode==="subagent")throw new Error(`default agent "${m.default_agent}" is a subagent`);if(p.hidden===true)throw new Error(`default agent "${m.default_agent}" is hidden`);return p.name}let a=Object.values(f).find(p=>p.mode!=="subagent"&&p.hidden!==true);if(!a)throw new Error("no primary visible agent found");return a.name}d.defaultAgent=c;async function l(m){let f=await he.get(),a=m.model??await xe.defaultModel(),p=await xe.getModel(a.providerId,a.modelId),u=await xe.getLanguage(p),g=[jP];await Le.triggerEvent(HookEvent.SystemTransform,{model:p});let h=await i(),S={experimental_telemetry:{isEnabled:f.experimental?.openTelemetry,metadata:{userId:f.username??"unknown"}},temperature:.3,messages:[...g.map(y=>({role:"system",content:y})),{role:"user",content:`Create an agent configuration based on this request: "${m.description}".
877
+
878
+ IMPORTANT: The following identifiers already exist and must NOT be used: ${h.map(y=>y.name).join(", ")}
879
+ Return ONLY the JSON object, no other text, do not wrap in backticks`}],model:u,schema:F.object({identifier:F.string(),whenToUse:F.string(),systemPrompt:F.string()})};if(a.providerId==="openai"&&(await Qe.get(a.providerId))?.type==="oauth"){let y=streamObject({...S,providerOptions:wt.providerOptions(p,{instructions:g.join(`
880
+ `),store:false}),onError:()=>{}});for await(let x of y.fullStream)if(x.type==="error")throw x.error;return y.object}return (await generateObject(S)).object}d.generate=l;})(Ue||(Ue={}));var qn=a.create({service:"agent-cli-api-agent"});async function bh(){try{qn.debug("Get agent list");let t=(await Ue.list()).map(n=>{let o=n.model,s;if(o&&typeof o=="string"){let{provider:r,model:i}=parseModelId(o);r&&i&&(s={providerId:r,modelId:i});}return {...n,model:s}});return qn.debug("Get agent list successful",{count:t.length}),t}catch(e){throw qn.error("Failed to get agent list",{error:e}),e}}async function ld(e){try{e=e?.trim()??await Ue.defaultAgent(),qn.debug("Get agent details",{agentName:e});let t=await Ue.get(e);return t?(qn.debug("Get agent details successful",{agentName:e}),t):(qn.warn("Agent does not exist",{agentName:e}),null)}catch(t){throw qn.error("Failed to get agent details",{agentName:e,error:t}),t}}async function QP(){try{qn.debug("Get default agent");let e=await Ue.defaultAgent(),t=await ld(e);if(!t)throw new Error(`Default agent "${e}" not found`);return qn.debug("Get default agent successful",{agentName:e}),t}catch(e){throw qn.error("Failed to get default agent",{error:e}),e}}var ZP=bh;async function wh(e){try{if(qn.debug("Creating agent",{name:e.name,mode:e.mode}),!e.name||e.name.trim()==="")throw new Error("Agent name is required");let t=["subagent","primary","all"],n=e.mode||"primary";if(!t.includes(n))throw new Error(`Invalid agent mode: ${e.mode}. Valid modes are: ${t.join(", ")}`);if(await ld(e.name))throw new Error(`Agent "${e.name}" already exists`);let s={mode:n};e.description&&(s.description=e.description),e.prompt&&(s.prompt=e.prompt),e.model&&(s.model=`${e.model.providerId}/${e.model.modelId}`),e.temperature!==void 0&&(s.temperature=e.temperature),e.topP!==void 0&&(s.top_p=e.topP),e.color&&(s.color=e.color),e.hidden!==void 0&&(s.hidden=e.hidden),e.variant&&(s.variant=e.variant),e.steps!==void 0&&(s.steps=e.steps),e.permission&&(s.permission=e.permission),e.options&&(s.options=e.options);let{Config:r}=await import('./config-MLDSMYKU.mjs');await r.update({agent:{[e.name]:s}}),qn.debug("Agent created successfully",{name:e.name});let i=await ld(e.name);if(!i)throw new Error(`Failed to retrieve created agent "${e.name}"`);return i}catch(t){throw qn.error("Failed to create agent",{name:e.name,error:t}),t}}var eT=wh;var na={};a$7(na,{formatModels:()=>iT,getDefaultModel:()=>tT,listModels:()=>oT,listProviders:()=>nT,parseModel:()=>rT,refreshModels:()=>sT});async function tT(){try{let e=await xe.defaultModel();return e?`${e.providerId}/${e.modelId}`:void 0}catch{return}}async function nT(){return xe.list()}async function oT(e){let t=await xe.list();if(e){let n=t[e];if(!n)throw new Error(`Provider not found: ${e}`);return {[e]:n}}return t}async function sT(){await a$3.refresh();}function rT(e){let t=xe.parseModel(e);if(t?.providerId)return {providerId:t.providerId,modelId:t.modelId}}function iT(e,t=false){let n=[],o=Object.keys(e).sort((s,r)=>{let i=s.startsWith("opencode"),c=r.startsWith("opencode");return i&&!c?-1:!i&&c?1:s.localeCompare(r)});for(let s of o){let r=e[s];if(!r?.models)continue;let i=Object.entries(r.models).sort(([c],[l])=>c.localeCompare(l));for(let[c,l]of i)n.push(`${s}/${c}`),t&&l&&n.push(JSON.stringify(l,null,2));}return n.join(`
881
+ `)}var zs={};a$7(zs,{command:()=>fT,deleteMessage:()=>dT,deletePart:()=>uT,getMessage:()=>cT,list:()=>aT,listMessages:()=>Ih,send:()=>mT,updateMessage:()=>lT,updatePart:()=>pT});var qr=a.create({service:"agent-cli-api-message"});async function Ih(e,t){qr.debug(i$1("message.history.start"),{sessionId:e});let n=await X.messages({sessionId:e,limit:t});return qr.debug(i$1("message.history.success"),{sessionId:e,count:n.length}),n}var aT=Ih;async function cT(e,t){return await ve.get({sessionId:e,messageId:t})}async function dT(e,t){return X.removeMessage({sessionId:e,messageId:t})}async function lT(e){return X.updateMessage(e)}async function uT(e,t,n){return X.removePart({sessionId:e,messageId:t,partId:n})}async function pT(e){return X.updatePart(e)}async function mT(e){qr.debug(i$1("message.send.start"),{sessionId:e.sessionId});let t=[{type:"text",text:e.text}];if(e.files&&e.files.length>0)for(let o of e.files)t.push({type:"file",url:o.url,filename:o.filename,mime:o.mime});e.subAgent&&t.push({type:"agent",name:e.subAgent});let n=await Je.prompt({sessionId:e.sessionId,messageId:Identifier.ascending("message"),agent:e.agent,model:e.model,variant:e.variant,noReply:e.noReply,contextMode:e.contextMode,parts:t,system:e.system});return qr.debug(i$1("message.send.success"),{sessionId:e.sessionId,messageId:n.info.id}),n}async function fT(e){qr.debug(i$1("message.command.start"),{sessionId:e.sessionId,command:e.command});let t=await Je.command({sessionId:e.sessionId,messageId:e.messageId||Identifier.ascending("message"),command:e.command,arguments:e.arguments||"",agent:e.agent,model:e.model,variant:e.variant,contextMode:e.contextMode,parts:e.parts});return qr.debug(i$1("message.command.success"),{sessionId:e.sessionId,command:e.command,title:t.title}),t}a.create({service:"agent-cli-api-tool"});var Co={};a$7(Co,{getConfig:()=>hT,getConfigDirectories:()=>xT,getGlobalConfig:()=>yT,updateConfig:()=>bT,updateGlobalConfig:()=>wT,waitForConfigDependencies:()=>IT});async function hT(){return he.get()}async function yT(){return he.getGlobal()}async function bT(e){return await he.update(e),he.get()}async function wT(e){return await he.updateGlobal(e),he.getGlobal()}async function xT(){return he.directories()}async function IT(){await he.waitForDependencies();}var ud={};a$7(ud,{getProvider:()=>ST,listAllProviders:()=>vT,listProviders:()=>vh});var Po=a.create({service:"agent-cli-api-provider"});async function vh(){try{Po.debug("List providers");let e=await xe.list(),t=Object.values(e);return Po.debug("List providers success",{count:t.length}),t}catch(e){throw Po.error("List providers failed",{error:e}),e}}async function vT(){try{Po.debug("List all available providers");let e=await a$3.get(),t=Object.values(e).map(n=>xe.fromModelsDevProvider(n));return Po.debug("List all available providers success",{count:t.length}),t}catch(e){throw Po.error("List all available providers failed",{error:e}),e}}async function ST(e){try{Po.debug("Get provider details",{providerId:e});let n=(await vh()).find(o=>o.id===e);return n?(Po.debug("Get provider details success",{providerId:e}),n):(Po.warn("Provider not found",{providerId:e}),null)}catch(t){throw Po.error("Get provider details failed",{providerId:e,error:t}),t}}var pd={};a$7(pd,{list:()=>CT,listCommands:()=>Sh});async function Sh(e){return (await vn.list(e)).map(o=>({name:o.name,description:o.description,source:o.source,subtask:o.subtask,hints:o.hints??[],agent:o.agent,model:o.model,commandType:o.commandType,hidden:o.hidden??false}))}var CT=Sh;var Hn={};a$7(Hn,{add:()=>TT,addMcpServer:()=>GT,authCallback:()=>qT,authenticate:()=>DT,clients:()=>HT,connect:()=>AT,disconnect:()=>ET,finishAuth:()=>$T,getAuthStatus:()=>zT,getMcpServerInfo:()=>VT,getPrompt:()=>OT,hasStoredTokens:()=>UT,list:()=>PT,listMcpServers:()=>BT,prompts:()=>_T,readResource:()=>jT,removeAuth:()=>FT,removeMcpServer:()=>WT,resources:()=>MT,startAuth:()=>LT,status:()=>kT,supportsOAuth:()=>NT,tools:()=>RT});async function kT(){return ze.status()}async function PT(){return ze.status()}async function TT(e,t){await ze.add(e,t);return ze.status()}async function AT(e){await ze.connect(e);return ze.status()}async function ET(e){await ze.disconnect(e);return ze.status()}async function RT(){return ze.tools()}async function _T(){return ze.prompts()}async function MT(){return ze.resources()}async function OT(e,t,n){return ze.getPrompt(e,t,n)}async function jT(e,t){return ze.readResource(e,t)}async function LT(e){return ze.startAuth(e)}async function DT(e){return ze.authenticate(e)}async function $T(e,t){return ze.finishAuth(e,t)}async function FT(e){return ze.removeAuth(e)}async function NT(e){return ze.supportsOAuth(e)}async function UT(e){return ze.hasStoredTokens(e)}async function zT(e){return ze.getAuthStatus(e)}async function qT(e,t){return ze.finishAuth(e,t)}async function HT(){return ze.clients()}async function BT(){let t=(await he.get()).mcp??{};return Object.entries(t).map(([n,o])=>({name:n,...o}))}async function GT(e){let{name:t,...n}=e;return await he.update({mcp:{[t]:n}}),{name:t,...n}}async function WT(e){await he.update({mcp:{[e]:void 0}});}async function VT(e){let n=(await he.get()).mcp?.[e];return n?{name:e,...n}:null}var md={};a$7(md,{getLspStatus:()=>Ch,status:()=>KT});var Zu=a.create({service:"agent-cli-api-lsp"});async function Ch(){try{Zu.debug("Get LSP status");let e=await We.status();return Zu.debug("Get LSP status successful",{count:e.length}),e}catch(e){throw Zu.error("Failed to get LSP status",{error:e}),e}}var KT=Ch;var Uo={};a$7(Uo,{publish:()=>JT,subscribe:()=>ZT,subscribeAll:()=>QT,subscribeMessage:()=>tA,subscribeSession:()=>eA});var Rn=a.create({service:"agent-cli-api-events"});async function JT(e){try{Rn.debug("Publish event",{eventType:e.type});let t=a$5.define(e.type,F.record(F.string(),F.any()));await pe.publish(t,e.properties??{});}catch(t){throw Rn.error("Publish event failed",{eventType:e.type,error:t}),t}}function kh(e){return typeof e!="object"||e===null?false:typeof e.sessionId=="string"}function YT(e){return kh(e)?typeof e.messageId=="string":false}function Ph(e){if(kh(e))return e.sessionId}function XT(e){if(YT(e))return e.messageId}async function QT(e){try{Rn.debug("Subscribe all events");let t=await pe.subscribeAll(e);return Rn.debug("Subscribe all events success"),t}catch(t){throw Rn.error("Subscribe all events failed",{error:t}),t}}async function ZT(e,t){try{Rn.debug("Subscribe event",{eventType:e});let n=await pe.subscribeAll(o=>{o.type===e&&t(o);});return Rn.debug("Subscribe event success",{eventType:e}),n}catch(n){throw Rn.error("Subscribe event failed",{eventType:e,error:n}),n}}async function eA(e,t){try{Rn.debug("Subscribe session events",{sessionId:e});let n=await pe.subscribeAll(o=>{Ph(o.properties)===e&&t(o);});return Rn.debug("Subscribe session events success",{sessionId:e}),n}catch(n){throw Rn.error("Subscribe session events failed",{sessionId:e,error:n}),n}}async function tA(e,t,n){try{Rn.debug("Subscribe message events",{sessionId:e,messageId:t});let o=await pe.subscribeAll(s=>{let r=Ph(s.properties),i=XT(s.properties);r===e&&(t===void 0||i===t)&&n(s);});return Rn.debug("Subscribe message events success",{sessionId:e,messageId:t}),o}catch(o){throw Rn.error("Subscribe message events failed",{sessionId:e,messageId:t,error:o}),o}}var fd={};a$7(fd,{all:()=>nA});function nA(){return Jt.all()}var oa={};a$7(oa,{remove:()=>sA,set:()=>oA});async function oA(e,t){return Qe.set(e,t)}async function sA(e){return Qe.remove(e)}var qs={};a$7(qs,{current:()=>aA,initGit:()=>cA,list:()=>iA,update:()=>dA});async function iA(){return Ht.list()}async function aA(){return _.project}async function cA(e){let t=e.directory||_.directory,n=await git(["init"],{cwd:t});if(n.exitCode!==0)throw new Error(`Git init failed: ${await n.text()}`);return _.project}async function dA(e,t){return _.project}var zo={};a$7(zo,{connect:()=>hA,create:()=>pA,get:()=>uA,list:()=>lA,remove:()=>fA,resize:()=>gA,update:()=>mA});async function lA(){return st.list()}async function uA(e){return st.get(e)}async function pA(e){return st.create(e)}async function mA(e,t){return st.update(e,t)}async function fA(e){return st.remove(e)}async function gA(e,t,n){return st.resize(e,t,n)}async function hA(e){return st.get(e)}var Th;(t=>{async function e(){return []}t.list=e;})(Th||(Th={}));var Hr={};a$7(Hr,{list:()=>bA,listQuestions:()=>Ah,reject:()=>xA,rejectQuestion:()=>Rh,reply:()=>wA,replyQuestion:()=>Eh});async function Ah(){return Ot.list()}async function Eh(e){return await Ot.reply(e),true}async function Rh(e){return await Ot.reject(e.requestId),true}var bA=Ah,wA=Eh,xA=Rh;var Hs={};a$7(Hs,{list:()=>IA,read:()=>vA,search:()=>CA,status:()=>SA});async function IA(e){return bt.list(e.path)}async function vA(e){return bt.read(e.path)}async function SA(){return bt.status()}async function CA(e){return bt.search(e)}var gd={};a$7(gd,{dispose:()=>kA});async function kA(){return _.dispose()}var Br={};a$7(Br,{list:()=>PA,listPermissions:()=>_h,reply:()=>TA,replyPermission:()=>Mh,respond:()=>AA,respondPermission:()=>Oh});async function _h(){return Me.list()}async function Mh(e){return await Me.reply(e),true}async function Oh(e){return await Me.reply({requestId:e.permissionId,reply:e.response}),true}var PA=_h,TA=Mh,AA=Oh;var hd={};a$7(hd,{getContext:()=>EA,getProtocolMetadata:()=>RA});async function EA(){return go.getContext()}async function RA(){return go.getProtocolMetadata()}var _n={};a$7(_n,{getSchedulerStatus:()=>_A,isSchedulerInitialized:()=>MA,listSchedulerCommands:()=>LA,listSchedulerHeartbeats:()=>OA,listSchedulerScheduled:()=>jA});async function _A(){return Lt.getStatus()}async function MA(){return Lt.isInitialized()}async function OA(){return Lt.listHeartbeats()}async function jA(){return Lt.listScheduled()}async function LA(){return Lt.listCommands()}function sa(){let e=null,t=false,n=[];return {stream:{[Symbol.asyncIterator](){return {next(){return t?Promise.resolve({value:void 0,done:true}):n.length>0?Promise.resolve({value:n.shift(),done:false}):new Promise(i=>{e=i;})}}}},push:i=>{t||(e?(e({value:i,done:false}),e=null):n.push(i));},close:()=>{t=true,e&&(e({value:void 0,done:true}),e=null);}}}function jh(e){let t={directory:e.directory};return {config:{get:async(n,o)=>({data:await Se(()=>Co.getConfig(),"CONFIG_GET_ERROR",t)}),providers:async(n,o)=>({data:{providers:await Se(()=>ud.listProviders(),"CONFIG_PROVIDERS_ERROR",t)}})},model:{default:async(n,o)=>{let s=await Se(()=>na.getDefaultModel(),"MODEL_DEFAULT_ERROR",t);if(!s)return {data:void 0};let{provider:r,model:i}=parseModelId(s);return {data:{providerId:r,modelId:i}}},parse:async(n,o)=>({data:await Se(()=>Promise.resolve(na.parseModel(n.model)),"MODEL_PARSE_ERROR",t)})},command:{list:async(n,o)=>({data:await Se(()=>pd.listCommands(n.contextMode),"COMMAND_LIST_ERROR",t)})},permission:{list:async(n,o)=>({data:await Se(()=>Br.listPermissions(),"PERMISSION_LIST_ERROR",t)}),respond:async(n,o)=>(await Se(()=>Br.respondPermission({sessionId:n.sessionId,permissionId:n.permissionId,response:n.response}),"PERMISSION_RESPOND_ERROR",t),{data:true}),reply:async(n,o)=>(await Se(()=>Br.replyPermission({requestId:n.requestId,reply:n.reply,message:n.message}),"PERMISSION_REPLY_ERROR",t),{data:true})},question:{list:async(n,o)=>({data:await Se(()=>Hr.listQuestions(),"QUESTION_LIST_ERROR",t)}),reply:async(n,o)=>(await Se(()=>Hr.replyQuestion({requestId:n.requestId,answers:n.answers}),"QUESTION_REPLY_ERROR",t),{data:true}),reject:async(n,o)=>(await Se(()=>Hr.rejectQuestion({requestId:n.requestId}),"QUESTION_REJECT_ERROR",t),{data:true})},session:{create:async(n,o)=>({data:await Se(()=>nn.createSession({title:n?.title,directory:n?.directory??t.directory}),"SESSION_CREATE_ERROR",t)}),get:async(n,o)=>({data:await Se(()=>nn.getSession(n.sessionId),"SESSION_GET_ERROR",t)}),list:async(n,o)=>({data:await Se(()=>nn.listSessions({limit:n?.limit,directory:n?.directory??t.directory}),"SESSION_LIST_ERROR",t)}),fork:async(n,o)=>{let s=n?.directory??t.directory;return {data:await Se(()=>nn.forkSession(n.sessionId,n.messageId,s),"SESSION_FORK_ERROR",t)}},delete:async(n,o)=>(await Se(()=>nn.deleteSession(n.sessionId),"SESSION_DELETE_ERROR",t),{data:true}),abort:async(n,o)=>(await Se(()=>nn.abortSession(n.sessionId),"SESSION_ABORT_ERROR",t),{data:true}),summarize:async(n,o)=>({data:await Se(()=>nn.summarizeSession({sessionId:n.sessionId,providerId:n.providerId,modelId:n.modelId,auto:n.auto}),"SESSION_SUMMARIZE_ERROR",t)}),contextMode:{get:async(n,o)=>({data:await Se(()=>nn.getSessionContextMode(n.sessionId),"SESSION_CONTEXT_MODE_ERROR",t)}),set:async(n,o)=>(await Se(()=>nn.setSessionContextMode(n.sessionId,n.mode),"SESSION_CONTEXT_MODE_ERROR",t),{data:n.mode})},messages:async(n,o)=>({data:await Se(()=>zs.listMessages(n.sessionId,n.limit),"SESSION_MESSAGES_ERROR",t)}),message:async(n,o)=>({data:await Se(()=>zs.getMessage(n.sessionId,n.messageId),"SESSION_MESSAGE_ERROR",t)}),prompt:async(n,o)=>{let s=(n.parts??[]).filter(l=>l.type==="text").map(l=>l.text).join(`
882
+ `),r=(n.parts??[]).filter(l=>l.type==="file").map(l=>({url:l.url,filename:l.filename,mime:l.mime})),i=(n.parts??[]).find(l=>l.type==="agent")?.name;return {data:await Se(()=>zs.send({sessionId:n.sessionId,text:s,agent:n.agent,subAgent:i,model:n.model,variant:n.variant,files:r.length>0?r:void 0,noReply:n.noReply,contextMode:n.contextMode,system:n.system}),"SESSION_PROMPT_ERROR",t)}},command:async(n,o)=>({data:await Se(()=>zs.command({sessionId:n.sessionId,command:n.command,arguments:n.arguments,agent:n.agent,model:n.model,variant:n.variant,messageId:n.messageId,contextMode:n.contextMode,parts:n.parts}),"SESSION_COMMAND_ERROR",t)}),event:async(n,o)=>{let{stream:s,push:r,close:i}=sa(),c;try{c=await Se(()=>Uo.subscribeSession(n.sessionId,d=>{r({sessionId:n.sessionId,payload:d});}),"SESSION_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},update:async(n,o)=>({data:await Se(()=>nn.updateSession(n.sessionId,n),"SESSION_UPDATE_ERROR",t)}),children:async(n,o)=>({data:await Se(()=>nn.getSessionChildren(n.sessionId),"SESSION_CHILDREN_ERROR",t)}),init:async(n,o)=>({data:await Se(()=>nn.initSession(n),"SESSION_INIT_ERROR",t)}),status:async(n,o)=>({data:await Se(()=>nn.listSessionStatuses(),"SESSION_STATUS_ERROR",t)})},message:{event:async(n,o)=>{let{stream:s,push:r,close:i}=sa(),c;try{c=await Se(()=>Uo.subscribeMessage(n.sessionId,n.messageId,d=>{r({sessionId:n.sessionId,messageId:n.messageId,payload:d});}),"MESSAGE_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}}},event:{subscribe:async(n,o)=>{let{stream:s,push:r,close:i}=sa(),c;try{c=await Se(()=>Uo.subscribeAll(d=>{r({payload:d});}),"EVENT_SUBSCRIBE_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},publish:async(n,o)=>(await Se(()=>Uo.publish(n),"EVENT_PUBLISH_ERROR",t),{data:true})},agent:{list:async(n,o)=>({data:await Se(()=>ps.listAgents(),"AGENT_LIST_ERROR",t)}),get:async(n,o)=>({data:await Se(()=>ps.getAgent(n.agentId),"AGENT_GET_ERROR",t)}),default:async(n,o)=>({data:await Se(()=>ps.getDefaultAgent(),"AGENT_DEFAULT_ERROR",t)}),create:async(n,o)=>({data:await Se(()=>ps.createAgent({name:n.name,mode:n.mode,permission:n.permission}),"AGENT_CREATE_ERROR",t)}),event:async(n,o)=>{let{stream:s,push:r,close:i}=sa(),c;try{c=await Se(()=>Uo.subscribeAll(d=>{d.properties?.agentId===n.agentId&&r({agentId:n.agentId,payload:d});}),"AGENT_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}}},global:{event:async(n,o)=>{let{stream:s,push:r,close:i}=sa(),c;try{c=await Se(()=>Uo.subscribeAll(d=>{r({payload:d});}),"GLOBAL_EVENT_ERROR",t);}catch(d){throw i(),d}let l=n?.signal;return l&&l.addEventListener("abort",()=>{c?.(),i();}),{stream:s}},config:{get:async(n,o)=>({data:await Se(()=>Co.getGlobalConfig(),"CONFIG_GET_ERROR",t)}),update:async(n,o)=>({data:await Se(()=>Co.updateGlobalConfig(n),"CONFIG_UPDATE_ERROR",t)})},dispose:async(n,o)=>(await Se(()=>gd.dispose(),"GLOBAL_DISPOSE_ERROR",t),{data:true})},app:{agents:async(n,o)=>({data:await Se(()=>ps.listAgents(),"APP_AGENTS_ERROR",t)}),skills:async(n,o)=>({data:(await Se(()=>fd.all(),"APP_SKILLS_ERROR",t)).map(r=>({name:r.name,description:r.description??"",location:r.location}))}),log:async(n,o)=>({data:[]}),context:async(n,o)=>({data:await Se(()=>hd.getContext(),"APP_CONTEXT_ERROR",t)})},auth:{set:async(n,o)=>(await Se(()=>oa.set(n.providerId,n.info),"AUTH_SET_ERROR",t),{data:true}),remove:async(n,o)=>(await Se(()=>oa.remove(n.providerId),"AUTH_REMOVE_ERROR",t),{data:true})},project:{list:async(n,o)=>({data:await Se(()=>qs.list(),"PROJECT_LIST_ERROR",t)}),current:async(n,o)=>({data:await Se(()=>qs.current(),"PROJECT_CURRENT_ERROR",t)}),initGit:async(n,o)=>({data:await Se(()=>qs.initGit(n),"PROJECT_INIT_GIT_ERROR",t)}),update:async(n,o)=>({data:await Se(()=>qs.update(n.providerId,n),"PROJECT_UPDATE_ERROR",t)})},pty:{list:async(n,o)=>({data:await Se(()=>zo.list(),"PTY_LIST_ERROR",t)}),get:async(n,o)=>({data:await Se(()=>zo.get(n.id),"PTY_GET_ERROR",t)}),create:async(n,o)=>({data:await Se(()=>zo.create(n),"PTY_CREATE_ERROR",t)}),update:async(n,o)=>({data:await Se(()=>zo.update(n.id,n),"PTY_UPDATE_ERROR",t)}),remove:async(n,o)=>(await Se(()=>zo.remove(n.id),"PTY_REMOVE_ERROR",t),{data:true}),connect:async(n,o)=>({data:await Se(()=>zo.connect(n.id),"PTY_CONNECT_ERROR",t)})},file:{list:async(n,o)=>({data:await Se(()=>Hs.list({directory:n?.directory,path:n?.path}),"FILE_LIST_ERROR",t)}),read:async(n,o)=>({data:await Se(()=>Hs.read({directory:n?.directory,path:n?.path}),"FILE_READ_ERROR",t)}),status:async(n,o)=>({data:await Se(()=>Hs.status(),"FILE_STATUS_ERROR",t)}),search:async(n,o)=>({data:await Se(()=>Hs.search(n),"FILE_SEARCH_ERROR",t)})},mcp:{status:async(n,o)=>({data:await Se(()=>Hn.status(),"MCP_STATUS_ERROR",t)}),add:async(n,o)=>{let{name:s,config:r}=n;return {data:await Se(()=>Hn.add(s,r),"MCP_ADD_ERROR",t)}},connect:async(n,o)=>{let{name:s}=n;return {data:await Se(()=>Hn.connect(s),"MCP_CONNECT_ERROR",t)}},disconnect:async(n,o)=>{let{name:s}=n;return {data:await Se(()=>Hn.disconnect(s),"MCP_DISCONNECT_ERROR",t)}},tools:async(n,o)=>{let s=await Se(()=>Hn.tools(),"MCP_TOOLS_ERROR",t),r={};for(let i of Object.keys(s)){let c=i.split("_"),l=c[0];if(!l)continue;let d=c.slice(1).join("_");r[l]||(r[l]=[]),r[l].push(d);}return {data:r}},auth:{start:async(n,o)=>{let{name:s}=n;return {data:await Se(()=>Hn.startAuth(s),"MCP_AUTH_START_ERROR",t)}},authenticate:async(n,o)=>{let{name:s}=n;return {data:await Se(()=>Hn.authenticate(s),"MCP_AUTH_AUTHENTICATE_ERROR",t)}},finish:async(n,o)=>{let{name:s,authorizationCode:r}=n;return {data:await Se(()=>Hn.finishAuth(s,r),"MCP_AUTH_FINISH_ERROR",t)}},callback:async(n,o)=>{let{name:s,callbackUrl:r}=n;return {data:await Se(()=>Hn.authCallback(s,r),"MCP_AUTH_CALLBACK_ERROR",t)}},remove:async(n,o)=>{let{name:s}=n;return await Se(()=>Hn.removeAuth(s),"MCP_AUTH_REMOVE_ERROR",t),{data:true}}}},lsp:{status:async(n,o)=>({data:await Se(()=>md.getLspStatus(),"LSP_STATUS_ERROR",t)})},scheduler:{status:async(n,o)=>({data:await Se(()=>_n.getSchedulerStatus(),"SCHEDULER_STATUS_ERROR",t)}),initialized:async(n,o)=>({data:await Se(()=>_n.isSchedulerInitialized(),"SCHEDULER_INITIALIZED_ERROR",t)}),heartbeats:async(n,o)=>({data:await Se(()=>_n.listSchedulerHeartbeats(),"SCHEDULER_LIST_HEARTBEATS_ERROR",t)}),scheduled:async(n,o)=>({data:await Se(()=>_n.listSchedulerScheduled(),"SCHEDULER_LIST_SCHEDULED_ERROR",t)}),commands:async(n,o)=>({data:await Se(()=>_n.listSchedulerCommands(),"SCHEDULER_LIST_COMMANDS_ERROR",t)})}}}async function DA(){let{Server:e}=await import('./server-SQMRITFT.mjs');return e.openapi()}var Ne=a.create({service:"cli-tui-state"});async function UA(e,t,n){let o=t.options,s=m=>{if(!m)return SessionTitle.createDefault(false);let f=m.trim();return f.slice(0,50)+(f.length>50?"...":"")};if(o?.new){let m=s(o.prompt),{data:f}=await e.session.create({title:m,directory:_.directory,contextMode:n.contextMode});return Ne.debug("New session created via --new",{sessionId:f?.id,contextMode:n.contextMode}),f?.id??null}let{data:r}=await e.session.list({limit:1}),i=r?.find(m=>!m.parentId)?.id,c=t.sessionId||n.sessionId||i;if(c&&o?.fork){let{data:m}=await e.session.fork({sessionId:c,contextMode:n.contextMode});return Ne.debug("Session forked",{baseID:c,forkedID:m?.id,contextMode:n.contextMode}),m?.id??null}if(c)return Ne.debug("Using existing session",{sessionId:c}),c;let l=s(o?.prompt),{data:d}=await e.session.create({title:l,directory:_.directory,contextMode:n.contextMode});return Ne.debug("New session created (fallback)",{sessionId:d?.id,contextMode:n.contextMode}),d?.id??null}async function zA(e={}){Ne.debug("Creating TUI state",{options:e});let t={directory:_.directory,projectId:_.project.id},n={toolsExpanded:true,showThinking:true,thinkingLevel:"low",verboseLevel:"off",messageLimit:20,localShellPermission:"ask",contextMode:void 0,model:void 0,agent:void 0,sessionId:void 0},o=e.sessionId||e.options?.sessionId;if(o)try{n=await a$b(o),Ne.debug("Loaded TUI state from session",{sessionId:o,persistedState:n});}catch{Ne.debug("No persisted state found for session",{sessionId:o});}let s=jh({directory:t.directory}),r=await UA(s,{...e,sessionId:o},n),i=r||"new";if(r)try{let m=(await s.session.get({sessionId:r})).data;m?.title&&(i=m.title);}catch(d){Ne.debug("Failed to load session title",{sessionId:r,error:d});}if(r&&r!==o)try{n=await a$b(r),Ne.debug("Loaded TUI state from resolved session",{sessionId:r,persistedState:n});}catch{Ne.debug("No persisted state found for resolved session",{sessionId:r});}let c=e.model||n.model;if(!c)try{let d=await s.model.default({});d.data&&(c=`${d.data.providerId}/${d.data.modelId}`,Ne.debug("Got default model from backend",{model:c}));}catch(d){Ne.warn("Failed to get default model",{error:d});}let l=e.agent||n.agent;if(!l)try{let f=((await s.app.agents({})).data||[]).filter(a=>a.mode!=="subagent");f.length>0?(l=f[0].name,Ne.debug("Got default agent from backend",{agent:l})):(l="",Ne.warn("No agents available"));}catch(d){l="",Ne.warn("Failed to get default agent",{error:d});}return r||Ne.warn("No session ID provided, TUI may not function correctly"),Ne.debug("TUI state resolved",{agent:{provided:e.agent,persisted:n.agent,final:l},model:{provided:e.model,persisted:n.model,final:c},sessionId:{provided:e.sessionId,persisted:n.sessionId,final:r},contextMode:n.contextMode}),{agent:l,currentSessionKey:i,currentSessionId:r,activeChatRunId:null,historyLoaded:false,toolsExpanded:n.toolsExpanded,showThinking:n.showThinking,thinkingLevel:n.thinkingLevel,verboseLevel:n.verboseLevel,messageLimit:n.messageLimit,localShellPermission:n.localShellPermission,contextMode:n.contextMode,pendingShellCommand:null,sessionInfo:{model:c,modelProvider:void 0,totalTokens:null,contextTokens:null},pendingPermission:null,pendingQuestion:null,questionDisplayTimer:null,instanceContext:t,sdk:s}}var tp;function qA(){if(!tp){let e=_.state(()=>new Map,async t=>{Ne.debug("Disposing TUI state",{count:t.size}),t.clear();});tp=async t=>{let n=e(),o=JSON.stringify(t);if(!n.has(o)){let s=await zA(t);n.set(o,s);}return n.get(o)};}return tp}async function np(e={}){return qA()(e)}async function nQ(e,t,n,o){Ne.debug("Initializing TUI state with health check and event subscription");let s=await np(e);if(s.currentSessionId&&!s.contextMode)try{let i=await s.sdk.session.contextMode.get({sessionId:s.currentSessionId});i.data&&(s.contextMode=i.data,Ne.debug("Got contextMode from session API",{sessionId:s.currentSessionId,contextMode:s.contextMode}));}catch(i){Ne.debug("Failed to get contextMode from session API",{sessionId:s.currentSessionId,error:i});}s.currentSessionId?(Ne.debug("Saving initial TUI state to storage",{sessionId:s.currentSessionId}),b$4(s)):Ne.warn("No session ID, skipping initial state save"),HA(s,n),Ne.debug("Running TUI state health check (background)"),Fh(s).then(i=>{i.healthy?Ne.debug("TUI state health check passed"):(Ne.warn("TUI state health check failed",{report:i}),Ne.debug("Attempting to auto-heal TUI state"),GA(s).then(c=>{c.success?(Ne.debug("TUI state auto-heal successful",{report:c}),n.addSystem(i$1("tui.state.healed")),b$4(s)):(Ne.error("TUI state auto-heal failed",{report:c}),n.addSystem(i$1("tui.state.heal_failed")));}));}),Ne.debug("Subscribing to backend state events");let r=await BA(s,t,n,o);return Ne.debug("Backend state events subscribed"),{state:s,unsubscribe:r}}async function HA(e,t){Ne.debug("Validating local preferences",{localModel:e.sessionInfo.model,localAgent:e.agent,sessionId:e.currentSessionId});try{let n=[];if(e.sessionInfo.model)try{let o=await e.sdk.model.parse({model:e.sessionInfo.model});o.data&&(((await e.sdk.config.providers({})).data?.providers||[]).find(l=>l.id===o.data.providerId)?.models?.[o.data.modelId]?(n.push(`model: ${e.sessionInfo.model}`),Ne.debug("Model validated successfully",{model:e.sessionInfo.model})):(Ne.warn("Local model does not exist",{model:e.sessionInfo.model,providerId:o.data.providerId,modelId:o.data.modelId}),t.addSystem(i$1("tui.state.model_not_found",{vars:{model:e.sessionInfo.model}})),e.sessionInfo.model=void 0));}catch(o){Ne.error("Failed to validate model",{model:e.sessionInfo.model,error:o});}if(e.agent)try{((await e.sdk.app.agents({})).data||[]).find(i=>i.name===e.agent)?(n.push(`agent: ${e.agent}`),Ne.debug("Agent validated successfully",{agent:e.agent})):(Ne.warn("Local agent does not exist",{agent:e.agent}),t.addSystem(i$1("tui.state.agent_not_found",{vars:{agent:e.agent}})),e.agent="");}catch(o){Ne.error("Failed to validate agent",{agent:e.agent,error:o});}n.length>0&&(Ne.debug("Local preferences validated",{validationResults:n}),t.addSystem(i$1("tui.state.preferences_validated",{vars:{items:n.join(", ")}}))),Ne.debug("Local preferences validation completed");}catch(n){Ne.error("Failed to validate local preferences",{error:n});}}async function Lh(e,t){return _.provide({directory:e.instanceContext.directory,init:void 0,fn:t})}async function ho(e,t,n){await Lh(e,async()=>{await pe.publish(t,n);});}async function yd(e,t,n){let o=()=>{};return await Lh(e,async()=>{o=pe.subscribe(t,n),await pe.waitForSubscription();}),o}async function oQ(e,t){await e.sdk.permission.reply({requestId:t.requestId,reply:t.reply});}async function sQ(e,t){await e.sdk.question.reply({requestId:t.requestId,answers:t.answers});}var to={async appendPrompt(e,t){await ho(e,c$2.PromptAppend,t);},async openHelp(e){await ho(e,c$2.CommandExecute,{command:"help.show"});},async openSessions(e){await ho(e,c$2.CommandExecute,{command:"session.list"});},async openThemes(e){await ho(e,c$2.CommandExecute,{command:"session.list"});},async openModels(e){await ho(e,c$2.CommandExecute,{command:"model.list"});},async submitPrompt(e){await ho(e,c$2.CommandExecute,{command:"prompt.submit"});},async clearPrompt(e){await ho(e,c$2.CommandExecute,{command:"prompt.clear"});},async executeCommand(e,t){let n={session_new:"session.new",session_share:"session.share",session_interrupt:"session.interrupt",session_compact:"session.compact",messages_page_up:"session.page.up",messages_page_down:"session.page.down",messages_line_up:"session.line.up",messages_line_down:"session.line.down",messages_half_page_up:"session.half.page.up",messages_half_page_down:"session.half.page.down",messages_first:"session.first",messages_last:"session.last",agent_cycle:"agent.cycle"};await ho(e,c$2.CommandExecute,{command:n[t.command]||t.command});},async showToast(e,t){await ho(e,c$2.ToastShow,t);},async selectSession(e,t){await ho(e,c$2.SessionSelect,t);},async publish(e,t){let n=Object.values(c$2).find(o=>o.type===t.type);n&&await ho(e,n,t.properties);}};async function Dh(e){return (await e.sdk.app.agents({})).data||[]}async function rQ(e){return (await e.sdk.session.list({limit:50})).data||[]}async function $h(e){let n=(await e.sdk.config.providers({})).data?.providers||[];return Object.fromEntries(n.filter(o=>typeof o.id=="string"&&o.id.length>0).map(o=>[o.id,{name:o.name,models:o.models}]))}async function BA(e,t,n,o){let s=[];Ne.debug("Subscribing to backend events");let r=await yd(e,X.Event.Created,async d=>{Ne.debug("Session created",{sessionId:d.properties.info.id}),n.addSystem(i$1("tui.state.session.created",{vars:{title:d.properties.info.title||d.properties.info.id}}));});s.push(r);let i=await yd(e,X.Event.Updated,async d=>{Ne.debug("Session updated",{sessionId:d.properties.info.id}),e.currentSessionId===d.properties.info.id&&o();});s.push(i);let c=await yd(e,X.Event.Deleted,async d=>{let m=d.properties.info.id,f=d.properties.info.title||m;Ne.debug("Session deleted",{sessionId:m,sessionTitle:f}),n.addSystem(i$1("tui.state.session.deleted",{vars:{title:f}})),e.currentSessionId===m&&(e.currentSessionId=null,e.currentSessionKey="new",o());});s.push(c);let l=await yd(e,ze.ToolsChanged,async d=>{Ne.debug("MCP tools changed",{server:d.properties.server});});return s.push(l),Ne.debug("Backend events subscribed",{count:s.length}),()=>{Ne.debug("Unsubscribing from backend events");for(let d of s)d();}}async function Fh(e){let t={checks:[],healthy:true};Ne.debug("Running TUI state diagnostics");try{await(await import('fs/promises')).access(e.instanceContext.directory),t.checks.push({name:"Instance Context",status:"pass",message:`Directory exists: ${e.instanceContext.directory}`});}catch{t.healthy=false,t.checks.push({name:"Instance Context",status:"fail",message:`Directory not accessible: ${e.instanceContext.directory}`,suggestion:"Reinitialize Instance context"});}try{let n=await Dh(e);Ne.debug("Agent list retrieved for health check",{agent:e.agent,availableAgents:n.map(s=>s.name),agentCount:n.length}),n.find(s=>s.name===e.agent)?t.checks.push({name:"Current Agent",status:"pass",message:`Agent exists: ${e.agent}`}):(t.healthy=!1,t.checks.push({name:"Current Agent",status:"fail",message:`Agent not found: ${e.agent}`,suggestion:"Switch to default agent or first available agent"}),Ne.warn("Current agent not found in available agents",{agent:e.agent,availableAgents:n.map(s=>s.name)}));}catch(n){t.healthy=false,t.checks.push({name:"Current Agent",status:"fail",message:`Failed to check agent: ${String(n)}`,suggestion:"Check Instance context and API layer"});}if(e.currentSessionId)try{(await e.sdk.session.get({sessionId:e.currentSessionId})).data?t.checks.push({name:"Current Session",status:"pass",message:`Session exists: ${e.currentSessionId}`}):(t.healthy=!1,t.checks.push({name:"Current Session",status:"fail",message:`Session not found: ${e.currentSessionId}`,suggestion:"Clear invalid session ID or create new session"}));}catch(n){t.healthy=false,t.checks.push({name:"Current Session",status:"fail",message:`Failed to check session: ${String(n)}`,suggestion:"Clear invalid session ID"});}if(e.sessionInfo.model)try{let n=await $h(e),{provider:o,model:s}=parseModelId(e.sessionInfo.model);n[o]?.models?.[s]?t.checks.push({name:"Current Model",status:"pass",message:`Model exists: ${e.sessionInfo.model}`}):(t.healthy=!1,t.checks.push({name:"Current Model",status:"fail",message:`Model not found: ${e.sessionInfo.model}`,suggestion:"Switch to default model or first available model"}));}catch(n){t.healthy=false,t.checks.push({name:"Current Model",status:"fail",message:`Failed to check model: ${String(n)}`,suggestion:"Check Instance context and API layer"});}return Ne.debug("TUI state diagnostics completed",{healthy:t.healthy,checks:t.checks.length}),t}async function GA(e){let t={actions:[],success:true};Ne.debug("Running TUI state auto-heal");let n=await Fh(e);for(let o of n.checks)if(o.status==="fail")try{switch(o.name){case "Current Agent":{let s=await Dh(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 $h(e),r=Object.keys(s);if(r.length>0){let i=r[0],c=s[i];if(c?.models){let l=Object.keys(c.models);if(l.length>0){let d=l[0];e.sessionInfo.model=`${i}/${d}`,t.actions.push({name:"Fix Current Model",status:"success",message:`Switched to model: ${e.sessionInfo.model}`});}else t.success=!1,t.actions.push({name:"Fix Current Model",status:"fail",message:"No models available in provider"});}else t.success=!1,t.actions.push({name:"Fix Current Model",status:"fail",message:"No models available"});}else t.success=!1,t.actions.push({name:"Fix Current Model",status:"fail",message:"No providers available"});break}}}catch(s){t.success=false,t.actions.push({name:`Fix ${o.name}`,status:"fail",message:`Failed to fix: ${String(s)}`});}return Ne.debug("TUI state auto-heal completed",{success:t.success,actions:t.actions.length}),t}var WA={400:{description:"Bad request",content:{"application/json":{schema:resolver(F.object({data:F.any(),errors:F.array(F.record(F.string(),F.any())),success:F.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,WA[t]]))}var yo=()=>np(),KA=F.object({path:F.string(),body:F.any()}),JA=new AsyncQueue,YA=new AsyncQueue;var XA=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(KA)}}}}}),async e=>{let t=await JA.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(F.boolean())}}}}}),validator("json",F.any()),async e=>{let t=e.req.valid("json");return YA.push(t),e.json(true)}),qh=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(F.boolean())}}},...Te(400)}}),validator("json",b$2.PromptAppend.properties),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),async e=>{let t=await yo();return await to.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(F.boolean())}}},...Te(400)}}),validator("json",F.object({command:F.string()})),async e=>{let t=await yo();return await to.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(F.boolean())}}}}}),validator("json",b$2.ToastShow.properties),async e=>{let t=await yo();return await to.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(F.boolean())}}},...Te(400)}}),validator("json",F.union(Object.values(b$2).map(e=>F.object({type:F.literal(e.type),properties:e.properties}).meta({ref:"Event."+e.type})))),async e=>{let t=await yo();return await to.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(F.boolean())}}},...Te(400,404)}}),validator("json",b$2.SessionSelect.properties),async e=>{let t=await yo();return await to.selectSession(t,e.req.valid("json")),e.json(true)}).route("/control",XA));var Hh=a.create({service:"vcs"}),Gs;(l=>{l.Event={BranchUpdated:a$5.define("vcs.branch.updated",F.object({branch:F.string().optional()}))},l.Info=F.object({branch:F.string()}).meta({ref:"VcsInfo"});async function n(){return $`git rev-parse --abbrev-ref HEAD`.quiet().nothrow().cwd(_.worktree).text().then(d=>d.trim()).catch(()=>{})}let o;function s(){return o||(o=_.state(async()=>{if(_.project.vcs!=="git")return {branch:async()=>{},unsubscribe:void 0};let d=await n();Hh.info("initialized",{branch:d});let m=pe.subscribe(Nn.Event.Updated,async f=>{if(f.properties.file.endsWith("HEAD"))return;let a=await n();a!==d&&(Hh.info("branch changed",{from:d,to:a}),d=a,await pe.publish(l.Event.BranchUpdated,{branch:a}));});return {branch:async()=>d,unsubscribe:m}},async d=>{d.unsubscribe?.();})),o}function r(){return s()()}async function i(){return r()}l.init=i;async function c(){return await r().then(d=>d.branch())}l.branch=c;})(Gs||(Gs={}));var Wh=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(Ht.Info.array())}}}}}),async e=>{let t=await Ht.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(Ht.Info)}}}}}),async e=>e.json(_.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(Ht.Info)}}},...Te(400,404)}}),validator("param",F.object({providerId:F.string()})),validator("json",Ht.update.schema.omit({providerId:true})),async e=>{let t=e.req.valid("param").providerId,n=e.req.valid("json"),o=await Ht.update({...n,providerId:t});return e.json(o)}));var Wr=a.create({service:"server"}),Jh=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(X.Info.array())}}}}}),validator("query",F.object({directory:F.string().optional().meta({description:"Filter sessions by project directory"}),roots:F.coerce.boolean().optional().meta({description:"Only return root sessions (no parentId)"}),start:F.coerce.number().optional().meta({description:"Filter sessions updated on or after this timestamp (milliseconds since epoch)"}),search:F.string().optional().meta({description:"Filter sessions by title (case-insensitive)"}),limit:F.coerce.number().optional().meta({description:"Maximum number of sessions to return"})})),async e=>{let t=e.req.valid("query"),n=t.search?.toLowerCase(),o=[];for await(let s of X.list())if(!(t.directory!==void 0&&s.directory!==t.directory)&&!(t.roots&&s.parentId)&&!(t.start!==void 0&&s.time.updated<t.start)&&!(n!==void 0&&!s.title.toLowerCase().includes(n))&&(o.push(s),t.limit!==void 0&&o.length>=t.limit))break;return e.json(o)}).get("/status",describeRoute({summary:"Get session status",description:"Retrieve the current status of all sessions, including active, idle, and completed states.",operationId:"session.status",responses:{200:{description:"Get session status",content:{"application/json":{schema:resolver(F.record(F.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(X.Info)}}},...Te(400,404)}}),validator("param",F.object({sessionId:X.get.schema})),async e=>{let t=e.req.valid("param").sessionId;Wr.debug("SEARCH",{url:e.req.url});let n=await X.get(t);return e.json(n)}).get("/:sessionId/children",describeRoute({summary:"Get session children",tags:["Session"],description:"Retrieve all child sessions that were forked from the specified parent session.",operationId:"session.children",responses:{200:{description:"List of children",content:{"application/json":{schema:resolver(X.Info.array())}}},...Te(400,404)}}),validator("param",F.object({sessionId:X.children.schema})),async e=>{let t=e.req.valid("param").sessionId,n=await X.children(t);return e.json(n)}).get("/:sessionId/todo",describeRoute({summary:"Get session todos",description:"Retrieve the todo list associated with a specific session, showing tasks and action items.",operationId:"session.todo",responses:{200:{description:"Todo list",content:{"application/json":{schema:resolver(po.Info.array())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),async e=>{let t=e.req.valid("param").sessionId,n=await po.get(t);return e.json(n)}).post("/",describeRoute({summary:"Create session",description:"Create a new EasBot session for interacting with AI assistants and managing conversations.",operationId:"session.create",responses:{...Te(400),200:{description:"Successfully created session",content:{"application/json":{schema:resolver(X.Info)}}}}}),validator("json",X.create.schema.optional()),async e=>{let t=e.req.valid("json")??{},n=await X.create(t);return e.json(n)}).delete("/:sessionId",describeRoute({summary:"Delete session",description:"Delete a session and permanently remove all associated data, including messages and history.",operationId:"session.delete",responses:{200:{description:"Successfully deleted session",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:X.remove.schema})),async e=>{let t=e.req.valid("param").sessionId;return await X.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(X.Info)}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string()})),validator("json",F.object({title:F.string().optional(),time:F.object({archived:F.number().optional()}).optional()})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await X.update(t,s=>{n.title!==void 0&&(s.title=n.title),n.time?.archived!==void 0&&(s.time.archived=n.time.archived);},{touch:false});return e.json(o)}).post("/:sessionId/init",describeRoute({summary:"Initialize session",description:"Analyze the current application and create an AGENTS.md file with project-specific agent configurations.",operationId:"session.init",responses:{200:{description:"200",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",X.initialize.schema.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json");return await X.initialize({...n,sessionId:t}),e.json(true)}).post("/:sessionId/fork",describeRoute({summary:"Fork session",description:"Create a new session by forking an existing session at a specific message point.",operationId:"session.fork",responses:{200:{description:"200",content:{"application/json":{schema:resolver(X.Info)}}}}}),validator("param",F.object({sessionId:X.fork.schema.shape.sessionId})),validator("json",X.fork.schema.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await X.fork({...n,sessionId:t});return e.json(o)}).post("/:sessionId/abort",describeRoute({summary:"Abort session",description:"Abort an active session and stop any ongoing AI processing or command execution.",operationId:"session.abort",responses:{200:{description:"Aborted session",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string()})),async e=>(await Je.cancel(e.req.valid("param").sessionId),e.json(true))).post("/:sessionId/share",describeRoute({summary:"Share session",description:"Create a shareable link for a session, allowing others to view the conversation.",operationId:"session.share",responses:{200:{description:"Successfully shared session",content:{"application/json":{schema:resolver(X.Info)}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string()})),async e=>{let t=e.req.valid("param").sessionId;await X.share(t);let n=await X.get(t);return e.json(n)}).get("/:sessionId/diff",describeRoute({summary:"Get message diff",description:"Get the file changes (diff) that resulted from a specific user message in the session.",operationId:"session.diff",responses:{200:{description:"Successfully retrieved diff",content:{"application/json":{schema:resolver(yt.FileDiff.array())}}}}}),validator("param",F.object({sessionId:Qo.diff.schema.shape.sessionId})),validator("query",F.object({messageId:Qo.diff.schema.shape.messageId})),async e=>{let t=e.req.valid("query"),n=e.req.valid("param"),o=await Qo.diff({sessionId:n.sessionId,messageId:t.messageId});return e.json(o)}).delete("/:sessionId/share",describeRoute({summary:"Unshare session",description:"Remove the shareable link for a session, making it private again.",operationId:"session.unshare",responses:{200:{description:"Successfully unshared session",content:{"application/json":{schema:resolver(X.Info)}}},...Te(400,404)}}),validator("param",F.object({sessionId:X.unshare.schema})),async e=>{let t=e.req.valid("param").sessionId;await X.unshare(t);let n=await X.get(t);return e.json(n)}).post("/:sessionId/summarize",describeRoute({summary:"Summarize session",description:"Generate a concise summary of the session using AI compaction to preserve key information.",operationId:"session.summarize",responses:{200:{description:"Summarized session",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",F.object({providerId:F.string(),modelId:F.string(),auto:F.boolean().optional().default(false)})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await X.get(t);return await ao.cleanup(o),await sn.create({sessionId:t,agent:"compaction",model:{providerId:n.providerId,modelId:n.modelId},auto:n.auto}),await Je.loop({sessionId:t}),e.json(true)}).get("/:sessionId/contextMode",describeRoute({summary:"Get session context mode",description:"Get the context mode of a session (general or coder).",tags:["Session"],operationId:"session.contextMode.get",responses:{200:{description:"Context mode",content:{"application/json":{schema:resolver(F.enum(["general","coder"]))}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),async e=>{let t=e.req.valid("param").sessionId,n=await X.getContextMode(t);return e.json(n)}).put("/:sessionId/contextMode",describeRoute({summary:"Set session context mode",description:"Set the context mode of a session (general or coder).",tags:["Session"],operationId:"session.contextMode.set",responses:{200:{description:"Successfully updated context mode",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",F.object({mode:F.enum(["general","coder"]).meta({description:"Context mode to set"})})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json");return await X.setContextMode(t,n.mode),e.json(true)}).get("/:sessionId/message",describeRoute({summary:"Get session messages",description:"Retrieve all messages in a session, including user prompts and AI responses.",operationId:"session.messages",responses:{200:{description:"List of messages",content:{"application/json":{schema:resolver(ve.WithParts.array())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("query",F.object({limit:F.coerce.number().optional()})),async e=>{let t=e.req.valid("query"),n=await X.messages({sessionId:e.req.valid("param").sessionId,limit:t.limit});return e.json(n)}).get("/:sessionId/message/:messageId",describeRoute({summary:"Get message",description:"Retrieve a specific message from a session by its message ID.",operationId:"session.message",responses:{200:{description:"Message",content:{"application/json":{schema:resolver(F.object({info:ve.Info,parts:ve.Part.array()}))}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"}),messageId:F.string().meta({description:"Message ID"})})),async e=>{let t=e.req.valid("param"),n=await ve.get({sessionId:t.sessionId,messageId:t.messageId});return e.json(n)}).delete("/:sessionId/message/:messageId/part/:partId",describeRoute({description:"Delete a part from a message",operationId:"part.delete",responses:{200:{description:"Successfully deleted part",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"}),messageId:F.string().meta({description:"Message ID"}),partId:F.string().meta({description:"Part ID"})})),async e=>{let t=e.req.valid("param");return await X.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",F.object({sessionId:F.string().meta({description:"Session ID"}),messageId:F.string().meta({description:"Message ID"}),partId:F.string().meta({description:"Part ID"})})),validator("json",ve.Part),async e=>{let t=e.req.valid("param"),n=e.req.valid("json");if(n.id!==t.partId||n.messageId!==t.messageId||n.sessionId!==t.sessionId)throw new Error(`Part mismatch: body.id='${n.id}' vs partId='${t.partId}', body.messageId='${n.messageId}' vs messageId='${t.messageId}', body.sessionId='${n.sessionId}' vs sessionId='${t.sessionId}'`);let o=await X.updatePart(n);return e.json(o)}).post("/:sessionId/message",describeRoute({summary:"Send message",description:"Create and send a new message to a session, streaming the AI response.",operationId:"session.prompt",responses:{200:{description:"Created message",content:{"application/json":{schema:resolver(F.object({info:ve.Assistant,parts:ve.Part.array()}))}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",Je.PromptInput.omit({sessionId:true})),async e=>(e.status(200),e.header("Content-Type","application/json"),stream(e,async t=>{let n=e.req.valid("param").sessionId,o=e.req.valid("json"),s=await Je.prompt({...o,sessionId:n});t.write(JSON.stringify(s));}))).post("/:sessionId/prompt_async",describeRoute({summary:"Send async message",description:"Create and send a new message to a session asynchronously, starting the session if needed and returning immediately.",operationId:"session.prompt_async",responses:{204:{description:"Prompt accepted"},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",Je.PromptInput.omit({sessionId:true})),async e=>(e.status(204),e.header("Content-Type","application/json"),stream(e,async()=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json");Je.prompt({...n,sessionId:t});}))).post("/:sessionId/command",describeRoute({summary:"Send command",description:"Send a new command to a session for execution by the AI assistant.",operationId:"session.command",responses:{200:{description:"Created message",content:{"application/json":{schema:resolver(F.object({info:ve.Assistant.optional(),parts:ve.Part.array().optional(),title:F.string(),metadata:F.record(F.string(),F.unknown()),output:F.string(),success:F.boolean(),error:F.string().optional()}))}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",Je.CommandInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Je.command({...n,sessionId:t});return e.json(o)}).post("/:sessionId/shell",describeRoute({summary:"Run shell command",description:"Execute a shell command within the session context and return the AI's response.",operationId:"session.shell",responses:{200:{description:"Created message",content:{"application/json":{schema:resolver(ve.Assistant)}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string().meta({description:"Session ID"})})),validator("json",Je.ShellInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId,n=e.req.valid("json"),o=await Je.shell({...n,sessionId:t});return e.json(o)}).post("/:sessionId/revert",describeRoute({summary:"Revert message",description:"Revert a specific message in a session, undoing its effects and restoring the previous state.",operationId:"session.revert",responses:{200:{description:"Updated session",content:{"application/json":{schema:resolver(X.Info)}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string()})),validator("json",ao.RevertInput.omit({sessionId:true})),async e=>{let t=e.req.valid("param").sessionId;Wr.info("revert",e.req.valid("json"));let n=await ao.revert({sessionId:t,...e.req.valid("json")});return e.json(n)}).post("/:sessionId/unrevert",describeRoute({summary:"Restore reverted messages",description:"Restore all previously reverted messages in a session.",operationId:"session.unrevert",responses:{200:{description:"Updated session",content:{"application/json":{schema:resolver(X.Info)}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string()})),async e=>{let t=e.req.valid("param").sessionId,n=await ao.unrevert({sessionId:t});return e.json(n)}).post("/:sessionId/permissions/:permissionId",describeRoute({summary:"Respond to permission",deprecated:true,description:"Approve or deny a permission request from the AI assistant.",operationId:"permission.respond",responses:{200:{description:"Permission processed successfully",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({sessionId:F.string(),permissionId:F.string()})),validator("json",F.object({response:Me.Reply})),async e=>{let t=e.req.valid("param");return Me.reply({requestId:t.permissionId,reply:e.req.valid("json").response}),e.json(true)}).get("/:sessionId/event",describeRoute({summary:"Get session events",description:"Subscribe to events for a specific session using server-sent events.",operationId:"session.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:resolver(F.object({sessionId:F.string(),directory:F.string(),payload:a$5.payloads()}))}}}}}),validator("param",F.object({sessionId:F.string()})),async e=>{let{sessionId:t}=e.req.valid("param");return Wr.info("session event connected",{sessionId:t}),streamSSE(e,async n=>{await n.writeSSE({data:JSON.stringify({sessionId:t,payload:{type:"session.connected",properties:{}}})});async function o(r){(r.properties?.sessionId??r.properties?.sessionId)===t&&await n.writeSSE({data:JSON.stringify({sessionId:t,payload:r})});}ft.on("event",o);let s=setInterval(()=>{n.writeSSE({data:JSON.stringify({sessionId:t,payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(r=>{n.onAbort(()=>{clearInterval(s),ft.off("event",o),Wr.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(F.object({sessionId:F.string(),messageId:F.string(),directory:F.string(),payload:a$5.payloads()}))}}}}}),validator("param",F.object({sessionId:F.string(),messageId:F.string()})),async e=>{let{sessionId:t,messageId:n}=e.req.valid("param");return Wr.debug("message event connected",{sessionId:t,messageId:n}),streamSSE(e,async o=>{await o.writeSSE({data:JSON.stringify({sessionId:t,messageId:n,payload:{type:"message.connected",properties:{}}})});async function s(i){let c=i.properties?.sessionId??i.properties?.sessionId,l=i.properties?.messageId??i.properties?.messageId;c===t&&l===n&&await o.writeSSE({data:JSON.stringify({sessionId:t,messageId:n,payload:i})});}ft.on("event",s);let r=setInterval(()=>{o.writeSSE({data:JSON.stringify({sessionId:t,messageId:n,payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(i=>{o.onAbort(()=>{clearInterval(r),ft.off("event",s),Wr.debug("message event disconnected",{sessionId:t,messageId:n}),i();});});})}));var Yh=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(st.Info.array())}}}}}),async e=>e.json(st.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(st.Info)}}},...Te(400)}}),validator("json",st.CreateInput),async e=>{let t=await st.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(st.Info)}}},...Te(404)}}),validator("param",F.object({ptyId:F.string()})),async e=>{let t=st.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(st.Info)}}},...Te(400)}}),validator("param",F.object({ptyId:F.string()})),validator("json",st.UpdateInput),async e=>{let t=await st.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(F.boolean())}}},...Te(404)}}),validator("param",F.object({ptyId:F.string()})),async e=>(await st.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(F.boolean())}}},...Te(404)}}),validator("param",F.object({ptyId:F.string()})),async e=>e.json({error:"WebSocket not implemented in Node.js mode yet"},501)));var Xh=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(F.record(F.string(),Status))}}}}}),async e=>e.json(await ze.status())).post("/",describeRoute({summary:"Add MCP server",description:"Dynamically add a new Model Context Protocol (MCP) server to the system.",operationId:"mcp.add",responses:{200:{description:"MCP server added successfully",content:{"application/json":{schema:resolver(F.record(F.string(),Status))}}},...Te(400)}}),validator("json",F.object({name:F.string(),config:he.Mcp})),async e=>{let{name:t,config:n}=e.req.valid("json"),o=await ze.add(t,n);return e.json(o.status)}).post("/:name/auth",describeRoute({summary:"Start MCP OAuth",description:"Start OAuth authentication flow for a Model Context Protocol (MCP) server.",operationId:"mcp.auth.start",responses:{200:{description:"OAuth flow started",content:{"application/json":{schema:resolver(F.object({authorizationUrl:F.string().describe("URL to open in browser for authorization")}))}}},...Te(400,404)}}),async e=>{let t=e.req.param("name");if(!await ze.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let o=await ze.startAuth(t);return e.json(o)}).post("/:name/auth/callback",describeRoute({summary:"Complete MCP OAuth",description:"Complete OAuth authentication for a Model Context Protocol (MCP) server using the authorization code.",operationId:"mcp.auth.callback",responses:{200:{description:"OAuth authentication completed",content:{"application/json":{schema:resolver(Status)}}},...Te(400,404)}}),validator("json",F.object({code:F.string().describe("Authorization code from OAuth callback")})),async e=>{let t=e.req.param("name"),{code:n}=e.req.valid("json"),o=await ze.finishAuth(t,n);return e.json(o)}).post("/:name/auth/authenticate",describeRoute({summary:"Authenticate MCP OAuth",description:"Start OAuth flow and wait for callback (opens browser)",operationId:"mcp.auth.authenticate",responses:{200:{description:"OAuth authentication completed",content:{"application/json":{schema:resolver(Status)}}},...Te(400,404)}}),async e=>{let t=e.req.param("name");if(!await ze.supportsOAuth(t))return e.json({error:`MCP server ${t} does not support OAuth`},400);let o=await ze.authenticate(t);return e.json(o)}).delete("/:name/auth",describeRoute({summary:"Remove MCP OAuth",description:"Remove OAuth credentials for an MCP server",operationId:"mcp.auth.remove",responses:{200:{description:"OAuth credentials removed",content:{"application/json":{schema:resolver(F.object({success:F.literal(true)}))}}},...Te(404)}}),async e=>{let t=e.req.param("name");return await ze.removeAuth(t),e.json({success:true})}).post("/:name/connect",describeRoute({description:"Connect an MCP server",operationId:"mcp.connect",responses:{200:{description:"MCP server connected successfully",content:{"application/json":{schema:resolver(F.boolean())}}}}}),validator("param",F.object({name:F.string()})),async e=>{let{name:t}=e.req.valid("param");return await ze.connect(t),e.json(true)}).post("/:name/disconnect",describeRoute({description:"Disconnect an MCP server",operationId:"mcp.disconnect",responses:{200:{description:"MCP server disconnected successfully",content:{"application/json":{schema:resolver(F.boolean())}}}}}),validator("param",F.object({name:F.string()})),async e=>{let{name:t}=e.req.valid("param");return await ze.disconnect(t),e.json(true)}).get("/tools",describeRoute({summary:"Get MCP tools",description:"Get the list of tools from all connected MCP servers.",operationId:"mcp.tools",responses:{200:{description:"MCP tools by server",content:{"application/json":{schema:resolver(F.record(F.string(),F.array(F.string())))}}}}}),async e=>{let t=await ze.tools(),n={};for(let o of Object.keys(t)){let s=o.split("_"),r=s[0];if(!r)continue;let i=s.slice(1).join("_");n[r]||(n[r]=[]),n[r].push(i);}return e.json(n)}));var 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",F.object({pattern:F.string()})),async e=>{let t=e.req.valid("query").pattern,n=await a$8.search({cwd:_.directory,pattern:t,limit:10});return e.json(n)}).get("/find/file",describeRoute({summary:"Find files",description:"Search for files or directories by name or pattern in the project directory.",operationId:"find.files",responses:{200:{description:"File paths",content:{"application/json":{schema:resolver(F.string().array())}}}}}),validator("query",F.object({query:F.string(),dirs:F.enum(["true","false"]).optional(),type:F.enum(["file","directory"]).optional(),limit:F.coerce.number().int().min(1).max(200).optional()})),async e=>{let t=e.req.valid("query").query,n=e.req.valid("query").dirs,o=e.req.valid("query").type,s=e.req.valid("query").limit,r=await bt.search({query:t,limit:s??10,dirs:n!=="false",type:o});return e.json(r)}).get("/find/symbol",describeRoute({summary:"Find symbols",description:"Search for workspace symbols like functions, classes, and variables using LSP.",operationId:"find.symbols",responses:{200:{description:"Symbols",content:{"application/json":{schema:resolver(We.LspSymbol.array())}}}}}),validator("query",F.object({query:F.string()})),async e=>e.json([])).get("/file",describeRoute({summary:"List files",description:"List files and directories in a specified path.",operationId:"file.list",responses:{200:{description:"Files and directories",content:{"application/json":{schema:resolver(bt.Node.array())}}}}}),validator("query",F.object({path:F.string()})),async e=>{let t=e.req.valid("query").path,n=await bt.list(t);return e.json(n)}).get("/file/content",describeRoute({summary:"Read file",description:"Read the content of a specified file.",operationId:"file.read",responses:{200:{description:"File content",content:{"application/json":{schema:resolver(bt.Content)}}}}}),validator("query",F.object({path:F.string()})),async e=>{let t=e.req.valid("query").path,n=await bt.read(t);return e.json(n)}).get("/file/status",describeRoute({summary:"Get file status",description:"Get the git status of all files in the project.",operationId:"file.status",responses:{200:{description:"File status",content:{"application/json":{schema:resolver(bt.Info.array())}}}}}),async e=>{let t=await bt.status();return e.json(t)}));var pE=a.create({service:"server"}),ey=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(F.object({providers:xe.Info.array(),default:F.record(F.string(),F.string())}))}}}}}),async e=>{var o=[];try{let t=c(o,pE.time("providers"));let n=await xe.list().then(c=>mapValues(c,l=>l));return e.json({providers:Object.values(n),default:mapValues(n,c=>xe.sort(Object.values(c.models))[0]?.id??"")})}catch(s){var r=s,i=true;}finally{d(o,r,i);}}));var vd;(m=>{let e=a.create({service:"share-next"});async function t(){return he.get().then(f=>f.enterprise?.url??"https://api.easbot.cn")}m.url=t;let n=process.env.EASBOT_DISABLE_SHARE==="true"||process.env.EASBOT_DISABLE_SHARE==="1";async function o(){n||(pe.subscribe(X.Event.Updated,async f=>{await c(f.properties.info.id,[{type:"session",data:f.properties.info}]);}),pe.subscribe(ve.Event.Updated,async f=>{await c(f.properties.info.sessionId,[{type:"message",data:f.properties.info}]),f.properties.info.role==="user"&&await c(f.properties.info.sessionId,[{type:"model",data:[await xe.getModel(f.properties.info.model.providerId,f.properties.info.model.modelId).then(a=>a)]}]);}),pe.subscribe(ve.Event.PartUpdated,async f=>{await c(f.properties.part.sessionId,[{type:"part",data:f.properties.part}]);}),pe.subscribe(X.Event.Diff,async f=>{await c(f.properties.sessionId,[{type:"session_diff",data:f.properties.diff}]);}));}m.init=o;async function s(f){if(n)return {id:"",url:"",secret:""};e.info("creating share",{sessionId:f});let p=(await Fetch.post(`${await t()}/api/share`,{sessionId:f})).data;return await a$6.write(["session_share",f],p),await d(f),p}m.create=s;function r(f){return a$6.read(["session_share",f])}let i=new Map;async function c(f,a){if(n)return;let p=i.get(f);if(p){for(let h of a)p.data.set("id"in h?h.id:ulid(),h);return}let u=new Map;for(let h of a)u.set("id"in h?h.id:ulid(),h);let g=setTimeout(async()=>{let h=i.get(f);if(!h)return;i.delete(f);let S=await r(f).catch(()=>{});S&&await Fetch.post(`${await t()}/api/share/${S.id}/sync`,{secret:S.secret,data:Array.from(h.data.values())});},1e3);i.set(f,{timeout:g,data:u});}async function l(f){if(n)return;e.debug("removing share",{sessionId:f});let a=await r(f);a&&(await Fetch.del(`${await t()}/api/share/${a.id}`,{secret:a.secret}),await a$6.remove(["session_share",f]));}m.remove=l;async function d(f){e.info("full sync",{sessionId:f});let a=await X.get(f),p=await X.diff(f),u=await Array.fromAsync(ve.stream(f)),g=await Promise.all(u.filter(h=>h.info.role==="user").map(h=>h.info.model).map(h=>xe.getModel(h.providerId,h.modelId).then(S=>S)));await c(f,[{type:"session",data:a},...u.map(h=>({type:"message",data:h.info})),...u.flatMap(h=>h.parts.map(S=>({type:"part",data:S}))),{type:"session_diff",data:p},{type:"model",data:g}]);}})(vd||(vd={}));var mE=a$5.define("command.executed",F.object({name:F.string(),sessionId:F.string(),arguments:F.union([F.string(),F.record(F.string(),F.unknown())]),messageId:F.string().optional()})),ny=false;async function ia(){if(ny){a.Default.debug("InstanceBootstrap already executed, skipping");return}ny=true,a.Default.info("bootstrapping",{directory:_.directory}),await ms.init(),vd.init(),Ss.init(),We.init(),Nn.init(),bt.init(),Gs.init(),yt.init(),Ve.init(),pe.subscribe(mE,async e=>{e.properties.name===pu.Default.INIT&&await Ht.setInitialized(_.project.id);});}var Ao;(I=>{let e=a.create({service:"worktree"});I.Event={Ready:a$5.define("worktree.ready",F.object({name:F.string(),branch:F.string()})),Failed:a$5.define("worktree.failed",F.object({message:F.string()}))},I.Info=F.object({name:F.string(),branch:F.string(),directory:F.string()}).meta({ref:"Worktree"}),I.CreateInput=F.object({name:F.string().optional(),startCommand:F.string().optional().describe("Additional startup script to run after the project's start command")}).meta({ref:"WorktreeCreateInput"}),I.RemoveInput=F.object({directory:F.string()}).meta({ref:"WorktreeRemoveInput"}),I.ResetInput=F.object({directory:F.string()}).meta({ref:"WorktreeResetInput"}),I.NotGitError=NamedError.create("WorktreeNotGitError",F.object({message:F.string()})),I.NameGenerationFailedError=NamedError.create("WorktreeNameGenerationFailedError",F.object({message:F.string()})),I.CreateFailedError=NamedError.create("WorktreeCreateFailedError",F.object({message:F.string()})),I.StartCommandFailedError=NamedError.create("WorktreeStartCommandFailedError",F.object({message:F.string()})),I.RemoveFailedError=NamedError.create("WorktreeRemoveFailedError",F.object({message:F.string()})),I.ResetFailedError=NamedError.create("WorktreeResetFailedError",F.object({message:F.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(M){return M[Math.floor(Math.random()*M.length)]}function g(M){return M.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+/,"").replace(/-+$/,"")}function h(){return `${u(a$2)}-${u(p)}`}async function S(M){return Tt__default.stat(M).then(()=>true).catch(()=>false)}function A(M){return M?.length===0?"":new TextDecoder().decode(M).trim()}function y(M){return [A(M.stderr),A(M.stdout)].filter(Boolean).join(`
883
+ `)}function x(M){return [A(M.stderr),A(M.stdout)].filter(Boolean).flatMap(v=>v.split(`
884
+ `).map(T=>T.trim()).flatMap(T=>{let R=T.match(/^warning:\s+failed to remove\s+(.+):\s+/i);if(!R)return [];let j=R[1]?.trim().replace(/^['"]|['"]$/g,"");return j?[j]:[]}))}async function b(M,v){let T=await C(M);await Promise.all(v.map(async R=>{let j=await C(Ce__default.resolve(M,R));j!==T&&j.startsWith(`${T}${Ce__default.sep}`)&&await Tt__default.rm(j,{recursive:true,force:true}).catch(()=>{});}));}async function w(M){let v=await $`git clean -ffdx`.quiet().nothrow().cwd(M);if(v.exitCode===0)return v;let T=x(v);return T.length===0?v:(await b(M,T),$`git clean -ffdx`.quiet().nothrow().cwd(M))}async function C(M){let v=Ce__default.resolve(M),T=await Tt__default.realpath(v).catch(()=>v),R=Ce__default.normalize(T);return process.platform==="win32"?R.toLowerCase():R}async function k(M,v){for(let T of Array.from({length:26},(R,j)=>j)){let R=v?T===0?v:`${v}-${h()}`:h(),j=`easbot/${R}`,U=Ce__default.join(M,R);if(await S(U))continue;let Y=`refs/heads/${j}`;if((await $`git show-ref --verify --quiet ${Y}`.quiet().nothrow().cwd(_.worktree)).exitCode!==0)return I.Info.parse({name:R,branch:j,directory:U})}throw new I.NameGenerationFailedError({message:"Failed to generate a unique worktree name"})}async function P(M,v){return process.platform==="win32"?$`cmd /c ${v}`.nothrow().cwd(M):$`bash -lc ${v}`.nothrow().cwd(M)}async function E(M,v,T){let R=v.trim();if(!R)return true;let j=await P(M,R);return j.exitCode===0?true:(e.error("worktree start command failed",{kind:T,directory:M,message:y(j)}),false)}async function O(M,v){let R=(await a$6.read(["project",v.providerId]).catch(()=>{}))?.commands?.start?.trim()??"";if(!await E(M,R,"project"))return false;let U=v.extra??"";return await E(M,U,"worktree"),true}function N(M,v){setTimeout(()=>{(async()=>{await O(M,v);})().catch(R=>{e.error("worktree start task failed",{directory:M,error:R});});},0);}async function L(M){if(_.project.vcs!=="git")throw new I.NotGitError({message:"Worktrees are only supported for git projects"});let v=Ce__default.join(a$1.Path.data,"worktree",_.project.id);await Tt__default.mkdir(v,{recursive:true});let T=M?g(M):"";return k(v,T||void 0)}I.makeWorktreeInfo=L;async function K(M){if(_.project.vcs!=="git")throw new I.NotGitError({message:"Worktrees are only supported for git projects"});let v=await $`git worktree add --no-checkout -b ${M.branch} ${M.directory}`.quiet().nothrow().cwd(_.worktree);if(v.exitCode!==0)throw new I.CreateFailedError({message:y(v)||"Failed to create git worktree"});await Ht.addSandbox(_.project.id,M.directory).catch(()=>{});let T=_.project.id;setTimeout(()=>{(async()=>{let j=await $`git reset --hard`.quiet().nothrow().cwd(M.directory);if(j.exitCode!==0){let Y=y(j)||"Failed to populate worktree";e.error("worktree checkout failed",{directory:M.directory,message:Y}),ft.emit("event",{directory:M.directory,payload:{type:I.Event.Failed.type,properties:{message:Y}}});return}await _.provide({directory:M.directory,init:ia,fn:()=>{}}).then(()=>true).catch(Y=>{let J=Y instanceof Error?Y.message:String(Y);return e.error("worktree bootstrap failed",{directory:M.directory,message:J}),ft.emit("event",{directory:M.directory,payload:{type:I.Event.Failed.type,properties:{message:J}}}),false})&&(ft.emit("event",{directory:M.directory,payload:{type:I.Event.Ready.type,properties:{name:M.name,branch:M.branch}}}),await O(M.directory,{providerId:T}));})().catch(j=>{e.error("worktree start task failed",{directory:M.directory,error:j});});},0);}I.createFromInfo=K,I.create=fn$1(I.CreateInput.optional(),async M=>{if(_.project.vcs!=="git")throw new I.NotGitError({message:"Worktrees are only supported for git projects"});let v=Ce__default.join(a$1.Path.data,"worktree",_.project.id);await Tt__default.mkdir(v,{recursive:true});let T=M?.name?g(M.name):"",R=await k(v,T||void 0),j=await $`git worktree add --no-checkout -b ${R.branch} ${R.directory}`.quiet().nothrow().cwd(_.worktree);if(j.exitCode!==0)throw new I.CreateFailedError({message:y(j)||"Failed to create git worktree"});await Ht.addSandbox(_.project.id,R.directory).catch(()=>{});let U=_.project.id,Y=M?.startCommand?.trim();return setTimeout(()=>{(async()=>{let ee=await $`git reset --hard`.quiet().nothrow().cwd(R.directory);if(ee.exitCode!==0){let ae=y(ee)||"Failed to populate worktree";e.error("worktree checkout failed",{directory:R.directory,message:ae}),ft.emit("event",{directory:R.directory,payload:{type:I.Event.Failed.type,properties:{message:ae}}});return}await _.provide({directory:R.directory,init:ia,fn:()=>{}}).then(()=>true).catch(ae=>{let we=ae instanceof Error?ae.message:String(ae);return e.error("worktree bootstrap failed",{directory:R.directory,message:we}),ft.emit("event",{directory:R.directory,payload:{type:I.Event.Failed.type,properties:{message:we}}}),false})&&(ft.emit("event",{directory:R.directory,payload:{type:I.Event.Ready.type,properties:{name:R.name,branch:R.branch}}}),await O(R.directory,{providerId:U,extra:Y}));})().catch(ee=>{e.error("worktree start task failed",{directory:R.directory,error:ee});});},0),R}),I.remove=fn$1(I.RemoveInput,async M=>{if(_.project.vcs!=="git")throw new I.NotGitError({message:"Worktrees are only supported for git projects"});let v=await C(M.directory),T=await $`git worktree list --porcelain`.quiet().nothrow().cwd(_.worktree);if(T.exitCode!==0)throw new I.RemoveFailedError({message:y(T)||"Failed to read git worktrees"});let j=A(T.stdout).split(`
885
+ `).map(ee=>ee.trim()).reduce((ee,se)=>{if(!se)return ee;if(se.startsWith("worktree "))return ee.push({path:se.slice(9).trim()}),ee;let ae=ee[ee.length-1];return ae&&se.startsWith("branch ")&&(ae.branch=se.slice(7).trim()),ee},[]),U=await(async()=>{for(let ee of j){if(!ee.path)continue;if(await C(ee.path)===v)return ee}})();if(!U?.path)return await S(v)&&await Tt__default.rm(v,{recursive:true,force:true}),true;let Y=await $`git worktree remove --force ${U.path}`.quiet().nothrow().cwd(_.worktree);if(Y.exitCode!==0)throw new I.RemoveFailedError({message:y(Y)||"Failed to remove git worktree"});let J=U.branch?.replace(/^refs\/heads\//,"");if(J){let ee=await $`git branch -D ${J}`.quiet().nothrow().cwd(_.worktree);if(ee.exitCode!==0)throw new I.RemoveFailedError({message:y(ee)||"Failed to delete worktree branch"})}return true}),I.reset=fn$1(I.ResetInput,async M=>{if(_.project.vcs!=="git")throw new I.NotGitError({message:"Worktrees are only supported for git projects"});let v=await C(M.directory),T=await C(_.worktree);if(v===T)throw new I.ResetFailedError({message:"Cannot reset the primary workspace"});let R=await $`git worktree list --porcelain`.quiet().nothrow().cwd(_.worktree);if(R.exitCode!==0)throw new I.ResetFailedError({message:y(R)||"Failed to read git worktrees"});let U=A(R.stdout).split(`
886
+ `).map(re=>re.trim()).reduce((re,$e)=>{if(!$e)return re;if($e.startsWith("worktree "))return re.push({path:$e.slice(9).trim()}),re;let Ae=re[re.length-1];return Ae&&$e.startsWith("branch ")&&(Ae.branch=$e.slice(7).trim()),re},[]),Y=await(async()=>{for(let re of U){if(!re.path)continue;if(await C(re.path)===v)return re}})();if(!Y?.path)throw new I.ResetFailedError({message:"Worktree not found"});let J=await $`git remote`.quiet().nothrow().cwd(_.worktree);if(J.exitCode!==0)throw new I.ResetFailedError({message:y(J)||"Failed to list git remotes"});let ee=A(J.stdout).split(`
887
+ `).map(re=>re.trim()).filter(Boolean),se=ee.includes("origin")?"origin":ee.length===1?ee[0]:ee.includes("upstream")?"upstream":"",ae=se?await $`git symbolic-ref refs/remotes/${se}/HEAD`.quiet().nothrow().cwd(_.worktree):{exitCode:1,stdout:void 0},we=ae.exitCode===0?A(ae.stdout):"",ie=we?we.replace(/^refs\/remotes\//,""):"",Z=se&&ie.startsWith(`${se}/`)?ie.slice(`${se}/`.length):"",H=await $`git show-ref --verify --quiet refs/heads/main`.quiet().nothrow().cwd(_.worktree),$$1=await $`git show-ref --verify --quiet refs/heads/master`.quiet().nothrow().cwd(_.worktree),te=H.exitCode===0?"main":$$1.exitCode===0?"master":"",W=Z?`${se}/${Z}`:te;if(!W)throw new I.ResetFailedError({message:"Default branch not found"});if(Z){let re=await $`git fetch ${se} ${Z}`.quiet().nothrow().cwd(_.worktree);if(re.exitCode!==0)throw new I.ResetFailedError({message:y(re)||`Failed to fetch ${W}`})}if(!Y.path)throw new I.ResetFailedError({message:"Worktree path not found"});let V=Y.path,oe=await $`git reset --hard ${W}`.quiet().nothrow().cwd(V);if(oe.exitCode!==0)throw new I.ResetFailedError({message:y(oe)||"Failed to reset worktree to target"});let de=await w(V);if(de.exitCode!==0)throw new I.ResetFailedError({message:y(de)||"Failed to clean worktree"});let me=await $`git submodule update --init --recursive --force`.quiet().nothrow().cwd(V);if(me.exitCode!==0)throw new I.ResetFailedError({message:y(me)||"Failed to update submodules"});let ce=await $`git submodule foreach --recursive git reset --hard`.quiet().nothrow().cwd(V);if(ce.exitCode!==0)throw new I.ResetFailedError({message:y(ce)||"Failed to reset submodules"});let ye=await $`git submodule foreach --recursive git clean -fdx`.quiet().nothrow().cwd(V);if(ye.exitCode!==0)throw new I.ResetFailedError({message:y(ye)||"Failed to clean submodules"});let je=await $`git status --porcelain=v1`.quiet().nothrow().cwd(V);if(je.exitCode!==0)throw new I.ResetFailedError({message:y(je)||"Failed to read git status"});let Ie=A(je.stdout);if(Ie)throw new I.ResetFailedError({message:`Worktree reset left local changes:
888
+ ${Ie}`});let ke=_.project.id;return N(V,{providerId:ke}),true});})(Ao||(Ao={}));var oy=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(F.array(F.string()).meta({ref:"ToolIDs"}))}}},...Te(400)}}),async e=>e.json(await zn.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(F.array(F.object({id:F.string(),description:F.string(),parameters:F.any()}).meta({ref:"ToolListItem"})).meta({ref:"ToolList"}))}}},...Te(400)}}),validator("query",F.object({provider:F.string(),model:F.string()})),async e=>{let{provider:t,model:n}=e.req.valid("query"),o=await zn.tools({providerId:t,modelId:n});return e.json(o.map(s=>({id:s.id,description:s.description,parameters:s.parameters?._def?zodToJsonSchema(s.parameters):s.parameters})))}).post("/worktree",describeRoute({summary:"Create worktree",description:"Create a new git worktree for the current project and run any configured startup scripts.",operationId:"worktree.create",responses:{200:{description:"Worktree created",content:{"application/json":{schema:resolver(Ao.Info)}}},...Te(400)}}),validator("json",Ao.create.schema),async e=>{let t=e.req.valid("json"),n=await Ao.create(t);return e.json(n)}).get("/worktree",describeRoute({summary:"List worktrees",description:"List all sandbox worktrees for the current project.",operationId:"worktree.list",responses:{200:{description:"List of worktree directories",content:{"application/json":{schema:resolver(F.array(F.string()))}}}}}),async e=>{let t=await Ht.sandboxes(_.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(F.boolean())}}},...Te(400)}}),validator("json",Ao.remove.schema),async e=>{let t=e.req.valid("json");return await Ao.remove(t),await Ht.removeSandbox(_.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(F.boolean())}}},...Te(400)}}),validator("json",Ao.reset.schema),async e=>{let t=e.req.valid("json");return await Ao.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(F.record(F.string(),F.unknown()))}}}}}),async e=>e.json(await ze.resources())));var fs;(a=>{let e;function t(){return e||(e=_.state(async()=>({methods:pipe(await ms.list(),filter(u=>u.auth?.provider!==void 0),map(u=>[u.auth.provider,u.auth]),fromEntries()),pending:{}}))),e}function n(){return t()()}a.Method=F.object({type:F.union([F.literal("oauth"),F.literal("api")]),label:F.string()}).meta({ref:"ProviderAuthMethod"});async function s(){let p=await n().then(u=>u.methods);return mapValues(p,u=>u.methods.map(g=>({type:g.type,label:g.label})))}a.methods=s,a.Authorization=F.object({url:F.string(),method:F.union([F.literal("auto"),F.literal("code")]),instructions:F.string()}).meta({ref:"ProviderAuthAuthorization"}),a.authorize=fn$1(F.object({providerId:F.string(),method:F.number()}),async p=>{let u=await n().then(h=>h.methods[p.providerId]);if(!u)return;let g=u.methods[p.method];if(g&&g.type==="oauth"&&g.authorize){let h=await g.authorize();return h?(await n().then(S=>S.pending[p.providerId]=h),{url:h.url??"",method:h.method??"",instructions:h.instructions??""}):void 0}}),a.callback=fn$1(F.object({providerId:F.string(),method:F.number(),code:F.string().optional()}),async p=>{let u=await n().then(h=>h.pending[p.providerId]);if(!u)throw new a.OauthMissing({providerId:p.providerId});let g;if(u.method==="code"){if(!p.code)throw new a.OauthCodeMissing({providerId:p.providerId});g=await u.callback(p.code);}if(u.method==="auto"&&(g=await u.callback()),g?.type==="success"){if("key"in g&&g.key&&await Qe.set(p.providerId,{type:"api",key:g.key??""}),"refresh"in g&&g.refresh){let h={type:"oauth",access:g.access??"",refresh:g.refresh??"",expires:g.expires??0};g.accountId&&(h.accountId=g.accountId),await Qe.set(p.providerId,h);}return}throw new a.OauthCallbackFailed({})}),a.api=fn$1(F.object({providerId:F.string(),key:F.string()}),async p=>{await Qe.set(p.providerId,{type:"api",key:p.key});}),a.OauthMissing=NamedError.create("ProviderAuthOauthMissing",F.object({providerId:F.string()})),a.OauthCodeMissing=NamedError.create("ProviderAuthOauthCodeMissing",F.object({providerId:F.string()})),a.OauthCallbackFailed=NamedError.create("ProviderAuthOauthCallbackFailed",F.object({}));})(fs||(fs={}));var ry=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(F.object({all:a$3.Provider.array(),default:F.record(F.string(),F.string()),connected:F.array(F.string())}))}}}}}),async e=>{let t=await he.get(),n=new Set(t.disabled_providers??[]),o=t.enabled_providers?new Set(t.enabled_providers):void 0,s=await a$3.get(),r={};for(let[l,d]of Object.entries(s))(!o||o.has(l))&&!n.has(l)&&(r[l]=d);let i=await xe.list(),c=Object.assign(mapValues(r,l=>xe.fromModelsDevProvider(l)),i);return e.json({all:Object.values(c),default:mapValues(c,l=>xe.sort(Object.values(l.models))[0]?.id??""),connected:Object.keys(i)})}).get("/auth",describeRoute({summary:"Get provider auth methods",description:"Retrieve available authentication methods for all AI providers.",operationId:"provider.auth",responses:{200:{description:"Provider auth methods",content:{"application/json":{schema:resolver(F.record(F.string(),F.array(fs.Method)))}}}}}),async e=>e.json(await fs.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(fs.Authorization.optional())}}},...Te(400)}}),validator("param",F.object({providerId:F.string().meta({description:"Provider ID"})})),validator("json",F.object({method:F.number().meta({description:"Auth method index"})})),async e=>{let t=e.req.valid("param").providerId,{method:n}=e.req.valid("json"),o=await fs.authorize({providerId:t,method:n});return e.json(o)}).post("/:providerId/oauth/callback",describeRoute({summary:"OAuth callback",description:"Handle the OAuth callback from a provider after user authorization.",operationId:"provider.oauth.callback",responses:{200:{description:"OAuth callback processed successfully",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400)}}),validator("param",F.object({providerId:F.string().meta({description:"Provider ID"})})),validator("json",F.object({method:F.number().meta({description:"Auth method index"}),code:F.string().optional().meta({description:"OAuth authorization code"})})),async e=>{let t=e.req.valid("param").providerId,{method:n,code:o}=e.req.valid("json");return await fs.callback({providerId:t,method:n,code:o}),e.json(true)}));var cy=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(F.object({providerId:F.string(),modelId:F.string()}).optional())}}},...Te(400)}}),async e=>{let t=await xe.defaultModel();return t?e.json({providerId:t.providerId,modelId:t.modelId}):e.json(void 0)}).get("/parse",describeRoute({summary:"Parse model string",description:'Parse a model string in the format "providerId/modelId" and return its components.',operationId:"model.parse",responses:{200:{description:"Parsed model",content:{"application/json":{schema:resolver(F.object({providerId:F.string(),modelId:F.string()}).optional())}}},...Te(400)}}),async e=>{let t=e.req.query("model");if(!t)return e.json(void 0);let n=xe.parseModel(t);return n?.providerId?e.json({providerId:n.providerId,modelId:n.modelId}):e.json(void 0)}));var dy=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(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({requestId:F.string()})),validator("json",Ot.Reply),async e=>{let t=e.req.valid("param"),n=e.req.valid("json");return await Ot.reply({requestId:t.requestId,answers:n.answers}),e.json(true)}).post("/:requestId/reject",describeRoute({summary:"Reject question request",description:"Reject a question request from the AI assistant.",operationId:"question.reject",responses:{200:{description:"Question rejected successfully",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({requestId:F.string()})),async e=>{let t=e.req.valid("param");return await Ot.reject(t.requestId),e.json(true)}));var my=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(F.boolean())}}},...Te(400,404)}}),validator("param",F.object({requestId:F.string()})),validator("json",F.object({reply:Me.Reply,message:F.string().optional()})),async e=>{let t=e.req.valid("param"),n=e.req.valid("json");return await Me.reply({requestId:t.requestId,reply:n.reply,message:n.message}),e.json(true)}).get("/",describeRoute({summary:"List pending permissions",description:"Get all pending permission requests across all sessions.",operationId:"permission.list",responses:{200:{description:"List of pending permissions",content:{"application/json":{schema:resolver(Me.Request.array())}}}}}),async e=>{let t=await Me.list();return e.json(t)}));var fy=a.create({service:"server"}),jE=a$5.define("global.disposed",F.object({})),gy=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(F.object({healthy:F.literal(true),version:F.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(F.object({directory:F.string(),payload:a$5.payloads()}).meta({ref:"GlobalEvent"}))}}}}}),async e=>(fy.info("global event connected"),streamSSE(e,async t=>{t.writeSSE({data:JSON.stringify({payload:{type:"server.connected",properties:{}}})});async function n(s){await t.writeSSE({data:JSON.stringify(s)});}ft.on("event",n);let o=setInterval(()=>{t.writeSSE({data:JSON.stringify({payload:{type:"server.heartbeat",properties:{}}})});},3e4);await new Promise(s=>{t.onAbort(()=>{clearInterval(o),ft.off("event",n),s(),fy.info("global event disconnected");});});}))).get("/config",describeRoute({summary:"Get global configuration",description:"Retrieve the current global EasBot configuration settings and preferences.",operationId:"global.config.get",responses:{200:{description:"Get global config info",content:{"application/json":{schema:resolver(he.Info)}}}}}),async e=>e.json(await he.getGlobal())).patch("/config",describeRoute({summary:"Update global configuration",description:"Update global EasBot configuration settings and preferences.",operationId:"global.config.update",responses:{200:{description:"Successfully updated global config",content:{"application/json":{schema:resolver(he.Info)}}},...Te(400)}}),validator("json",he.Info),async e=>{let t=e.req.valid("json"),n=await he.updateGlobal(t);return e.json(n)}).post("/dispose",describeRoute({summary:"Dispose instance",description:"Clean up and dispose all EasBot instances, releasing all resources.",operationId:"global.dispose",responses:{200:{description:"Global disposed",content:{"application/json":{schema:resolver(F.boolean())}}}}}),async e=>(await _.disposeAll(),ft.emit("event",{directory:"global",payload:{type:jE.type,properties:{}}}),e.json(true))));var hy=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(F.array(Ue.Info))}}}}}),async e=>{let t=await Ue.list();return e.json(t)}).get("/:agentId",describeRoute({summary:"Get agent",description:"Get details of a specific AI agent by name or ID.",operationId:"agent.get",responses:{200:{description:"Agent details",content:{"application/json":{schema:resolver(Ue.Info)}}},...Te(404)}}),async e=>{let t=e.req.param("agentId"),n=await Ue.get(t);return n?e.json(n):e.json({error:`Agent not found: ${t}`},404)}).get("/:agentId/event",describeRoute({summary:"Get agent events",description:"Subscribe to events for a specific agent using server-sent events.",operationId:"agent.event",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:{type:"object"}}}}}}),async e=>{let t=e.req.param("agentId");return streamSSE(e,async n=>{await n.writeSSE({data:JSON.stringify({type:"agent.connected",properties:{agentId:t}})});let o=pe.subscribeAll(async s=>{s.properties?.agentId===t&&await n.writeSSE({data:JSON.stringify(s)});});await new Promise(s=>{n.onAbort(()=>{o(),s();});});})}).get("/default",describeRoute({summary:"Get default agent",description:"Get the default agent configuration.",operationId:"agent.default",responses:{200:{description:"Default agent details",content:{"application/json":{schema:resolver(Ue.Info)}}},...Te(404)}}),async e=>{let t=await Ue.defaultAgent(),n=await Ue.get(t);return n?e.json(n):e.json({error:`Default agent not found: ${t}`},404)}).post("/",describeRoute({summary:"Create agent",description:"Create a new AI agent with specified configuration.",operationId:"agent.create",responses:{201:{description:"Agent created successfully",content:{"application/json":{schema:resolver(Ue.Info)}}},...Te(400),...Te(404)}}),validator("json",F.object({name:F.string(),mode:F.enum(["subagent","primary","all"]).optional(),permission:F.record(F.string(),F.any()).optional(),description:F.string().optional(),prompt:F.string().optional(),model:F.object({providerId:F.string(),modelId:F.string()}).optional(),temperature:F.number().optional(),topP:F.number().optional(),color:F.string().optional(),hidden:F.boolean().optional(),variant:F.string().optional(),steps:F.number().int().positive().optional(),options:F.record(F.string(),F.any()).optional()})),async e=>{let t=e.req.valid("json");try{if(!t.name||t.name.trim()==="")return e.json({error:"Agent name is required"},400);if(await Ue.get(t.name))return e.json({error:`Agent "${t.name}" already exists`},400);let o={mode:t.mode||"primary"};t.description&&(o.description=t.description),t.prompt&&(o.prompt=t.prompt),t.model&&(o.model=`${t.model.providerId}/${t.model.modelId}`),t.temperature!==void 0&&(o.temperature=t.temperature),t.topP!==void 0&&(o.topP=t.topP),t.color&&(o.color=t.color),t.hidden!==void 0&&(o.hidden=t.hidden),t.variant&&(o.variant=t.variant),t.steps!==void 0&&(o.steps=t.steps),t.permission&&(o.permission=t.permission),t.options&&(o.options=t.options),await he.update({agent:{[t.name]:o}});let s=await Ue.get(t.name);return s?e.json(s,201):e.json({error:`Failed to retrieve created agent "${t.name}"`},500)}catch(n){let o=n instanceof Error?n.message:"Agent creation failed";return e.json({error:o},400)}}));function yy(){let e=new Hono;return e.get("/status",async t=>{let n=await _n.getSchedulerStatus();return t.json({status:n})}),e.get("/initialized",async t=>{let n=await _n.isSchedulerInitialized();return t.json({initialized:n})}),e.get("/heartbeats",async t=>{let n=await _n.listSchedulerHeartbeats();return t.json({heartbeats:n})}),e.get("/scheduled",async t=>{let n=await _n.listSchedulerScheduled();return t.json({scheduled:n})}),e.get("/commands",async t=>{let n=await _n.listSchedulerCommands();return t.json({commands:n})}),e}var ua=a.create({service:"mdns"}),pa;(s=>{let e,t;function n(r,i){if(t!==r){e&&o();try{let c=i??"easbot.local",l=`easbot-${r}`;e=new UE;let d=e.publish({name:l,type:"http",host:c,port:r,txt:{path:"/"}});d.on("up",()=>{ua.info("mDNS service published",{name:l,port:r});}),d.on("error",m=>{ua.error("mDNS service error",{error:m});}),t=r;}catch(c){if(ua.error("mDNS publish failed",{error:c}),e)try{e.destroy();}catch{}e=void 0,t=void 0;}}}s.publish=n;function o(){if(e){try{e.unpublishAll(),e.destroy();}catch(r){ua.error("mDNS unpublish failed",{error:r});}e=void 0,t=void 0,ua.info("mDNS service unpublished");}}s.unpublish=o;})(pa||(pa={}));globalThis.AI_SDK_LOG_WARNINGS=false;var ma;(f=>{let e=a.create({service:"server"}),t=compress(),n=(a,p)=>!!(a==="/event"||a==="/global/event"||a==="/global/sync-event"||p==="POST"&&/\/session\/[^/]+\/(message|prompt_async)$/.test(a)),o,s=[];function r(){return o??new URL("http://localhost:4096")}f.url=r;let i=new Hono;f.App=lazy(()=>i.onError((a,p)=>{if(e.error("failed",{error:a}),a instanceof NamedError){let g;return a instanceof a$6.NotFoundError?g=404:a instanceof xe.ModelNotFoundError||a.name==="ProviderAuthValidationFailed"||a.name.startsWith("Worktree")?g=400:g=500,p.json(a.toObject(),{status:g})}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 g=a$2.EASBOT_SERVER_USERNAME??"easbot";return basicAuth({username:g,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 g=e.time("request",{method:a.req.method,path:a.req.path});await p(),u||g.stop();}).use(cors({maxAge:86400,origin(a){if(a&&(a.startsWith("http://localhost:")||a.startsWith("http://127.0.0.1:")||a==="tauri://localhost"||a==="http://tauri.localhost"||a==="https://tauri.localhost"||/^https:\/\/([a-z0-9-]+\.)*easbot\.ai$/.test(a)||s.includes(a)))return a}})).use((a,p)=>n(a.req.path,a.req.method)?p():t(a,p)).route("/global",gy()).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(F.boolean())}}},...Te(400)}}),validator("param",F.object({providerId:F.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(F.boolean())}}},...Te(400)}}),validator("param",F.object({providerId:F.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(),g=Filesystem.resolve((()=>{try{return decodeURIComponent(u)}catch{return u}})());return _.provide({directory:g,init:ia,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",F.object({directory:F.string().optional(),workspace:F.string().optional()}))).route("/project",Wh()).route("/pty",Yh()).route("/config",ey()).route("/experimental",oy()).route("/session",Jh()).route("/permission",my()).route("/question",dy()).route("/provider",ry()).route("/model",cy()).route("/",Qh()).route("/mcp",Xh()).route("/agent",hy()).route("/tui",qh()).route("/scheduler",yy()).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(F.boolean())}}}}}),async a=>(await _.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(F.object({home:F.string(),state:F.string(),config:F.string(),worktree:F.string(),directory:F.string()}).meta({ref:"Path"}))}}}}}),async a=>a.json({home:a$1.Path.home,state:a$1.Path.state,config:a$1.Path.config,worktree:_.worktree,directory:_.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(Gs.Info)}}}}}),async a=>{let p=await Gs.branch();return a.json({branch:p})}).get("/command",describeRoute({summary:"List commands",description:"Get a list of all available commands in the EasBot system.",operationId:"command.list",responses:{200:{description:"List of commands",content:{"application/json":{schema:resolver(vn.Info.array())}}}}}),validator("query",F.object({contextMode:F.string().optional()})),async a=>{let{contextMode:p}=a.req.valid("query"),u=await vn.list(p);return a.json(u)}).post("/log",describeRoute({summary:"Write log",description:"Write a log entry to the server logs with specified level and metadata.",operationId:"app.log",responses:{200:{description:"Log entry written successfully",content:{"application/json":{schema:resolver(F.boolean())}}},...Te(400)}}),validator("json",F.object({service:F.string().meta({description:"Service name for the log entry"}),level:F.enum(["debug","info","error","warn"]).meta({description:"Log level"}),message:F.string().meta({description:"Log message"}),extra:F.record(F.string(),F.any()).optional().meta({description:"Additional metadata for the log entry"})})),async a$1=>{let{service:p,level:u,message:g,extra:h}=a$1.req.valid("json"),S=a.create({service:p});switch(u){case "debug":S.debug(g,h);break;case "info":S.info(g,h);break;case "error":S.error(g,h);break;case "warn":S.warn(g,h);break}return a$1.json(true)}).get("/agent",describeRoute({summary:"List agents",description:"Get a list of all available AI agents in the EasBot system.",operationId:"app.agents",responses:{200:{description:"List of agents",content:{"application/json":{schema:resolver(Ue.Info.array())}}}}}),async a=>{let p=await Ue.list();return a.json(p)}).get("/skill",describeRoute({summary:"List skills",description:"Get a list of all available skills in the EasBot system.",operationId:"app.skills",responses:{200:{description:"List of skills",content:{"application/json":{schema:resolver(Jt.Info.array())}}}}}),async a=>{let p=await Jt.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(Ss.Status.array())}}}}}),async a=>a.json(await Ss.status())).get("/event",describeRoute({summary:"Subscribe to events",description:"Get events",operationId:"event.subscribe",responses:{200:{description:"Event stream",content:{"text/event-stream":{schema:resolver(a$5.payloads())}}}}}),async a=>(e.info("event connected"),streamSSE(a,async p=>{p.writeSSE({data:JSON.stringify({type:"server.connected",properties:{}})});let u=pe.subscribeAll(async h=>{await p.writeSSE({data:JSON.stringify(h)}),h.type===pe.InstanceDisposed.type&&p.close();}),g=setInterval(()=>{p.writeSSE({data:JSON.stringify({type:"server.heartbeat",properties:{}})});},3e4);await new Promise(h=>{p.onAbort(()=>{clearInterval(g),u(),h(),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(F.boolean())}}}}}),validator("json",F.object({type:F.string(),properties:F.record(F.string(),F.any()).optional()})),async a=>{let p=a.req.valid("json"),u=a$5.define(p.type,F.record(F.string(),F.any()));return await pe.publish(u,p.properties??{}),a.json(true)}).get("/context",describeRoute({summary:"Get context info",description:"Retrieve context information including protocol metadata, workspace path, and agent name.",operationId:"app.context",responses:{200:{description:"Context information",content:{"application/json":{schema:resolver(F.object({protocolMetadata:F.object({agentId:F.string().optional(),workspace:F.string(),name:F.string(),userName:F.string(),mission:F.string(),preferredName:F.string().optional(),coreRelationship:F.string().optional(),coreValues:F.array(F.string()).optional(),behaviorStyle:F.string().optional(),decisionPrinciples:F.array(F.string()).optional()}),protocolInitialized:F.boolean()}))}}}}}),async a=>{let p=await go.getContext();return a.json(p)}).all("/*",async a=>{let p=a.req.path,u=await proxy(`https://app.easbot.cn${p}`,{...a.req,headers:{...a.req.raw.headers,host:"app.easbot.cn"}});return u.headers.set("Content-Security-Policy","default-src 'self'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' data:; media-src 'self' data:; connect-src 'self' data:"),u}));async function l(){return await generateSpecs((0, f.App)(),{documentation:{info:{title:"easbot",version:"1.0.0",description:"easbot api"},openapi:"3.1.1"}})}f.openapi=l;function d(a){s=a.cors??[];let p=createServer((b,w)=>{(0, f.App)().fetch;let k=new URL(b.url??"/",`http://${b.headers.host}`),P=new Headers;for(let[L,K]of Object.entries(b.headers))K&&P.set(L,Array.isArray(K)?K.join(", "):K);let E=new AbortController;b.on("close",()=>E.abort());let O=new Request(k,{method:b.method,headers:P,body:b.method!=="GET"&&b.method!=="HEAD"?b:void 0,signal:E.signal,duplex:"half"}),N=(0, f.App)().fetch(O);Promise.resolve(N).then(L=>{w.statusCode=L.status,w.statusMessage=L.statusText;for(let[K,Q]of L.headers.entries())w.setHeader(K,Q);L.body?L.body.pipeTo(new WritableStream({write(K){w.write(K);},close(){w.end();}})):w.end();}).catch(L=>{e.error("Server error",{error:L.message}),w.statusCode=500,w.end("Internal Server Error");});}),u=b=>{try{return p.listen(b,a.hostname),!0}catch{return false}},g=a.port===0?u(4096)?4096:u(0)?p.address().port:null:u(a.port)?a.port:null;if(g===null)throw new Error(`Failed to start server on port ${a.port}`);let h=p.address(),S=typeof h=="object"&&h?h.port:g,A=a.hostname==="0.0.0.0"?"localhost":a.hostname;o=new URL(`http://${A}:${S}`);let y=a.mdns&&S&&a.hostname!=="127.0.0.1"&&a.hostname!=="localhost"&&a.hostname!=="::1";return y?pa.publish(S,a.mdnsDomain):a.mdns&&e.warn("mDNS enabled but hostname is loopback; skipping mDNS publish"),{url:o,port:S,stop:async b=>(y&&pa.unpublish(),new Promise(w=>{p.close(()=>{w();});})),raw:p}}f.listen=d,f.Default=f.App;})(ma||(ma={}));var yp=a.create({service:"plugin.codex"}),ga="app_EMoamEEZ73f0CkXaXp7hrann",gs="https://auth.openai.com",eR="https://chatgpt.com/backend-api/codex/responses",Xs=1455,tR=3e3;async function nR(){let e=oR(43),n=new TextEncoder().encode(e),o=await crypto.subtle.digest("SHA-256",n),s=Iy(o);return {verifier:e,challenge:s}}function oR(e){let t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",n=crypto.getRandomValues(new Uint8Array(e));return Array.from(n).map(o=>t[o%t.length]).join("")}function Iy(e){let t=new Uint8Array(e),n=String.fromCharCode(...t);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function sR(){return Iy(crypto.getRandomValues(new Uint8Array(32)).buffer)}function wy(e){let t=e.split(".");if(t.length===3)try{let n=t[1];return n?JSON.parse(Buffer.from(n,"base64url").toString()):void 0}catch{return}}function xy(e){return e.chatgpt_account_id||e["https://api.openai.com/auth"]?.chatgpt_account_id||e.organizations?.[0]?.id}function gp(e){if(e.id_token){let t=wy(e.id_token),n=t&&xy(t);if(n)return n}if(e.access_token){let t=wy(e.access_token);return t?xy(t):void 0}}function rR(e,t,n){let o=new URLSearchParams({response_type:"code",client_id:ga,redirect_uri:e,scope:"openid profile email offline_access",code_challenge:t.challenge,code_challenge_method:"S256",id_token_add_organizations:"true",codex_cli_simplified_flow:"true",state:n,originator:"easbot"});return `${gs}/oauth/authorize?${o.toString()}`}async function iR(e,t,n){let o=await fetch(`${gs}/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:ga,code_verifier:n.verifier}).toString()});if(!o.ok)throw new Error(`Token exchange failed: ${o.status}`);return o.json()}async function aR(e){let t=await fetch(`${gs}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:e,client_id:ga}).toString()});if(!t.ok)throw new Error(`Token refresh failed: ${t.status}`);return t.json()}var cR=`<!doctype html>
889
+ <html>
890
+ <head>
891
+ <title>EasBot - Codex Authorization Successful</title>
892
+ <style>
893
+ body {
894
+ font-family:
895
+ system-ui,
896
+ -apple-system,
897
+ sans-serif;
898
+ display: flex;
899
+ justify-content: center;
900
+ align-items: center;
901
+ height: 100vh;
902
+ margin: 0;
903
+ background: #131010;
904
+ color: #f1ecec;
905
+ }
906
+ .container {
907
+ text-align: center;
908
+ padding: 2rem;
909
+ }
910
+ h1 {
911
+ color: #f1ecec;
912
+ margin-bottom: 1rem;
913
+ }
914
+ p {
915
+ color: #b7b1b1;
916
+ }
917
+ </style>
918
+ </head>
919
+ <body>
920
+ <div class="container">
921
+ <h1>Authorization Successful</h1>
922
+ <p>You can close this window and return to EasBot.</p>
923
+ </div>
924
+ <script>
925
+ setTimeout(() => window.close(), 2000)
926
+ </script>
927
+ </body>
928
+ </html>`,hp=e=>`<!doctype html>
929
+ <html>
930
+ <head>
931
+ <title>EasBot - Codex Authorization Failed</title>
932
+ <style>
933
+ body {
934
+ font-family:
935
+ system-ui,
936
+ -apple-system,
937
+ sans-serif;
938
+ display: flex;
939
+ justify-content: center;
940
+ align-items: center;
941
+ height: 100vh;
942
+ margin: 0;
943
+ background: #131010;
944
+ color: #f1ecec;
945
+ }
946
+ .container {
947
+ text-align: center;
948
+ padding: 2rem;
949
+ }
950
+ h1 {
951
+ color: #fc533a;
952
+ margin-bottom: 1rem;
953
+ }
954
+ p {
955
+ color: #b7b1b1;
956
+ }
957
+ .error {
958
+ color: #ff917b;
959
+ font-family: monospace;
960
+ margin-top: 1rem;
961
+ padding: 1rem;
962
+ background: #3c140d;
963
+ border-radius: 0.5rem;
964
+ }
965
+ </style>
966
+ </head>
967
+ <body>
968
+ <div class="container">
969
+ <h1>Authorization Failed</h1>
970
+ <p>An error occurred during authorization.</p>
971
+ <div class="error">${e}</div>
972
+ </div>
973
+ </body>
974
+ </html>`,fa,Cn;async function dR(){return fa?{port:Xs,redirectUri:`http://localhost:${Xs}/auth/callback`}:(fa=serve({port:Xs,fetch(e){let t=new URL(e.url);if(t.pathname==="/auth/callback"){let n=t.searchParams.get("code"),o=t.searchParams.get("state"),s=t.searchParams.get("error"),r=t.searchParams.get("error_description");if(s){let c=r||s;return Cn?.reject(new Error(c)),Cn=void 0,new Response(hp(c),{headers:{"Content-Type":"text/html"}})}if(!n){let c="Missing authorization code";return Cn?.reject(new Error(c)),Cn=void 0,new Response(hp(c),{status:400,headers:{"Content-Type":"text/html"}})}if(!Cn||o!==Cn.state){let c="Invalid state - potential CSRF attack";return Cn?.reject(new Error(c)),Cn=void 0,new Response(hp(c),{status:400,headers:{"Content-Type":"text/html"}})}let i=Cn;return Cn=void 0,iR(n,`http://localhost:${Xs}/auth/callback`,i.pkce).then(c=>i.resolve(c)).catch(c=>i.reject(c)),new Response(cR,{headers:{"Content-Type":"text/html"}})}return t.pathname==="/cancel"?(Cn?.reject(new Error("Login cancelled")),Cn=void 0,new Response("Login cancelled",{status:200})):new Response("Not found",{status:404})}}),yp.info("codex oauth server started",{port:Xs}),{port:Xs,redirectUri:`http://localhost:${Xs}/auth/callback`})}function lR(){fa&&(fa.close(),fa=void 0,yp.info("codex oauth server stopped"));}function uR(e,t){return new Promise((n,o)=>{let s=setTimeout(()=>{Cn&&(Cn=void 0,o(new Error("OAuth callback timeout - authorization took too long")));},3e5);Cn={pkce:e,state:t,resolve:r=>{clearTimeout(s),n(r);},reject:r=>{clearTimeout(s),o(r);}};})}async function vy(e){return {auth:{provider:"openai",loader:async(t,n)=>{if((await t()).type!=="oauth")return {};let s=new Set(["gpt-5.1-codex-max","gpt-5.1-codex-mini","gpt-5.2","gpt-5.2-codex","gpt-5.3-codex","gpt-5.1-codex"]);for(let r of Object.keys(n.models))s.has(r)||delete n.models[r];if(!n.models["gpt-5.3-codex"]){let r={id:"gpt-5.3-codex",providerId:"openai",api:{id:"gpt-5.3-codex",url:"https://chatgpt.com/backend-api/codex",npm:"@ai-sdk/openai"},name:"GPT-5.3 Codex",capabilities:{temperature:false,reasoning:true,attachment:true,toolcall:true,input:{text:true,audio:false,image:true,video:false,pdf:false},output:{text:true,audio:false,image:false,video:false,pdf:false},interleaved:false},cost:{input:0,output:0,cache:{read:0,write:0}},limit:{context:4e5,input:272e3,output:128e3},status:"active",options:{},headers:{},release_date:"2026-02-05",variants:{},family:"gpt-codex"};r.variants=wt.variants(r),n.models["gpt-5.3-codex"]=r;}for(let r of Object.values(n.models))r.cost={input:0,output:0,cache:{read:0,write:0}};return {apiKey:Jp,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()){yp.info("refreshing codex access token");let a=await aR(c.refresh),p=gp(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(eR):m;return fetch(f,{...i,headers:d})}}},methods:[{label:"ChatGPT Pro/Plus (browser)",type:"oauth",authorize:async()=>{let{redirectUri:t}=await dR(),n=await nR(),o=sR(),s=rR(t,n,o),r=uR(n,o);return {url:s,instructions:"Complete authorization in your browser. This window will close automatically.",method:"auto",callback:async()=>{let i=await r;lR();let c=gp(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(`${gs}/api/accounts/deviceauth/usercode`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({client_id:ga})});if(!t.ok)throw new Error("Failed to initiate device authorization");let n=await t.json(),o=Math.max(parseInt(n.interval,10)||5,1)*1e3;return {url:`${gs}/codex/device`,instructions:`Enter code: ${n.user_code}`,method:"auto",async callback(){for(;;){let s=await fetch(`${gs}/api/accounts/deviceauth/token`,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`easbot/${b$3.getVersion()}`},body:JSON.stringify({device_auth_id:n.device_auth_id,user_code:n.user_code})});if(s.ok){let r=await s.json(),i=await fetch(`${gs}/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:`${gs}/deviceauth/callback`,client_id:ga,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:gp(c)}}if(s.status!==403&&s.status!==404)return {type:"failed"};await new Promise(r=>setTimeout(r,o+tR));}}}}},{label:"Manually enter API Key",type:"api"}]},"llm.headers":async(t,n)=>{t.model&&t.model.providerId==="openai"&&(t.headers??(t.headers={}),t.headers.originator="easbot",t.headers["User-Agent"]=`easbot/${b$3.getVersion()} (${sc.platform()} ${sc.release()}; ${sc.arch()})`,t.headers.session_id=t.sessionId,n.modified=true,n.input=t);}}}var Sy="Ov23li8tweQw6odWQebz",bp=3e3;function Cy(e){return e.replace(/^https?:\/\//,"").replace(/\/$/,"")}function mR(e){return {DEVICE_CODE_URL:`https://${e}/login/device/code`,ACCESS_TOKEN_URL:`https://${e}/login/oauth/access_token`}}async function ky(e){let t=e.client;return {auth:{provider:"github-copilot",async loader(n,o){let s=await n();if(!s||s.type!=="oauth")return {};let r=s.enterpriseUrl,i=r?`https://copilot-api.${Cy(r)}`:void 0;if(o?.models)for(let c of Object.values(o.models))c.cost={input:0,output:0,cache:{read:0,write:0}},c.api.npm="@ai-sdk/github-copilot";return {baseURL:i,apiKey:"",async fetch(c,l){let d=await n();if(d.type!=="oauth")return fetch(c,l);let m=c instanceof URL?c.href:c.toString(),{isVision:f,isAgent:a}=iife(()=>{try{let u=typeof l?.body=="string"?JSON.parse(l.body):l?.body;if(u?.messages&&m.includes("completions")){let g=u.messages[u.messages.length-1];return {isVision:u.messages.some(h=>Array.isArray(h.content)&&h.content.some(S=>S.type==="image_url")),isAgent:g?.role!=="user"}}if(u?.input){let g=u.input[u.input.length-1];return {isVision:u.input.some(h=>Array.isArray(h?.content)&&h.content.some(S=>S.type==="input_image")),isAgent:g?.role!=="user"}}if(u?.messages){let g=u.messages[u.messages.length-1],h=Array.isArray(g?.content)&&g.content.some(S=>S?.type!=="tool_result");return {isVision:u.messages.some(S=>Array.isArray(S?.content)&&S.content.some(A=>A?.type==="image"||A?.type==="tool_result"&&Array.isArray(A?.content)&&A.content.some(y=>y?.type==="image"))),isAgent:!(g?.role==="user"&&h)}}}catch{}return {isVision:false,isAgent:false}}),p={"x-initiator":a?"agent":"user",...l?.headers,"User-Agent":`easbot/${b$3.getVersion()}`,Authorization:`Bearer ${d.refresh}`,"Openai-Intent":"conversation-edits"};return f&&(p["Copilot-Vision-Request"]="true"),delete p["x-api-key"],delete p.authorization,fetch(c,{...l,headers:p})}}},methods:[{type:"oauth",label:"Login with GitHub Copilot",prompts:[{type:"select",key:"deploymentType",message:"Select GitHub deployment type",options:[{label:"GitHub.com",value:"github.com",hint:"Public"},{label:"GitHub Enterprise",value:"enterprise",hint:"Data residency or self-hosted"}]},{type:"text",key:"enterpriseUrl",message:"Enter your GitHub Enterprise URL or domain",placeholder:"company.ghe.com or https://company.ghe.com",condition:n=>n.deploymentType==="enterprise",validate:n=>{if(!n)return "URL or domain is required";try{return (n.includes("://")?new URL(n):new URL(`https://${n}`)).hostname?void 0:"Please enter a valid URL or domain"}catch{return "Please enter a valid URL (e.g., company.ghe.com or https://company.ghe.com)"}}}],async authorize(n={}){let o=n.deploymentType||"github.com",s="github.com",r="github-copilot";if(o==="enterprise"){let d=n.enterpriseUrl;s=Cy(d),r="github-copilot-enterprise";}let i=mR(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:Sy,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:Sy,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+bp));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+bp));continue}if(m.error)return {type:"failed"};await new Promise(f=>setTimeout(f,l.interval*1e3+bp));}}}}}]},"llm.headers":async(n,o)=>{!n.model||typeof n.model=="string"||!n.model.providerId.includes("github-copilot")||(n.headers??(n.headers={}),"api"in n.model&&typeof n.model.api=="object"&&n.model.api?.npm==="@ai-sdk/anthropic"&&(n.headers["anthropic-beta"]="interleaved-thinking-2025-05-14"),!(await t.session.get({sessionId:n.sessionId}).catch(()=>{}))?.data?.parentId)||(n.headers["x-initiator"]="agent",o.modified=true,o.input=n);}}}var ms;(m=>{let e=a.create({service:"plugin"}),t=[],n=[vy,ky],o;function s(f){if(f.hooks&&Array.isArray(f.hooks))for(let a of f.hooks)Le.registerMatcher(a),e.debug("registered plugin hook matcher to Hook system",{event:a.event,hookCount:a.hooks.length});}async function r(f){if(f.tool&&Object.keys(f.tool).length>0)for(let[a,p]of Object.entries(f.tool))await zn.register({id:a,init:async()=>({parameters:F.object(p.args),description:p.description,execute:async(u,g)=>{if(!p.execute)throw new Error(`Tool ${a} does not have an execute function`);let h={...g,directory:_.directory,worktree:_.worktree};return await p.execute(u,h)}})}),e.debug("registered plugin tool to Tool system",{toolId:a});}function i(){return o||(o=_.state(async()=>{let f=createEasbotClient({baseUrl:"http://localhost:4096",directory:_.directory,fetch:async(...h)=>ma.App().fetch(...h)}),a=await he.get(),p=[],u={client:f,project:_.project,worktree:_.worktree,directory:_.directory,serverUrl:ma.url(),$:shell};for(let h of n){e.info("loading internal plugin",{name:h.name});let S=await h(u).catch(A=>{e.error("failed to load internal plugin",{name:h.name,error:A});});S&&(p.push(S),s(S),await r(S));}let g=a.plugin??[];g.length>0&&await he.waitForDependencies(),a$2.EASBOT_DISABLE_DEFAULT_PLUGINS||(g=[...t,...g]);for(let h of g)if(!(h.includes("easbot-openai-codex-auth")||h.includes("easbot-copilot-auth"))){if(e.info("loading plugin",{path:h}),!h.startsWith("file://")){let S=h.lastIndexOf("@"),A=S>0?h.substring(0,S):h,y=S>0?h.substring(S+1):"latest",x=t.some(b=>b.startsWith(A+"@"));if(h=await Shell.install(A,y).catch(b=>{if(!x)throw b;let w=b instanceof Error?b.message:String(b);return e.error("failed to install builtin plugin",{pkg:A,version:y,error:w}),pe.publish(X.Event.Error,{error:new NamedError.Unknown({message:`Failed to install built-in plugin ${A}@${y}: ${w}`}).toObject()}).catch(C=>{e.error("failed to publish error event",{error:C});}),""}),!h)continue}await import(h).then(async S=>{let A=new Set;for(let[y,x]of Object.entries(S)){if(A.has(x))continue;A.add(x);let b=await x(u);p.push(b),s(b),await r(b);}}).catch(S=>{let A=S instanceof Error?S.message:String(S);e.error("failed to load plugin",{path:h,error:A}),pe.publish(X.Event.Error,{error:new NamedError.Unknown({message:`Failed to load plugin ${h}: ${A}`}).toObject()}).catch(y=>{e.error("failed to publish error event",{error:y});});});}return {plugins:p,input:u}})),o}function c(){return i()()}async function l(){return c().then(f=>f.plugins)}m.list=l;async function d(){await Le.init(),await vn.init(),await zn.init();let f=await c().then(p=>p.plugins),a=await he.get();for(let p of f)await p.config?.(a);pe.subscribeAll(async p=>{let u=await c().then(g=>g.plugins);for(let g of u)g.event?.({event:p});});}m.init=d;})(ms||(ms={}));var IR={"@ai-sdk/amazon-bedrock":()=>import('@ai-sdk/amazon-bedrock').then(e=>e.createAmazonBedrock),"@ai-sdk/anthropic":()=>import('@ai-sdk/anthropic').then(e=>e.createAnthropic),"@ai-sdk/azure":()=>import('@ai-sdk/azure').then(e=>e.createAzure),"@ai-sdk/google":()=>import('@ai-sdk/google').then(e=>e.createGoogleGenerativeAI),"@ai-sdk/google-vertex":()=>import('@ai-sdk/google-vertex').then(e=>e.createVertex),"@ai-sdk/google-vertex/anthropic":()=>import('@ai-sdk/google-vertex/anthropic').then(e=>e.createVertexAnthropic),"@ai-sdk/openai":()=>import('@ai-sdk/openai').then(e=>e.createOpenAI),"@ai-sdk/openai-compatible":()=>import('@ai-sdk/openai-compatible').then(e=>e.createOpenAICompatible),"@openrouter/ai-sdk-provider":()=>import('@openrouter/ai-sdk-provider').then(e=>e.createOpenRouter),"@ai-sdk/xai":()=>import('@ai-sdk/xai').then(e=>e.createXai),"@ai-sdk/mistral":()=>import('@ai-sdk/mistral').then(e=>e.createMistral),"@ai-sdk/groq":()=>import('@ai-sdk/groq').then(e=>e.createGroq),"@ai-sdk/deepinfra":()=>import('@ai-sdk/deepinfra').then(e=>e.createDeepInfra),"@ai-sdk/cerebras":()=>import('@ai-sdk/cerebras').then(e=>e.createCerebras),"@ai-sdk/cohere":()=>import('@ai-sdk/cohere').then(e=>e.createCohere),"@ai-sdk/gateway":()=>import('@ai-sdk/gateway').then(e=>e.createGateway),"@ai-sdk/togetherai":()=>import('@ai-sdk/togetherai').then(e=>e.createTogetherAI),"@ai-sdk/perplexity":()=>import('@ai-sdk/perplexity').then(e=>e.createPerplexity),"@ai-sdk/vercel":()=>import('@ai-sdk/vercel').then(e=>e.createVercel),"@ai-sdk/alibaba":()=>import('@ai-sdk/alibaba').then(e=>e.createAlibaba),"@ai-sdk/deepseek":()=>import('@ai-sdk/deepseek').then(e=>e.createDeepSeek),"gitlab-ai-provider":()=>import('gitlab-ai-provider').then(e=>e.createGitLab),"@ai-sdk/github-copilot":()=>import('./copilot-I52DJYYX.mjs').then(e=>e.createOpenaiCompatible),"@easbot/ollama-sdk":()=>import('@easbot/ollama-sdk').then(e=>e.createOllama),"@easbot/local-model-sdk":()=>import('@easbot/local-model-sdk').then(e=>e.createLocal)},xe;(ue=>{ue.DEFAULT_CONTEXT_LIMIT=2e5,ue.DEFAULT_INPUT_LIMIT_RATIO=.9,ue.DEFAULT_OUTPUT_LIMIT=8192;function o(D=2e5){return Math.floor(D*.9)}ue.getDefaultInputLimit=o;let s=a.create({service:"provider"});function r(D){let I=/^gpt-(\d+)/.exec(D);return I?Number(I[1])>=5:false}function i(D){return r(D)&&!D.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(D){let I=await(async()=>{let M=await tt.all();return !!(D.env.some(T=>M[T])||await Qe.get(D.id)||(await he.get()).provider?.opencode?.options?.apiKey)})();if(!I)for(let[M,v]of Object.entries(D.models))v.cost.input!==0&&delete D.models[M];return {autoload:Object.keys(D.models).length>0,options:I?{}:{apiKey:"public"}}},openai:async()=>{let D=await tt.get("OPENAI_BASE_URL");return {autoload:false,async getModel(I,M,v){return I.responses(M)},options:D?{baseURL:D}:{}}},"github-copilot":async()=>({autoload:false,async getModel(D,I,M){return D.responses===void 0&&D.chat===void 0?D.languageModel(I):i(I)?D.responses(I):D.chat(I)},options:{}}),"github-copilot-enterprise":async()=>({autoload:false,async getModel(D,I,M){return D.responses===void 0&&D.chat===void 0?D.languageModel(I):i(I)?D.responses(I):D.chat(I)},options:{}}),azure:async()=>({autoload:false,async getModel(D,I,M){return M?.useCompletionUrls?D.chat(I):D.responses(I)},options:{}}),"azure-cognitive-services":async()=>{let D=tt.get("AZURE_COGNITIVE_SERVICES_RESOURCE_NAME");return {autoload:false,async getModel(I,M,v){return v?.useCompletionUrls?I.chat(M):I.responses(M)},options:{baseURL:D?`https://${D}.cognitiveservices.azure.com/openai`:void 0}}},"amazon-bedrock":async()=>{let I=(await he.get()).provider?.["amazon-bedrock"],M=await Qe.get("amazon-bedrock"),v=I?.options?.region,T=tt.get("AWS_REGION"),R=v??T??"us-east-1",j=I?.options?.profile,U=tt.get("AWS_PROFILE"),Y=j??U,J=tt.get("AWS_ACCESS_KEY_ID"),ee=iife(()=>{let Z=process.env.AWS_BEARER_TOKEN_BEDROCK;if(Z)return Z;if(M?.type==="api")return process.env.AWS_BEARER_TOKEN_BEDROCK=M.key,M.key}),se=tt.get("AWS_WEB_IDENTITY_TOKEN_FILE"),ae=!!(process.env.AWS_CONTAINER_CREDENTIALS_RELATIVE_URI||process.env.AWS_CONTAINER_CREDENTIALS_FULL_URI);if(!Y&&!J&&!ee&&!se&&!ae)return {autoload:false};let we={region:R};if(!ee){let Z=await Shell.install("@aws-sdk/credential-providers"),{pathToFileURL:H}=await import('url'),$=Ce__default.join(Z,"dist-cjs","index.js"),{fromNodeProviderChain:te}=await import(H($).href),W=Y?{profile:Y}:{};we.credentialProvider=te(W);}let ie=I?.options?.endpoint??I?.options?.baseURL;return ie&&(we.baseURL=ie),{autoload:true,options:we,async getModel(Z,H,$){if(["global.","us.","eu.","jp.","apac.","au."].some(oe=>H.startsWith(oe)))return Z.languageModel(H);let W=$?.region??R,V=W.split("-")[0];switch(V){case "us":{let oe=["nova-micro","nova-lite","nova-pro","nova-premier","nova-2","claude","deepseek"].some(me=>H.includes(me)),de=W.startsWith("us-gov");oe&&!de&&(H=`${V}.${H}`);break}case "eu":{let oe=["eu-west-1","eu-west-2","eu-west-3","eu-north-1","eu-central-1","eu-south-1","eu-south-2"].some(me=>W.includes(me)),de=["claude","nova-lite","nova-micro","llama3","pixtral"].some(me=>H.includes(me));oe&&de&&(H=`${V}.${H}`);break}case "ap":{let oe=["ap-southeast-2","ap-southeast-4"].includes(W),de=W==="ap-northeast-1";oe&&["anthropic.claude-sonnet-4-5","anthropic.claude-haiku"].some(me=>H.includes(me))?(V="au",H=`${V}.${H}`):de?["claude","nova-lite","nova-micro","nova-pro"].some(ce=>H.includes(ce))&&(V="jp",H=`${V}.${H}`):["claude","nova-lite","nova-micro","nova-pro"].some(ce=>H.includes(ce))&&(V="apac",H=`${V}.${H}`);break}}return Z.languageModel(H)}}},nvidia:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.ai/","X-Title":"easbot"}}}),openrouter:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.cn/","X-Title":"easbot"}}}),vercel:async()=>({autoload:false,options:{headers:{"http-referer":"https://easbot.cn/","x-title":"easbot"}}}),"google-vertex":async()=>{let D=await tt.get("GOOGLE_CLOUD_PROJECT")??tt.get("GCP_PROJECT")??tt.get("GCLOUD_PROJECT"),I=await tt.get("GOOGLE_CLOUD_LOCATION")??tt.get("VERTEX_LOCATION")??"us-east5";return !D?{autoload:false}:{autoload:true,vars(v){let T=I==="global"?"aiplatform.googleapis.com":`${I}-aiplatform.googleapis.com`;return {...D&&{GOOGLE_VERTEX_PROJECT:D},GOOGLE_VERTEX_LOCATION:I,GOOGLE_VERTEX_ENDPOINT:T}},options:{project:D,location:I,fetch:async(v,T)=>{let{GoogleAuth:R}=await import('google-auth-library'),Y=await(await new R().getApplicationDefault()).credential.getAccessToken(),J=new Headers(T?.headers);return J.set("Authorization",`Bearer ${Y.token}`),fetch(v,{...T,headers:J})}},async getModel(v,T){let R=String(T).trim();return v.languageModel(R)}}},"google-vertex-anthropic":async()=>{let D=tt.get("GOOGLE_CLOUD_PROJECT")??tt.get("GCP_PROJECT")??tt.get("GCLOUD_PROJECT"),I=tt.get("GOOGLE_CLOUD_LOCATION")??tt.get("VERTEX_LOCATION")??"global";return !D?{autoload:false}:{autoload:true,options:{project:D,location:I},async getModel(v,T){let R=String(T).trim();return v.languageModel(R)}}},"sap-ai-core":async()=>{let D=await Qe.get("sap-ai-core"),I=iife(()=>{let T=process.env.AICORE_SERVICE_KEY;if(T)return T;if(D?.type==="api")return process.env.AICORE_SERVICE_KEY=D.key,D.key}),M=process.env.AICORE_DEPLOYMENT_ID,v=process.env.AICORE_RESOURCE_GROUP;return {autoload:!!I,options:I?{deploymentId:M,resourceGroup:v}:{},async getModel(T,R){return T(R)}}},zenmux:async()=>({autoload:false,options:{headers:{"HTTP-Referer":"https://easbot.cn/","X-Title":"easbot"}}}),gitlab:async D=>{let I=tt.get("GITLAB_INSTANCE_URL")||"https://gitlab.com",M=await Qe.get(D.id),v=await(async()=>M?.type==="oauth"?M.access:M?.type==="api"?M.key:tt.get("GITLAB_TOKEN"))(),R=(await he.get()).provider?.gitlab,{VERSION:j,createGitLab:U}=await import('gitlab-ai-provider'),Y={"User-Agent":`easbot/${b$3.getVersion()} gitlab-ai-provider/${j} (${sc.platform()} ${sc.release()}; ${sc.arch()})`,...R?.options?.aiGatewayHeaders||{}};return {autoload:!!v,options:{instanceUrl:I,apiKey:v,aiGatewayHeaders:Y,featureFlags:{duo_agent_platform_agentic_chat:true,duo_agent_platform:true,...R?.options?.featureFlags||{}}},async getModel(J,ee){return J.agenticChat(ee,{aiGatewayHeaders:Y,featureFlags:{duo_agent_platform_agentic_chat:true,duo_agent_platform:true,...R?.options?.featureFlags||{}}})}}},"cloudflare-workers-ai":async D=>{let I=tt.get("CLOUDFLARE_ACCOUNT_ID");if(!I)return {autoload:false};let M=await iife(async()=>{let v=tt.get("CLOUDFLARE_API_KEY");if(v)return v;let T=await Qe.get(D.id);if(T?.type==="api")return T.key});return {autoload:!!M,options:{apiKey:M,baseURL:`https://api.cloudflare.com/client/v4/accounts/${I}/ai/v1`},async getModel(v,T){return v.languageModel(T)}}},"cloudflare-ai-gateway":async D=>{let I=await tt.get("CLOUDFLARE_ACCOUNT_ID"),M=await tt.get("CLOUDFLARE_GATEWAY_ID");if(!I||!M)return {autoload:false};let v=await(async()=>{let Y=await tt.get("CLOUDFLARE_API_TOKEN")||await tt.get("CF_AIG_TOKEN");if(Y)return Y;let J=await Qe.get(D.id);if(J?.type==="api")return J.key})();if(!v)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:T}=await import('ai-gateway-provider'),{createUnified:R}=await import('ai-gateway-provider/providers/unified'),j=T({accountId:I,gateway:M,apiKey:v}),U=R();return {autoload:true,async getModel(Y,J,ee){return j(U(J))},options:{}}},cerebras:async()=>({autoload:false,options:{headers:{"X-Cerebras-3rd-Party-Integration":"easbot"}}}),ollama:async()=>{let D=await tt.get("OLLAMA_BASE_URL")||"http://localhost:11434",I=a.file(),M=I?Ce__default.dirname(I):"",v=a.getLevel();return {autoload:true,options:{baseURL:D,logDir:M,logLevel:v},async getModel(T,R,j){return T.languageModel?T.languageModel(R):T(R)}}},"easbot-local":async()=>{let{Global:D}=await import('./global-HVRSDT3G.mjs'),I=await tt.get("LOCAL_MODEL_PATH")||Ce__default.join(D.Path.cache,"models"),M=a.file(),v=M?Ce__default.dirname(M):"",T=a.getLevel(),{SUPPORTED_EMBEDDING_MODELS:R}=await import('@easbot/local-model-sdk');return {autoload:true,options:{cacheDir:I,logDir:v,logLevel:T,verbose:true},async getModel(j,U,Y){return U in R?j.embeddingModel(U,Y):U.startsWith("rerank-")?j.rerankingModel?j.rerankingModel(U.slice(6),Y):j(U):j.languageModel?j.languageModel(U,Y):j(U)}}}};ue.Model=F.object({id:F.string(),providerId:F.string(),api:F.object({id:F.string(),url:F.string(),npm:F.string()}),name:F.string(),family:F.string().optional(),capabilities:F.object({temperature:F.boolean(),reasoning:F.boolean(),attachment:F.boolean(),toolcall:F.boolean(),input:F.object({text:F.boolean(),audio:F.boolean(),image:F.boolean(),video:F.boolean(),pdf:F.boolean()}),output:F.object({text:F.boolean(),audio:F.boolean(),image:F.boolean(),video:F.boolean(),pdf:F.boolean()}),interleaved:F.union([F.boolean(),F.object({field:F.enum(["reasoning_content","reasoning_details"])})])}),cost:F.object({input:F.number(),output:F.number(),cache:F.object({read:F.number(),write:F.number()}),experimentalOver200K:F.object({input:F.number(),output:F.number(),cache:F.object({read:F.number(),write:F.number()})}).optional()}),limit:F.object({context:F.number(),input:F.number().optional(),output:F.number()}),status:F.enum(["alpha","beta","deprecated","active"]),options:F.record(F.string(),F.any()),headers:F.record(F.string(),F.string()),release_date:F.string(),variants:F.record(F.string(),F.record(F.string(),F.any())).optional()}).meta({ref:"Model"}),ue.Info=F.object({id:F.string(),name:F.string(),source:F.enum(["env","config","custom","api"]),env:F.string().array(),key:F.string().optional(),options:F.record(F.string(),F.any()),models:F.record(F.string(),ue.Model)}).meta({ref:"Provider"});function m(D,I){let M={id:I.id,providerId:D.id,name:I.name,family:I.family,api:{id:I.id,url:D.api,npm:I.provider?.npm??D.npm??"@ai-sdk/openai-compatible"},status:I.status??"active",headers:I.headers??{},options:I.options??{},cost:{input:I.cost?.input??0,output:I.cost?.output??0,cache:{read:I.cost?.cache_read??0,write:I.cost?.cache_write??0},experimentalOver200K:I.cost?.context_over_200k?{cache:{read:I.cost.context_over_200k.cache_read??0,write:I.cost.context_over_200k.cache_write??0},input:I.cost.context_over_200k.input,output:I.cost.context_over_200k.output}:void 0},limit:{context:I.limit.context??2e5,input:I.limit.input??o(I.limit.context??2e5),output:I.limit.output??8192},capabilities:{temperature:I.temperature,reasoning:I.reasoning,attachment:I.attachment,toolcall:I.tool_call,input:{text:I.modalities?.input?.includes("text")??false,audio:I.modalities?.input?.includes("audio")??false,image:I.modalities?.input?.includes("image")??false,video:I.modalities?.input?.includes("video")??false,pdf:I.modalities?.input?.includes("pdf")??false},output:{text:I.modalities?.output?.includes("text")??false,audio:I.modalities?.output?.includes("audio")??false,image:I.modalities?.output?.includes("image")??false,video:I.modalities?.output?.includes("video")??false,pdf:I.modalities?.output?.includes("pdf")??false},interleaved:I.interleaved??false},release_date:I.release_date,variants:{}};return M.variants=mapValues(wt.variants(M),v=>v),M}function f(D){return {id:D.id,source:"custom",name:D.name,env:D.env??[],options:{},models:mapValues(D.models,I=>m(D,I))}}ue.fromModelsDevProvider=f;async function a$1(){var Z=[];try{let D=c(Z,s.time("state"));let I=await he.get();let M=await a$3.get();let v=mapValues(M,f);let T=new Set(I.disabled_providers??[]);let R=I.enabled_providers?new Set(I.enabled_providers):null;function j(W){return !(R&&!R.has(W)||T.has(W))}let U={};let Y=new Map;let J={};let ee=new Map;let se=new Map;s.info("init");let ae=Object.entries(I.provider??{});if(v["github-copilot"]){let W=v["github-copilot"];v["github-copilot-enterprise"]={...W,id:"github-copilot-enterprise",name:"GitHub Copilot Enterprise",models:mapValues(W.models,V=>({...V,providerId:"github-copilot-enterprise"}))};}function we(W,V){let oe=U[W];if(oe){U[W]=mergeDeep(oe,V);return}let de=v[W];de&&(U[W]=mergeDeep(de,V));}for(let[W,V]of ae){let oe=v[W],de={id:W,name:V.name??oe?.name??W,env:V.env??oe?.env??[],options:mergeDeep(oe?.options??{},V.options??{}),source:"config",models:oe?.models??{}};for(let[me,ce]of Object.entries(V.models??{})){let ye=de.models[ce.id??me],je=iife(()=>ce.name?ce.name:ce.id&&ce.id!==me?me:ye?.name??me),Ie={id:me,api:{id:ce.id??ye?.api.id??me,npm:ce.provider?.npm??V.npm??ye?.api.npm??M[W]?.npm??"@ai-sdk/openai-compatible",url:V?.api??ye?.api.url??M[W]?.api??""},status:ce.status??ye?.status??"active",name:je,providerId:W,capabilities:{temperature:ce.temperature??ye?.capabilities.temperature??!1,reasoning:ce.reasoning??ye?.capabilities.reasoning??!1,attachment:ce.attachment??ye?.capabilities.attachment??!1,toolcall:ce.tool_call??ye?.capabilities.toolcall??!0,input:{text:ce.modalities?.input?.includes("text")??ye?.capabilities.input.text??!0,audio:ce.modalities?.input?.includes("audio")??ye?.capabilities.input.audio??!1,image:ce.modalities?.input?.includes("image")??ye?.capabilities.input.image??!1,video:ce.modalities?.input?.includes("video")??ye?.capabilities.input.video??!1,pdf:ce.modalities?.input?.includes("pdf")??ye?.capabilities.input.pdf??!1},output:{text:ce.modalities?.output?.includes("text")??ye?.capabilities.output.text??!0,audio:ce.modalities?.output?.includes("audio")??ye?.capabilities.output.audio??!1,image:ce.modalities?.output?.includes("image")??ye?.capabilities.output.image??!1,video:ce.modalities?.output?.includes("video")??ye?.capabilities.output.video??!1,pdf:ce.modalities?.output?.includes("pdf")??ye?.capabilities.output.pdf??!1},interleaved:ce.interleaved??!1},cost:{input:ce?.cost?.input??ye?.cost?.input??0,output:ce?.cost?.output??ye?.cost?.output??0,cache:{read:ce?.cost?.cache_read??ye?.cost?.cache.read??0,write:ce?.cost?.cache_write??ye?.cost?.cache.write??0}},options:mergeDeep(ye?.options??{},ce.options??{}),limit:{context:ce.limit?.context??ye?.limit?.context??2e5,input:ce.limit?.input??ye?.limit?.input??o(ce.limit?.context??2e5),output:ce.limit?.output??ye?.limit?.output??8192},headers:mergeDeep(ye?.headers??{},ce.headers??{}),family:ce.family??ye?.family??"",release_date:ce.release_date??ye?.release_date??"",variants:{}},ke=mergeDeep(wt.variants(Ie),ce.variants??{});Ie.variants=mapValues(pickBy(ke,re=>!re.disabled),re=>omit(re,["disabled"])),de.models[me]=Ie;}v[W]=de;}let ie=await tt.all();for(let[W,V]of Object.entries(v)){if(T.has(W))continue;let oe=V.env.map(de=>ie[de]).find(Boolean);oe&&we(W,{source:"env",key:V.env.length===1?oe:void 0});}for(let[W,V]of Object.entries(await Qe.all()))T.has(W)||V.type==="api"&&we(W,{source:"api",key:V.key});for(let W of await ms.list()){if(!W.auth)continue;let V=W.auth.provider;if(T.has(V))continue;let oe=!1,de=await Qe.get(V);if(de&&(oe=!0),V==="github-copilot"&&!oe&&await Qe.get("github-copilot-enterprise")&&(oe=!0),!!oe&&W.auth.loader){if(de){let me=v[W.auth.provider];if(!me){s.error(`Auth provider ${W.auth.provider} not found in database`);return}let ye=await W.auth.loader(()=>Qe.get(V),me)??{},je=U[V]?{options:ye}:{source:"custom",options:ye};we(V,je);}if(V==="github-copilot"){let me="github-copilot-enterprise";if(!T.has(me)&&await Qe.get(me)){let ye=v[me];if(!ye){s.error(`Enterprise provider ${me} not found in database`);return}let Ie=await W.auth.loader(()=>Qe.get(me),ye)??{},ke=U[me]?{options:Ie}:{source:"custom",options:Ie};we(me,ke);}}}}for(let[W,V]of Object.entries(c$1)){if(T.has(W))continue;let oe=v[W];if(!oe){s.error("Provider does not exist in model list "+W);continue}let de=await V(oe);if(de&&(de.autoload||U[W])){de.getModel&&(J[W]=de.getModel);let me=de.options??{},ce=U[W]?{options:me}:{source:"custom",options:me};we(W,ce);}}for(let[W,V]of ae){let oe={source:"config"};V.env&&(oe.env=V.env),V.name&&(oe.name=V.name),V.options&&(oe.options=V.options),we(W,oe);}for(let[W,V]of Object.entries(U)){if(!j(W)){delete U[W];continue}let oe=I.provider?.[W];for(let[de,me]of Object.entries(V.models)){me.api.id=me.api.id??me.id??de,(de==="gpt-5-chat-latest"||W==="openrouter"&&de==="openai/gpt-5-chat")&&delete V.models[de],me.status==="alpha"&&!a$2.EASBOT_ENABLE_EXPERIMENTAL_MODELS&&delete V.models[de],me.status==="deprecated"&&delete V.models[de],(oe?.blacklist?.includes(de)||oe?.whitelist&&!oe.whitelist.includes(de))&&delete V.models[de],me.variants=mapValues(wt.variants(me),ye=>ye);let ce=oe?.models?.[de]?.variants;if(ce&&me.variants){let ye=mergeDeep(me.variants,ce);me.variants=mapValues(pickBy(ye,je=>!je.disabled),je=>omit(je,["disabled"]));}}if(Object.keys(V.models).length===0){delete U[W];continue}s.info("found",{providerId:W});}return {models:Y,providers:U,sdk:ee,localProxy:se,modelLoaders:J}}catch(H){var $=H,te=true;}finally{d(Z,$,te);}}let p;function u(){return p||(p=_.state(a$1)),p}async function g(){return u()()}async function h(){return (await g())?.providers??{}}ue.list=h;async function S(){return (await g())?.localProxy??{}}ue.getLocalProxy=S;async function A(D){try{var I=[];try{let R=c(I,s.time("getSDK",{providerId:D.providerId}));let j=await g();if(!j)throw new Error("Provider state not available");let U=j.providers[D.providerId];if(!U)throw new Error(`Provider ${D.providerId} not found`);let Y={...U.options};D.api.npm.includes("@ai-sdk/openai-compatible")&&Y.includeUsage!==!1&&(Y.includeUsage=!0);Y.baseURL||(Y.baseURL=D.api.url);Y.apiKey===void 0&&U.key&&(Y.apiKey=U.key);D.headers&&(Y.headers={...Y.headers,...D.headers});let J=JSON.stringify({providerId:D.providerId,npm:D.api.npm,options:Y}).split("").reduce((ye,je)=>(ye=(ye<<5)-ye+je.charCodeAt(0),ye&ye),0);let ee=j.sdk.get(J);if(ee)return ee;let se=Y.fetch;Y.fetch=async(ye,je)=>{let Ie=se??fetch,ke=je??{};if(Y.timeout!==void 0&&Y.timeout!==null){let re=[];ke.signal&&re.push(ke.signal),Y.timeout!==!1&&re.push(AbortSignal.timeout(Y.timeout));let $e=re.length>1?AbortSignal.any(re):re[0];ke.signal=$e;}if(D.api.npm==="@ai-sdk/openai"&&ke.body&&ke.method==="POST"){let re=JSON.parse(ke.body);if(!(D.providerId.includes("azure")&&re.store===!0)&&Array.isArray(re.input)){for(let pt of re.input)"id"in pt&&delete pt.id;ke.body=JSON.stringify(re);}}return Ie(ye,{...ke,timeout:!1})};let ae=IR[D.api.npm];if(ae){s.info("using bundled provider",{providerId:D.providerId,pkg:D.api.npm});let je=(await ae())({name:D.providerId,...Y});return j.sdk.set(J,je),je}let we;D.api.npm.startsWith("file://")?we=D.api.npm:we=await Shell.install(D.api.npm,"latest");let{pathToFileURL:ie}=await import('url');let Z=await import('path');let H=await import('fs/promises');let $=Z.join(we,"package.json");let te=JSON.parse(await H.readFile($,"utf-8"));let W;te.exports?.["."]?.import?W=te.exports["."].import:te.exports?.["."]?.require?W=te.exports["."].require:te.module?W=te.module:te.main?W=te.main:W="index.js";let V=Z.join(we,W);let oe=ie(V).href;let de=await import(oe);let me=de[Object.keys(de).find(ye=>ye.startsWith("create"))];let ce=me({name:D.providerId,...Y});j.sdk.set(J,ce);return ce}catch(M){var v=M,T=!0;}finally{d(I,v,T);}}catch(R){throw new ue.InitError({providerId:D.providerId},{cause:R})}}async function y(D){return (await g())?.providers[D]}ue.getProvider=y;async function x(D,I){let M=await g();if(!M)throw new Error("Provider state not available");let v=M.providers[D];if(!v){let R=Object.keys(M.providers),U=Ty.go(D,R,{limit:3,threshold:-1e4}).map(Y=>Y.target);throw new ue.ModelNotFoundError({providerId:D,modelId:I,suggestions:U})}let T=v.models[I];if(!T){let R=Object.keys(v.models),U=Ty.go(I,R,{limit:3,threshold:-1e4}).map(Y=>Y.target);throw new ue.ModelNotFoundError({providerId:D,modelId:I,suggestions:U})}return T}ue.getModel=x;async function b(D){s.debug("getLanguage called",{providerId:D.providerId,modelId:D.id});let I=await g();if(!I)throw new Error("Provider state not available");let M=`${D.providerId}/${D.id}`;if(I.models.has(M))return I.models.get(M);let v=I.providers[D.providerId];if(!v)throw new Error(`Provider ${D.providerId} not found`);let T=await A(D);try{let R=I.modelLoaders[D.providerId],j=R?await R(T,D.api.id,v.options):T.languageModel(D.api.id);return I.models.set(M,j),j}catch(R){throw s.error("Failed to create language model",{providerId:D.providerId,modelId:D.id,error:R}),R instanceof NoSuchModelError?new ue.ModelNotFoundError({modelId:D.id,providerId:D.providerId},{cause:R}):R}}ue.getLanguage=b;async function w(D,I){s.debug("getEmbedding called",{providerId:D,modelId:I});let M=await x(D,I),v=await A(M),T,R=v;if(typeof R.embeddingModel=="function")T=R.embeddingModel(M.api.id);else if(typeof R.textEmbeddingModel=="function")T=R.textEmbeddingModel(M.api.id);else throw new Error(`Provider ${D} does not support embedding model. SDK missing both 'embeddingModel' and 'textEmbeddingModel' methods.`);return T}ue.getEmbedding=w;async function C(D,I){s.debug("getRerank called",{providerId:D,modelId:I});let M=await x(D,I),v=await A(M),T,R=v;if(typeof R.rerankingModel=="function")T=R.rerankingModel(M.api.id);else if(typeof R.languageModel=="function"){let j=await S(),U=`${D}/${I}`;if(U in j)return j[U];let Y=await b(M);if(Y){let J=await x("easbot-local","rerank-proxy"),se=await A(J);T=se.rerankingModel?se.rerankingModel(J.api.id,{llm:Y,useEnhancedPrompt:true,promptLanguage:"cn",totalScore:1}):void 0,T&&j.set(U,T);}}if(!T)throw new Error(`Provider ${D} and model ${I} does not support rerank`);return T}ue.getRerank=C;async function k(D,I){let M=await g();if(!M)return;let v=M.providers[D];if(v){for(let T of I)for(let R of Object.keys(v.models))if(R.includes(T))return {providerId:D,modelId:R}}}ue.closest=k;async function P(D){let I=await he.get();if(I.small_model){let R=L(I.small_model);if(!R.providerId||!R.modelId)throw new Error("Invalid small_model format");return x(R.providerId,R.modelId)}let M=await g(),v=M?.providers[D];if(v){let R=["claude-haiku-4-5","claude-haiku-4.5","3-5-haiku","3.5-haiku","gemini-3-flash","gemini-2.5-flash","gpt-5-nano"];D.startsWith("easbot")&&(R=["gpt-5-nano"]),D.startsWith("github-copilot")&&(R=["gpt-5-mini","claude-haiku-4.5",...R]);for(let j of R)if(D==="amazon-bedrock"){let U=["global.","us.","eu."],Y=Object.keys(v.models).filter(ae=>ae.includes(j)),J=Y.find(ae=>ae.startsWith("global."));if(J)return x(D,J);let ee=v.options?.region;if(ee){let ae=ee.split("-")[0];if(ae==="us"||ae==="eu"){let we=Y.find(ie=>ie.startsWith(`${ae}.`));if(we)return x(D,we)}}let se=Y.find(ae=>!U.some(we=>ae.startsWith(we)));if(se)return x(D,se)}else for(let U of Object.keys(v.models))if(U.includes(j))return x(D,U)}if(M?.providers.easbot?.models["gpt-5-nano"])return x("easbot","gpt-5-nano")}ue.getSmallModel=P;let E=["gpt-5","claude-sonnet-4","big-pickle","gemini-3-pro"];function O(D){return sortBy(D,[I=>E.findIndex(M=>I.id.includes(M)),"desc"],[I=>I.id.includes("latest")?0:1,"asc"],[I=>I.id,"desc"])}ue.sort=O;async function N(){let D=await he.get();if(D.model)return L(D.model);let I=await h().then(v=>Object.values(v)).then(v=>v.find(T=>!D.provider||Object.keys(D.provider).includes(T.id)));if(!I)throw new Error("no providers found");let[M]=O(Object.values(I.models));if(!M)throw new Error("no models found");return {providerId:I.id,modelId:M.id}}ue.defaultModel=N;function L(D){let{provider:I,model:M}=parseModelId(D);if(!I)throw new Error("Invalid model format: "+D);return {providerId:I,modelId:M}}ue.parseModel=L,ue.ModelNotFoundError=NamedError.create("ProviderModelNotFoundError",F.object({providerId:F.string(),modelId:F.string(),suggestions:F.array(F.string()).optional()})),ue.InitError=NamedError.create("ProviderInitError",F.object({providerId:F.string()}));})(xe||(xe={}));var Xt;(p=>{let e=a.create({service:"knowledge.note"}),t;async function n(u){let g=await he.get(),h=u?.embedding?.model||g.embedding_model||"easbot-local/bge-base-zh-v1.5",{provider:S,model:A}=parseModelId(h),y=S||"easbot-local",x=A||"bge-base-zh-v1.5",b=await xe.getEmbedding(y,x),w=u?.graph?.model??g.graph_model,C,k;if(w){let{provider:K,model:Q}=parseModelId(w);C=K||"easbot-local",k=Q||w;}else {let K=await xe.defaultModel();C=K.providerId,k=K.modelId;}let P;try{let K=await xe.getModel(C,k);P=await xe.getLanguage(K);}catch(K){e.error("note loadModels graphLlm failed",{graphProvider:C,graphModel:k,error:String(K)});}let E=u?.rerank?.model||g.rerank_model,O,N;if(E){let{provider:K,model:Q}=parseModelId(E);O=K||"easbot-local",N=Q||E;}else {let K=await xe.defaultModel();O="easbot-local",N=`rerank-${K.providerId}/${K.modelId}`;}let L;try{L=await xe.getRerank(O,N);}catch(K){e.error("note loadModels rerankLlm failed",{rerankProvider:O,rerankModel:N,error:String(K)});}return {embeddingLlm:b,graphLlm:P,rerankLlm:L}}function o(){return t||(t=_.state(async()=>{let u=await rr();if(!u||u.enabled===false)return {kb:null,config:null,rootDir:"",sources:[],initialized:true};let{Global:g}=await import('./global-HVRSDT3G.mjs'),h=_.worktree??_.directory,S=Filesystem.normalize(Ce__default.join(h,".easbot","knowledge")),A=Filesystem.normalize(u.database?Ce__default.isAbsolute(u.database)?u.database:Ce__default.resolve(h,u.database):Ce__default.join(_.worktree,".easbot","db","note.db")),{embeddingLlm:y,graphLlm:x,rerankLlm:b}=await n(u),w=(u?.sources?.length??0)>0?u.sources:["docs","tasks"];for(let P of w??[]){let E=Filesystem.normalize(Ce__default.join(S,P));await Filesystem.exists(E)||await Filesystem.mkdir(E);}let C={workspaceDir:S,vectorDims:u.embedding?.dimensions??1,embeddingLlm:y,graphLlm:x,rerankLlm:b,search:{maxResults:u.search?.maxResults??3,minScore:u.search?.minScore??0,hybrid:{enabled:u.search?.hybrid?.enabled??true,vectorWeight:u.search?.hybrid?.vectorWeight??0,textWeight:u.search?.hybrid?.textWeight??1}},indexer:{batchSize:20,ignorePatterns:[...Glob.DEFAULT_IGNORE_PATTERNS,...u.indexer?.ignorePatterns??[],...(await Glob.parseGitignore(Ce__default.join(_.worktree,".gitignore"))).filter(P=>!P.includes(".easbot"))],incremental:u.indexer?.incremental??true},sync:u.sync,sources:w};A&&(C.database={path:A,walMode:true}),await initLog$2({logDir:g.Path.log,logFile:"note.log",level:a.getLevel(),print:false});let k=await createNoteKnowledge(C);return u.sync?.onBoot&&await k.sync().catch(P=>e.warn("note sync on boot failed",{error:String(P)})),{kb:k,config:u??null,rootDir:S,sources:w??[],initialized:true}},async u=>{u.kb&&await u?.kb?.close().catch(()=>{});})),t}function s(){return o()()}p.state=s;async function r(){return (await s()).kb}p.get=r;async function i(){return (await s()).rootDir}p.rootDir=i;async function c(){return (await s()).sources}p.sources=c;async function l(){return (await s()).kb!==null}p.isEnabled=l;async function d(){return (await s()).config}p.config=d;async function m(){return (await s()).initialized}p.isInitialized=m;async function f(){let u=await r();u&&u.sync().catch(g=>e.warn("note sync failed",{error:String(g)}));}p.sync=f;async function a$1(){let u=await r();if(!u)return null;let g=u.getStatus();return {dbPath:g.dbPath,documentsCount:g.documentsCount,chunksCount:g.chunksCount,nodesCount:g.nodesCount,edgesCount:g.edgesCount,vectorDims:0,vectorSearchAvailable:g.embeddingLlmAvailable,llmAvailable:g.graphLlmAvailable,healthy:g.healthy}}p.status=a$1;})(Xt||(Xt={}));var on=a.create({service:"context-instructions"});async function kR(e){let t=[{name:"memory",description:"Use this tool to store, retrieve, update, and delete persistent memories across agent sessions. Memory enables learning from interactions, remembering user preferences, and building long-term knowledge",condition:async()=>In.isEnabled()},{name:"note",description:"Use this tool to search and retrieve information from the local note/document knowledge base. It returns document paths, line ranges, snippets, and related graph nodes",condition:async()=>Xt.isEnabled()}],n=["| Tool | Description |","|------|-------------|"];for(let o of t)await o.condition()&&n.push(`| \`${o.name}\` | ${o.description} |`);return n.join(`
975
+ `)}async function PR(e){let t=["| Directory | Description |","|-------------|-------------|"],n=[{path:async()=>Xt.rootDir(),description:"Knowledge base root directory",condition:async()=>Xt.isEnabled()},{path:async()=>`${await Xt.rootDir()}/tasks`,description:"Task files - each task in separate folder (task_plan.md, progress.md, findings.md)",condition:async()=>Xt.isEnabled()},{path:async()=>`${await Xt.rootDir()}/docs`,description:"Documentation - categorized by topic as needed",condition:async()=>Xt.isEnabled()}];for(let o of n)if(o.condition?await o.condition():true){let r=await o.path();t.push(`| \`${r}/\` | ${o.description} |`);}return t.join(`
976
+ `)}async function Ip(e,t){let n=e;if(n.includes("{{tools}}"))try{n=n.replace("{{tools}}",await kR(t));}catch(s){on.warn("failed to render {{tools}} placeholder",{error:String(s)}),n=n.replace("{{tools}}","");}if(n.includes("{{directories}}"))try{n=n.replace("{{directories}}",await PR(t));}catch(s){on.warn("failed to render {{directories}} placeholder",{error:String(s)}),n=n.replace("{{directories}}","");}n=n.replace(/\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g,(s,r,i)=>{let c=t[r];return c!=null&&c!==0&&c!==""?i:""}),n=n.replace(/\{\{#each\s+(\w+)\}\}([\s\S]*?)\{\{\/each\}\}/g,(s,r,i)=>{let c=t[r];return !Array.isArray(c)||c.length===0?"":c.map(l=>{let d=i;return typeof l=="object"&&l!==null&&Object.entries(l).forEach(([m,f])=>{d=d.replace(new RegExp(`\\{\\{${m}\\}\\}`,"g"),String(f));}),d}).join("")});let o={};return t.metadata&&Object.entries(t.metadata).forEach(([s,r])=>{o[s]=r;}),Object.entries(t).forEach(([s,r])=>{s==="metadata"||s==="tools"||s==="directories"||s==="files"||(o[s]=r);}),Object.keys(o).length>0&&(n=a$9.replaceVariables(n,o)),n}function TR(e){let t=`| File | Priority | Description | Scope | Type | Permission | Location | Status |
977
+ |------|----------|-------------|-------|------|------------|----------|--------|`,n=e.map(o=>`| ${o.name} | ${o.priority} | ${o.description} | ${o.scope} | ${o.type} | ${o.permission} | ${o.location} | ${o.status} |`).join(`
978
+ `);return `${t}
979
+ ${n}`}function bo(e){if(e)return typeof e=="string"?e:String(e)}function vp(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 jy(e){if(e!=null){if(typeof e=="boolean")return e;if(typeof e=="string")return e.toLowerCase()==="true"}}function _d(e){if(e){if(Array.isArray(e))return e.map(t=>String(t));if(typeof e=="string")try{let t=JSON.parse(e);if(Array.isArray(t))return t.map(n=>String(n))}catch{return e.split(",").map(t=>t.trim())}}}function Ly(e,t){return e.scope===i?true:e.scope===t}function AR(e,t){return !e.owner||e.owner.length===0?true:t?!!(e.owner.includes(t)||e.share?.includes(t)):false}async function ER(e,t,n){if(await Filesystem.isDir(e))try{let o=await Tt__default.readdir(e,{withFileTypes:!0});for(let s of o){if(!s.isFile()||!s.name.endsWith(".md"))continue;let r=s.name;if(!l.includes(r)||t.has(r))continue;let i=Ce__default.join(e,r),c=await Md(i,n);c&&t.set(r,c);}}catch(o){on.warn("failed to scan builtin system files",{dir:e,error:String(o)});}}async function RR(e,t,n$1){for(let[o,s]of Object.entries(n))if(!n$1.has(o))for await(let r of Filesystem.up({targets:[s],start:e,stop:_.worktree})){let i=await Md(r,t);if(i){n$1.set(o,i);break}}}async function _R(e,t,n){let o=Ce__default.join(e,"rules"),s=new Map;if(!await Filesystem.isDir(o))return s;try{let r=await Tt__default.readdir(o,{withFileTypes:!0});for(let i of r){if(!i.isFile()||!i.name.endsWith(".md")||t.has(i.name))continue;let c=Ce__default.join(o,i.name),l=await Md(c,n);l&&s.set(i.name,l);}}catch(r){on.warn("failed to scan rules directory",{dir:o,error:String(r)});}return s}async function MR(e,t,n,o){let s=new Map,r=await he.get(),i$1=r.context?.files,c=r.context?.contextFiles;if(!c)return s;let l=c[t]||c[i]||[];if(l.length===0||!await Filesystem.isDir(e))return s;try{let d=await Tt__default.readdir(e,{withFileTypes:!0});for(let m of l){if(s.has(m))continue;let f=d.find(g=>g.isFile()&&g.name===m);if(!f)continue;let a=Ce__default.join(e,f.name),p=await Md(a,o);if(!p)continue;let u=Dy(m,i$1,p.frontmatter);Ly(u,t)&&AR(u,n)&&s.set(m,{...p,config:u});}}catch(d){on.warn("failed to load context files",{root:e,error:String(d)});}return s}function Dy(e,t,n){let o=p[e],s=t?.[e];return {name:e,type:bo(n?.type)??s?.type??o?.type??"system",scope:bo(n?.scope)??s?.scope??o?.scope??"all",priority:vp(n?.priority)??s?.priority??o?.priority??q,owner:_d(n?.owner)??s?.owner??o?.owner,share:_d(n?.share)??s?.share??o?.share,permission:bo(n?.permission)??s?.permission??o?.permission??"read",description:bo(n?.description)??s?.description??o?.description,dynamic:jy(n?.dynamic)??s?.dynamic??o?.dynamic}}function Rd(e,t,n,o,s,r=false){let i=n.permission==="write"?"writable":"readonly",c=`<file path="${o}" priority="${s}" mode="${i}">
980
+ ${t}
981
+ </file>`;return {name:e,content:c,priority:s,dynamic:r,location:o,permission:n.permission,owner:n.owner,share:n.share}}async function OR(e,t){try{if(await ec(e))return on.debug("workspace already initialized, skipping builtin bootstrap"),null;let o=null,s="",r=await Jt.get("eas-agent-evolution");if(r){let l=Ce__default.join(Ce__default.dirname(r.location),"assets","BOOTSTRAP.md");try{o=await Tt__default.readFile(l,"utf-8"),s=l;}catch{}}if(!o){let l=m.replace(".md","");o=await loadTextFileAsync(`./template/${l}.txt`,import.meta.url)(),o&&(s=`context/template/${l}.txt`);}if(!o)return on.debug("builtin bootstrap template not found"),null;let i=await Ip(o,t).catch(l=>(on.warn("renderTemplate failed for bootstrap, using raw content",{error:String(l)}),o)),c=p[m]??{name:m,type:"system",scope:"all",priority:20};return on.debug("loaded builtin bootstrap template",{location:s}),Rd(m,i,c,`<builtin:${s}>`,c.priority??20,!1)}catch(n){return on.warn("failed to load builtin bootstrap",{error:String(n)}),null}}function jR(e,t,n$1=false){let o$1=[],s=(r,i$1)=>{let c=i$1?.frontmatter||{},l=p[r],d=bo(c.scope)||l?.scope||i;d!==i&&d!==t||n$1&&!o.includes(r)||o$1.push({name:r,priority:vp(c.priority)||l?.priority||q,description:bo(c.description)||l?.description||"",scope:d,type:bo(c.type)||l?.type||"system",permission:bo(c.permission)||l?.permission||"read",location:i$1?.location||"",status:i$1?"\u2705":"\u274C"});};for(let r of l)s(r,e.get(r));for(let r of Object.keys(n))s(r,e.get(r));for(let[r,i]of e)p[r]||s(r,i);return o$1.sort((r,i)=>r.priority-i.priority),o$1}async function LR(e,t,n=false){let o={};if(o.isMainAgent=!n,t);else try{let r=`${await Ei(e)}/protocol.json`,i=await xl(r);o.metadata=i.metadata;}catch(s){on.debug("failed to read protocol for render context",{error:String(s)});}return o}async function Md(e,t){let n=t??{};try{let o=await a$9.parse(e);return {content:await Ip(o.content,n).catch(r=>(on.warn("renderTemplate failed on parsed content, using raw",{filePath:e,error:String(r)}),o.content)),frontmatter:o.data,location:e}}catch(o){if(o.code==="ENOENT")return null;try{let s=await Tt__default.readFile(e,"utf-8");return on.warn("failed to parse frontmatter, using raw content",{filePath:e,error:String(o)}),{content:await Ip(s,n).catch(i=>(on.warn("renderTemplate failed on raw content, using as-is",{filePath:e,error:String(i)}),s)),frontmatter:{},location:e}}catch(s){return on.warn("failed to load template file",{filePath:e,error:String(s)}),null}}}async function DR(e){let t=e.mode??f$1,n=e.workspaceDir??_.directory,o$1=e.agent?.mode==="subagent",s=e.agent?.name,r$1=[],i=new Set,c=new Map,l=await LR(n,void 0,o$1),d=e.protocolInitialized??await ec(n);if(on.debug("loadTemplatesForMode: initialization status",{workspaceDir:n,isInitialized:d,protocolInitializedProvided:e.protocolInitialized!==void 0}),d){for await(let m of Filesystem.up({targets:[".easbot"],start:n,stop:_.worktree}))await ER(m,c,l);await RR(n,l,c);for(let[m,f]of c){if(i.has(m)||o$1&&!o.includes(m))continue;let a=Dy(m,void 0,f.frontmatter);if(!Ly(a,t))continue;let p=a.priority??q,u=m==="HEARTBEAT.md"||a.dynamic===true;r$1.push(Rd(m,f.content,a,f.location,p,u)),i.add(m);}}else {let m$1=await OR(n,l);m$1&&(r$1.push(m$1),i.add(m));}for await(let m of Filesystem.up({targets:[".easbot"],start:n,stop:_.worktree})){let f=await _R(m,i,l);for(let[p,u]of f){if(i.has(p))continue;let g={scope:bo(u.frontmatter?.scope)??"all",priority:vp(u.frontmatter?.priority)??r,permission:bo(u.frontmatter?.permission)??"read",dynamic:jy(u.frontmatter?.dynamic)??true,owner:_d(u.frontmatter?.owner),share:_d(u.frontmatter?.share),description:bo(u.frontmatter?.description)};r$1.push(Rd(p,u.content,g,u.location,g.priority,g.dynamic)),i.add(p);}let a=await MR(m,t,s,l);for(let[p,u]of a)i.has(p)||(r$1.push(Rd(p,u.content,u.config,u.location,u.config.priority??q)),i.add(p));}if(l.files=jR(c,t,o$1),l.files&&l.files.length>0)try{let m=TR(l.files);for(let f of r$1)f.content.includes("{{files}}")&&(f.content=f.content.replace("{{files}}",m));}catch(m){on.warn("failed to render {{files}} placeholder",{error:String(m)});}return r$1.sort((m,f)=>m.priority-f.priority),on.debug("templates loaded from filesystem",{mode:t,workspaceDir:n,agentMode:e.agent?.mode,isInitialized:d,sectionCount:r$1.length,sections:r$1.map(m=>({name:m.name,priority:m.priority,location:m.location,dynamic:m.dynamic}))}),r$1}var Oy=new Map;async function $y(e){let t=e.mode??f$1,n=e.workspaceDir??_.directory,s=e.agent?.mode==="subagent"?e.agent.name:"primary",r=n?`template:${t}:${s}:${n}`:`template:${t}:${s}`,i=Oy.get(r);if(i)return i;let l={sections:await DR(e),mode:t,loadedAt:Date.now()};return Oy.set(r,l),l}async function Sp(e){return (await $y(e)).sections}var hs=a.create({service:"file-cache"}),Fy=25*1024*1024,Ny=100,kp=class{constructor(t=Ny,n=Fy){b$1(this,"cache");b$1(this,"maxEntries");b$1(this,"maxSizeBytes");b$1(this,"currentSizeBytes");this.cache=new Map,this.maxEntries=t,this.maxSizeBytes=n,this.currentSizeBytes=0;}get(t){let n=this.cache.get(t);return n!==void 0&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){for(this.cache.has(t)&&(this.cache.delete(t),this.currentSizeBytes-=this.estimateSize(n));this.cache.size>=this.maxEntries||this.currentSizeBytes>=this.maxSizeBytes;){let o=this.cache.keys().next().value;if(o!==void 0){let s=this.cache.get(o);s!==void 0&&(this.currentSizeBytes-=this.estimateSize(s)),this.cache.delete(o),hs.debug("cache entry evicted",{key:o});}else break}this.cache.set(t,n),this.currentSizeBytes+=this.estimateSize(n);}has(t){return this.cache.has(t)}delete(t){let n=this.cache.get(t);return n!==void 0&&(this.currentSizeBytes-=this.estimateSize(n)),this.cache.delete(t)}clear(){this.cache.clear(),this.currentSizeBytes=0;}get size(){return this.cache.size}get sizeBytes(){return this.currentSizeBytes}estimateSize(t){return typeof t=="string"?t.length*2:100}keys(){return this.cache.keys()}values(){return this.cache.values()}entries(){return this.cache.entries()}},Od=class{constructor(t=Ny,n=Fy){b$1(this,"maxEntries",t);b$1(this,"maxSizeBytes",n);b$1(this,"cache");this.cache=new kp(this.maxEntries,this.maxSizeBytes),hs.debug("file state cache created",{maxEntries:this.maxEntries,maxSizeBytes:this.maxSizeBytes});}async readFile(t,n){try{let o=await Tt__default.stat(t),s=o.mtimeMs,r=this.cache.get(t);if(r&&r.timestamp===s&&r.offset===n?.offset&&r.limit===n?.limit)return hs.debug("cache hit",{filePath:t}),r.content;let i;if(n?.offset!==void 0||n?.limit!==void 0){let d=(await Tt__default.readFile(t,"utf-8")).split(`
982
+ `),m=n.offset??0,f=n.limit?m+n.limit:d.length;i=d.slice(m,f).join(`
983
+ `);}else i=await Tt__default.readFile(t,"utf-8");let c={content:i,timestamp:s,lineCount:i.split(`
984
+ `).length,size:o.size,offset:n?.offset,limit:n?.limit};return this.cache.set(t,c),hs.debug("cache miss, file read",{filePath:t,size:o.size}),i}catch(o){if(o.code==="ENOENT"){this.cache.delete(t);return}throw o}}getState(t){return this.cache.get(t)}async detectChanges(){let t=[];for(let[n,o]of this.cache.entries())try{let s=await Tt__default.stat(n);if(s.mtimeMs!==o.timestamp){let r=await Tt__default.readFile(n,"utf-8");t.push({path:n,oldContent:o.content,newContent:r,oldMtime:o.timestamp,newMtime:s.mtimeMs}),this.cache.set(n,{...o,content:r,timestamp:s.mtimeMs});}}catch(s){s.code==="ENOENT"&&(t.push({path:n,oldContent:o.content,newContent:"",oldMtime:o.timestamp,newMtime:0}),this.cache.delete(n));}return t.length>0&&hs.info("file changes detected",{count:t.length}),t}invalidate(t){this.cache.delete(t),hs.debug("cache invalidated",{filePath:t});}invalidateAll(){this.cache.clear(),hs.info("all cache invalidated");}has(t){return this.cache.has(t)}clear(){this.cache.clear(),hs.info("cache cleared");}get size(){return this.cache.size}get sizeBytes(){return this.cache.sizeBytes}getFilePaths(){return Array.from(this.cache.keys())}},Cp=null;function ri(e,t){return Cp||(Cp=new Od(e,t)),Cp}var ii=a.create({service:"static-prompt"}),er;(f=>{let e$1;function t(){return e$1||(e$1=_.state(()=>({promptCache:new Map,fileCache:ri()}))),e$1}function n(){return t()()}function o(a,p,u){return [a.agent.name,a.model.id,p,u??"primary"].join("|")}function s(a,p,u){return `${a.agent.name}/${a.model.id}/${p}/${u??"primary"}`}function r(a,p,u){let g=n(),h=u?.mode,S=s(a,p,h),A=g.promptCache.get(S);return A&&A.configHash===o(a,p,h)?(ii.debug("static prompt cache hit",{cacheKey:S}),A.sections):null}f.getCached=r;function i(a,p,u,g){let h=n(),S=g?.mode,A=s(a,p,S),y={sections:u,configHash:o(a,p,S),builtAt:Date.now()};h.promptCache.set(A,y),ii.debug("static prompt cached",{cacheKey:A,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;ii.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 g=await Sp(a);return i(a,p,g,a.agent),ii.debug("static prompt built",{length:g.length}),g}f.buildStaticPrompt=c;function l(a,p){let u=n();if(a&&p){for(let g of e){let h=`${a}/${p}/${g}`;u.promptCache.delete(h);}ii.debug("static prompt cache entries invalidated",{agentName:a,modelId:p});}else u.promptCache.clear(),ii.debug("all static prompt cache invalidated");}f.invalidateCache=l;function d(){let a=n(),p=Date.now(),u=[];for(let[g,h]of a.promptCache.entries())u.push({key:g,age:p-h.builtAt});return {size:a.promptCache.size,entries:u}}f.getCacheStats=d;function m(){return n().fileCache}f.getFileCache=m;})(er||(er={}));var wa;(m=>{a.create({service:"summary"});let t=loadTextFile("./memory-summary.txt",import.meta.url),n=loadTextFile("./knowledge-summary.txt",import.meta.url);async function r(f,a,p,u,g){return streamText({model:f,system:a,prompt:p,maxOutputTokens:u,abortSignal:g}).text}async function i(f){let a=await xe.defaultModel(),p=f??await xe.getModel(a.providerId??"default",a.modelId??"default");return xe.getLanguage(p)}function c(f){return f.map(a=>{let p=[` - node: id=${a.id} type=${a.type} name=${a.name}`];if(a.edges&&a.edges.length>0)for(let u of a.edges){let g=u.targetId!==void 0?` (id=${u.targetId})`:"";p.push(` \u2192 [${u.direction}] ${u.relation} \u2192 target=${u.targetType}:${u.targetName}${g}`);}return p.join(`
985
+ `)}).join(`
986
+ `)}async function l(f,a){let{query:p,chunks:u,model:g,maxLength:h}=f;if(u.length===0)return "";let S=await i(g),A=n()??"Synthesize the following document chunks into a concise summary relevant to the query. Order by Priority descending.",y=u.map((w,C)=>{let k=w.startLine!=null?`#L${w.startLine}-L${w.endLine??w.startLine}`:"",P=w.score??0,E=`[Chunk ${C+1}] Priority: ${P.toFixed(3)}
987
+ Source: [${w.path}](./${w.path}${k})
988
+ ${w.content}`;return !w.nodes||w.nodes.length===0?E:`${E}
989
+ Graph Nodes:
990
+ ${c(w.nodes)}`}).join(`
991
+
992
+ `),x=`[Query]
993
+ ${p}
994
+
995
+ [Knowledge Chunks]
996
+ ${y}`;return (await r(S,A,x,h??1e3,a)).trim()}m.summarizeNote=l;async function d(f,a){let{query:p,facts:u,model:g,maxLength:h}=f;if(u.length===0)return "";let S=await i(g),A=t()??"Synthesize the following memory facts into a concise summary relevant to the query. Order by Priority descending.",y=u.map((w,C)=>{let k=w.score??0,P=`[Fact ${C+1}] Priority: ${k.toFixed(3)}
997
+ Category: ${w.category} | Importance: ${w.importance} | Source: ${w.source}
998
+ ${w.content}`;if(!w.nodes||w.nodes.length===0)return P;let E=w.nodes.map(O=>{let N=[` - node: id=${O.id} type=${O.type} name=${O.name}`];if(O.edges&&O.edges.length>0)for(let L of O.edges){let K=L.direction??(L.source===O.id?"out":"in");N.push(` \u2192 [${K}] ${L.relation} \u2192 target=${L.targetNode?.type??"node"}:${L.targetNode?.name??`id=${L.target}`} (id=${L.target})`);}return N.join(`
999
+ `)}).join(`
1000
+ `);return `${P}
1001
+ Graph Nodes:
1002
+ ${E}`}).join(`
1003
+
1004
+ `),x=`[Query]
1005
+ ${p}
1006
+
1007
+ [Memory Facts]
1008
+ ${y}`;return (await r(S,A,x,h??1e3,a)).trim()}m.summarizeMemoryFacts=d;})(wa||(wa={}));a.create({service:"context-token"});function ys(e){return e?Token.estimate(e):0}var Pp=800,xa=a.create({service:"dynamic-prompt"}),Ia;(l=>{async function e(d){let m=[],{mode:f}=d,a=d.useLLMSummary??true,p=d.maxTokens??Pp;if(d.memoryResults&&d.memoryResults.length>0){let u=await t(d.query??"",d.memoryResults,a,p);u&&m.push(u);}if(d.knowledgeResults&&d.knowledgeResults.length>0){let u=await n(d.query??"",d.knowledgeResults,a,p);u&&m.push(u);}if(d.fileChanges&&d.fileChanges.length>0){let u=r(d.fileChanges);m.push(u);}if((d.includeTodos??true)&&d.sessionId)try{let u=await po.get(d.sessionId),g=o(u);m.push(g);}catch(u){xa.warn("failed to load todos for dynamic prompt",{error:String(u)});}if((d.includeTaskAgents??true)&&d.sessionId)try{let u=await jt.list(d.sessionId),g=s(u);g&&m.push(g);}catch(u){xa.warn("failed to load task agents for dynamic prompt",{error:String(u)});}if(f==="coder"&&d.includeCoderContext){let u=i();m.push(...u);}return xa.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=Pp){if(m.length===0)return `<memory>
1009
+ ## Memory Summary
1010
+
1011
+ No memory found.
1012
+ </memory>`;if(f)try{return `<memory>
1013
+ ## Memory Summary
1014
+
1015
+ ${await wa.summarizeMemoryFacts({query:d,facts:m.map(h=>({content:h.snippet,category:h.category,importance:h.importance,source:h.source,score:h.score,createdAt:h.createdAt,nodes:h.nodes?.map(S=>({id:S.id,name:S.name,type:S.type,edges:S.edges?.map(A=>({source:A.source,target:A.target,relation:A.relation,direction:A.source===S.id?"out":"in",targetNode:A.targetNode?{name:A.targetNode.name,type:A.targetNode.type}:void 0}))}))})),maxLength:a})}
1016
+ </memory>`}catch(g){xa.warn("memory LLM summary failed, falling back to basic format",{error:String(g)});}let p=["<memory>","## Memory Search Results","",`Query: ${d||"(no query)"}`,""],u=Math.floor(a/m.length);for(let g=0;g<m.length;g++){let h=m[g],S=new Date(h.createdAt).getTime(),A=(Date.now()-S)/864e5,y=Math.exp(-0.1*A),x=(h.importance-1)/9,b=.35*h.score+.35*y+.3*x;if(p.push(`[${g+1}] Priority: ${b.toFixed(3)}`),p.push(`Category: ${h.category} | Importance: ${h.importance} | Source: ${h.source}`),h.nodes&&h.nodes.length>0){let C=[];for(let O of h.nodes){let N=O.edges&&O.edges.length>0?O.edges.map(L=>` --[${L.source===O.id?"out":"in"}] ${L.relation}--> ${L.targetNode?.name??`node:${L.target}`} (${L.targetNode?.type??"node"})`).join(`
1017
+ `):" (no relations)";C.push(` Node: ${O.name} (${O.type})
1018
+ ${N}`);}let k=C.join(`
1019
+ `),P=Math.floor(u*4*.5),E=c(k,P);p.push(`Graph Nodes:
1020
+ ${E}`);}let w=Math.max(0,u-ys(p.join(`
1021
+ `)));if(w>30){let C=Math.floor(w*4),k=c(h.snippet,C);p.push(k);}p.push("");}return p.push("</memory>"),p.join(`
1022
+ `)}l.buildMemorySummary=t;async function n(d,m,f,a=Pp){if(m.length===0)return `<note>
1023
+ ## Knowledge Summary
1024
+
1025
+ No knowledge found.
1026
+ </note>`;if(f)try{return `<note>
1027
+ ## Knowledge Summary
1028
+
1029
+ ${await wa.summarizeNote({query:d,chunks:m.map(h=>({path:h.chunk.path,content:h.chunk.content,startLine:h.chunk.startLine,endLine:h.chunk.endLine,score:h.score,updatedAt:h.document.updatedAt,nodes:h.nodes?.map(S=>({id:S.id,name:S.name,type:S.type,properties:S.properties,edges:S.edges?.map(A=>{let y=A.source===S.id?"out":"in",x=h.nodes?.find(b=>b.id===A.target);return {direction:y,relation:A.relation,targetId:A.target,targetName:x?.name??String(A.target),targetType:x?.type??"node"}})}))})),maxLength:a})}
1030
+ </note>`}catch(g){xa.warn("knowledge LLM summary failed, falling back to basic format",{error:String(g)});}let p=["<note>","## Knowledge Search Results","",`Query: ${d||"(no query)"}`,""],u=Math.floor(a/m.length);for(let g=0;g<m.length;g++){let h=m[g],S=h.chunk.startLine!=null?`#L${h.chunk.startLine}-L${h.chunk.endLine??h.chunk.startLine}`:"",A=.7*(h.score??0);if(p.push(`[${g+1}] Priority: ${A.toFixed(3)}`),p.push(`Source: [${h.chunk.path}](./${h.chunk.path}${S})`),h.nodes&&h.nodes.length>0){let x=[];for(let k of h.nodes){let P=k.edges&&k.edges.length>0?k.edges.map(E=>` --[${E.source===k.id?"out":"in"}] ${E.relation}--> node:${E.target} (node)`).join(`
1031
+ `):" (no relations)";x.push(` Node: ${k.name} (${k.type})
1032
+ ${P}`);}let b=x.join(`
1033
+ `),w=Math.floor(u*4*.5),C=c(b,w);p.push(`Graph Nodes:
1034
+ ${C}`);}let y=Math.max(0,u-ys(p.join(`
1035
+ `)));if(y>20){let x=Math.floor(y*4),b=c(h.chunk.content,x);p.push(b);}p.push("");}return p.push("</note>"),p.join(`
1036
+ `)}l.buildKnowledgeSummary=n;function o(d){let m=["<todo>","## Todo List",""];if(!d||d.length===0)return m.push("No todo items. Use the todo tool to add tasks."),m.push("</todo>"),m.join(`
1037
+ `);m.push("The following tasks need to be tracked:","");let f=d.filter(p=>p.status==="pending"),a=d.filter(p=>p.status==="in_progress");if(a.length>0){m.push("### In Progress");for(let p of a){let u=p.priority?` [${p.priority.toUpperCase()}]`:"";m.push(`- [ ] ${p.content}${u}`);}m.push("");}if(f.length>0){m.push("### Pending");for(let p of f){let u=p.priority?` [${p.priority.toUpperCase()}]`:"";m.push(`- [ ] ${p.content}${u}`);}m.push("");}return m.push("</todo>"),m.join(`
1038
+ `)}l.buildTodosSummary=o;function s(d){let m=["<tasks>","## Agent Tasks",""];if(!d||d.length===0)return m.push("No running tasks."),m.push("</tasks>"),m.join(`
1039
+ `);let f=d.filter(u=>u.status==="running"),a=d.filter(u=>u.status==="pending"),p=d.filter(u=>u.status==="error");if(f.length===0&&a.length===0&&p.length===0)return m.push("No active tasks."),m.push("</tasks>"),m.join(`
1040
+ `);if(m.push("Active tasks (pending/running):",""),f.length>0){m.push("### Running");for(let u of f)m.push(`- [ ] ${u.description} \`[${u.agentType}]\` \`${u.taskId}\``);m.push("");}if(a.length>0){m.push("### Pending");for(let u of a)m.push(`- [ ] ${u.description} \`[${u.agentType}]\` \`${u.taskId}\``);m.push("");}if(p.length>0){m.push("### Failed");for(let u of p)m.push(`- [ ] ${u.description} \`[${u.agentType}]\` \`${u.taskId}\` - ${u.error||"unknown error"}`);m.push("");}return m.push("</tasks>"),m.join(`
1041
+ `)}l.buildTaskAgentSummary=s;function r(d){if(d.length===0)return "";let m=["<changes>","## Recently Changed Files","The following files have been modified since your last check:",""];for(let f of d)m.push(`- ${f.path}`),f.newMtime===0?m.push(" Status: deleted"):m.push(` Modified: ${new Date(f.newMtime).toISOString()}`);return m.push(""),m.push("Consider reading these files if relevant to the current task."),m.push("</changes>"),m.join(`
1042
+ `)}l.buildFileChangesSummary=r;function i(d){return []}l.buildCoderContext=i;function c(d,m){if(d.length<=m)return d;let a=d.slice(0,m).lastIndexOf(`
1043
+ `),p=a>m*.8?a:m;return d.slice(0,p).trimEnd()+`
1044
+ [...truncated...]`}})(Ia||(Ia={}));var UR=loadTextFile("./prompt/anthropic.txt",import.meta.url)(),zR=loadTextFile("./prompt/default.txt",import.meta.url)(),qR=loadTextFile("./prompt/beast.txt",import.meta.url)(),HR=loadTextFile("./prompt/gemini.txt",import.meta.url)(),BR=loadTextFile("./prompt/codex.txt",import.meta.url)(),GR=loadTextFile("./prompt/gpt.txt",import.meta.url)(),WR=loadTextFile("./prompt/trinity.txt",import.meta.url)(),VR=loadTextFile("./prompt/kimi.txt",import.meta.url)(),KR=loadTextFile("./prompt/qwen.txt",import.meta.url)(),JR=loadTextFile("./prompt/glm.txt",import.meta.url)(),YR=loadTextFile("./prompt/minimax.txt",import.meta.url)();function Tp(e){let t=e.model.id.toLowerCase(),n=e.protocolMetadata;return t.includes("gpt-4")||t.includes("o1")||t.includes("o3")?[a$9.replaceVariables(qR,n)]:t.includes("gpt")?t.includes("codex")?[a$9.replaceVariables(BR,n)]:[GR]:t.includes("gemini-")?[a$9.replaceVariables(HR,n)]:t.includes("claude")?[a$9.replaceVariables(UR,n)]:t.includes("trinity")?[a$9.replaceVariables(WR,n)]:t.includes("kimi")?[a$9.replaceVariables(VR,n)]:t.includes("qwen")?[a$9.replaceVariables(KR,n)]:t.includes("glm")?[a$9.replaceVariables(JR,n)]:t.includes("minimax")?[a$9.replaceVariables(YR,n)]:[a$9.replaceVariables(zR,n)]}function XR(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 QR(e,t){if(Me.disabled(["skill"],e.permission).has("skill"))return [];let n=await Jt.available(e,t);return ["<skills>",Jt.format(n,{verbose:false}),"</skills>"]}async function Ap(e){let{Instance:t}=await import('./instance-5OB47GH5.mjs'),n=t.project,o=new Date,s=Intl.DateTimeFormat().resolvedOptions().timeZone,r=[];return r.push("<env>"),r.push("Here is some useful information about the environment you are running in:"),r.push(` Current model: ${e.model.id}`),r.push(` Agent ID: ${e.protocolMetadata.agentId}`),r.push(` Workspace directory: ${t.directory}`),r.push(` Worktree root folder: ${t.worktree}`),r.push(` Is directory a git repo: ${n.vcs==="git"?"yes":"no"}`),r.push(` Platform: ${process.platform}`),r.push(` Local time: ${formatLocalISOCompact(o)} (${s})`),r.push(` UTC time: ${o.toISOString()}`),r.push("</env>"),r.push(...XR(e.mode)),r.push(...await QR(e.agent,e.mode)),[r.join(`
1045
+ `)]}var va=a.create({service:"context-search"});async function Ep(e,t,n){try{let o=await In.get();return !o||!t?[]:await o.query(t,{agentId:e.agent.name,maxResults:n,minScore:.2})}catch(o){return va.warn("memory search error",{error:String(o)}),[]}}async function Rp(e,t,n){try{let o=await Xt.get();if(!o||!t)return va.debug("searchKnowledge: kb or query not available",{kb:!!o,query:!!t}),[];va.debug("searchKnowledge: calling kb.search",{query:t,maxResults:n,minScore:.3});let s=await o.search(t,{maxResults:n,minScore:.3});return va.debug("searchKnowledge: kb.search returned",{query:t,resultsCount:s.length,results:s.map(r=>({score:r.score,path:r.document.path}))}),s}catch(o){return va.warn("knowledge search error",{error:String(o)}),[]}}var tr=a.create({service:"context-engine"}),e_=loadTextFile("./prompt/max-steps.txt",import.meta.url),t_=e_(),n_=loadTextFile("./prompt/plan.txt",import.meta.url),o_=n_(),s_=loadTextFile("./prompt/coder-plan.txt",import.meta.url),r_=s_(),i_=loadTextFile("./prompt/build-switch.txt",import.meta.url),qy=i_();function Op(e,t,n){let o=n?`A plan file already exists at ${t}. You can read it and make incremental edits using the edit tool.`:`No plan file exists yet. You should create your plan at ${t} using the write tool.`;return e.replace("{{planFileInfo}}",o)}var go;(x=>{let e,t;async function n(){return t||(t=Ii().then(b=>({mode:b.mode??f$1,fileCacheMaxEntries:b.fileCache?.maxEntries??100,fileCacheMaxBytes:b.fileCache?.maxBytes??25*1024*1024,maxTokens:b.maxTokens??2e3,searchMaxResults:b.searchMaxResults??3}))),t}function o(){return e||(e=_.state(async()=>{let b=await n(),w=_.directory,C={workspace:w,name:"EasBot",userName:"",mission:""},k=false;try{let P=Ce__default.join(w,".easbot"),E=Ce__default.join(P,"protocol.json"),O=await Tt__default.readFile(E,"utf-8"),N=JSON.parse(O);N.metadata&&(C={agentId:N.metadata.agentId,workspace:N.metadata.workspace||w,name:N.metadata.name||"EasBot",userName:N.metadata.userName||"",mission:N.metadata.mission||""}),k=typeof N.setupCompletedAt=="string"&&N.setupCompletedAt.trim().length>0;}catch{tr.debug("protocol.json not found, using default metadata");}return {config:b,initialized:true,protocolInitialized:k,fileCache:ri(),protocolMetadata:C}})),e}async function s(){return o()()}function r(b){t=Promise.resolve({mode:b.mode??f$1,fileCacheMaxEntries:b.fileCacheMaxEntries??100,fileCacheMaxBytes:b.fileCacheMaxBytes??25*1024*1024,maxTokens:b.maxTokens??2e3,searchMaxResults:b.searchMaxResults??3}),tr.info("context engine configured",{mode:b.mode,maxTokens:b.maxTokens,searchMaxResults:b.searchMaxResults});}x.configure=r;async function i(){return (await s()).config}x.getConfig=i;async function c(b){let w=await s();return !w.protocolInitialized&&!w.protocolMetadata.agentId&&b&&(w.protocolMetadata.agentId=b.name),w.protocolMetadata}x.getProtocolMetadata=c;async function l(){let b=await s();return {protocolMetadata:b.protocolMetadata,protocolInitialized:b.protocolInitialized}}x.getContext=l;function d(){return ri()}x.getFileCache=d;function m(b){let w=[];for(let C of b.parts)C.type==="text"&&C.text&&w.push(C.text);return w.join(" ").trim()}x.extractQuery=m;async function f(b){let w=await Le.triggerEvent(HookEvent.ContextBuildBefore,b,{sessionId:b.sessionId});w.modified&&w.output&&(b=w.output);let C=await s();C.protocolMetadata.agentId||(C.protocolMetadata.agentId=b.agent.name);let k=b.mode??C.config.mode??f$1,P=b.maxTokens??C.config.maxTokens??2e3,E=b.searchMaxResults??C.config.searchMaxResults??3,O=m(b.userMessage),[N,L]=[Ep(b,O,E).catch(V=>(tr.warn("memory search failed",{error:String(V)}),[])),Rp(b,O,E).catch(V=>(tr.warn("knowledge search failed",{error:String(V)}),[]))],K=er.buildStaticPrompt({mode:k,workspaceDir:b.session.directory,agent:b.agent,model:b.model,protocolMetadata:C.protocolMetadata,protocolInitialized:C.protocolInitialized}),[Q,ue,D]=await Promise.all([K,N,L]),I=C.protocolMetadata,M=Q.map(V=>V.name),v=Q.map(V=>V.content),R=b.agent.mode==="subagent"?[]:await Ia.build({query:O,mode:k,sessionId:b.sessionId,memoryResults:ue,knowledgeResults:D,includeTodos:true,includeCoderContext:k==="coder",useLLMSummary:true,maxTokens:P}),j=await a({sessionId:b.sessionId,model:b.model,agent:b.agent,user:b.user,workspace:b.session.directory,staticPrompt:v,staticPromptSources:M,dynamicParts:R,maxChars:P*4,protocolMetadata:C.protocolMetadata,mode:k}),{messages:U,lastUserMessage:Y,lastAssistantMessage:J}=await p(b),ee=g(U,j),se=b.model.limit?.context??0,ae=se>0?se:xe.DEFAULT_CONTEXT_LIMIT,ie=Math.max(ae-2e4,5e4)-ee,Z=sn.calculateTokenUsageState(ee,b.model),H=Z.isAboveAutoCompactThreshold||Z.isAtBlockingLimit;Z.isAboveWarningThreshold&&tr.warn("context window running low",{remaining:ie,tokenEstimate:ee,percentLeft:Z.percentLeft,needsCompaction:H});let $={sessionId:b.sessionId,isLastStep:b.isLastStep??false,mode:k,messageCount:U.length,tokenEstimate:ee,remaining:ie,sources:h(k,ue.length>0,D.length>0),memoryResults:ue.length,knowledgeResults:D.length,lastUserMessage:Y,lastAssistantMessage:J,needsCompaction:H,protocolMetadata:I};tr.debug("context build completed",{...$,lastUserMessage:Y?.info.id,lastAssistantMessage:J?.info.id});let te={system:j,messages:U,tools:b.tools,model:b.model,agent:b.agent,session:b.session,metadata:$},W=await Le.triggerEvent(HookEvent.ContextBuildAfter,{context:te},{sessionId:b.sessionId});return W.modified&&W.output?W.output.context:te}x.build=f;async function a(b){let {sessionId:w,model:C,agent:k,user:P,staticPrompt:O,staticPromptSources:N,dynamicParts:L,maxChars:K,protocolMetadata:Q,mode:ue}=b;await xe.getProvider(C.providerId);await Qe.get(C.providerId);let M=[];k.prompt&&k.prompt.trim().length>0?M.push(a$9.replaceVariables(k.prompt,Q)):M.push(...Tp({model:C,protocolMetadata:Q}));for(let v=0;v<O.length;v++){let T=N?.[v]??`template-${v}`,R=await TruncateContent.truncate(O[v],{label:"static prompt",sourcePath:T,maxChars:K});M.push(R.content);}if(M.push(...await Ap({model:C,mode:ue,agent:k,protocolMetadata:Q})),M.push(...L),P.system){let v=await TruncateContent.truncate(P.system,{label:"user system prompt",maxChars:K});M.push(v.content);}return await Le.triggerEvent(HookEvent.SystemTransform,{sessionId:w,model:C}),M}async function p(b){let w=clone(b.messages),C=b.mode??f$1;for(let K=w.length-1;K>=0;K--){let Q=w[K];if(Q&&Q.info.role==="assistant"&&Q.info.finish){break}}(b.includeReminders??true)&&await u(w,{agent:b.agent,session:b.session,userMessageId:b.userMessage.info.id,lastFinished:b.lastFinished,step:b.step??1,isLastStep:b.isLastStep??false,mode:C});let E=w;b.maxMessages&&b.maxMessages>0&&(E=w.slice(-b.maxMessages));let O=await ve.toModelMessages(E,b.model);b.isLastStep&&O.push({role:"assistant",content:[{type:"text",text:t_}]});let N=w.findLast(K=>K.info.role==="user"),L=w.findLast(K=>K.info.role==="assistant");return {messages:O,lastUserMessage:N,lastAssistantMessage:L}}async function u(b,w){let{agent:C,session:k,lastFinished:P,step:E,isLastStep:O,mode:N}=w,L=b.findLast(I=>I.info.role==="user");if(!L)return;let K=N==="coder"?r_:o_,Q=X.plan(k),ue=false;try{await Tt__default.access(Q),ue=!0;}catch{ue=false;}let D=Op(K,Q,ue);if(!a$2.EASBOT_PLAN_MODE)C.name==="plan"&&L.parts.push({id:Identifier.ascending("part"),messageId:L.info.id,sessionId:L.info.sessionId,type:"text",text:D,synthetic:true}),b.some(M=>M.info.role==="assistant"&&M.info.agent==="plan")&&C.name==="build"&&L.parts.push({id:Identifier.ascending("part"),messageId:L.info.id,sessionId:L.info.sessionId,type:"text",text:Op(qy,Q,ue),synthetic:true});else {let I=b.findLast(M=>M.info.role==="assistant");if(C.name!=="plan"&&I?.info.agent==="plan"){if(ue){let M=await X.updatePart({id:Identifier.ascending("part"),messageId:L.info.id,sessionId:L.info.sessionId,type:"text",text:Op(qy,Q,ue),synthetic:true});L.parts.push(M);}return}if(C.name==="plan"&&I?.info.agent!=="plan"){ue||await Tt__default.mkdir(Ce__default.dirname(Q),{recursive:true});let M=await X.updatePart({id:Identifier.ascending("part"),messageId:L.info.id,sessionId:L.info.sessionId,type:"text",text:D,synthetic:true});L.parts.push(M);return}}if(E>1&&P&&!O){for(let I of b)if(!(I.info.role!=="user"||I.info.id<=P.info.id))for(let M of I.parts)M.type!=="text"||M.ignored||M.synthetic||M.text?.trim()&&(M.text=`<system-reminder>
1046
+ The user sent the following message:
1047
+ `+M.text+`
1048
+
1049
+ Please address this message and continue with your tasks.
1050
+ </system-reminder>`);}await Le.triggerEvent(HookEvent.MessageTransform,{sessionId:w.session.id,userMessageId:w.userMessageId});}function g(b,w){let C=0;if(w)for(let k of w)C+=ys(k);for(let k of b)if(k.content){if(typeof k.content=="string")C+=ys(k.content);else if(Array.isArray(k.content)){for(let P of k.content)if(typeof P=="object"&&P!==null){let E=P;typeof E.text=="string"&&(C+=ys(E.text));}}}return C}x.tokenCountWithEstimation=g;function h(b,w,C){let k=["system","history","tools","templates"];return w&&k.push("memory"),C&&k.push("knowledge"),b==="coder"&&k.push("coder-context"),k}function S(b,w){er.invalidateCache(b,w);}x.invalidateCache=S;function A(){return er.getCacheStats()}x.getCacheStats=A;async function y(){(await s()).fileCache.clear(),tr.debug("file cache reset");}x.resetFileCache=y;})(go||(go={}));var X;(v=>{let e$1=a.create({service:"session"});function t(T=false){return SessionTitle.createDefault(T)}v.createDefaultTitle=t;function n(T){return SessionTitle.isDefault(T)}v.isDefaultTitle=n;function o(T){return SessionTitle.getForked(T)}v.Info=F.object({id:Identifier.schema("session"),slug:F.string(),providerId:F.string(),directory:F.string(),parentId:Identifier.schema("session").optional(),contextMode:F.enum(e).optional(),summary:F.object({additions:F.number(),deletions:F.number(),files:F.number(),diffs:yt.FileDiff.array().optional()}).optional(),share:F.object({url:F.string()}).optional(),title:F.string(),version:F.string(),time:F.object({created:F.number(),updated:F.number(),compacting:F.number().optional(),archived:F.number().optional()}),permission:Me.Ruleset.optional(),revert:F.object({messageId:F.string(),partId:F.string().optional(),snapshot:F.string().optional(),diff:F.string().optional()}).optional()}).meta({ref:"Session"}),v.ProjectInfo=F.object({id:F.string(),name:F.string().optional(),worktree:F.string()}).meta({ref:"ProjectSummary"}),v.GlobalInfo=v.Info.extend({project:v.ProjectInfo.nullable()}).meta({ref:"GlobalSession"}),v.ShareInfo=F.object({secret:F.string(),url:F.string()}).meta({ref:"SessionShare"}),v.Event={Created:a$5.define("session.created",F.object({info:v.Info})),Updated:a$5.define("session.updated",F.object({info:v.Info})),Deleted:a$5.define("session.deleted",F.object({info:v.Info})),Diff:a$5.define("session.diff",F.object({sessionId:F.string(),diff:yt.FileDiff.array()})),Error:a$5.define("session.error",F.object({sessionId:F.string().optional(),error:ve.Assistant.shape.error})),ContextModeChanged:a$5.define("session.context_mode_changed",F.object({sessionId:F.string(),contextMode:F.enum(e)}))},v.create=fn$1(F.object({parentId:Identifier.schema("session").optional(),title:F.string().optional(),directory:F.string().optional(),permission:v.Info.shape.permission,contextMode:v.Info.shape.contextMode}).optional(),async T=>a$3({parentId:T?.parentId,directory:T?.directory??_.directory,title:T?.title,permission:T?.permission,contextMode:T?.contextMode})),v.fork=fn$1(F.object({sessionId:Identifier.schema("session"),directory:F.string().optional(),messageId:Identifier.schema("message").optional(),contextMode:v.Info.shape.contextMode}),async T=>{let R=await(0, v.get)(T.sessionId);if(!R)throw new Error("session not found");let j=o(R.title),U=await a$3({directory:T?.directory??R.directory??_.directory,title:j,contextMode:T.contextMode}),Y=await(0, v.messages)({sessionId:T.sessionId}),J=new Map;for(let ee of Y){if(T.messageId&&ee.info.id>=T.messageId)break;let se=Identifier.ascending("message");J.set(ee.info.id,se);let ae=ee.info.role==="assistant"&&ee.info.parentId?J.get(ee.info.parentId):void 0,we=await(0, v.updateMessage)({...ee.info,sessionId:U.id,id:se,...ae&&{parentId:ae}});for(let ie of ee.parts)await(0, v.updatePart)({...ie,id:Identifier.ascending("part"),messageId:we.id,sessionId:U.id});}return U}),v.touch=fn$1(Identifier.schema("session"),async T=>{await w(T,R=>{R.time.updated=Date.now();});});async function a$3(T){let R=await he.get(),j={id:Identifier.descending("session",T.id),slug:Slug.create(),version:b$3.getVersion(),providerId:_.project.id,directory:T.directory,parentId:T.parentId,contextMode:T.contextMode??R.context?.mode,title:T.title??t(!!T.parentId),permission:T.permission,time:{created:Date.now(),updated:Date.now()}};return e$1.debug("created",j),await a$6.write(["session",_.project.id,j.id],j),await pe.publish(v.Event.Created,{info:j}),!j.parentId&&(a$2.EASBOT_AUTO_SHARE||R.share==="auto")&&(0, v.share)(j.id).then(U=>{w(j.id,Y=>{Y.share=U;});}).catch(()=>{}),await pe.publish(v.Event.Updated,{info:j}),j}v.createNext=a$3;function p(T){let R=_.project.vcs?Ce__default.join(_.worktree,".easbot","plans"):Ce__default.join(a$1.Path.data,"plans");return Ce__default.join(R,[T.time.created,T.slug].join("-")+".md")}v.plan=p,v.get=fn$1(Identifier.schema("session"),async T=>await a$6.read(["session",_.project.id,T])),v.getShare=fn$1(Identifier.schema("session"),async T=>a$6.read(["share",T])),v.getProjectInfo=fn$1(F.void(),async()=>({id:_.project.id,name:_.project.name,worktree:_.worktree})),v.getGlobalInfo=fn$1(Identifier.schema("session"),async T=>{let R=await(0, v.get)(T);if(R)return {...R,project:{id:_.project.id,name:_.project.name,worktree:_.worktree}}});async function A(T){let R=await(0, v.get)(T);if(R?.contextMode)return R.contextMode;let j=await he.get();return j.context?.mode?j.context.mode:"general"}v.getContextMode=A;async function y(T,R){if(!e.includes(R))throw new Error(`Invalid contextMode: ${R}. Must be one of: ${e.join(", ")}`);await w(T,j=>{j.contextMode=R;}),await pe.publish(v.Event.ContextModeChanged,{sessionId:T,contextMode:R});}v.setContextMode=y,v.share=fn$1(Identifier.schema("session"),async T=>{if((await he.get()).share==="disabled")throw new Error("Sharing is disabled in configuration");let{Share:j}=await import('./share-6NJ4W4CC.mjs'),U=await j.create(T);return await w(T,Y=>{Y.share={url:U.url};},{touch:false}),U}),v.unshare=fn$1(Identifier.schema("session"),async T=>{let{Share:R}=await import('./share-6NJ4W4CC.mjs');await R.remove(T),await w(T,j=>{j.share=void 0;},{touch:false});});async function w(T,R,j){let U=_.project,Y=await a$6.update(["session",U.id,T],J=>{R(J),j?.touch!==false&&(J.time.updated=Date.now());});return await pe.publish(v.Event.Updated,{info:Y}),Y}v.update=w,v.diff=fn$1(Identifier.schema("session"),async T=>await a$6.read(["session_diff",T])??[]),v.messages=fn$1(F.object({sessionId:Identifier.schema("session"),limit:F.number().optional()}),async T=>{let R=[];for await(let j of ve.stream(T.sessionId)){if(T.limit&&R.length>=T.limit)break;R.push(j);}return R.reverse(),R});async function*P(){let T=_.project;for(let R of await a$6.list(["session",T.id])){let j=await a$6.read(R).catch(()=>{});j&&(yield j);}}v.list=P,v.children=fn$1(Identifier.schema("session"),async T=>{let R=_.project,j=[];for(let U of await a$6.list(["session",R.id])){let Y=await a$6.read(U).catch(()=>{});Y&&Y.parentId===T&&j.push(Y);}return j}),v.remove=fn$1(Identifier.schema("session"),async T=>{let R=_.project;try{let j=await(0,v.get)(T);for(let U of await(0,v.children)(T))await(0,v.remove)(U.id);await(0,v.unshare)(T).catch(()=>{});for(let U of await a$6.list(["message",T])){let Y=U.at(-1);for(let se of await a$6.list(["part",Y]))await a$6.remove(se);let J=await a$6.dir(["part",Y]);await a$6.rmdir(J).catch(()=>{}),await a$6.remove(U);let ee=await a$6.dir(["message",T]);await a$6.rmdir(ee).catch(()=>{});}await a$6.remove(["session",R.id,T]),await a$6.remove(["tui",T]).catch(()=>{}),await pe.publish(v.Event.Deleted,{info:j});}catch(j){e$1.error(j);}}),v.updateMessage=fn$1(ve.Info,async T=>(await a$6.write(["message",T.sessionId,T.id],T),pe.publish(ve.Event.Updated,{info:T}),T)),v.removeMessage=fn$1(F.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message")}),async T=>(await a$6.remove(["message",T.sessionId,T.messageId]),pe.publish(ve.Event.Removed,{sessionId:T.sessionId,messageId:T.messageId}),T.messageId)),v.removePart=fn$1(F.object({sessionId:Identifier.schema("session"),messageId:Identifier.schema("message"),partId:Identifier.schema("part")}),async T=>(await a$6.remove(["part",T.messageId,T.partId]),pe.publish(ve.Event.PartRemoved,{sessionId:T.sessionId,messageId:T.messageId,partId:T.partId}),T.partId));let Q=F.union([ve.Part,F.object({part:ve.TextPart,delta:F.string()}),F.object({part:ve.ReasoningPart,delta:F.string()})]);v.updatePart=fn$1(Q,async T=>{let R="delta"in T?T.part:T,j="delta"in T?T.delta:void 0;return await a$6.write(["part",R.messageId,R.id],R),pe.publish(ve.Event.PartUpdated,{part:R,delta:j,time:Date.now()}),R}),v.getUsage=fn$1(F.object({model:F.custom(),usage:F.custom(),metadata:F.custom().optional()}),T=>{let R=H=>Number.isFinite(H)?H:0,j=R(T.usage.inputTokens??0),U=R(T.usage.outputTokens??0),Y=R(T.usage.reasoningTokens??0),J=R(T.usage.cachedInputTokens??0),ee=R(T.metadata?.anthropic?.cacheCreationInputTokens??T.metadata?.bedrock?.usage?.cacheWriteInputTokens??T.metadata?.venice?.usage?.cacheCreationInputTokens??0),se=!!(T.metadata?.anthropic||T.metadata?.bedrock),ae=R(se?j:j-J-ee),ie={total:iife(()=>T.model.api.npm==="@ai-sdk/anthropic"||T.model.api.npm==="@ai-sdk/amazon-bedrock"||T.model.api.npm==="@ai-sdk/google-vertex/anthropic"?ae+U+J+ee:T.usage.totalTokens),input:ae,output:U,reasoning:Y,cache:{write:ee,read:J}},Z=T.model.cost?.experimentalOver200K&&ie.input+ie.cache.read>2e5?T.model.cost.experimentalOver200K:T.model.cost;return {cost:R(new Decimal(0).add(new Decimal(ie.input).mul(Z?.input??0).div(1e6)).add(new Decimal(ie.output).mul(Z?.output??0).div(1e6)).add(new Decimal(ie.cache.read).mul(Z?.cache?.read??0).div(1e6)).add(new Decimal(ie.cache.write).mul(Z?.cache?.write??0).div(1e6)).add(new Decimal(ie.reasoning).mul(Z?.output??0).div(1e6)).toNumber()),tokens:ie}});class I extends Error{constructor(j){super(`Session ${j} is busy`);b$1(this,"sessionId",j);}}v.BusyError=I,v.initialize=fn$1(F.object({sessionId:Identifier.schema("session"),modelId:F.string(),providerId:F.string(),messageId:Identifier.schema("message")}),async T=>{await Je.command({sessionId:T.sessionId,messageId:T.messageId,model:T.providerId+"/"+T.modelId,command:vn.Default.INIT,arguments:""});});})(X||(X={}));var Ht;(a$1=>{let e=a.create({service:"project"});a$1.Info=F.object({id:F.string(),worktree:F.string(),vcs:F.literal("git").optional(),name:F.string().optional(),icon:F.object({url:F.string().optional(),override:F.string().optional(),color:F.string().optional()}).optional(),commands:F.object({start:F.string().optional().describe("Startup script to run when creating a new workspace (worktree)")}).optional(),time:F.object({created:F.number(),updated:F.number(),initialized:F.number().optional()}),sandboxes:F.array(F.string())}).meta({ref:"Project"}),a$1.Event={Updated:a$5.define("project.updated",a$1.Info)};async function o(p){e.debug("fromDirectory",{directory:p});let{id:u,sandbox:g,worktree:h,vcs:S}=await iife(async()=>{let x=Filesystem.up({targets:[".git"],start:p}),b=await x.next().then(C=>C.value);if(await x.return(void 0),b){let C=Ce__default.dirname(b),k=await PKG.which("git"),P=await Tt__default.readFile(Ce__default.join(b,"easbot"),"utf-8").then(N=>N.trim()).catch(()=>{});if(!k)return {id:P??"global",worktree:C,sandbox:C,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};if(!P){let N=await $`git rev-list --max-parents=0 --all`.quiet().nothrow().cwd(C).text().then(L=>L.split(`
1051
+ `).filter(Boolean).map(K=>K.trim()).toSorted()).catch(()=>{});if(!N)return {id:"global",worktree:C,sandbox:C,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};P=N[0],P&&Tt__default.writeFile(Ce__default.join(b,"easbot"),P).catch(()=>{});}if(!P)return {id:"global",worktree:C,sandbox:C,vcs:"git"};let E=await $`git rev-parse --show-toplevel`.quiet().nothrow().cwd(C).text().then(N=>Ce__default.resolve(C,N.trim())).catch(()=>{});if(!E)return {id:P,sandbox:C,worktree:C,vcs:a$1.Info.shape.vcs.parse(a$2.EASBOT_FAKE_VCS)};C=E;let O=await $`git rev-parse --git-common-dir`.quiet().nothrow().cwd(C).text().then(N=>{let L=Ce__default.dirname(N.trim());return L==="."?C:L}).catch(()=>{});return O?{id:P,sandbox:C,worktree:O,vcs:"git"}:{id:P,sandbox:C,worktree:C,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)}}),A=await a$6.read(["project",u]).catch(()=>{});A||(A={id:u,worktree:h,vcs:S,sandboxes:[],time:{created:Date.now(),updated:Date.now()}},u!=="global"&&await r(u,h)),A?.sandboxes||(A.sandboxes=[]),a$2.EASBOT_ICON_DISCOVERY&&await s(A);let y={...A,worktree:h,vcs:S,time:{...A?.time,updated:Date.now()}};return g!==y.worktree&&!y.sandboxes.includes(g)&&y.sandboxes.push(g),y.sandboxes=y.sandboxes.filter(x=>existsSync(x)),await a$6.write(["project",u],y),ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:y}}),{project:y,sandbox:g}}a$1.fromDirectory=o;async function s(p){if(p.vcs!=="git"||p.icon?.override||p.icon?.url)return;let g=(await glob("**/{favicon}.{ico,png,svg,jpg,jpeg,webp}",{cwd:p.worktree,absolute:true,nodir:true,follow:false,dot:false})).sort((w,C)=>w.length-C.length)[0];if(!g)return;let S=(await Tt__default.readFile(g)).toString("base64"),A=Ce__default.extname(g).toLowerCase(),b=`data:${{".ico":"image/x-icon",".png":"image/png",".svg":"image/svg+xml",".jpg":"image/jpeg",".jpeg":"image/jpeg",".webp":"image/webp"}[A]||"image/png"};base64,${S}`;await(0, a$1.update)({providerId:p.id,icon:{url:b}});}a$1.discover=s;async function r(p,u){if(!await a$6.read(["project","global"]).catch(()=>{}))return;let h=await a$6.list(["session","global"]).catch(()=>[]);h.length!==0&&(e.info("migrating sessions from global",{newProjectID:p,worktree:u,count:h.length}),await work(10,h,async S=>{let A=S[S.length-1]??"",y=await a$6.read(S).catch(()=>{});y&&(y.directory&&y.directory!==u||(y.providerId=p,e.debug("migrating session",{sessionId:A,from:"global",to:p}),await a$6.write(["session",p,A],y),await a$6.remove(S)));}).catch(S=>{e.error("failed to migrate sessions from global to project",{error:S,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(g=>a$6.read(g)))).map(g=>({...g,sandboxes:g.sandboxes?.filter(h=>existsSync(h))}))}a$1.list=c,a$1.update=fn$1(F.object({providerId:F.string(),name:F.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],g=>{if(p.name!==void 0&&(g.name=p.name),p.icon!==void 0&&(g.icon={...g.icon},p.icon.url!==void 0&&(g.icon.url=p.icon.url),p.icon.override!==void 0&&(g.icon.override=p.icon.override||void 0),p.icon.color!==void 0&&(g.icon.color=p.icon.color)),p.commands?.start!==void 0){let h=p.commands.start||void 0;g.commands={...g.commands??{}},g.commands.start=h,g.commands.start||(g.commands=void 0);}g.time.updated=Date.now();});return ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:u}}),u});async function d(p){let u=await a$6.read(["project",p]).catch(()=>{});if(!u?.sandboxes)return [];let g=[];for(let h of u.sandboxes)(await Tt__default.stat(h).catch(()=>{}))?.isDirectory()&&g.push(h);return g}a$1.sandboxes=d;async function m(p,u){let g=await a$6.update(["project",p],h=>{let S=h.sandboxes??[];S.includes(u)||S.push(u),h.sandboxes=S,h.time.updated=Date.now();});return ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:g}}),g}a$1.addSandbox=m;async function f(p,u){let g=await a$6.update(["project",p],h=>{let S=h.sandboxes??[];h.sandboxes=S.filter(A=>A!==u),h.time.updated=Date.now();});return ft.emit("event",{payload:{type:a$1.Event.Updated.type,properties:g}}),g}a$1.removeSandbox=f;})(Ht||(Ht={}));var Sa;(s=>{let e=a.create({service:"state"}),t=new Map;function n(r,i,c){return ()=>{let l=r(),d=t.get(l);d||(d=new Map,t.set(l,d));let m=d.get(i);if(m)return m.state;let f=i();return d.set(i,{state:f,dispose:c}),f}}s.create=n;async function o(r){let i=t.get(r);if(!i)return;e.info("waiting for state disposal to complete",{key:r});let c=false;setTimeout(()=>{c||e.warn("state disposal is taking an unusually long time - if it does not complete in a reasonable time, please report this as a bug",{key:r});},1e4).unref();let l=[];for(let[d,m]of i){if(!m.dispose)continue;let f=typeof d=="function"?d.name:String(d),a=Promise.resolve(m.state).then(p=>m.dispose(p)).catch(p=>{e.error("Error while disposing state:",{error:p,key:r,init:f});});l.push(a);}await Promise.all(l),i.clear(),t.delete(r),c=true,e.info("state disposal completed",{key:r});}s.dispose=o;})(Sa||(Sa={}));var di=Context.create("instance"),bs=new Map,Ca={all:void 0},_={async provide(e){let t=bs.get(e.directory);t||(a.Default.info("creating instance",{directory:e.directory}),t=iife(async()=>{let{project:o,sandbox:s}=await Ht.fromDirectory(e.directory),r={directory:e.directory,worktree:s,project:o};return await di.provide(r,async()=>{await e.init?.();}),r}),bs.set(e.directory,t));let n=await t;return di.provide(n,async()=>e.fn())},get directory(){return di.use().directory},get worktree(){return di.use().worktree},get project(){return di.use().project},containsPath(e){return Filesystem.contains(_.directory,e)?true:_.worktree==="/"?false:Filesystem.contains(_.worktree,e)},state(e,t){return Sa.create(()=>_.directory,e,t)},async dispose(){a.Default.info("disposing instance",{directory:_.directory}),await Sa.dispose(_.directory),bs.delete(_.directory),ft.emit("event",{directory:_.directory,payload:{type:"server.instance.disposed",properties:{directory:_.directory}}});},async disposeAll(){return Ca.all||(Ca.all=iife(async()=>{a.Default.info("disposing all instances");let e=[...bs.entries()];for(let[t,n]of e){if(bs.get(t)!==n)continue;let o=await n.catch(s=>{a.Default.warn("instance dispose failed",{key:t,error:s});});if(!o){bs.get(t)===n&&bs.delete(t);continue}bs.get(t)===n&&await di.provide(o,async()=>{await _.dispose();});}}).finally(()=>{Ca.all=void 0;})),Ca.all}};var pe;(f=>{let e=a.create({service:"bus"});f.InstanceDisposed=a$5.define("server.instance.disposed",F.object({directory:F.string()}));let n;function o(){return n||(n=_.state(async()=>({subscriptions:new Map}),async a=>{let p=a.subscriptions.get("*");if(!p)return;let u={type:f.InstanceDisposed.type,properties:{directory:_.directory}};for(let g of [...p])g(u);})),n}function s(){return o()()}async function r(a,p){let u={type:a.type,properties:p};e.debug("publishing",{type:a.type});let g=[],h=await s();for(let S of [a.type,"*"]){let A=h.subscriptions.get(S);for(let y of A??[])g.push(y(u));}return ft.emit("event",{directory:_.directory,payload:u}),Promise.all(g)}f.publish=r;function i(a,p){return d(a.type,p)}f.subscribe=i;function c(a,p){let u=i(a,g=>{p(g)&&u();});}f.once=c;function l(a){return d("*",a)}f.subscribeAll=l;function d(a,p){e.debug("subscribing",{type:a});s().then(g=>{let h=g.subscriptions,S=h.get(a)??[];S.push(p),h.set(a,S);});return ()=>{e.debug("unsubscribing",{type:a}),s().then(g=>{let h=g.subscriptions.get(a);if(!h)return;let S=h.indexOf(p);S!==-1&&h.splice(S,1);});}}async function m(){await s();}f.waitForSubscription=m;})(pe||(pe={}));export{jt as $,Fa as $a,fi as A,Je as Aa,gi as B,Le as Ba,La as C,lf as Ca,hi as D,uf as Da,mr as E,ou as Ea,tl as F,Mc as Fa,Mo as G,os as Ga,nl as H,Lt as Ha,wi as I,ol as J,yt as Ja,sl as K,ve as Ka,Gb as L,il as La,Wb as M,rw as Ma,Vb as N,iw as Na,sn as O,Ii as Oa,ze as P,vd as Pa,kr as Q,X as Qa,Np as R,Ht as Ra,Bd as S,_ as Sa,Si as T,Da as Ta,Xa as U,al as Ua,Iw as V,cl as Va,pl as W,dl as Wa,vw as X,$a as Xa,Sw as Y,fr as Ya,ts as Z,dw as Za,As as _,vs as _a,pe as a,Ra as aa,Na as ab,We as b,_a as ba,Ua as bb,qe as c,Ma as ca,za as cb,tu as d,rr as da,Jn as db,Tr as e,ir as ea,qa as eb,ns as f,ar as fa,ht as fb,Ac as g,Kd as ga,vi as gb,av as h,nn as ha,Ha as hb,nf as i,bt as ia,Ba as ib,xe as j,Yc as ja,io as jb,Me as k,Fg as ka,Ga as kb,ao as l,Se as la,Wa as lb,Ot as m,zn as ma,Va as mb,Yx as n,nQ as na,Ka as nb,mc as o,HA as oa,Ja as ob,Xx as p,ho as pa,ur as pb,Zx as q,yd as qa,ll as qb,oo as r,oQ as ra,ul as rb,ui as s,sQ as sa,Pw as sb,pi as t,Dh as ta,he as tb,_o as u,rQ as ua,ia as ub,so as v,$h as va,ro as w,ma as wa,dr as x,jh as xa,lr as y,DA as ya,mi as z,vn as za};