blade-code 0.10.66 → 0.10.67

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 (41) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-te21eb71.js → chunk-0aja46wq.js} +1 -1
  3. package/dist/{chunk-a2594p5r.js → chunk-2a9rndk2.js} +1 -1
  4. package/dist/{chunk-4sztphe9.js → chunk-2wz3mf50.js} +1 -1
  5. package/dist/{chunk-ax9ftraa.js → chunk-37g8mh93.js} +1 -1
  6. package/dist/{chunk-30kmydfj.js → chunk-38x7njj5.js} +1 -1
  7. package/dist/{chunk-dc64v4sa.js → chunk-3j8q6yrf.js} +1 -1
  8. package/dist/{chunk-ybv6stfh.js → chunk-53xbkvk1.js} +1 -1
  9. package/dist/{chunk-a3xnd8cg.js → chunk-5kz804w9.js} +1 -1
  10. package/dist/{chunk-1c69c4rd.js → chunk-696t7mzc.js} +1 -1
  11. package/dist/{chunk-pzb5sqwd.js → chunk-6am7zz57.js} +1 -1
  12. package/dist/{chunk-zk42hrdh.js → chunk-7agkmjm7.js} +1 -1
  13. package/dist/{chunk-gezg1mpa.js → chunk-7pxpwkeg.js} +1 -1
  14. package/dist/{chunk-rf01e14b.js → chunk-8mr5vydg.js} +1 -1
  15. package/dist/{chunk-jmjn6zcc.js → chunk-8t2xknh6.js} +1 -1
  16. package/dist/{chunk-j38jh128.js → chunk-amaxww4b.js} +1 -1
  17. package/dist/chunk-cn9jekw9.js +1 -0
  18. package/dist/{chunk-ha50z8dp.js → chunk-eqqxr26g.js} +1 -1
  19. package/dist/{chunk-89090tyx.js → chunk-fs6ashcf.js} +1 -1
  20. package/dist/{chunk-t89q7d03.js → chunk-gak96awp.js} +1 -1
  21. package/dist/{chunk-qdah5kkc.js → chunk-gayy8vky.js} +3 -3
  22. package/dist/chunk-gn3fxtkj.js +1 -0
  23. package/dist/{chunk-0scxrkcf.js → chunk-gvxpdb2v.js} +1 -1
  24. package/dist/{chunk-2xk6m4fc.js → chunk-k5a3n7q5.js} +1 -1
  25. package/dist/{chunk-p0b4mv7e.js → chunk-kccs7c9r.js} +1 -1
  26. package/dist/{chunk-abef6dq1.js → chunk-nacssmem.js} +1 -1
  27. package/dist/{chunk-0qtrv97b.js → chunk-nrh7qjat.js} +1 -1
  28. package/dist/{chunk-k99r5c4v.js → chunk-p0gyfy9p.js} +1 -1
  29. package/dist/{chunk-q3mfescm.js → chunk-pf6ftbra.js} +2 -2
  30. package/dist/{chunk-nt55nz8d.js → chunk-pv576mrv.js} +1 -1
  31. package/dist/{chunk-kv0bkxhd.js → chunk-rbdd49vr.js} +1 -1
  32. package/dist/{chunk-b66veqye.js → chunk-tb363yj8.js} +1 -1
  33. package/dist/{chunk-xny9q252.js → chunk-te88v4a8.js} +1 -1
  34. package/dist/{chunk-w6p2hcfw.js → chunk-vavy5dw8.js} +1 -1
  35. package/dist/{chunk-8nmwft1y.js → chunk-w5jdnsyz.js} +1 -1
  36. package/dist/{chunk-c8zcyvss.js → chunk-wr60s2qh.js} +1 -1
  37. package/dist/{chunk-69j98a7j.js → chunk-yq2891kc.js} +55 -55
  38. package/dist/{chunk-rhs1dv6w.js → chunk-zd05g5qs.js} +1 -1
  39. package/package.json +1 -1
  40. package/dist/chunk-2eq5dyga.js +0 -1
  41. package/dist/chunk-8c677xtx.js +0 -1
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.66",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.67",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
2
  export{y as ih,p as jh,v as kh,g as lh,f as mh,w as nh};
@@ -0,0 +1 @@
1
+ import{jd as a,kd as b}from"./chunk-38x7njj5.js";import"./chunk-amaxww4b.js";import"./chunk-hcv17986.js";export{a as globalOptions,b as cliConfig};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-4sztphe9.js";import"./chunk-j38jh128.js";import"./chunk-hcv17986.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{a as o}from"./chunk-2wz3mf50.js";import"./chunk-amaxww4b.js";import"./chunk-hcv17986.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
@@ -1 +1 @@
1
- import{Gd as a,Hd as b,Id as c,Jd as d,Kd as e,Ld as f,Md as g,Nd as h,Od as i,Pd as j,Qd as k,Rd as l,Sd as m,Td as n,Ud as o,Vd as p,Wd as q}from"./chunk-a3xnd8cg.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-j38jh128.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{Gd as a,Hd as b,Id as c,Jd as d,Kd as e,Ld as f,Md as g,Nd as h,Od as i,Pd as j,Qd as k,Rd as l,Sd as m,Td as n,Ud as o,Vd as p,Wd as q}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,4 +1,4 @@
1
- import{s as Pz,t as xz}from"./chunk-a2594p5r.js";import{u as E}from"./chunk-1c69c4rd.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-0qtrv97b.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-qdah5kkc.js";import{wa as qz}from"./chunk-pzb5sqwd.js";import"./chunk-5147jh26.js";import{db as n,pb as t,yb as s}from"./chunk-69j98a7j.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-8nmwft1y.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as Ez}from"./chunk-xny9q252.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-a3xnd8cg.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-2kkpn41a.js";import"./chunk-f99n8812.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-b66veqye.js";import"./chunk-2xk6m4fc.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-k99r5c4v.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-j38jh128.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as Pz,t as xz}from"./chunk-2a9rndk2.js";import{u as E}from"./chunk-696t7mzc.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-nrh7qjat.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-gayy8vky.js";import{wa as qz}from"./chunk-6am7zz57.js";import"./chunk-5147jh26.js";import{db as n,pb as t,yb as s}from"./chunk-yq2891kc.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-w5jdnsyz.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as Ez}from"./chunk-te88v4a8.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-2kkpn41a.js";import"./chunk-f99n8812.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-tb363yj8.js";import"./chunk-k5a3n7q5.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function Iz(z){if(!p(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...d("capacity"),resource:z.resource}}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Hz({maxPendingItems:$z,maxPendingBytes:Qz,writeTimeoutMs:Wz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([F.loadSession(this.id,this.cwd),F.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await F.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Zz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(B.debug(`[AcpSession ${this.id}] Initializing...`),await F.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),B.debug(`[AcpSession ${this.id}] ACP service context initialized`),await s.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?Sz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await e.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(X)=>Q.onOutput?.("stdout",X)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Xz(this.cwd),B.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=n.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!r(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of Mz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);B.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{B.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,D,G=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},L=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(U)=>{if(X)G(U);else D=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,D)G(D);return L}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,X)},complete:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,X)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),D=await X.completion,G=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!G)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:D.status,findings:D.findings.length,content:m(G.start,D)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,X)=>{let D=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:G})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Dz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await F.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){return B.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=Lz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});B.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),B.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){B.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((L)=>L.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=o(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let L=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(B.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let j=new AbortController,X=!1,D,G=new Promise((L)=>{D=L});this.pendingPrompt=j,this.pendingPromptCompletion=G;try{if(B.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),jz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,j.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},U=await t(this.agent.chatStream(Y,L,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let A=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let q=JSON.parse(V.function.arguments),K=q.resume_from??q.resume;if(typeof K==="string")w=`Resuming ${String(q.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:A});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,A=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;A.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))A.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,Tz=Jz(i(zz(K,O),l));A.push({type:"content",content:{type:"text",text:Tz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))A.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let q=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:q,content:A});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
@@ -1,4 +1,4 @@
1
- import{oa as R,pa as g0,ua as g3,va as w9,wa as h0}from"./chunk-pzb5sqwd.js";import{Aa as l4,Ra as jJ,xa as bJ,za as AJ}from"./chunk-5147jh26.js";import{$a as $7,Db as g9,Gb as u9,Sa as L$,Ta as V1,Ua as X9,Va as l$,Wa as n8,Xa as Q9,Ya as s8,Za as V9,_a as z9,db as Q0,fb as u2,ib as s2,kb as l6,lb as e2,mb as $5,pb as Y$,vb as B5,wb as C3,xb as o7}from"./chunk-69j98a7j.js";import{Bc as v3,Fc as h9,Kc as H3,Lc as O3,Mb as H0,Nb as N1,Nc as r,Ob as y$,Pb as V2,Qb as s4,Rb as o2,Sb as t2,jc as G5,kc as D0,lc as t0,uc as e4,vc as m0,wc as z1,xc as G3,yc as K3}from"./chunk-8nmwft1y.js";import{Oc as g,Pc as W7,Qc as X7,Rc as y2}from"./chunk-0wxkymqv.js";import{Sc as TJ,Vc as CJ,cd as RJ,id as PJ}from"./chunk-zdxxqchm.js";import{td as pZ,ud as mZ}from"./chunk-bjqjdw34.js";import{Gd as Z5,Hd as _0,Id as f,Ld as F0,Md as m2,Nd as G1,Od as T$,Pd as X4,Qd as m$,Rd as y9,Wd as U1}from"./chunk-a3xnd8cg.js";import{Xd as O$}from"./chunk-0j22w4wh.js";import{$d as x9,ae as k9,de as L3,ee as d2}from"./chunk-2kkpn41a.js";import{ge as R0,he as v$}from"./chunk-f99n8812.js";import{ie as P3}from"./chunk-yn51162x.js";import{ke as X3,le as U3,me as Q3}from"./chunk-b66veqye.js";import{Ae as O5,Be as s$,Ce as e$,De as z3,He as A4,Je as P0,Ke as X$,Me as p2,Ne as _3,ne as i2,oe as r2,qe as n2,re as a2,se as H1,te as G7,ve as z$,we as s0,xe as i0,ye as y5,ze as W1}from"./chunk-2xk6m4fc.js";import{Pe as K1,Re as J$,Se as R2}from"./chunk-hat9v5c5.js";import{Te as a3,Ve as V3,We as z5,Xe as cZ}from"./chunk-cdy9efgm.js";import{$e as A0,Ze as g4}from"./chunk-k99r5c4v.js";import{af as $2,bf as t4,cf as Z2,df as $1}from"./chunk-m57w4p91.js";import{$f as R9,Af as W9,Gf as r$,Jf as t8,Tf as b9,Uf as A9,Vf as j9,Wf as M9,Xf as Y4,Yf as T9,Zf as M$,_f as C9,ag as P9,cg as qZ,eg as B3,ff as CZ,fg as W3,gg as X0,kf as RZ,mf as v4,rf as h3,vf as PZ,xf as Z3,zf as Y9}from"./chunk-abef6dq1.js";import{jg as Y1}from"./chunk-h0ft81a3.js";import{kg as K2,lg as f5,mg as _,ng as B7,og as S,pg as l}from"./chunk-v0rsz1rt.js";import{rg as n7,sg as a7}from"./chunk-xz6y0w4n.js";import{ug as q2,wg as C}from"./chunk-k0pa8874.js";import{Xg as i}from"./chunk-98n2rxmq.js";import{ah as J3,bh as Y3}from"./chunk-ypqp368c.js";import{ch as t3,fh as r3}from"./chunk-t8xmh4w2.js";import{jh as ZJ}from"./chunk-j38jh128.js";import{ph as k0}from"./chunk-t2gq918a.js";import{sh as Q2,uh as A$,wh as $3,xh as KZ,zh as Z0}from"./chunk-ppsvzgs5.js";import{Bh as n0}from"./chunk-hcv17986.js";import{randomUUID as P5}from"crypto";import{randomUUID as iJ}from"node:crypto";var mJ=String.raw`
1
+ import{oa as R,pa as g0,ua as g3,va as w9,wa as h0}from"./chunk-6am7zz57.js";import{Aa as l4,Ra as jJ,xa as bJ,za as AJ}from"./chunk-5147jh26.js";import{$a as $7,Db as g9,Gb as u9,Sa as L$,Ta as V1,Ua as X9,Va as l$,Wa as n8,Xa as Q9,Ya as s8,Za as V9,_a as z9,db as Q0,fb as u2,ib as s2,kb as l6,lb as e2,mb as $5,pb as Y$,vb as B5,wb as C3,xb as o7}from"./chunk-yq2891kc.js";import{Bc as v3,Fc as h9,Kc as H3,Lc as O3,Mb as H0,Nb as N1,Nc as r,Ob as y$,Pb as V2,Qb as s4,Rb as o2,Sb as t2,jc as G5,kc as D0,lc as t0,uc as e4,vc as m0,wc as z1,xc as G3,yc as K3}from"./chunk-w5jdnsyz.js";import{Oc as g,Pc as W7,Qc as X7,Rc as y2}from"./chunk-0wxkymqv.js";import{Sc as TJ,Vc as CJ,cd as RJ,id as PJ}from"./chunk-zdxxqchm.js";import{td as pZ,ud as mZ}from"./chunk-bjqjdw34.js";import{Gd as Z5,Hd as _0,Id as f,Ld as F0,Md as m2,Nd as G1,Od as T$,Pd as X4,Qd as m$,Rd as y9,Wd as U1}from"./chunk-5kz804w9.js";import{Xd as O$}from"./chunk-0j22w4wh.js";import{$d as x9,ae as k9,de as L3,ee as d2}from"./chunk-2kkpn41a.js";import{ge as R0,he as v$}from"./chunk-f99n8812.js";import{ie as P3}from"./chunk-yn51162x.js";import{ke as X3,le as U3,me as Q3}from"./chunk-tb363yj8.js";import{Ae as O5,Be as s$,Ce as e$,De as z3,He as A4,Je as P0,Ke as X$,Me as p2,Ne as _3,ne as i2,oe as r2,qe as n2,re as a2,se as H1,te as G7,ve as z$,we as s0,xe as i0,ye as y5,ze as W1}from"./chunk-k5a3n7q5.js";import{Pe as K1,Re as J$,Se as R2}from"./chunk-hat9v5c5.js";import{Te as a3,Ve as V3,We as z5,Xe as cZ}from"./chunk-cdy9efgm.js";import{$e as A0,Ze as g4}from"./chunk-p0gyfy9p.js";import{af as $2,bf as t4,cf as Z2,df as $1}from"./chunk-m57w4p91.js";import{$f as R9,Af as W9,Gf as r$,Jf as t8,Tf as b9,Uf as A9,Vf as j9,Wf as M9,Xf as Y4,Yf as T9,Zf as M$,_f as C9,ag as P9,cg as qZ,eg as B3,ff as CZ,fg as W3,gg as X0,kf as RZ,mf as v4,rf as h3,vf as PZ,xf as Z3,zf as Y9}from"./chunk-nacssmem.js";import{jg as Y1}from"./chunk-h0ft81a3.js";import{kg as K2,lg as f5,mg as _,ng as B7,og as S,pg as l}from"./chunk-v0rsz1rt.js";import{rg as n7,sg as a7}from"./chunk-xz6y0w4n.js";import{ug as q2,wg as C}from"./chunk-k0pa8874.js";import{Xg as i}from"./chunk-98n2rxmq.js";import{ah as J3,bh as Y3}from"./chunk-ypqp368c.js";import{ch as t3,fh as r3}from"./chunk-t8xmh4w2.js";import{jh as ZJ}from"./chunk-amaxww4b.js";import{ph as k0}from"./chunk-t2gq918a.js";import{sh as Q2,uh as A$,wh as $3,xh as KZ,zh as Z0}from"./chunk-ppsvzgs5.js";import{Bh as n0}from"./chunk-hcv17986.js";import{randomUUID as P5}from"crypto";import{randomUUID as iJ}from"node:crypto";var mJ=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -782,7 +782,7 @@ ${V0}
782
782
  </approved-plan>
783
783
 
784
784
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof H==="string")Y0=H+k;else Y0=[...H,{type:"text",text:k}]}P=yield*this.runLoop(Y0,O,{...A,inputMessageId:void 0})}if(!this.sessionRuntime||!b)return P;let v=await this.sessionRuntime.recordGoalProgress({tokens:P.metadata?.tokensUsed??0,elapsedMs:P.metadata?.duration??0});if(v)yield{kind:"goal_updated",goal:v};if(!P.success||O.signal?.aborted){if(v=await this.sessionRuntime.pauseActiveGoal(O.signal?.aborted?"goal paused after user cancellation":P.error?.message??"goal paused after turn failure"),v)yield{kind:"goal_updated",goal:v}}if(P.success&&!O.signal?.aborted&&L<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(b,O.signal);let $0=P.success&&!O.signal?.aborted&&L<20,I=OU(P);if(N=await this.sessionRuntime.finishTurn(b,{continuePending:$0,...I?{acknowledgeInput:!0}:{},outcome:P.success&&!O.signal?.aborted?{status:"completed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}:{status:"aborted",cause:O.signal?.aborted?"cancelled":"failed",turnsCount:P.metadata?.turnsCount??0,toolCallsCount:P.metadata?.toolCallsCount??0,durationMs:P.metadata?.duration??0}}),N){L++,F=!0,B=!1,E=null,H="",D=void 0,q=T(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:j()};continue}if(!P.success||O.signal?.aborted)return P;if(v=await this.sessionRuntime.getGoal(),!v||v.status!=="active"&&v.status!=="verifying")return P;if(E=await this.sessionRuntime.beginGoalContinuation(),!E)return P;N=await this.sessionRuntime.beginTurn("goal"),F=!1,B=!0,H=Q6(E),D=void 0,q=void 0,yield{kind:"goal_continuation_started",goal:E,continuation:E.continuationCount},yield{kind:"goal_updated",goal:E}}}finally{if(this.sessionRuntime&&N)await this.sessionRuntime.finishTurn(N)}}let z=typeof Q==="string"?Q:Q.filter((H)=>H.type==="text").map((H)=>H.text).join(`
785
- `),G={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-zk42hrdh.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await d$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,environmentOptions:I9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=S1($);else{let X=$.filter((U)=>U.type==="text");if(X.length>0){let U=X[0];W=$.map((Q)=>Q===U?{type:"text",text:S1(U.text)}:Q)}else W=[{type:"text",text:S1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await d$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:I9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return u9(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,U=J.output,Q={success:X,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],z=g9(Y,Q);if(z)V.push(z);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await d$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await c2({sessionId:"default",configDir:Z0(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await D2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=h0.createIsolated({artifactWriter:new P1(`legacy-${HU()}`)});this.legacyMcpRegistry=Z;for(let[X,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,U),p.debug(`MCP server "${X}" connected`)}catch(Q){p.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(y1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await P0(C());if(this.agentResources=p2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
785
+ `),G={id:this.generateTaskId(),type:"simple",prompt:z};return{success:!0,finalMessage:(await this.executeTask(G)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-7agkmjm7.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){p.debug("Processing Plan mode message...");let{prompt:Y}=await d$({projectPath:Z.workspaceRoot||C(),mode:"plan",includeEnvironment:!0,environmentOptions:I9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot}),W;if(typeof $==="string")W=S1($);else{let X=$.filter((U)=>U.type==="text");if(X.length>0){let U=X[0];W=$.map((Q)=>Q===U?{type:"text",text:S1(U.text)}:Q)}else W=[{type:"text",text:S1("")},...$]}return yield*this.executeLoop(W,Z,J,Y)}async*runLoop($,Z,J){p.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z.workspaceRoot||C());return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await d$({projectPath:$,replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:I9,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let W=this.buildLoopDependencies();return u9(W,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},W=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,U=J.output,Q={success:X,llmContent:typeof U==="string"||U!==null&&typeof U==="object"?U:U===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(U),...J.error?{error:{type:"execution_error",message:J.error}}:{},...W?{metadata:W}:{}},V=[{kind:"tool_result",toolCall:Y,result:Q}],z=g9(Y,Q);if(z)V.push(z);return V})}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,p.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((W)=>!$.includes(W.name));for(let W of Y)Z.unregister(W.name);p.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);p.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){p.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){p.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await d$({projectPath:this.sessionRuntime?.workspaceRoot??C(),replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),projectInstructionSourcePath:this.sessionRuntime?.projectRoot});if(J.prompt)this.log("系统提示配置验证成功"),p.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await c2({sessionId:"default",configDir:Z0(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});p.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;p.debug(`Builtin tools registered: ${Z} tools`),p.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw p.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await D2({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){p.debug("No MCP servers configured");return}let Z=h0.createIsolated({artifactWriter:new P1(`legacy-${HU()}`)});this.legacyMcpRegistry=Z;for(let[X,U]of Object.entries($))try{p.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,U),p.debug(`MCP server "${X}" connected`)}catch(Q){p.warn(`Warning: MCP server "${X}" connection failed:`,Q)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(y1(Z));let W=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:W.revision,reason:"snapshot",replace:!0,instructions:W.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)p.debug(`Registered ${Y.tools.length} MCP tools`),p.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){p.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await P0(C());if(this.agentResources=p2($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)p.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else p.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;p.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{return Z.some((W)=>{if(W===Y.name)return!0;let X=W.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return p.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)p.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
786
786
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;p.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let W=this.buildAttachmentText(Y);if(!W)return $;return[...$,{type:"text",text:W}]}catch(Y){return p.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let W of $)if(W.type==="file"){let X=W.metadata?.lineRange?` (lines ${W.metadata.lineRange.start}${W.metadata.lineRange.end?`-${W.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${W.path}"${X?` range="${X}"`:""}>`,W.content,"</file>")}else if(W.type==="directory")Z.push(`<directory path="${W.path}">`,W.content,"</directory>");else if(W.type==="error")J.push(`- @${W.path}: ${W.error}`);let Y="";if(Z.length>0)Y+=`
787
787
 
788
788
  <system-reminder>
@@ -1583,7 +1583,7 @@ ${J}
1583
1583
  `)),{success:!0,message:"Schedules listed",content:V.join(`
1584
1584
  `)}}case"create":{let Q=yG(X);if("error"in Q)return Y.sendMessage(`创建失败:${Q.error}`),{success:!1,error:Q.error};let V={prompt:Q.prompt,projectPath:U,trigger:Q.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let z=await $.create(V),G=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${z.id}\`
1585
1585
  ${l4(z.trigger)} · 下次运行: ${G}`),{success:!0,message:`Schedule ${z.id} created`}}catch(z){let G=z instanceof Error?z.message:String(z);return Y.sendMessage(`创建失败:${G}`),{success:!1,error:G}}}case"remove":case"rm":{let Q=X[0];if(!Q)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let V=await $.remove(Q);return Y.sendMessage(V?`[OK] 已删除 \`${Q}\``:`未找到 \`${Q}\``),{success:V,message:V?"Removed":"Not found"}}case"enable":case"disable":{let Q=X[0];if(!Q)return Y.sendMessage(`用法:/schedule ${W} <id>`),{success:!1,error:"Missing schedule id"};let V=await $.setEnabled(Q,W==="enable");return Y.sendMessage(V?`[OK] 已${W==="enable"?"启用":"停用"} \`${Q}\``:`未找到 \`${Q}\``),{success:Boolean(V),message:V?"Updated":"Not found"}}case"run":{let Q=X[0];if(!Q)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await xG(Q),Y.sendMessage(`[OK] 已触发 \`${Q}\``),{success:!0,message:"Schedule triggered"}}catch(V){let z=V instanceof Error?V.message:String(V);return Y.sendMessage(`运行失败:${z}`),{success:!1,error:z}}}default:return Y.sendMessage(`未知子命令: ${W}
1586
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var MJ=hG();import*as w1 from"node:fs/promises";import*as L1 from"node:path";async function SJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,U=X??Q2(W??C());if(!X){let H=await gG($,W??C(),J,Y);if(H)return H}let Q;try{Q=(await w1.readdir(U)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>L1.join(U,O))}catch{return[]}let z=(await Promise.all(Q.map(async(H)=>{try{let O=await w1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),G=[],K=Y?$:$.toLowerCase();for(let H of z){if(G.length>=J)break;let O=L1.basename(H,".jsonl"),F=await uG(H,K,Y,O);if(G.push(...F),G.length>=J){G.length=J;break}}return G}async function gG($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-kmarzy98.js"),X=await RJ();if(!X)return null;let{SessionService:U}=await import("./chunk-0scxrkcf.js");await W(X,U.projectionDeriverForSearch());let Q=L1.resolve(Z),V=PJ(X,$,Q,J*4),z=Y?$:$.toLowerCase(),G=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=i4(K.text,z,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)G.push(H);if(G.length>=J)break}return G}catch{return null}}async function uG($,Z,J,Y){try{let W=await w1.readFile($,"utf8"),U=W.split(`
1586
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${W}`}}}}}var MJ=hG();import*as w1 from"node:fs/promises";import*as L1 from"node:path";async function SJ($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:W,storagePath:X}=Z,U=X??Q2(W??C());if(!X){let H=await gG($,W??C(),J,Y);if(H)return H}let Q;try{Q=(await w1.readdir(U)).filter((O)=>O.endsWith(".jsonl")&&!O.startsWith("agent_")).map((O)=>L1.join(U,O))}catch{return[]}let z=(await Promise.all(Q.map(async(H)=>{try{let O=await w1.stat(H);return{path:H,mtime:O.mtimeMs}}catch{return null}}))).filter((H)=>H!==null).sort((H,O)=>O.mtime-H.mtime).map((H)=>H.path),G=[],K=Y?$:$.toLowerCase();for(let H of z){if(G.length>=J)break;let O=L1.basename(H,".jsonl"),F=await uG(H,K,Y,O);if(G.push(...F),G.length>=J){G.length=J;break}}return G}async function gG($,Z,J,Y){try{let{syncAll:W}=await import("./chunk-kmarzy98.js"),X=await RJ();if(!X)return null;let{SessionService:U}=await import("./chunk-gvxpdb2v.js");await W(X,U.projectionDeriverForSearch());let Q=L1.resolve(Z),V=PJ(X,$,Q,J*4),z=Y?$:$.toLowerCase(),G=[];for(let K of V){if(K.role!=="user"&&K.role!=="assistant")continue;let H=i4(K.text,z,Y,K.session_id,K.role,K.timestamp??void 0,0);if(H)G.push(H);if(G.length>=J)break}return G}catch{return null}}async function uG($,Z,J,Y){try{let W=await w1.readFile($,"utf8"),U=W.split(`
1587
1587
  `).flatMap((K,H)=>{if(!K.trim())return[];try{return[{event:JSON.parse(K),index:H}]}catch{return[]}});if(!U.some(({event:K})=>K.type==="session_created"))return mG(U,Z,J,Y);let V=new Map(U.flatMap(({event:K,index:H})=>typeof K.id==="string"?[[K.id,H+1]]:[])),z=TJ(CJ(W,$)),G=new Map;for(let K of z){if(K.type==="message_created"&&(K.data.role==="user"||K.data.role==="assistant"))G.set(K.data.messageId,{role:K.data.role,content:[],timestamp:K.timestamp,lineNumber:V.get(K.id)??0});if(K.type==="part_created"&&K.data.partType==="text"){let H=G.get(K.data.messageId),O=K.data.payload.text;if(H&&typeof O==="string")H.content.push(O)}}return[...G.values()].flatMap((K)=>{let H=i4(K.content.join(" "),Z,J,Y,K.role,K.timestamp,K.lineNumber);return H?[H]:[]})}catch{return[]}}function mG($,Z,J,Y){return $.flatMap(({event:W,index:X})=>{if(W.type!=="message")return[];let U=W.message;if(U?.role!=="user"&&U?.role!=="assistant"||!U.content)return[];let Q=typeof U.content==="string"?U.content:Array.isArray(U.content)?U.content.filter((z)=>typeof z==="object"&&z!==null&&z.type==="text"&&typeof z.text==="string").map((z)=>z.text).join(" "):"",V=i4(Q,Z,J,Y,U.role,typeof W.timestamp==="string"?W.timestamp:void 0,X+1);return V?[V]:[]})}function i4($,Z,J,Y,W,X,U){if(!$)return;let Q=J?$:$.toLowerCase();if(!Q.includes(Z))return;let V=Q.indexOf(Z),z=Math.max(0,V-80),G=Math.min($.length,V+Z.length+80);return{sessionId:Y,role:W,content:(z>0?"...":"")+$.slice(z,G).replace(/\n/g," ")+(G<$.length?"...":""),timestamp:X,lineNumber:U}}function fJ($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1588
1588
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",W=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${W} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1589
1589
  `)}var dG={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=h(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let W=await SJ(Y,{maxResults:15,projectPath:Z.cwd}),X=fJ(W);return J.sendMessage(X),{success:!0,message:`found ${W.length} results`,data:{matches:W.length}}}catch(W){let X=W instanceof Error?W.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},kJ=dG;var pG={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await X$(J,async(Y)=>{await Y.skills.refresh(),e$(J),await s$(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return f().addAssistantMessage(Y),{success:!1,error:Y}}}},vJ=pG;import cG from"node:path";function b5($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function IJ($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function yJ($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function lG($,Z){let J=h(Z),Y=$[0],W=a.getInstance(),X=e.getInstance(),U=Z.sessionId??"",Q=Z.sessionId?{sessionId:Z.sessionId,projectPath:cG.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let O=$[1],F=$.slice(2).join(" ").trim();if(!O||!F)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let B=await Z.subagents.resume(O,F),q=`Resumed \`${O}\` as \`${B.session.id}\` (depth ${B.session.resumeDepth}).`;return J.sendMessage(q),{success:!0,message:q,data:{action:"subagent_resumed",sourceAgentId:O,subagent:B.session}}}if(Y==="clean"){let O=X.cleanupExpiredSessionsForParent(Q??U,0);return J.sendMessage(`已清理 ${O} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${O} agent sessions`}}let V=[`**后台任务列表**
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-2wz3mf50.js";import"./chunk-amaxww4b.js";import"./chunk-hcv17986.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1 +1 @@
1
- import{Hc as a,Ic as b,Jc as c,Kc as d,Lc as e,Mc as f,Nc as g}from"./chunk-8nmwft1y.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import"./chunk-yn51162x.js";import"./chunk-cdy9efgm.js";import"./chunk-m57w4p91.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-98n2rxmq.js";import"./chunk-t8xmh4w2.js";import"./chunk-j38jh128.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{Hc as a,Ic as b,Jc as c,Kc as d,Lc as e,Mc as f,Nc as g}from"./chunk-w5jdnsyz.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import"./chunk-yn51162x.js";import"./chunk-cdy9efgm.js";import"./chunk-m57w4p91.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-98n2rxmq.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1,4 +1,4 @@
1
- import{Oe as j1,Pe as L0,Qe as F1}from"./chunk-hat9v5c5.js";import{Ue as WO,Ve as IO}from"./chunk-cdy9efgm.js";import{Ye as B1}from"./chunk-zvz2cnt4.js";import{$e as J0,Ze as b0}from"./chunk-k99r5c4v.js";import{bg as z0,cg as $O,gg as I0}from"./chunk-abef6dq1.js";import{kg as u,mg as L,pg as P1}from"./chunk-v0rsz1rt.js";import{wg as M}from"./chunk-k0pa8874.js";import{Xg as k,Yg as z}from"./chunk-98n2rxmq.js";import{jh as g0}from"./chunk-j38jh128.js";import{ph as N}from"./chunk-t2gq918a.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
1
+ import{Oe as j1,Pe as L0,Qe as F1}from"./chunk-hat9v5c5.js";import{Ue as WO,Ve as IO}from"./chunk-cdy9efgm.js";import{Ye as B1}from"./chunk-zvz2cnt4.js";import{$e as J0,Ze as b0}from"./chunk-p0gyfy9p.js";import{bg as z0,cg as $O,gg as I0}from"./chunk-nacssmem.js";import{kg as u,mg as L,pg as P1}from"./chunk-v0rsz1rt.js";import{wg as M}from"./chunk-k0pa8874.js";import{Xg as k,Yg as z}from"./chunk-98n2rxmq.js";import{jh as g0}from"./chunk-amaxww4b.js";import{ph as N}from"./chunk-t2gq918a.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -1,4 +1,4 @@
1
- import{f as T,g as W,h as X,i as Y}from"./chunk-kv0bkxhd.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-a2594p5r.js";import"./chunk-1c69c4rd.js";import"./chunk-0qtrv97b.js";import"./chunk-qdah5kkc.js";import"./chunk-pzb5sqwd.js";import"./chunk-5147jh26.js";import"./chunk-69j98a7j.js";import"./chunk-th4jjfgm.js";import"./chunk-8nmwft1y.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as R}from"./chunk-xny9q252.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-a3xnd8cg.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-2kkpn41a.js";import"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-b66veqye.js";import"./chunk-2xk6m4fc.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-k99r5c4v.js";import"./chunk-m57w4p91.js";import"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-j38jh128.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import m from"chalk";import K from"open";var A=`
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-rbdd49vr.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-2a9rndk2.js";import"./chunk-696t7mzc.js";import"./chunk-nrh7qjat.js";import"./chunk-gayy8vky.js";import"./chunk-6am7zz57.js";import"./chunk-5147jh26.js";import"./chunk-yq2891kc.js";import"./chunk-th4jjfgm.js";import"./chunk-w5jdnsyz.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as R}from"./chunk-te88v4a8.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-2kkpn41a.js";import"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-tb363yj8.js";import"./chunk-k5a3n7q5.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -1,4 +1,4 @@
1
- import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-98n2rxmq.js";import{_g as $t,bh as J}from"./chunk-ypqp368c.js";import{jh as an,kh as xn}from"./chunk-j38jh128.js";import{ph as h}from"./chunk-t2gq918a.js";import{zh as mn}from"./chunk-ppsvzgs5.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-98n2rxmq.js";import{_g as $t,bh as J}from"./chunk-ypqp368c.js";import{jh as an,kh as xn}from"./chunk-amaxww4b.js";import{ph as h}from"./chunk-t2gq918a.js";import{zh as mn}from"./chunk-ppsvzgs5.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=y.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+kt;while(Date.now()<M)try{let e=await P.open(n,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!nM(M.pid))await P.unlink(n)}}var cn="127.0.0.1",bn=7777,wn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Pn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1,2 +1,2 @@
1
- import{K as I}from"./chunk-qdah5kkc.js";import{Nc as M}from"./chunk-8nmwft1y.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{K as I}from"./chunk-gayy8vky.js";import{Nc as M}from"./chunk-w5jdnsyz.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -25,7 +25,7 @@ import{df as YO}from"./chunk-m57w4p91.js";import{kg as qO,mg as S,pg as y}from".
25
25
  `):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
26
26
  `):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
27
27
  `):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
28
- `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-89090tyx.js"),{createChatServiceAsync:W}=await import("./chunk-eq99gcj8.js"),{resolveModelConfig:J}=await import("./chunk-yy6h97k0.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-jmjn6zcc.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
28
+ `):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-fs6ashcf.js"),{createChatServiceAsync:W}=await import("./chunk-eq99gcj8.js"),{resolveModelConfig:J}=await import("./chunk-yy6h97k0.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-8t2xknh6.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
29
29
 
30
30
  `+`## 评估指令
31
31
  ${O.prompt}
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{gg as Q}from"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as L}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-j38jh128.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as F}from"./chunk-hcv17986.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-kmarzy98.js"),{SessionService:B}=await import("./chunk-0scxrkcf.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{gg as Q}from"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as L}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as F}from"./chunk-hcv17986.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-kmarzy98.js"),{SessionService:B}=await import("./chunk-gvxpdb2v.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,4 +1,4 @@
1
- import{b as QY,c as JY,d as YY}from"./chunk-4sztphe9.js";import{j as _J,k as NJ}from"./chunk-dktrankr.js";import{u as c8}from"./chunk-1c69c4rd.js";import{$ as vJ,B as w6,D as HY,F as s2,G as a2,H as O6,N as h1,P as V4,Q as j4,V as Y8,W as fJ,X as kJ,_ as SJ,da as $4,ea as D6,ga as k6,ha as S6,ia as WY,ja as d4,la as r4,na as b6}from"./chunk-qdah5kkc.js";import{ra as x9,sa as u9,ta as l9,wa as FY}from"./chunk-pzb5sqwd.js";import"./chunk-5147jh26.js";import{cb as e4,db as $6,pb as Q6,yb as u2}from"./chunk-69j98a7j.js";import{Hb as K8}from"./chunk-th4jjfgm.js";import{Ac as m4,Cc as V8,Kc as J8,Nc as P0,_b as a4,mc as v4,rc as D4,yc as g4,zc as x2}from"./chunk-8nmwft1y.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{od as eJ}from"./chunk-s7jsadnc.js";import{pd as G8,qd as x8,sd as f1}from"./chunk-xny9q252.js";import"./chunk-bjqjdw34.js";import{Ad as v$,Bd as j8,Cd as z9,Dd as uQ,Ed as ZJ,Fd as _9,Gd as f$,Hd as $1,Id as _Y,Jd as a0,Kd as sJ,Ld as P2,Md as Z8,Pd as u4,Wd as m0,wd as C$,xd as r0,yd as Q$,zd as yQ}from"./chunk-a3xnd8cg.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-2kkpn41a.js";import{he as lQ}from"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-b66veqye.js";import{Ae as TJ,Je as NY,se as I6,ve as uJ}from"./chunk-2xk6m4fc.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import{$e as z1,Ze as CQ}from"./chunk-k99r5c4v.js";import"./chunk-m57w4p91.js";import{bg as OY,gg as IJ,hg as zY}from"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as D$,rg as h8,sg as IQ}from"./chunk-xz6y0w4n.js";import{wg as l0}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Ug as UY,Xg as e1}from"./chunk-98n2rxmq.js";import{Zg as UJ,_g as OJ,bh as E1}from"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{nh as e9}from"./chunk-j38jh128.js";import{ph as eQ}from"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as MQ}from"./chunk-hcv17986.js";import{useMemoizedFn as v2}from"ahooks";import{useEffect as J7,useState as D2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as oX,useRef as f2}from"react";import{useShallow as BY}from"zustand/react/shallow";import{useStore as LY}from"zustand";function t($){return LY(f$,$)}var wY=[],k$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),Q4=()=>t(($)=>$.session.messages),J4=()=>t(($)=>$.session.clearCount),Y4=()=>t(($)=>$.session.isCompacting),Z4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return $4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),K4=()=>t(($)=>$.session.providerCircuit),G4=()=>t(($)=>$.session.providerAdmission),q4=()=>t(($)=>$.session.providerRetry),U4=()=>t(($)=>$.session.providerStall),O4=()=>t(($)=>$.session.actionStationarity),n1=()=>t(($)=>$.session.actions),z4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),_4=()=>t(($)=>$.app.initializationStatus),N4=()=>t(($)=>$.app.initializationError),y8=()=>t(($)=>$.app.activeModal),F4=()=>t(($)=>$.app.tasks),H4=()=>t(($)=>$.app.modelEditorTarget),W4=()=>t(($)=>$.app.sessionSelectorData),L4=()=>t(($)=>$.app.awaitingSecondCtrlC),t1=()=>t(($)=>$.app.actions),R8=()=>t(($)=>$.app.initializationStatus==="ready"),B4=()=>t(($)=>$.app.tasks.length>0),S$=()=>t(($)=>$.config.config?.permissionMode||"default"),w4=()=>t(($)=>$.config.config?.models??wY),M8=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),C8=()=>t(($)=>$.config.config?.currentModelId),A0=()=>t(($)=>{return r0.getTheme()}),b4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),A4=()=>t(($)=>$.focus.actions),s1=()=>t(($)=>$.command.isProcessing),P4=()=>t(($)=>$.command.actions),I8=()=>t(($)=>$.command.pendingCommands),y4=()=>t(($)=>$.command.recoveredSteeringCount),T8=()=>t(($)=>$.app.thinkingModeEnabled),f8=()=>t(($)=>$.app.reasoningEffort),k8=()=>t(($)=>$.app.serviceTier),S8=()=>t(($)=>$.app.responseVerbosity),v8=()=>t(($)=>$.app.communicationStyle),R4=()=>t(($)=>$.session.currentThinkingContent),M4=()=>t(($)=>$.session.thinkingExpanded),C4=()=>t(($)=>$.session.currentStreamingMessageId),I4=()=>t(BY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),T4=()=>t(($)=>$.session.finalizingStreamingMessageId),f4=()=>t(($)=>$.session.historyExpanded),k4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as j$}from"ahooks";import{useEffect as l8,useRef as t4}from"react";function bY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function AY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function PY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function D8($){let Q=AY($),Y=PY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=bY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as yY,mkdirSync as RY,writeFileSync as MY}from"node:fs";import CY from"node:os";import h2 from"node:path";var S4=null;function IY(){let $=process.env.BLADE_STORAGE_ROOT||h2.join(CY.homedir(),".blade");return h2.join($,"logs","stream-debug.log")}function TY($){if(S4===$)return;let Q=h2.dirname($);RY(Q,{recursive:!0,mode:493}),MY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{b as QY,c as JY,d as YY}from"./chunk-2wz3mf50.js";import{j as _J,k as NJ}from"./chunk-dktrankr.js";import{u as c8}from"./chunk-696t7mzc.js";import{$ as vJ,B as w6,D as HY,F as s2,G as a2,H as O6,N as h1,P as V4,Q as j4,V as Y8,W as fJ,X as kJ,_ as SJ,da as $4,ea as D6,ga as k6,ha as S6,ia as WY,ja as d4,la as r4,na as b6}from"./chunk-gayy8vky.js";import{ra as x9,sa as u9,ta as l9,wa as FY}from"./chunk-6am7zz57.js";import"./chunk-5147jh26.js";import{cb as e4,db as $6,pb as Q6,yb as u2}from"./chunk-yq2891kc.js";import{Hb as K8}from"./chunk-th4jjfgm.js";import{Ac as m4,Cc as V8,Kc as J8,Nc as P0,_b as a4,mc as v4,rc as D4,yc as g4,zc as x2}from"./chunk-w5jdnsyz.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{od as eJ}from"./chunk-s7jsadnc.js";import{pd as G8,qd as x8,sd as f1}from"./chunk-te88v4a8.js";import"./chunk-bjqjdw34.js";import{Ad as v$,Bd as j8,Cd as z9,Dd as uQ,Ed as ZJ,Fd as _9,Gd as f$,Hd as $1,Id as _Y,Jd as a0,Kd as sJ,Ld as P2,Md as Z8,Pd as u4,Wd as m0,wd as C$,xd as r0,yd as Q$,zd as yQ}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-2kkpn41a.js";import{he as lQ}from"./chunk-f99n8812.js";import"./chunk-yn51162x.js";import"./chunk-tb363yj8.js";import{Ae as TJ,Je as NY,se as I6,ve as uJ}from"./chunk-k5a3n7q5.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import{$e as z1,Ze as CQ}from"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import{bg as OY,gg as IJ,hg as zY}from"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as D$,rg as h8,sg as IQ}from"./chunk-xz6y0w4n.js";import{wg as l0}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Ug as UY,Xg as e1}from"./chunk-98n2rxmq.js";import{Zg as UJ,_g as OJ,bh as E1}from"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{nh as e9}from"./chunk-amaxww4b.js";import{ph as eQ}from"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as MQ}from"./chunk-hcv17986.js";import{useMemoizedFn as v2}from"ahooks";import{useEffect as J7,useState as D2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as oX,useRef as f2}from"react";import{useShallow as BY}from"zustand/react/shallow";import{useStore as LY}from"zustand";function t($){return LY(f$,$)}var wY=[],k$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),Q4=()=>t(($)=>$.session.messages),J4=()=>t(($)=>$.session.clearCount),Y4=()=>t(($)=>$.session.isCompacting),Z4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return $4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),K4=()=>t(($)=>$.session.providerCircuit),G4=()=>t(($)=>$.session.providerAdmission),q4=()=>t(($)=>$.session.providerRetry),U4=()=>t(($)=>$.session.providerStall),O4=()=>t(($)=>$.session.actionStationarity),n1=()=>t(($)=>$.session.actions),z4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),_4=()=>t(($)=>$.app.initializationStatus),N4=()=>t(($)=>$.app.initializationError),y8=()=>t(($)=>$.app.activeModal),F4=()=>t(($)=>$.app.tasks),H4=()=>t(($)=>$.app.modelEditorTarget),W4=()=>t(($)=>$.app.sessionSelectorData),L4=()=>t(($)=>$.app.awaitingSecondCtrlC),t1=()=>t(($)=>$.app.actions),R8=()=>t(($)=>$.app.initializationStatus==="ready"),B4=()=>t(($)=>$.app.tasks.length>0),S$=()=>t(($)=>$.config.config?.permissionMode||"default"),w4=()=>t(($)=>$.config.config?.models??wY),M8=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),C8=()=>t(($)=>$.config.config?.currentModelId),A0=()=>t(($)=>{return r0.getTheme()}),b4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),A4=()=>t(($)=>$.focus.actions),s1=()=>t(($)=>$.command.isProcessing),P4=()=>t(($)=>$.command.actions),I8=()=>t(($)=>$.command.pendingCommands),y4=()=>t(($)=>$.command.recoveredSteeringCount),T8=()=>t(($)=>$.app.thinkingModeEnabled),f8=()=>t(($)=>$.app.reasoningEffort),k8=()=>t(($)=>$.app.serviceTier),S8=()=>t(($)=>$.app.responseVerbosity),v8=()=>t(($)=>$.app.communicationStyle),R4=()=>t(($)=>$.session.currentThinkingContent),M4=()=>t(($)=>$.session.thinkingExpanded),C4=()=>t(($)=>$.session.currentStreamingMessageId),I4=()=>t(BY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),T4=()=>t(($)=>$.session.finalizingStreamingMessageId),f4=()=>t(($)=>$.session.historyExpanded),k4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as j$}from"ahooks";import{useEffect as l8,useRef as t4}from"react";function bY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function AY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function PY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function D8($){let Q=AY($),Y=PY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=bY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as yY,mkdirSync as RY,writeFileSync as MY}from"node:fs";import CY from"node:os";import h2 from"node:path";var S4=null;function IY(){let $=process.env.BLADE_STORAGE_ROOT||h2.join(CY.homedir(),".blade");return h2.join($,"logs","stream-debug.log")}function TY($){if(S4===$)return;let Q=h2.dirname($);RY(Q,{recursive:!0,mode:493}),MY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),S4=$}function E2($,Q,Y){try{let J=IY();TY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
3
3
  `;yY(J,K)}catch{}}var Q8=e1("UI");function h4($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,E2("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Q8.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),E2("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)v$(K,Z);j8(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===V8)break;if(Q8.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=V4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){Q8.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===V8)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===V8)break;Q8.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=D4(j4(Z.function.name,J.result),v4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":Q8.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -1,4 +1,4 @@
1
- import{j as X4,k as V4}from"./chunk-dktrankr.js";import{l as tO}from"./chunk-yvg961q3.js";import{s as QO,t as g1}from"./chunk-a2594p5r.js";import{u as a0}from"./chunk-1c69c4rd.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as $O}from"./chunk-0qtrv97b.js";import{$ as e1,C as w4,F as R1,G as VO,H as A$,I as iO,J as W$,K as E0,L as F$,M as f0,N as TO,Q as IO,R as SO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-qdah5kkc.js";import{qa as Q1,wa as U0}from"./chunk-pzb5sqwd.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-5147jh26.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-69j98a7j.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as YO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as aO,pc as qO,qc as D$,rc as kO,tc as j1,zc as T1}from"./chunk-8nmwft1y.js";import{Ld as J0,Pd as G1,Wd as L0}from"./chunk-a3xnd8cg.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as cO}from"./chunk-b66veqye.js";import{Be as MO,Ce as AO,Ge as d4,Je as T0,Ke as jO,Ne as l4,ue as D4,xe as a1}from"./chunk-2xk6m4fc.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as JO,_e as O1}from"./chunk-k99r5c4v.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as wO,rf as J1}from"./chunk-abef6dq1.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as P,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as oO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-98n2rxmq.js";import{bh as c0}from"./chunk-ypqp368c.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as xO}from"./chunk-j38jh128.js";import{ph as E$}from"./chunk-t2gq918a.js";import{uh as pO,yh as n$}from"./chunk-ppsvzgs5.js";import{Bh as C$}from"./chunk-hcv17986.js";var a5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as yO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var OO=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;OO.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,OO.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){OO.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),OO.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),OO.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let z=Q instanceof Error?Q.message:String(Q);OO.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:z,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((z)=>z.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class S extends Z0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Z0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Z0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Z0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Z0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Z0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=J0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=P(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:z}=J.data;return await L0().updateConfig(Q,z),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=J0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{j as X4,k as V4}from"./chunk-dktrankr.js";import{l as tO}from"./chunk-yvg961q3.js";import{s as QO,t as g1}from"./chunk-2a9rndk2.js";import{u as a0}from"./chunk-696t7mzc.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as $O}from"./chunk-nrh7qjat.js";import{$ as e1,C as w4,F as R1,G as VO,H as A$,I as iO,J as W$,K as E0,L as F$,M as f0,N as TO,Q as IO,R as SO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-gayy8vky.js";import{qa as Q1,wa as U0}from"./chunk-6am7zz57.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-5147jh26.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-yq2891kc.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as YO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as aO,pc as qO,qc as D$,rc as kO,tc as j1,zc as T1}from"./chunk-w5jdnsyz.js";import{Ld as J0,Pd as G1,Wd as L0}from"./chunk-5kz804w9.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as cO}from"./chunk-tb363yj8.js";import{Be as MO,Ce as AO,Ge as d4,Je as T0,Ke as jO,Ne as l4,ue as D4,xe as a1}from"./chunk-k5a3n7q5.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as JO,_e as O1}from"./chunk-p0gyfy9p.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as wO,rf as J1}from"./chunk-nacssmem.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as P,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as oO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-98n2rxmq.js";import{bh as c0}from"./chunk-ypqp368c.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as xO}from"./chunk-amaxww4b.js";import{ph as E$}from"./chunk-t2gq918a.js";import{uh as pO,yh as n$}from"./chunk-ppsvzgs5.js";import{Bh as C$}from"./chunk-hcv17986.js";var a5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as yO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var OO=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;OO.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,OO.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){OO.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),OO.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),OO.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let z=Q instanceof Error?Q.message:String(Q);OO.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let Y=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:z,nextRunAt:Y?Y.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((z)=>z.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Z0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class S extends Z0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Z0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Z0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Z0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Z0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Z0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Z0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=J0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=P(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:z}=J.data;return await L0().updateConfig(Q,z),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=J0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -1,2 +1,2 @@
1
- import{gg as F}from"./chunk-abef6dq1.js";import{ah as D,bh as E}from"./chunk-ypqp368c.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{gg as F}from"./chunk-nacssmem.js";import{ah as D,bh as E}from"./chunk-ypqp368c.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as ke,Q as le,T as me};
@@ -1,4 +1,4 @@
1
- import{Hd as N}from"./chunk-a3xnd8cg.js";import{$e as $}from"./chunk-k99r5c4v.js";import{wg as _}from"./chunk-k0pa8874.js";import{Vg as Y,Xg as Z}from"./chunk-98n2rxmq.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Hd as N}from"./chunk-5kz804w9.js";import{$e as $}from"./chunk-p0gyfy9p.js";import{wg as _}from"./chunk-k0pa8874.js";import{Vg as Y,Xg as Z}from"./chunk-98n2rxmq.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
4
4
  export{O as pd,y as qd,j as rd,C as sd};
@@ -1,4 +1,4 @@
1
- import{wa as H}from"./chunk-pzb5sqwd.js";import"./chunk-th4jjfgm.js";import"./chunk-0wxkymqv.js";import{Qd as $,Wd as T}from"./chunk-a3xnd8cg.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-k99r5c4v.js";import"./chunk-m57w4p91.js";import"./chunk-abef6dq1.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as k}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-j38jh128.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{wa as H}from"./chunk-6am7zz57.js";import"./chunk-th4jjfgm.js";import"./chunk-0wxkymqv.js";import{Qd as $,Wd as T}from"./chunk-5kz804w9.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-p0gyfy9p.js";import"./chunk-m57w4p91.js";import"./chunk-nacssmem.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as k}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import"./chunk-amaxww4b.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器