blade-code 0.7.5 → 0.7.6

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 (77) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-10q3krvh.js +6 -0
  3. package/dist/chunk-1tzcptyb.js +3 -0
  4. package/dist/{chunk-ay3rhhx8.js → chunk-1y33d6xh.js} +1 -1
  5. package/dist/chunk-5accz8n9.js +1 -0
  6. package/dist/{chunk-kfg3vx5z.js → chunk-64x50qbc.js} +1 -1
  7. package/dist/chunk-8raa4q9y.js +1564 -0
  8. package/dist/chunk-ad19yrq6.js +1 -0
  9. package/dist/{chunk-jsn8476q.js → chunk-arwynrtf.js} +2 -2
  10. package/dist/chunk-bvn4e2vq.js +1 -0
  11. package/dist/{chunk-63dzf6hr.js → chunk-cadngkwr.js} +1 -1
  12. package/dist/{chunk-98jpdmgc.js → chunk-cdx3hp1r.js} +5 -5
  13. package/dist/{chunk-373pmz70.js → chunk-d9qh7bat.js} +1 -1
  14. package/dist/chunk-ebynn53v.js +26 -0
  15. package/dist/{chunk-cyxb6fxe.js → chunk-ezkbqmvd.js} +1 -1
  16. package/dist/{chunk-a8znntss.js → chunk-fceeqn6k.js} +2 -2
  17. package/dist/{chunk-c3yn8ds8.js → chunk-g60w2r7f.js} +2 -2
  18. package/dist/{chunk-k4behavv.js → chunk-h7qab07x.js} +1 -1
  19. package/dist/{chunk-bmcc85nj.js → chunk-jhzf05kz.js} +1 -1
  20. package/dist/chunk-k76q8cyc.js +151 -0
  21. package/dist/chunk-krrm6bjr.js +1 -0
  22. package/dist/{chunk-gjf2d2yg.js → chunk-m3hsaaq5.js} +1 -1
  23. package/dist/chunk-n2yq1wn8.js +9 -0
  24. package/dist/{chunk-rtn0rb16.js → chunk-npaj13y3.js} +2 -2
  25. package/dist/{chunk-0rw4tdqy.js → chunk-pf45ctn7.js} +1 -1
  26. package/dist/{chunk-cw125vv3.js → chunk-q6sj33v8.js} +1 -1
  27. package/dist/chunk-qedtzcp2.js +1 -0
  28. package/dist/{chunk-e21htmg4.js → chunk-qyfdt8h1.js} +1 -1
  29. package/dist/{chunk-38h3yh6z.js → chunk-r0hc7wad.js} +1 -1
  30. package/dist/chunk-rhvxr82g.js +2 -0
  31. package/dist/chunk-t6qek6xk.js +1 -0
  32. package/dist/{chunk-jf48kahn.js → chunk-ttf06k8y.js} +3 -3
  33. package/dist/chunk-tyjns370.js +1 -0
  34. package/dist/{chunk-7pcm8vy5.js → chunk-ve6bvba4.js} +28 -28
  35. package/dist/chunk-wdxbjvd5.js +2 -0
  36. package/dist/{chunk-n969rv4v.js → chunk-wg5nxtb2.js} +1 -1
  37. package/dist/{chunk-qxvp127d.js → chunk-wstkn75a.js} +1 -1
  38. package/dist/chunk-x4fx52e7.js +24 -0
  39. package/dist/chunk-xj63cr29.js +1 -0
  40. package/dist/{chunk-yaj4nmmp.js → chunk-zmndvdgb.js} +1 -1
  41. package/dist/{chunk-pvxp2gzr.js → chunk-zr71r1z1.js} +1 -1
  42. package/dist/web/assets/{FilePreview-evNzCuVx.js → FilePreview-CbtOITD1.js} +1 -1
  43. package/dist/web/assets/{MarkdownRenderer-BQoiQTDd.js → MarkdownRenderer-CW8WpEw1.js} +1 -1
  44. package/dist/web/assets/McpModal-DnqrgBON.js +5 -0
  45. package/dist/web/assets/SettingsModal-CRNT-LCq.js +1 -0
  46. package/dist/web/assets/{SettingsStore-CfDjhOkS.js → SettingsStore-B2GIhfKs.js} +1 -1
  47. package/dist/web/assets/SkillsModal-COQMbIdT.js +1 -0
  48. package/dist/web/assets/{TerminalPanel-Cs16_6ew.js → TerminalPanel-dCMUvQaH.js} +1 -1
  49. package/dist/web/assets/index-21gV5nOE.css +1 -0
  50. package/dist/web/assets/index-Cnz-_jPt.js +10 -0
  51. package/dist/web/assets/{useRequest-BJp539HQ.js → useRequest-C7k7cDPD.js} +1 -1
  52. package/dist/web/assets/{vendor-icons-DlzC8I7m.js → vendor-icons-BKXQ7ALf.js} +75 -30
  53. package/dist/web/assets/{vendor-radix-CfxBc_4-.js → vendor-radix-2yBsoRqx.js} +2 -2
  54. package/dist/web/index.html +2 -2
  55. package/package.json +1 -1
  56. package/dist/chunk-1vngdr7p.js +0 -1
  57. package/dist/chunk-5smacbk0.js +0 -24
  58. package/dist/chunk-8ea9h3mb.js +0 -151
  59. package/dist/chunk-8w1hd9ct.js +0 -1534
  60. package/dist/chunk-aevyre2t.js +0 -1
  61. package/dist/chunk-apb1p5q4.js +0 -1
  62. package/dist/chunk-b4hmtjec.js +0 -1
  63. package/dist/chunk-cqrg2pp7.js +0 -1
  64. package/dist/chunk-g1eb7f4q.js +0 -1
  65. package/dist/chunk-jfykets9.js +0 -6
  66. package/dist/chunk-kssr4fbg.js +0 -1
  67. package/dist/chunk-rkhhzc4r.js +0 -26
  68. package/dist/chunk-vhc1yr3v.js +0 -1
  69. package/dist/chunk-w1zb8zac.js +0 -3
  70. package/dist/chunk-yz2jztga.js +0 -7
  71. package/dist/chunk-zye2s6f0.js +0 -2
  72. package/dist/web/assets/McpModal-BT9OivhK.js +0 -5
  73. package/dist/web/assets/SettingsModal-CDRcorCS.js +0 -1
  74. package/dist/web/assets/SkillsModal-DCPaqoOe.js +0 -1
  75. package/dist/web/assets/dialog-C8VDk-ma.js +0 -1
  76. package/dist/web/assets/index-9t-WxRrl.js +0 -10
  77. package/dist/web/assets/index-Bu13aXyE.css +0 -1
@@ -0,0 +1 @@
1
+ import{Db as a}from"./chunk-cdx3hp1r.js";import"./chunk-1tzcptyb.js";import"./chunk-64x50qbc.js";export{a as createChatServiceAsync};
@@ -1,2 +1,2 @@
1
- var s={name:"blade-code",version:"0.7.5",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","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","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","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",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",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@anthropic-ai/sandbox-runtime":"0.0.67","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",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.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:s.name,version:s.version,description:s.description}}function n(){return s.version}function o(){return s.name}function c(){return s.description}function a(){return`v${s.version}`}function d(){return`v${s.version} © 2025 Blade Code`}
2
- export{r as Da,n as Ea,o as Fa,c as Ga,a as Ha,d as Ia};
1
+ var s={name:"blade-code",version:"0.7.6",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","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","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","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",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",engines:{node:">=20.0.0"},optionalDependencies:{"@vscode/ripgrep":"^1.17.0","bun-pty":"^0.4.8","node-pty":"1.0.0"},dependencies:{"@agentclientprotocol/sdk":"^0.12.0","@ai-sdk/anthropic":"^3.0.7","@ai-sdk/azure":"^3.0.5","@ai-sdk/deepseek":"^2.0.4","@ai-sdk/google":"^3.0.4","@ai-sdk/openai":"^3.0.26","@ai-sdk/openai-compatible":"^2.0.4","@anthropic-ai/sandbox-runtime":"0.0.67","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.17.4",ahooks:"^3.9.6",ai:"^6.0.39","ansi-escapes":"^7.2.0","async-mutex":"^0.5.0",axios:"^1.12.2",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.1.0","gray-matter":"^4.0.3",hono:"^4.7.10",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.17.21",lowlight:"^3.3.0","lru-cache":"^11.2.4",nanoid:"^5.1.6",open:"^10.1.2",openai:"^6.2.0",picomatch:"^4.0.3",react:"^19.1.1","react-dom":"^19.1.1",semver:"^7.7.3","string-width":"^8.1.0",undici:"^7.16.0","write-file-atomic":"^7.0.0",ws:"^8.18.0",yaml:"^2.8.1",yargs:"^18.0.0",zod:"^3.24.2","zod-to-json-schema":"^3.24.6",zustand:"^5.0.9"},devDependencies:{"@biomejs/biome":"^2.2.4","@types/bun":"^1.3.4","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.2","@types/react":"^19.1.1","@types/react-dom":"^19.1.1","@types/semver":"^7.7.1","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.5.12","@types/yargs":"^17.0.33","@vitest/coverage-v8":"^3.0.0",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^3.0.0"}};function r(){return{name:s.name,version:s.version,description:s.description}}function n(){return s.version}function o(){return s.name}function c(){return s.description}function a(){return`v${s.version}`}function d(){return`v${s.version} © 2025 Blade Code`}
2
+ export{r as Ea,n as Fa,o as Ga,c as Ha,a as Ia,d as Ja};
@@ -0,0 +1 @@
1
+ import{f as y,g as A,h as C,i as D}from"./chunk-wdxbjvd5.js";import"./chunk-zr71r1z1.js";import"./chunk-8raa4q9y.js";import"./chunk-qyfdt8h1.js";import"./chunk-fceeqn6k.js";import"./chunk-npaj13y3.js";import{ta as q}from"./chunk-x4fx52e7.js";import"./chunk-ebynn53v.js";import"./chunk-arwynrtf.js";import"./chunk-ve6bvba4.js";import"./chunk-ezkbqmvd.js";import"./chunk-ttf06k8y.js";import"./chunk-rhvxr82g.js";import"./chunk-cadngkwr.js";import"./chunk-cdx3hp1r.js";import"./chunk-1tzcptyb.js";import"./chunk-64x50qbc.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as G}from"fs";import{cwd as K}from"process";var D=null;function N(){let q="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof G==="function"){let F=K();try{q=G(F).normalize("NFC")}catch{q=F.normalize("NFC")}}return{cwd:q,originalCwd:q,projectRoot:q}}function x(){if(!D)D=N();return D}function H(){return x().cwd}function Z(q){x().cwd=q.normalize("NFC")}function J(){return x().originalCwd}function $(){return x().projectRoot}function b(q){x().projectRoot=q.normalize("NFC")}var Q;((B)=>{B.DEFAULT="default";B.AUTO_EDIT="autoEdit";B.YOLO="yolo";B.PLAN="plan"})(Q||={});import{AsyncLocalStorage as R}from"async_hooks";var U=new R;function V(){return U.getStore()??H()}function W(){try{return V()}catch{return J()}}
2
- export{Z as ob,J as pb,$ as qb,b as rb,Q as sb,W as tb};
2
+ export{Z as rb,J as sb,$ as tb,b as ub,Q as vb,W as wb};
@@ -1,9 +1,9 @@
1
- import{Lb as R}from"./chunk-w1zb8zac.js";var m=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],d={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},g={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},h={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},T=(Q)=>{return h[Q]||{}};import{createAnthropic as k}from"@ai-sdk/anthropic";import{createAzure as I}from"@ai-sdk/azure";import{createDeepSeek as A}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as U}from"@ai-sdk/google";import{createOpenAI as C}from"@ai-sdk/openai";import{createOpenAICompatible as H}from"@ai-sdk/openai-compatible";import{generateText as v,jsonSchema as f,streamText as b}from"ai";var M=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function E(Q){return typeof Q==="string"&&M.has(Q)}function n(Q){if(!Q.aborted)return;if(E(Q.reason))return Q.reason;return"user-cancel"}function t(Q){if(E(Q))return!0;if(!(Q instanceof Error))return!1;if(Q.name==="AbortError")return!0;if(Q instanceof DOMException&&Q.name==="AbortError")return!0;if(Q.message.includes("aborted"))return!0;return!1}function r(...Q){let q=Q.filter(Boolean);if(q.length===0)return new AbortController().signal;if(q.length===1)return q[0];let Y=AbortSignal;if(typeof Y.any==="function")return Y.any(q);for(let $ of q)if($.aborted)return $;let J=new AbortController,X=new Map;for(let $ of q){let B=()=>{J.abort($.reason);for(let[Z,F]of X)Z.removeEventListener("abort",F)};X.set($,B)}for(let[$,B]of X)$.addEventListener("abort",B,{once:!0});return J.signal}function D(Q,q,Y){let J=Y?.throwOnAbort??!1;if(q?.aborted){if(J)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((X,$)=>{let B,Z=setTimeout(()=>{if(q&&B)q.removeEventListener("abort",B);X()},Q);if(q)B=()=>{if(clearTimeout(Z),J)$(new DOMException("Aborted","AbortError"));else X()},q.addEventListener("abort",B,{once:!0})})}var z=R("Chat");function x(Q){let q=new Set;for(let Y of Q)if(Y.role==="assistant"&&Y.tool_calls)for(let J of Y.tool_calls)q.add(J.id);return Q.filter((Y)=>{if(Y.role==="tool"){if(!Y.tool_call_id)return!1;return q.has(Y.tool_call_id)}return!0})}function V(Q){if(typeof Q==="string")return Q;return Q.filter((q)=>q.type==="text").map((q)=>q.text).join(`
2
- `)}function y(Q){let q=Q;return q.text??q.textDelta??q.delta}function u(Q,q={}){try{return JSON.parse(Q)}catch{return z.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:Q}),q}}class O{model;config;constructor(Q){this.config=Q,this.model=this.createModel(Q),z.debug("[VercelAIChatService] Initialized",{provider:Q.provider,model:Q.model})}createModel(Q){let{provider:q,apiKey:Y,baseUrl:J,model:X,customHeaders:$,apiVersion:B}=Q;switch(q){case"openai":return C({apiKey:Y,baseURL:J||void 0,headers:$})(X);case"anthropic":return k({apiKey:Y,baseURL:J||void 0,headers:$})(X);case"gemini":{if(J&&!this.isGeminiOfficialUrl(J))return H({name:"gemini",apiKey:Y,baseURL:J,headers:$})(X);return U({apiKey:Y,baseURL:J||void 0})(X)}case"google":case"google-generative-ai":case"google-vertex":{if(J&&!this.isGeminiOfficialUrl(J))return H({name:q,apiKey:Y,baseURL:J,headers:$})(X);return U({apiKey:Y,baseURL:J||void 0})(X)}case"azure-openai":{let Z=this.extractAzureResourceName(J);if(Z)return I({apiKey:Y,resourceName:Z,apiVersion:B||"2024-08-01-preview"})(X);let F=this.buildAzureBaseUrl(J,X);return H({name:"azure-openai",apiKey:Y,baseURL:F,headers:{...$,"api-key":Y},queryParams:{"api-version":B||"2024-08-01-preview"}})(X)}case"azure":{let Z=this.extractAzureResourceName(J);if(Z)return I({apiKey:Y,resourceName:Z,apiVersion:B||"2024-08-01-preview"})(X);let F=this.buildAzureBaseUrl(J,X);return H({name:"azure-openai",apiKey:Y,baseURL:F,headers:{...$,"api-key":Y},queryParams:{"api-version":B||"2024-08-01-preview"}})(X)}case"deepseek":return A({apiKey:Y,baseURL:J||void 0,headers:$})(X);default:return H({name:q,apiKey:Y,baseURL:J,headers:$})(X)}}extractAzureResourceName(Q){if(!Q)return;let q=Q.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return q?q[1]:void 0}buildAzureBaseUrl(Q,q){if(!Q)return"";let Y=Q.replace(/\/$/,"").replace(/\?.*$/,"");if(Y.includes("/openai/deployments/"))return Y;return`${Y}/openai/deployments/${q}`}isGeminiOfficialUrl(Q){return Q.includes("generativelanguage.googleapis.com")||Q.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(Q){let q=Q?.trim();if(!q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}flattenDeepSeekThinkingToolHistory(Q){let q=[],Y,J=()=>{if(!Y)return;q.push({role:"assistant",content:V(Y.content).trim()||"I will use the requested tool and continue from its result."}),Y=void 0};for(let X of Q){if(X.role==="system"){J(),q.push({role:"user",content:`<system>
1
+ import{Qb as R}from"./chunk-1tzcptyb.js";var m=["anthropic","openai","deepseek","google-generative-ai","groq","openrouter"],d={anthropic:"",openai:"","google-generative-ai":"",deepseek:"",groq:"",openrouter:"",azure:"",ollama:"",together:"",fireworks:"",mistral:"",cohere:"",perplexity:"",xai:"",default:""},g={anthropic:"https://api.anthropic.com",openai:"https://api.openai.com/v1",google:"https://generativelanguage.googleapis.com/v1beta",deepseek:"https://api.deepseek.com/v1",groq:"https://api.groq.com/openai/v1",openrouter:"https://openrouter.ai/api/v1",togetherai:"https://api.together.xyz/v1","fireworks-ai":"https://api.fireworks.ai/inference/v1",mistral:"https://api.mistral.ai/v1",cohere:"https://api.cohere.ai/v1",perplexity:"https://api.perplexity.ai",xai:"https://api.x.ai/v1",cerebras:"https://api.cerebras.ai/v1","novita-ai":"https://api.novita.ai/v3/openai",nvidia:"https://integrate.api.nvidia.com/v1"},h={anthropic:{"anthropic-beta":"claude-code-20250219,interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14"},openrouter:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"},vercel:{"http-referer":"https://github.com/anthropics/blade","x-title":"blade"},zenmux:{"HTTP-Referer":"https://github.com/anthropics/blade","X-Title":"blade"}},T=(Q)=>{return h[Q]||{}};import{createAnthropic as A}from"@ai-sdk/anthropic";import{createAzure as U}from"@ai-sdk/azure";import{createDeepSeek as C}from"@ai-sdk/deepseek";import{createGoogleGenerativeAI as I}from"@ai-sdk/google";import{createOpenAI as M}from"@ai-sdk/openai";import{createOpenAICompatible as H}from"@ai-sdk/openai-compatible";import{generateText as v,jsonSchema as f,streamText as b}from"ai";var k=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function E(Q){return typeof Q==="string"&&k.has(Q)}function i(Q){if(!Q.aborted)return;if(E(Q.reason))return Q.reason;return"user-cancel"}function t(Q){if(E(Q))return!0;if(!(Q instanceof Error))return!1;if(Q.name==="AbortError")return!0;if(Q instanceof DOMException&&Q.name==="AbortError")return!0;if(Q.message.includes("aborted"))return!0;return!1}function r(...Q){let q=Q.filter(Boolean);if(q.length===0)return new AbortController().signal;if(q.length===1)return q[0];let Y=AbortSignal;if(typeof Y.any==="function")return Y.any(q);for(let $ of q)if($.aborted)return $;let J=new AbortController,X=new Map;for(let $ of q){let B=()=>{J.abort($.reason);for(let[Z,F]of X)Z.removeEventListener("abort",F)};X.set($,B)}for(let[$,B]of X)$.addEventListener("abort",B,{once:!0});return J.signal}function D(Q,q,Y){let J=Y?.throwOnAbort??!1;if(q?.aborted){if(J)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((X,$)=>{let B,Z=setTimeout(()=>{if(q&&B)q.removeEventListener("abort",B);X()},Q);if(q)B=()=>{if(clearTimeout(Z),J)$(new DOMException("Aborted","AbortError"));else X()},q.addEventListener("abort",B,{once:!0})})}var N=R("Chat");function y(Q){let q=[];for(let Y=0;Y<Q.length;Y++){let J=Q[Y];if(J.role==="tool")continue;let X=J.role==="assistant"&&J.tool_calls?.length?J.tool_calls:void 0;if(!X){q.push(J);continue}let $=[],B=Y+1;while(B<Q.length&&Q[B].role==="tool")$.push(Q[B]),B++;let Z=new Set(X.map((_)=>_.id)),F=$.filter((_)=>_.tool_call_id&&Z.has(_.tool_call_id)),W=new Set(F.flatMap((_)=>_.tool_call_id?[_.tool_call_id]:[]));if(Z.size===X.length&&F.length===Z.size&&W.size===Z.size&&[...W].every((_)=>Z.has(_)))q.push(J,...F);Y=B-1}return q}function V(Q){if(typeof Q==="string")return Q;return Q.filter((q)=>q.type==="text").map((q)=>q.text).join(`
2
+ `)}function S(Q){let q=Q;return q.text??q.textDelta??q.delta}function u(Q,q={}){try{return JSON.parse(Q)}catch{return N.warn("[VercelAIChatService] Failed to parse JSON, using fallback",{str:Q}),q}}class O{model;config;constructor(Q){this.config=Q,this.model=this.createModel(Q),N.debug("[VercelAIChatService] Initialized",{provider:Q.provider,model:Q.model})}createModel(Q){let{provider:q,apiKey:Y,baseUrl:J,model:X,customHeaders:$,apiVersion:B}=Q;switch(q){case"openai":return M({apiKey:Y,baseURL:J||void 0,headers:$})(X);case"anthropic":return A({apiKey:Y,baseURL:J||void 0,headers:$})(X);case"gemini":{if(J&&!this.isGeminiOfficialUrl(J))return H({name:"gemini",apiKey:Y,baseURL:J,headers:$})(X);return I({apiKey:Y,baseURL:J||void 0})(X)}case"google":case"google-generative-ai":case"google-vertex":{if(J&&!this.isGeminiOfficialUrl(J))return H({name:q,apiKey:Y,baseURL:J,headers:$})(X);return I({apiKey:Y,baseURL:J||void 0})(X)}case"azure-openai":{let Z=this.extractAzureResourceName(J);if(Z)return U({apiKey:Y,resourceName:Z,apiVersion:B||"2024-08-01-preview"})(X);let F=this.buildAzureBaseUrl(J,X);return H({name:"azure-openai",apiKey:Y,baseURL:F,headers:{...$,"api-key":Y},queryParams:{"api-version":B||"2024-08-01-preview"}})(X)}case"azure":{let Z=this.extractAzureResourceName(J);if(Z)return U({apiKey:Y,resourceName:Z,apiVersion:B||"2024-08-01-preview"})(X);let F=this.buildAzureBaseUrl(J,X);return H({name:"azure-openai",apiKey:Y,baseURL:F,headers:{...$,"api-key":Y},queryParams:{"api-version":B||"2024-08-01-preview"}})(X)}case"deepseek":return C({apiKey:Y,baseURL:J||void 0,headers:$})(X);default:return H({name:q,apiKey:Y,baseURL:J,headers:$})(X)}}extractAzureResourceName(Q){if(!Q)return;let q=Q.match(/https:\/\/([^.]+)\.openai\.azure(?:\.com|\.us|\.cn|\.de)/);return q?q[1]:void 0}buildAzureBaseUrl(Q,q){if(!Q)return"";let Y=Q.replace(/\/$/,"").replace(/\?.*$/,"");if(Y.includes("/openai/deployments/"))return Y;return`${Y}/openai/deployments/${q}`}isGeminiOfficialUrl(Q){return Q.includes("generativelanguage.googleapis.com")||Q.includes("aiplatform.googleapis.com")}needsThinkingReplayMetadata(){return/deepseek/i.test([this.config.provider,this.config.model,this.config.baseUrl].join(" "))}getThinkingReplayProviderOptions(Q){let q=Q?.trim();if(!q||!this.needsThinkingReplayMetadata())return;return{openaiCompatible:{reasoning_content:q}}}shouldFlattenDeepSeekThinkingToolHistory(){return this.needsThinkingReplayMetadata()}flattenDeepSeekThinkingToolHistory(Q){let q=[],Y,J=()=>{if(!Y)return;q.push({role:"assistant",content:V(Y.content).trim()||"I will use the requested tool and continue from its result."}),Y=void 0};for(let X of Q){if(X.role==="system"){J(),q.push({role:"user",content:`<system>
3
3
  ${V(X.content)}
4
4
  </system>`});continue}if(X.role==="assistant"&&X.tool_calls&&X.tool_calls.length>0&&X.reasoningContent?.trim()){J(),Y=X;continue}if(X.role==="tool"&&Y){let $=Y.tool_calls?.find((Z)=>Z.id===X.tool_call_id),B=$?.type==="function"?$.function:void 0;q.push({role:"user",content:`Tool result for ${X.name||B?.name||"tool"}${B?.arguments?`(${B.arguments})`:""}:
5
5
  ${V(X.content)}
6
6
 
7
- Continue from this tool result.`});continue}J(),q.push(X)}return J(),q}convertMessages(Q){let q=[],Y=this.needsThinkingReplayMetadata(),J=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(Q):Q;for(let X of J)if(X.role==="system")if(Array.isArray(X.content)){let $=X.content.find((Z)=>Z.type==="text"),B={role:"system",content:V(X.content)};if($?.providerOptions)B.providerOptions=$.providerOptions;q.push(B)}else q.push({role:"system",content:X.content});else if(X.role==="user")if(Array.isArray(X.content)){let $=X.content.map((B)=>{if(B.type==="text"){let Z={type:"text",text:B.text};if(B.providerOptions)Z.providerOptions=B.providerOptions;return Z}return{type:"image",image:B.image_url.url}});q.push({role:"user",content:$})}else q.push({role:"user",content:X.content});else if(X.role==="assistant")if(X.tool_calls&&X.tool_calls.length>0){let $=X.tool_calls.map((W)=>{let G=W.function;return{type:"tool-call",toolCallId:W.id,toolName:G?.name||"",input:u(G?.arguments||"{}",{})}}),B=V(X.content),Z=Y&&X.reasoningContent?.trim()?[{type:"reasoning",text:X.reasoningContent}]:[],F=this.getThinkingReplayProviderOptions(X.reasoningContent);if(B){let W={role:"assistant",content:[...Z,{type:"text",text:B},...$]};if(F)W.providerOptions=F;q.push(W)}else if(Z.length>0){let W={role:"assistant",content:[...Z,...$]};if(F)W.providerOptions=F;q.push(W)}else q.push({role:"assistant",content:$})}else if(Y&&X.reasoningContent?.trim()){let $=V(X.content),B=[{type:"reasoning",text:X.reasoningContent}];if($)B.push({type:"text",text:$});let Z={role:"assistant",content:B},F=this.getThinkingReplayProviderOptions(X.reasoningContent);if(F)Z.providerOptions=F;q.push(Z)}else q.push({role:"assistant",content:V(X.content)});else if(X.role==="tool")q.push({role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:X.name||"unknown",output:{type:"text",value:V(X.content)}}]});if(this.config.enablePromptCaching&&this.config.provider==="anthropic"){let X=0;for(let $ of q)if($.role==="system"&&X<2)$.providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}},X++;for(let $=q.length-1;$>=0;$--)if(q[$].role==="user"){q[$].providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}};break}}return q}convertTools(Q){if(!Q||Q.length===0)return;let q={};for(let Y of Q)q[Y.name]={description:Y.description,inputSchema:f(Y.parameters)};return q}convertToolCalls(Q){return Q.map((q)=>({id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.args??q.input??{})}}))}convertUsage(Q,q){if(!Q)return;let Y=Q.promptTokens??Q.inputTokens??0,J=Q.completionTokens??Q.outputTokens??0,X={promptTokens:Y,completionTokens:J,totalTokens:Q.totalTokens??Y+J};if(Q.reasoningTokens)X.reasoningTokens=Q.reasoningTokens;if(q?.anthropic){if(q.anthropic.cacheCreationInputTokens!==void 0)X.cacheCreationInputTokens=q.anthropic.cacheCreationInputTokens;if(q.anthropic.cacheReadInputTokens!==void 0)X.cacheReadInputTokens=q.anthropic.cacheReadInputTokens}return X}isFallbackableError(Q){let q=[],Y=new Set,J=Q;while(J&&!Y.has(J)){if(q.push(J),Y.add(J),typeof J!=="object")break;let Z=J;J=Z.lastError??Z.cause}let X=q.filter((Z)=>Z instanceof Error).map((Z)=>Z.message.toLowerCase()),$=X.join(`
8
- `);if(["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"].some((Z)=>$.includes(Z)))return!1;let B=["timeout","timed out","econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","socket hang up","connection reset","connection refused"];if(B.some((Z)=>$.includes(Z)))return!0;for(let Z of q){if(!Z||typeof Z!=="object")continue;let F=Z,W=F.status??F.statusCode??F.response?.status??F.response?.statusCode;if(W!==void 0&&([408,409,429].includes(W)||W>=500))return!0;let G=F.code;if(typeof G==="string"&&B.some((L)=>G.toLowerCase().includes(L)))return!0}for(let Z of X){let F=Z.match(/\bstatus(?:\s+code)?[:\s]*(\d{3})\b/),W=F?Number(F[1]):void 0;if(W!==void 0&&([408,409,429].includes(W)||W>=500))return!0}return!1}async retryWithBackoff(Q,q,Y=2,J=1000){let X;for(let $=0;$<=Y;$++)try{return await Q()}catch(B){if(X=B,q?.aborted)await D(0,q,{throwOnAbort:!0});if($>=Y)break;if(!this.isFallbackableError(B))throw B;let Z=J*Math.pow(2,$);z.debug(`[VercelAIChatService] Retry ${$+1}/${Y} after ${Z}ms`),await D(Z,q,{throwOnAbort:!0})}throw X}getFallbackModelIds(){let Q=[];if(this.config.fallbackModels&&this.config.fallbackModels.length>0)Q.push(...this.config.fallbackModels);else if(this.config.fallbackModel)Q.push(this.config.fallbackModel);return Q}getThinkingProviderOptions(){if(!this.config.supportsThinking)return;let Q=this.config.thinkingMode??"budget";if(Q==="off")return;let q=Q==="adaptive",Y=this.config.thinkingBudget??1e4;if(this.config.provider==="anthropic")return{anthropic:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Y}}};if(this.config.provider==="deepseek"||/deepseek/i.test(this.config.model))return{deepseek:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Y}}};return}getStreamTextOptions(Q,q,Y,J){let X=J;if(this.config.timeout&&this.config.timeout>0){let Z=AbortSignal.timeout(this.config.timeout);if(J)X=AbortSignal.any([J,Z]);else X=Z}let $={model:Q,messages:q,tools:Y,maxOutputTokens:this.config.maxOutputTokens,maxRetries:0,temperature:this.config.temperature??0,abortSignal:X,allowSystemInMessages:!0},B=this.getThinkingProviderOptions();if(B)$.providerOptions=B;return $}async chat(Q,q,Y){let J=Date.now();z.debug("[VercelAIChatService] Starting chat request");let X=x(Q),$=this.convertMessages(X),B=this.convertTools(q),Z=async(F)=>{let W=await v(this.getStreamTextOptions(F,$,B,Y)),G=W.toolCalls&&W.toolCalls.length>0?this.convertToolCalls(W.toolCalls):void 0,L=Array.isArray(W.reasoning)?W.reasoning.map((P)=>P.text).join(""):void 0;return{content:W.text,reasoningContent:L,toolCalls:G,usage:this.convertUsage(W.usage,W.providerMetadata),finishReason:W.finishReason}};try{return await this.retryWithBackoff(()=>Z(this.model),Y,this.config.maxRetries)}catch(F){let W=Date.now()-J;if(z.error("[VercelAIChatService] Chat failed after",W,"ms"),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(!this.isFallbackableError(F))throw F;let G=this.getFallbackModelIds();if(G.length===0)throw F;for(let L of G){z.warn(`[VercelAIChatService] Trying fallback model: ${L}`);let P=this.createModel({...this.config,model:L});try{return await Z(P)}catch(_){if(z.warn(`[VercelAIChatService] Fallback ${L} failed: ${_ instanceof Error?_.message:_}`),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(!this.isFallbackableError(_))throw _}}throw F}}async*streamChat(Q,q,Y){let J=Date.now();z.debug("[VercelAIChatService] Starting stream request");let X=x(Q),$=this.convertMessages(X),B=this.convertTools(q),Z=async function*(_,N){let j=b(_.getStreamTextOptions(N,$,B,Y)),K=0;for await(let w of j.fullStream)switch(w.type){case"text-delta":yield{content:y(w)};break;case"reasoning-delta":yield{reasoningContent:y(w)};break;case"tool-call":yield{toolCalls:[{index:K++,id:w.toolCallId,type:"function",function:{name:w.toolName,arguments:JSON.stringify(w.args??w.input??{})}}]};break;case"finish":yield{finishReason:w.finishReason,usage:_.convertUsage(w.totalUsage,w.providerMetadata)};break}},F=this.config.maxRetries??2,W,G=!1;for(let _=0;_<=F;_++)try{for await(let j of Z(this,this.model))G=!0,yield j;let N=Date.now()-J;z.debug("[VercelAIChatService] Stream completed in",N,"ms");return}catch(N){if(W=N,Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(G)throw N;if(!this.isFallbackableError(N))throw N;if(_<F){let j=1000*Math.pow(2,_);z.debug(`[VercelAIChatService] Stream retry ${_+1}/${F} after ${j}ms`),await D(j,Y,{throwOnAbort:!0});continue}}let L=Date.now()-J;z.error("[VercelAIChatService] Stream failed after",L,"ms");let P=this.getFallbackModelIds();if(P.length===0)throw W;for(let _ of P){z.warn(`[VercelAIChatService] Stream fallback: ${_}`),yield{modelFallback:!0};let N=this.createModel({...this.config,model:_}),j=!1;try{for await(let K of Z(this,N))j=!0,yield K;return}catch(K){if(z.warn(`[VercelAIChatService] Stream fallback ${_} failed`),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(j)throw K;if(!this.isFallbackableError(K))throw K}}throw W}getConfig(){return{...this.config}}updateConfig(Q){z.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...Q},this.model=this.createModel(this.config),z.debug("[VercelAIChatService] Configuration updated")}}var c=R("Service");async function Gq(Q){let q=Q;if(q.provider){let Y=T(q.provider);if(Object.keys(Y).length>0)q={...q,customHeaders:{...Y,...q.customHeaders}},c.debug(`Injected ${q.provider} specific headers:`,Object.keys(Y))}return p(q)}function p(Q){return new O(Q)}
9
- export{m as ub,d as vb,g as wb,n as xb,t as yb,r as zb,Gq as Ab};
7
+ Continue from this tool result.`});continue}J(),q.push(X)}return J(),q}convertMessages(Q){let q=[],Y=this.needsThinkingReplayMetadata(),J=this.shouldFlattenDeepSeekThinkingToolHistory()?this.flattenDeepSeekThinkingToolHistory(Q):Q;for(let X of J)if(X.role==="system")if(Array.isArray(X.content)){let $=X.content.find((Z)=>Z.type==="text"),B={role:"system",content:V(X.content)};if($?.providerOptions)B.providerOptions=$.providerOptions;q.push(B)}else q.push({role:"system",content:X.content});else if(X.role==="user")if(Array.isArray(X.content)){let $=X.content.map((B)=>{if(B.type==="text"){let Z={type:"text",text:B.text};if(B.providerOptions)Z.providerOptions=B.providerOptions;return Z}return{type:"image",image:B.image_url.url}});q.push({role:"user",content:$})}else q.push({role:"user",content:X.content});else if(X.role==="assistant")if(X.tool_calls&&X.tool_calls.length>0){let $=X.tool_calls.map((W)=>{let z=W.function;return{type:"tool-call",toolCallId:W.id,toolName:z?.name||"",input:u(z?.arguments||"{}",{})}}),B=V(X.content),Z=Y&&X.reasoningContent?.trim()?[{type:"reasoning",text:X.reasoningContent}]:[],F=this.getThinkingReplayProviderOptions(X.reasoningContent);if(B){let W={role:"assistant",content:[...Z,{type:"text",text:B},...$]};if(F)W.providerOptions=F;q.push(W)}else if(Z.length>0){let W={role:"assistant",content:[...Z,...$]};if(F)W.providerOptions=F;q.push(W)}else q.push({role:"assistant",content:$})}else if(Y&&X.reasoningContent?.trim()){let $=V(X.content),B=[{type:"reasoning",text:X.reasoningContent}];if($)B.push({type:"text",text:$});let Z={role:"assistant",content:B},F=this.getThinkingReplayProviderOptions(X.reasoningContent);if(F)Z.providerOptions=F;q.push(Z)}else q.push({role:"assistant",content:V(X.content)});else if(X.role==="tool")q.push({role:"tool",content:[{type:"tool-result",toolCallId:X.tool_call_id,toolName:X.name||"unknown",output:{type:"text",value:V(X.content)}}]});if(this.config.enablePromptCaching&&this.config.provider==="anthropic"){let X=0;for(let $ of q)if($.role==="system"&&X<2)$.providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}},X++;for(let $=q.length-1;$>=0;$--)if(q[$].role==="user"){q[$].providerOptions={anthropic:{cacheControl:{type:"ephemeral"}}};break}}return q}convertTools(Q){if(!Q||Q.length===0)return;let q={};for(let Y of Q)q[Y.name]={description:Y.description,inputSchema:f(Y.parameters)};return q}convertToolCalls(Q){return Q.map((q)=>({id:q.toolCallId,type:"function",function:{name:q.toolName,arguments:JSON.stringify(q.args??q.input??{})}}))}convertUsage(Q,q){if(!Q)return;let Y=Q.promptTokens??Q.inputTokens??0,J=Q.completionTokens??Q.outputTokens??0,X={promptTokens:Y,completionTokens:J,totalTokens:Q.totalTokens??Y+J};if(Q.reasoningTokens)X.reasoningTokens=Q.reasoningTokens;if(q?.anthropic){if(q.anthropic.cacheCreationInputTokens!==void 0)X.cacheCreationInputTokens=q.anthropic.cacheCreationInputTokens;if(q.anthropic.cacheReadInputTokens!==void 0)X.cacheReadInputTokens=q.anthropic.cacheReadInputTokens}return X}isFallbackableError(Q){let q=[],Y=new Set,J=Q;while(J&&!Y.has(J)){if(q.push(J),Y.add(J),typeof J!=="object")break;let Z=J;J=Z.lastError??Z.cause}let X=q.filter((Z)=>Z instanceof Error).map((Z)=>Z.message.toLowerCase()),$=X.join(`
8
+ `);if(["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"].some((Z)=>$.includes(Z)))return!1;let B=["timeout","timed out","econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","socket hang up","connection reset","connection refused"];if(B.some((Z)=>$.includes(Z)))return!0;for(let Z of q){if(!Z||typeof Z!=="object")continue;let F=Z,W=F.status??F.statusCode??F.response?.status??F.response?.statusCode;if(W!==void 0&&([408,409,429].includes(W)||W>=500))return!0;let z=F.code;if(typeof z==="string"&&B.some((_)=>z.toLowerCase().includes(_)))return!0}for(let Z of X){let F=Z.match(/\bstatus(?:\s+code)?[:\s]*(\d{3})\b/),W=F?Number(F[1]):void 0;if(W!==void 0&&([408,409,429].includes(W)||W>=500))return!0}return!1}async retryWithBackoff(Q,q,Y=2,J=1000){let X;for(let $=0;$<=Y;$++)try{return await Q()}catch(B){if(X=B,q?.aborted)await D(0,q,{throwOnAbort:!0});if($>=Y)break;if(!this.isFallbackableError(B))throw B;let Z=J*Math.pow(2,$);N.debug(`[VercelAIChatService] Retry ${$+1}/${Y} after ${Z}ms`),await D(Z,q,{throwOnAbort:!0})}throw X}getFallbackModelIds(){let Q=[];if(this.config.fallbackModels&&this.config.fallbackModels.length>0)Q.push(...this.config.fallbackModels);else if(this.config.fallbackModel)Q.push(this.config.fallbackModel);return Q}getThinkingProviderOptions(){if(!this.config.supportsThinking)return;let Q=this.config.thinkingMode??"budget";if(Q==="off")return;let q=Q==="adaptive",Y=this.config.thinkingBudget??1e4;if(this.config.provider==="anthropic")return{anthropic:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Y}}};if(this.config.provider==="deepseek"||/deepseek/i.test(this.config.model))return{deepseek:{thinking:q?{type:"enabled",budgetTokens:0}:{type:"enabled",budgetTokens:Y}}};return}getStreamTextOptions(Q,q,Y,J){let X=J;if(this.config.timeout&&this.config.timeout>0){let Z=AbortSignal.timeout(this.config.timeout);if(J)X=AbortSignal.any([J,Z]);else X=Z}let $={model:Q,messages:q,tools:Y,maxOutputTokens:this.config.maxOutputTokens,maxRetries:0,temperature:this.config.temperature??0,abortSignal:X,allowSystemInMessages:!0},B=this.getThinkingProviderOptions();if(B)$.providerOptions=B;return $}async chat(Q,q,Y){let J=Date.now();N.debug("[VercelAIChatService] Starting chat request");let X=y(Q),$=this.convertMessages(X),B=this.convertTools(q),Z=async(F)=>{let W=await v(this.getStreamTextOptions(F,$,B,Y)),z=W.toolCalls&&W.toolCalls.length>0?this.convertToolCalls(W.toolCalls):void 0,_=Array.isArray(W.reasoning)?W.reasoning.map((P)=>P.text).join(""):void 0;return{content:W.text,reasoningContent:_,toolCalls:z,usage:this.convertUsage(W.usage,W.providerMetadata),finishReason:W.finishReason}};try{return await this.retryWithBackoff(()=>Z(this.model),Y,this.config.maxRetries)}catch(F){let W=Date.now()-J;if(N.error("[VercelAIChatService] Chat failed after",W,"ms"),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(!this.isFallbackableError(F))throw F;let z=this.getFallbackModelIds();if(z.length===0)throw F;for(let _ of z){N.warn(`[VercelAIChatService] Trying fallback model: ${_}`);let P=this.createModel({...this.config,model:_});try{return await Z(P)}catch(G){if(N.warn(`[VercelAIChatService] Fallback ${_} failed: ${G instanceof Error?G.message:G}`),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(!this.isFallbackableError(G))throw G}}throw F}}async*streamChat(Q,q,Y){let J=Date.now();N.debug("[VercelAIChatService] Starting stream request");let X=y(Q),$=this.convertMessages(X),B=this.convertTools(q),Z=async function*(G,w){let j=b(G.getStreamTextOptions(w,$,B,Y)),K=0;for await(let L of j.fullStream)switch(L.type){case"text-delta":yield{content:S(L)};break;case"reasoning-delta":yield{reasoningContent:S(L)};break;case"tool-call":yield{toolCalls:[{index:K++,id:L.toolCallId,type:"function",function:{name:L.toolName,arguments:JSON.stringify(L.args??L.input??{})}}]};break;case"finish":yield{finishReason:L.finishReason,usage:G.convertUsage(L.totalUsage,L.providerMetadata)};break}},F=this.config.maxRetries??2,W,z=!1;for(let G=0;G<=F;G++)try{for await(let j of Z(this,this.model))z=!0,yield j;let w=Date.now()-J;N.debug("[VercelAIChatService] Stream completed in",w,"ms");return}catch(w){if(W=w,Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(z)throw w;if(!this.isFallbackableError(w))throw w;if(G<F){let j=1000*Math.pow(2,G);N.debug(`[VercelAIChatService] Stream retry ${G+1}/${F} after ${j}ms`),await D(j,Y,{throwOnAbort:!0});continue}}let _=Date.now()-J;N.error("[VercelAIChatService] Stream failed after",_,"ms");let P=this.getFallbackModelIds();if(P.length===0)throw W;for(let G of P){N.warn(`[VercelAIChatService] Stream fallback: ${G}`),yield{modelFallback:!0};let w=this.createModel({...this.config,model:G}),j=!1;try{for await(let K of Z(this,w))j=!0,yield K;return}catch(K){if(N.warn(`[VercelAIChatService] Stream fallback ${G} failed`),Y?.aborted)await D(0,Y,{throwOnAbort:!0});if(j)throw K;if(!this.isFallbackableError(K))throw K}}throw W}getConfig(){return{...this.config}}updateConfig(Q){N.debug("[VercelAIChatService] Updating configuration"),this.config={...this.config,...Q},this.model=this.createModel(this.config),N.debug("[VercelAIChatService] Configuration updated")}}var p=R("Service");async function Gq(Q){let q=Q;if(q.provider){let Y=T(q.provider);if(Object.keys(Y).length>0)q={...q,customHeaders:{...Y,...q.customHeaders}},p.debug(`Injected ${q.provider} specific headers:`,Object.keys(Y))}return c(q)}function c(Q){return new O(Q)}
9
+ export{m as xb,d as yb,g as zb,i as Ab,t as Bb,r as Cb,Gq as Db};
@@ -1 +1 @@
1
- import{a as o}from"./chunk-gjf2d2yg.js";import"./chunk-kfg3vx5z.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-m3hsaaq5.js";import"./chunk-64x50qbc.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};
@@ -0,0 +1,26 @@
1
+ import{wb as V}from"./chunk-cadngkwr.js";import{Qb as j}from"./chunk-1tzcptyb.js";var G={currentModelId:"",models:[],temperature:0,maxContextTokens:128000,maxOutputTokens:void 0,stream:!0,topP:0.9,topK:50,timeout:180000,theme:"dracula",uiTheme:"system",language:"zh-CN",fontSize:14,autoSaveSessions:!0,notifyBuild:!0,notifyErrors:!1,notifySounds:!1,privacyTelemetry:!1,privacyCrash:!0,debug:!1,mcpEnabled:!1,mcpServers:{},permissions:{allow:["Bash(pwd)","Bash(which *)","Bash(whoami)","Bash(hostname)","Bash(uname *)","Bash(date)","Bash(echo *)","Bash(ls *)","Bash(tree *)","Bash(git status)","Bash(git status -*)","Bash(git log *)","Bash(git diff *)","Bash(git show *)","Bash(git branch -* *)","Bash(git branch)","Bash(git tag -l *)","Bash(git tag --list *)","Bash(git stash list *)","Bash(git stash show *)","Bash(git rev-parse *)","Bash(git describe *)","Bash(git blame *)","Bash(git ls-files *)","Bash(git config --get *)","Bash(git config --list *)","Bash(git shortlog *)","Bash(git merge-base *)","Bash(git cat-file *)","Bash(git for-each-ref *)","Bash(git grep *)","Bash(git worktree list *)","Bash(git reflog show *)","Bash(git reflog)","Bash(git rev-list *)","Bash(git ls-remote *)","Bash(git remote -v)","Bash(git remote --verbose)","Bash(git remote)","Bash(gh pr view *)","Bash(gh pr list *)","Bash(gh pr diff *)","Bash(gh pr checks *)","Bash(gh pr status *)","Bash(gh issue view *)","Bash(gh issue list *)","Bash(gh issue status *)","Bash(gh run list *)","Bash(gh run view *)","Bash(gh repo view *)","Bash(gh auth status)","Bash(npm list *)","Bash(bun pm ls *)","Bash(npm view *)","Bash(npm outdated *)","Bash(pnpm list *)","Bash(yarn list *)","Bash(pip list *)","Bash(pip show *)"],ask:["Bash(curl *)","Bash(wget *)","Bash(aria2c *)","Bash(axel *)","Bash(rm -rf *)","Bash(rm -r *)","Bash(rm --recursive *)","Bash(nc *)","Bash(netcat *)","Bash(telnet *)","Bash(ncat *)"],deny:["Read(./.env)","Read(./.env.*)","Bash(rm -rf /)","Bash(rm -rf /*)","Bash(sudo *)","Bash(chmod 777 *)","Bash(bash *)","Bash(sh *)","Bash(zsh *)","Bash(fish *)","Bash(dash *)","Bash(eval *)","Bash(source *)","Bash(mkfs *)","Bash(fdisk *)","Bash(dd *)","Bash(format *)","Bash(parted *)","Bash(open http*)","Bash(open https*)","Bash(xdg-open http*)","Bash(xdg-open https*)"]},permissionMode:"default",hooks:{enabled:!1,defaultTimeout:60,timeoutBehavior:"ignore",failureBehavior:"ignore",maxConcurrentHooks:5,PreToolUse:[],PostToolUse:[],PostToolUseFailure:[],PermissionRequest:[],UserPromptSubmit:[],SessionStart:[],SessionEnd:[],Stop:[],SubagentStop:[],Notification:[],Compaction:[]},env:{},disableAllHooks:!1,maxTurns:-1};import{promises as I}from"fs";import{merge as A}from"lodash-es";import R from"os";import $ from"path";var w={sonnet:"claude-sonnet-4-20250514",opus:"claude-opus-4-20250514",haiku:"claude-3-5-haiku-20241022",claude:"claude-sonnet-4-20250514",gpt4o:"gpt-4o",gpt4:"gpt-4o",o1:"o1",o3:"o3","o4-mini":"o4-mini",deepseek:"deepseek-chat","deepseek-v3":"deepseek-chat","deepseek-r1":"deepseek-reasoner","deepseek-v4":"deepseek-v4-0324",gemini:"gemini-2.5-pro",flash:"gemini-2.5-flash",qwen:"qwen3-235b-a22b","qwen-max":"qwen-max","qwen-plus":"qwen-plus"};function _(H){let q=H.toLowerCase().trim();return w[q]??H}class N{static instance=null;runtimePermissionOverrides;constructor(){}static getInstance(){if(!N.instance)N.instance=new N;return N.instance}static resetInstance(){N.instance=null}async initialize(H){try{this.runtimePermissionOverrides=H?.permissions;let q=await this.loadConfigFiles(),J=await this.loadSettingsFiles(),K={...q,...J};if(H)K=this.mergeSettings(K,H);let Q=this.normalizeConfig(K),W={...G,...Q};if(this.resolveEnvInterpolation(W),process.env.BLADE_MODEL&&W.models?.length>0){let X=_(process.env.BLADE_MODEL),Y=W.models.find((Z)=>Z.id===X||Z.model===X||Z.id===process.env.BLADE_MODEL||Z.model===process.env.BLADE_MODEL);if(Y)W.currentModelId=Y.id}if(process.env.BLADE_API_KEY&&W.models?.length>0){let X=W.models.find((Y)=>Y.id===W.currentModelId);if(X)X.apiKey=process.env.BLADE_API_KEY}if(process.env.BLADE_BASE_URL&&W.models?.length>0){let X=W.models.find((Y)=>Y.id===W.currentModelId);if(X)X.baseUrl=process.env.BLADE_BASE_URL}if(process.env.BLADE_DEBUG)W.debug=process.env.BLADE_DEBUG==="1"||process.env.BLADE_DEBUG==="true"||process.env.BLADE_DEBUG;if(W.debug)console.log("[ConfigManager] Configuration loaded successfully");return W}catch(q){return console.error("[ConfigManager] Failed to initialize:",q),G}}async loadConfigFiles(){let H=$.join(R.homedir(),".blade","config.json"),q=$.join(V(),".blade","config.json"),J={},K=await this.loadJsonFile(H);if(K)J={...J,...K};let Q=await this.loadJsonFile(q);if(Q){let W={...J.mcpServers||{},...Q.mcpServers||{}};if(J={...J,...Q},Object.keys(W).length>0)J.mcpServers=W}return J}async loadSettingsFiles(){let H=$.join(R.homedir(),".blade","settings.json"),q=$.join(V(),".blade","settings.json"),J=$.join(V(),".blade","settings.local.json"),K={},Q=await this.loadJsonFile(H);if(Q)K=this.mergeSettings(K,Q);let W=await this.loadJsonFile(q);if(W)K=this.mergeSettings(K,W);let X=await this.loadJsonFile(J);if(X)K=this.mergeSettings(K,X);return K}async loadWorkspacePermissions(H,q){let J={allow:[...q.allow],ask:[...q.ask],deny:[...q.deny]};if($.resolve(H)!==$.resolve(V())){let Q=await this.loadWorkspacePermissionOverrides(V()),W=await this.loadJsonFile($.join(R.homedir(),".blade","settings.json")),X={allow:Array.from(new Set([...G.permissions.allow,...W?.permissions?.allow||[],...this.runtimePermissionOverrides?.allow||[]])),ask:Array.from(new Set([...G.permissions.ask,...W?.permissions?.ask||[],...this.runtimePermissionOverrides?.ask||[]])),deny:Array.from(new Set([...G.permissions.deny,...W?.permissions?.deny||[],...this.runtimePermissionOverrides?.deny||[]]))};for(let Y of["allow","ask","deny"]){let Z=new Set(Q[Y].filter((D)=>!X[Y].includes(D)));J[Y]=J[Y].filter((D)=>!Z.has(D))}}let K=await this.loadWorkspacePermissionOverrides(H);for(let Q of["allow","ask","deny"])J[Q]=Array.from(new Set([...J[Q],...K[Q]]));return J}async loadWorkspacePermissionOverrides(H){let q={allow:[],ask:[],deny:[]},J=[$.join(H,".blade","settings.json"),$.join(H,".blade","settings.local.json")];for(let K of J){let Q=await this.loadJsonFile(K);if(!Q?.permissions)continue;for(let W of["allow","ask","deny"])q[W]=Array.from(new Set([...q[W],...Q.permissions[W]||[]]))}return q}mergeSettings(H,q){let J={...JSON.parse(JSON.stringify(H)),...JSON.parse(JSON.stringify(q))};if(q.permissions)J.permissions={allow:Array.from(new Set([...H.permissions?.allow||[],...q.permissions.allow||[]])),ask:Array.from(new Set([...H.permissions?.ask||[],...q.permissions.ask||[]])),deny:Array.from(new Set([...H.permissions?.deny||[],...q.permissions.deny||[]]))};if(q.hooks)J.hooks=A({},J.hooks,q.hooks);if(q.env)J.env=A({},J.env,q.env);if(q.mcpServers)J.mcpServers={...J.mcpServers||{},...q.mcpServers};if(q.disableAllHooks!==void 0)J.disableAllHooks=q.disableAllHooks;if(q.permissionMode!==void 0)J.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)J.maxTurns=q.maxTurns;return J}resolveEnvInterpolation(H){let q=/\$\{?([A-Z_][A-Z0-9_]*)(:-([^}]+))?\}?/g,J=(Q)=>{if(typeof Q==="string")return Q.replace(q,(W,X,Y,Z)=>{return process.env[X]||Z||W});if(Array.isArray(Q))return Q.map(J);if(typeof Q==="object"&&Q!==null){let W=Q;for(let[X,Y]of Object.entries(W))W[X]=J(Y);return W}return Q},K=H;for(let[Q,W]of Object.entries(K))K[Q]=J(W)}async loadJsonFile(H){try{if(await this.fileExists(H)){let q=await I.readFile(H,"utf-8");return JSON.parse(q)}}catch(q){console.warn(`[ConfigManager] Failed to load ${H}:`,q)}return null}async fileExists(H){try{return await I.access(H),!0}catch{return!1}}normalizeConfig(H){let q=JSON.parse(JSON.stringify(H)),J=(Q)=>Q.trim().replace(/^`|`$/g,""),K=(Q)=>{for(let[W,X]of Object.entries(Q))if(typeof X==="string")Q[W]=J(X);else if(Array.isArray(X))X.forEach((Y,Z)=>{if(typeof Y==="string")X[Z]=J(Y);else if(typeof Y==="object"&&Y!==null)K(Y)});else if(typeof X==="object"&&X!==null)K(X)};return K(q),q}validateConfig(H){let q=[],J=[];if(!H.models||H.models.length===0)q.push("没有可用的模型配置");if(H.models&&H.models.length>0){if(!H.currentModelId)q.push("未设置当前模型 ID");else if(!H.models.find((Q)=>Q.id===H.currentModelId))q.push(`当前模型 ID "${H.currentModelId}" 在 models 列表中不存在`);for(let K of H.models){let Q=`模型 "${K.name||K.id}"`;if(!K.apiKey)J.push(`${Q}: apiKey 为空`);if(!K.model)q.push(`${Q}: model 字段必填`);if(!K.provider)q.push(`${Q}: provider 字段必填`);if(K.baseUrl&&!K.baseUrl.startsWith("http"))J.push(`${Q}: baseUrl "${K.baseUrl}" 不是有效的 HTTP URL`)}}if(J.length>0)console.warn(`[ConfigManager] 配置警告:
2
+ ${J.map((K)=>` ⚠ ${K}`).join(`
3
+ `)}`);if(q.length>0)throw Error(`配置验证失败:
4
+ ${q.map((K)=>` - ${K}`).join(`
5
+ `)}
6
+
7
+ `+`请通过以下方式之一提供配置:
8
+ `+` 1. 首次启动: 运行 blade,系统会自动引导配置
9
+ `+` 2. 添加模型: blade 后输入 /model add
10
+ `+` 3. 初始化向导: 输入 /init
11
+
12
+ `+`配置文件示例 (~/.blade/config.json):
13
+ `+`{
14
+ "currentModelId": "model-id-123",
15
+ "models": [
16
+ {
17
+ "id": "model-id-123",
18
+ `+` "name": "默认模型",
19
+ `+` "provider": "openai-compatible",
20
+ "apiKey": "your-api-key",
21
+ "baseUrl": "https://api.example.com/v1",
22
+ "model": "model-name"
23
+ }
24
+ ]
25
+ }
26
+ `)}}function x(H,q={}){let J={...H};if(q.debug!==void 0)J.debug=q.debug===""?!0:q.debug;if(q.model){if(!H.models.some((Q)=>Q.id===q.model))throw Error(`模型配置未找到: ${q.model}`);J.currentModelId=q.model}if(q.yolo===!0)J.permissionMode="yolo";else if(q.permissionMode!==void 0)J.permissionMode=q.permissionMode;if(q.maxTurns!==void 0)J.maxTurns=q.maxTurns;return J.systemPrompt=q.systemPrompt,J.appendSystemPrompt=q.appendSystemPrompt,J.model=q.model,J.resumeSessionId=q.sessionId,J.forkSession=q.forkSession,J.allowedTools=q.allowedTools,J.disallowedTools=q.disallowedTools,J.mcpConfigPaths=q.mcpConfig,J.strictMcpConfig=q.strictMcpConfig,J.addDirs=q.addDir,J.outputFormat=q.outputFormat,J.inputFormat=q.inputFormat,J.print=q.print,J.includePartialMessages=q.includePartialMessages,J.replayUserMessages=q.replayUserMessages,J.agentsConfig=q.agents,J.settingSources=q.settingSources,J}import{promises as U}from"node:fs";import E from"node:os";import B from"node:path";import{Mutex as L}from"async-mutex";import{merge as S}from"lodash-es";import b from"write-file-atomic";var M=j("Service"),F={models:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},currentModelId:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},temperature:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxContextTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},maxOutputTokens:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},timeout:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},theme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},uiTheme:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},language:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},debug:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},fontSize:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},autoSaveSessions:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyBuild:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifyErrors:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},notifySounds:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyTelemetry:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},privacyCrash:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},permissionMode:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},permissions:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},hooks:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},env:{target:"settings",defaultScope:"local",mergeStrategy:"deep-merge",persistable:!0},disableAllHooks:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},maxTurns:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!0},mcpServers:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!0},stream:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topP:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},topK:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},mcpEnabled:{target:"config",defaultScope:"global",mergeStrategy:"replace",persistable:!1},systemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},appendSystemPrompt:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},initialMessage:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},resumeSessionId:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},forkSession:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},allowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},disallowedTools:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},mcpConfigPaths:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},strictMcpConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},addDirs:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},outputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},inputFormat:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},print:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},includePartialMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},replayUserMessages:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},agentsConfig:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1},settingSources:{target:"settings",defaultScope:"local",mergeStrategy:"replace",persistable:!1}},Jq=new Set(Object.entries(F).filter(([H,q])=>q.persistable).map(([H])=>H)),Kq=new Set(Object.entries(F).filter(([H,q])=>!q.persistable).map(([H])=>H));class z{static instance=null;pendingUpdates=new Map;timers=new Map;fileLocks=new Map;lastSaveError=null;debounceDelay=300;constructor(){}static getInstance(){if(!z.instance)z.instance=new z;return z.instance}static resetInstance(){if(z.instance)for(let H of z.instance.timers.values())clearTimeout(H);z.instance=null}async save(H,q={}){this.validatePersistableFields(H);let J=this.groupUpdatesByTarget(H,q.scope,q.projectDir);if(q.immediate)await Promise.all(Array.from(J.entries()).map(([K,Q])=>this.flushTarget(K,Q)));else for(let[K,Q]of J)this.scheduleSave(K,Q)}async flush(){for(let q of this.timers.values())clearTimeout(q);this.timers.clear();let H=Array.from(this.pendingUpdates.entries()).map(([q,J])=>this.flushTarget(q,J));this.pendingUpdates.clear(),await Promise.all(H)}getLastSaveError(){return this.lastSaveError}clearLastSaveError(){this.lastSaveError=null}async appendPermissionRule(H,q={}){await this.appendPermissionRuleForDecision(H,"allow",q)}async appendPermissionDenyRule(H,q={}){await this.appendPermissionRuleForDecision(H,"deny",q)}async appendPermissionRuleForDecision(H,q,J){let K=J.scope??"local",Q=this.resolveFilePath("settings",K,J.projectDir);await this.flushTargetWithModifier(Q,(W)=>{let X=W.permissions??{allow:[],ask:[],deny:[]},Y={allow:q==="allow"?this.dedupeArray([...X.allow||[],H]):X.allow||[],ask:X.ask||[],deny:q==="deny"?this.dedupeArray([...X.deny||[],H]):X.deny||[]};return{...W,permissions:Y}})}async appendLocalPermissionRule(H,q={}){await this.appendPermissionRule(H,{...q,scope:"local"})}async appendLocalPermissionDenyRule(H,q={}){await this.appendPermissionDenyRule(H,{...q,scope:"local"})}validatePersistableFields(H){for(let q of Object.keys(H)){let J=F[q];if(!J)throw Error(`Unknown config field: ${q}`);if(!J.persistable)throw Error(`Field "${q}" is non-persistable and cannot be saved to config files. Non-persistable fields are runtime-only and only valid for the current session.`)}}groupUpdatesByTarget(H,q,J){let K=new Map;for(let[Q,W]of Object.entries(H)){let X=F[Q];if(!X)continue;let Y=q??X.defaultScope,Z=this.resolveFilePath(X.target,Y,J);if(!K.has(Z))K.set(Z,{});K.get(Z)[Q]=W}return K}resolveFilePath(H,q,J){let K=J??V();if(H==="config")return q==="global"?B.join(E.homedir(),".blade","config.json"):B.join(K,".blade","config.json");switch(q){case"local":return B.join(K,".blade","settings.local.json");case"project":return B.join(K,".blade","settings.json");case"global":return B.join(E.homedir(),".blade","settings.json");default:return B.join(K,".blade","settings.local.json")}}scheduleSave(H,q){let J=this.pendingUpdates.get(H)??{},K=this.mergePendingUpdates(J,q);this.pendingUpdates.set(H,K);let Q=this.timers.get(H);if(Q)clearTimeout(Q);let W=setTimeout(async()=>{let X=this.pendingUpdates.get(H);if(X){this.pendingUpdates.delete(H),this.timers.delete(H);try{await this.flushTarget(H,X),this.lastSaveError=null}catch(Y){let Z=Y instanceof Error?Y:Error(String(Y));this.lastSaveError=Z,M.error(`Failed to save config to ${H}:`,Z.message),M.error("Stack trace:",Z.stack)}}},this.debounceDelay);this.timers.set(H,W)}mergePendingUpdates(H,q){let J={...H};for(let[K,Q]of Object.entries(q)){let W=F[K];if(!W){J[K]=Q;continue}switch(W.mergeStrategy){case"replace":J[K]=Q;break;case"append-dedupe":this.applyAppendDedupe(J,K,Q);break;case"deep-merge":this.applyDeepMerge(J,K,Q);break}}return J}async flushTarget(H,q){let J=this.fileLocks.get(H);if(!J)J=new L,this.fileLocks.set(H,J);await J.runExclusive(async()=>{await this.performWrite(H,q)})}async flushTargetWithModifier(H,q){let J=this.fileLocks.get(H);if(!J)J=new L,this.fileLocks.set(H,J);await J.runExclusive(async()=>{await U.mkdir(B.dirname(H),{recursive:!0,mode:493});let K={};try{let W=await U.readFile(H,"utf-8");K=JSON.parse(W)}catch{K={}}let Q=q(K);await this.atomicWrite(H,Q)})}async performWrite(H,q){await U.mkdir(B.dirname(H),{recursive:!0,mode:493});let J={};try{let Q=await U.readFile(H,"utf-8");J=JSON.parse(Q)}catch{J={}}let K={...J};for(let[Q,W]of Object.entries(q)){let X=F[Q];if(!X){K[Q]=W;continue}switch(X.mergeStrategy){case"replace":K[Q]=W;break;case"append-dedupe":this.applyAppendDedupe(K,Q,W);break;case"deep-merge":this.applyDeepMerge(K,Q,W);break}}await this.atomicWrite(H,K)}applyAppendDedupe(H,q,J){if(q==="permissions"&&typeof J==="object"&&J!==null){let K=H[q]??{allow:[],ask:[],deny:[]},Q=J;H[q]={allow:this.dedupeArray([...K.allow||[],...Q.allow||[]]),ask:this.dedupeArray([...K.ask||[],...Q.ask||[]]),deny:this.dedupeArray([...K.deny||[],...Q.deny||[]])}}else if(Array.isArray(J)){let K=Array.isArray(H[q])?H[q]:[];H[q]=this.dedupeArray([...K,...J])}else H[q]=J}applyDeepMerge(H,q,J){if(typeof J==="object"&&J!==null&&!Array.isArray(J)){let K=typeof H[q]==="object"&&H[q]!==null?H[q]:{};H[q]=S({},K,J)}else H[q]=J}dedupeArray(H){return Array.from(new Set(H))}async atomicWrite(H,q){await b(H,JSON.stringify(q,null,2),{mode:384,encoding:"utf-8"})}}function y(){return z.getInstance()}export{G as Aa,N as Ba,x as Ca,y as Da};
@@ -1 +1 @@
1
- function f(x){return x!==void 0&&typeof x.pattern==="string"&&typeof x.search_path==="string"}function b(x){return x!==void 0&&x.kind==="edit"&&typeof x.matches_found==="number"}function h(x){return x==="readonly"}export{f as ib,b as jb,h as kb};
1
+ function f(x){return x!==void 0&&typeof x.pattern==="string"&&typeof x.search_path==="string"}function b(x){return x!==void 0&&x.kind==="edit"&&typeof x.matches_found==="number"}function h(x){return x==="readonly"}var v="__aborted__";export{f as jb,b as kb,h as lb,v as mb};
@@ -1,4 +1,4 @@
1
- import{Ea as S,Fa as h}from"./chunk-jsn8476q.js";import{kb as M}from"./chunk-cyxb6fxe.js";import{Nb as c}from"./chunk-kfg3vx5z.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as p}from"lodash-es";function J(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${J(Y)},实际收到 ${J(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(p(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>J($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${J(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>J($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
1
+ import{Fa as S,Ga as h}from"./chunk-arwynrtf.js";import{lb as M}from"./chunk-ezkbqmvd.js";import{Sb as c}from"./chunk-64x50qbc.js";import{EventEmitter as r}from"events";import{z as L}from"zod";import{isPlainObject as p}from"lodash-es";function J(B){if(B===void 0)return"undefined";if(typeof B==="string")return B;try{let G=JSON.stringify(B);return G===void 0?String(B):G}catch{return String(B)}}class R extends Error{issues;type;constructor(B,G,Q="validation_error"){super(B);this.issues=G;this.type=Q;this.name="ToolValidationError"}}function g(B){let{code:G}=B,Q=B,X=Q.received;switch(G){case"invalid_type":{let Y=Q.expected;return`类型错误:期望 ${J(Y)},实际收到 ${J(X)}`}case"too_small":{let{minimum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能少于 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能小于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能少于 ${Y}`;return"值太小"}case"too_big":{let{maximum:Y,inclusive:$}=Q,W=typeof Q.type==="string"?Q.type:void 0;if(W==="string"&&typeof Y==="number")return`长度不能超过 ${Y} 个字符`;if(W==="number"&&typeof Y==="number")return`不能大于${$?"等于":""} ${Y}`;if(W==="array"&&typeof Y==="number")return`数组长度不能超过 ${Y}`;return"值太大"}case"invalid_string":{let Y=Q.validation;if(Y==="email")return"必须是有效的电子邮件地址";if(Y==="url")return"必须是有效的 URL";if(Y==="uuid")return"必须是有效的 UUID";if(p(Y)){let $=Y;if(typeof $.includes==="string")return`必须包含 "${$.includes}"`;if(typeof $.startsWith==="string")return`必须以 "${$.startsWith}" 开头`;if(typeof $.endsWith==="string")return`必须以 "${$.endsWith}" 结尾`}return"字符串格式不正确"}case"invalid_enum_value":{let Y=Q.options;if(Array.isArray(Y))return`必须是以下值之一:${Y.map(($)=>J($)).join(", ")}`;return"必须是枚举允许的值之一"}case"invalid_literal":{let Y=Q.expected;return`必须是字面量值:${J(Y)}`}case"unrecognized_keys":{let Y=Q.keys;if(Array.isArray(Y))return`包含未知的参数:${Y.map(($)=>J($)).join(", ")}`;return"包含未知的参数"}case"invalid_union":return"不符合任何有效的类型定义";case"invalid_date":return"必须是有效的日期";case"custom":return B.message||"自定义验证失败";default:return B.message||"验证失败"}}function u(B){let G=B.issues.map((X)=>{let Y=X.path.join("."),$=g(X),W=X.received;return{field:Y||"root",message:$,value:W}}),Q=G.length===1?`参数验证失败 [${G[0].field}]: ${G[0].message}`:`参数验证失败 (${G.length} 个错误):
2
2
  ${G.map((X)=>` - ${X.field}: ${X.message}`).join(`
3
3
  `)}`;return new R(Q,G)}function y(B,G){let Q=B.safeParse(G);if(!Q.success)throw u(Q.error);return Q.data}import{zodToJsonSchema as l}from"zod-to-json-schema";function H(B){let G=l(B,{target:"jsonSchema7",$refStrategy:"none"});if(G.type==="object"&&G.properties&&!Array.isArray(G.required))G.required=[];return G}class w{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(B,G,Q,X,Y){this.toolName=B;this.params=G;this.executeFn=Q;this.descriptionFn=X;this.affectedPathsFn=Y}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(B,G,Q){let X={signal:B,updateOutput:G,...Q};return this.executeFn(this.params,X)}}function k(B){return{name:B.name,displayName:B.displayName,kind:B.kind,isReadOnly:B.isReadOnly??M(B.kind),isConcurrencySafe:B.isConcurrencySafe??!1,strict:B.strict??!1,description:B.description,version:B.version||"1.0.0",category:B.category,tags:B.tags||[],getFunctionDeclaration(){let G=H(B.schema),Q=B.description.short;if(B.description.long)Q+=`
4
4
 
@@ -31,4 +31,4 @@ ${B.description.important.map((X)=>`[WARN] ${X}`).join(`
31
31
  `),X.close(),G(q)}catch(W){X.close(),Q(W)}});X.on("error",Q),X.listen(Z,()=>{console.log(`[OAuth] Callback server listening on port ${Z}`)}),setTimeout(()=>{X.close(),Q(Error("OAuth callback timeout"))},300000)})}async exchangeCodeForToken(B,G,Q){let X=B.redirectUri||`http://localhost:${Z}${D}`,Y=new URLSearchParams({grant_type:"authorization_code",code:G,redirect_uri:X,code_verifier:Q,client_id:B.clientId});if(B.clientSecret)Y.append("client_secret",B.clientSecret);let $=await fetch(B.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Y.toString()});if(!$.ok){let W=await $.text();throw Error(`Token exchange failed: ${$.status} - ${W}`)}return await $.json()}async refreshAccessToken(B,G){let Q=new URLSearchParams({grant_type:"refresh_token",refresh_token:G,client_id:B.clientId});if(B.clientSecret)Q.append("client_secret",B.clientSecret);if(B.scopes&&B.scopes.length>0)Q.append("scope",B.scopes.join(" "));let X=await fetch(B.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded",Accept:"application/json"},body:Q.toString()});if(!X.ok){let Y=await X.text();throw Error(`Token refresh failed: ${X.status} - ${Y}`)}return await X.json()}async authenticate(B,G){if(!G.clientId||!G.authorizationUrl||!G.tokenUrl)throw Error("Missing required OAuth configuration");let Q=this.generatePKCEParams(),X=this.buildAuthorizationUrl(G,Q);console.log(`
32
32
  [OAuth] Opening browser for authentication...`),console.log(`
33
33
  If the browser does not open automatically, copy and paste this URL:`),console.log(X),console.log("");let Y=this.startCallbackServer(Q.state);try{await this.openAuthorizationUrl(X)}catch(F){console.warn("[OAuth] Failed to open browser automatically:",F)}let $=await Y;console.log("[OAuth] Authorization code received, exchanging for tokens...");let W=await this.exchangeCodeForToken(G,$,Q.codeVerifier),q={accessToken:W.access_token,tokenType:W.token_type||"Bearer",refreshToken:W.refresh_token,scope:W.scope};if(W.expires_in)q.expiresAt=Date.now()+W.expires_in*1000;return await this.tokenStorage.saveToken(B,q,G.clientId,G.tokenUrl),console.log("[OAuth] Authentication successful! Token saved."),q}async openAuthorizationUrl(B){let{command:G,args:Q}=this.getBrowserCommand(B);await new Promise((X,Y)=>{let $=m(G,Q,{stdio:"ignore"});$.once("error",Y),$.once("close",(W)=>{if(W===0||W===null)X();else Y(Error(`Failed to open browser (exit code ${W})`))})})}getBrowserCommand(B){if(process.platform==="darwin")return{command:"open",args:[B]};if(process.platform==="win32")return{command:"cmd",args:["/c","start","",B]};return{command:"xdg-open",args:[B]}}async getValidToken(B,G){let Q=await this.tokenStorage.getCredentials(B);if(!Q)return null;let{token:X}=Q;if(!this.tokenStorage.isTokenExpired(X))return X.accessToken;if(X.refreshToken&&G.clientId&&Q.tokenUrl)try{console.log(`[OAuth] Refreshing expired token for server: ${B}`);let Y=await this.refreshAccessToken(G,X.refreshToken),$={accessToken:Y.access_token,tokenType:Y.token_type,refreshToken:Y.refresh_token||X.refreshToken,scope:Y.scope||X.scope};if(Y.expires_in)$.expiresAt=Date.now()+Y.expires_in*1000;return await this.tokenStorage.saveToken(B,$,G.clientId,Q.tokenUrl),$.accessToken}catch(Y){console.error("[OAuth] Failed to refresh token:",Y),await this.tokenStorage.deleteCredentials(B)}return null}}import{EventEmitter as i}from"events";class E extends i{client;config;checkTimer=null;isChecking=!1;consecutiveFailures=0;lastCheckTime=0;currentStatus="healthy";constructor(B,G={}){super();this.client=B,this.config={interval:G.interval??30000,timeout:G.timeout??1e4,enabled:G.enabled??!1,failureThreshold:G.failureThreshold??3}}start(){if(this.checkTimer){console.warn("[HealthMonitor] 健康监控已在运行");return}if(!this.config.enabled){console.log("[HealthMonitor] 健康监控未启用");return}console.log(`[HealthMonitor] 启动健康监控(间隔: ${this.config.interval}ms)`),this.scheduleNextCheck()}stop(){if(this.checkTimer)clearTimeout(this.checkTimer),this.checkTimer=null,console.log("[HealthMonitor] 停止健康监控")}scheduleNextCheck(){this.checkTimer=setTimeout(async()=>{await this.performHealthCheck(),this.scheduleNextCheck()},this.config.interval)}async performHealthCheck(){if(this.isChecking)return console.warn("[HealthMonitor] 上一次检查仍在进行中"),this.getLastResult();this.isChecking=!0,this.lastCheckTime=Date.now(),this.setStatus("checking");try{let B=this.client.connectionStatus;if(B==="connected"){await this.pingServer(),this.consecutiveFailures=0,this.setStatus("healthy");let G={status:"healthy",timestamp:Date.now(),consecutiveFailures:0};return this.emit("healthCheck",G),G}else throw Error(`连接状态异常: ${B}`)}catch(B){this.consecutiveFailures++;let G=B;console.warn(`[HealthMonitor] 健康检查失败(${this.consecutiveFailures}/${this.config.failureThreshold}):`,G.message);let Q;if(this.consecutiveFailures>=this.config.failureThreshold)Q="unhealthy",this.emit("unhealthy",this.consecutiveFailures,G),console.log("[HealthMonitor] 达到失败阈值,触发重连..."),this.triggerReconnection().catch((Y)=>{console.error("[HealthMonitor] 重连失败:",Y)});else Q="degraded";this.setStatus(Q);let X={status:Q,timestamp:Date.now(),consecutiveFailures:this.consecutiveFailures,lastError:G};return this.emit("healthCheck",X),X}finally{this.isChecking=!1}}async pingServer(){let B=new Promise((Q,X)=>{setTimeout(()=>X(Error("Health check timeout")),this.config.timeout)}),G=(async()=>{if(this.client.availableTools.length===0){if(!this.client.server)throw Error("Server info not available")}})();await Promise.race([G,B])}async triggerReconnection(){try{await this.client.disconnect(),await new Promise((B)=>setTimeout(B,1000)),await this.client.connect(),console.log("[HealthMonitor] 重连成功"),this.consecutiveFailures=0,this.setStatus("healthy"),this.emit("reconnected")}catch(B){throw console.error("[HealthMonitor] 重连失败:",B),B}}setStatus(B){if(this.currentStatus!==B){let G=this.currentStatus;this.currentStatus=B,this.emit("statusChanged",B,G)}}getStatus(){return this.currentStatus}getLastResult(){return{status:this.currentStatus,timestamp:this.lastCheckTime,consecutiveFailures:this.consecutiveFailures}}getStatistics(){return{status:this.currentStatus,consecutiveFailures:this.consecutiveFailures,lastCheckTime:this.lastCheckTime,isChecking:this.isChecking,config:this.config}}async checkNow(){return this.performHealthCheck()}resetFailureCount(){if(this.consecutiveFailures=0,this.currentStatus!=="checking")this.setStatus("healthy")}}function d(B){if(!(B instanceof Error))return{type:"unknown",isRetryable:!1,originalError:Error(String(B))};let G=B.message.toLowerCase();if(["command not found","no such file","permission denied","invalid configuration","malformed","syntax error"].some((Y)=>G.includes(Y)))return{type:"config_error",isRetryable:!1,originalError:B};if(G.includes("unauthorized")||G.includes("401")||G.includes("authentication failed"))return{type:"auth_error",isRetryable:!1,originalError:B};if(["timeout","connection refused","network error","temporary","try again","rate limit","too many requests","service unavailable","socket hang up","econnreset","enotfound","econnrefused","etimedout","503","429"].some((Y)=>G.includes(Y)))return{type:"network_temporary",isRetryable:!0,originalError:B};return{type:"unknown",isRetryable:!0,originalError:B}}class N extends n{config;status="disconnected";sdkClient=null;tools=new Map;serverInfo=null;reconnectAttempts=0;MAX_RECONNECT_ATTEMPTS=5;reconnectTimer=null;isManualDisconnect=!1;oauthProvider=null;serverName;healthMonitor=null;constructor(B,G,Q){super();this.config=B;if(this.serverName=G||"default",B.oauth?.enabled)this.oauthProvider=new O;if(Q?.enabled)this.healthMonitor=new E(this,Q),this.healthMonitor.on("unhealthy",(X,Y)=>{this.emit("unhealthy",X,Y)}),this.healthMonitor.on("reconnected",()=>{this.emit("healthMonitorReconnected")})}get connectionStatus(){return this.status}get availableTools(){return Array.from(this.tools.values())}get server(){return this.serverInfo}get healthCheck(){return this.healthMonitor}async connect(){return this.connectWithRetry(3,1000)}async connectWithRetry(B=3,G=1000){if(this.status!=="disconnected"&&this.status!=="error")throw Error("客户端已连接或正在连接中");if(this.status==="error"){if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected")}let Q=null;for(let X=1;X<=B;X++)try{await this.doConnect(),this.reconnectAttempts=0;return}catch(Y){Q=Y;let $=d(Y);if(!$.isRetryable)throw console.error("[McpClient] 检测到永久性错误,放弃重试:",$.type),Y;if(X<B){let W=G*Math.pow(2,X-1);console.warn(`[McpClient] 连接失败(${X}/${B}),${W}ms 后重试...`),await new Promise((q)=>setTimeout(q,W))}}throw Q||Error("连接失败")}async doConnect(){try{this.setStatus("connecting"),this.sdkClient=new t({name:h(),version:S()},{capabilities:{roots:{listChanged:!0},sampling:{}}}),this.sdkClient.onclose=()=>{this.handleUnexpectedClose()};let B=await this.createTransport();await this.sdkClient.connect(B);let G=this.sdkClient.getServerVersion();if(this.serverInfo={name:G?.name||"Unknown",version:G?.version||"0.0.0"},await this.loadTools(),this.setStatus("connected"),this.emit("connected",this.serverInfo),this.healthMonitor)this.healthMonitor.start()}catch(B){throw this.setStatus("error"),this.emit("error",B),B}}handleUnexpectedClose(){if(this.isManualDisconnect)return;if(this.status==="connected")console.warn("[McpClient] 检测到意外断连,准备重连..."),this.setStatus("error"),this.emit("error",Error("MCP服务器连接意外关闭")),this.scheduleReconnect()}scheduleReconnect(){if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.reconnectAttempts>=this.MAX_RECONNECT_ATTEMPTS){console.error("[McpClient] 达到最大重连次数,放弃重连"),this.emit("reconnectFailed");return}let B=Math.min(1000*Math.pow(2,this.reconnectAttempts),30000);this.reconnectAttempts++,console.log(`[McpClient] 将在 ${B}ms 后进行第 ${this.reconnectAttempts} 次重连...`),this.reconnectTimer=setTimeout(async()=>{try{if(this.sdkClient){try{await this.sdkClient.close()}catch{}this.sdkClient=null}this.setStatus("disconnected"),await this.doConnect(),console.log("[McpClient] 重连成功"),this.reconnectAttempts=0,this.emit("reconnected")}catch(G){if(console.error("[McpClient] 重连失败:",G),d(G).isRetryable)this.scheduleReconnect();else console.error("[McpClient] 检测到永久性错误,停止重连"),this.emit("reconnectFailed")}},B)}async disconnect(){if(this.isManualDisconnect=!0,this.healthMonitor)this.healthMonitor.stop();if(this.reconnectTimer)clearTimeout(this.reconnectTimer),this.reconnectTimer=null;if(this.sdkClient){try{await this.sdkClient.close()}catch(B){console.warn("[McpClient] 断开连接时出错:",B)}this.sdkClient=null}this.tools.clear(),this.serverInfo=null,this.reconnectAttempts=0,this.setStatus("disconnected"),this.emit("disconnected"),this.isManualDisconnect=!1}async callTool(B,G={}){if(!this.sdkClient)throw Error("客户端未连接到服务器");if(!this.tools.has(B))throw Error(`工具 "${B}" 不存在`);try{return await this.sdkClient.callTool({name:B,arguments:G})}catch(Q){throw console.error(`[McpClient] 调用工具 "${B}" 失败:`,Q),Q}}async createTransport(){let{type:B,command:G,args:Q,env:X,url:Y,headers:$,oauth:W}=this.config,q={...$};if(W?.enabled&&this.oauthProvider&&(B==="sse"||B==="http"))try{let F=await this.oauthProvider.getValidToken(this.serverName,W);if(!F){console.log(`[McpClient] 服务器 "${this.serverName}" 需要 OAuth 认证`);let A=await this.oauthProvider.authenticate(this.serverName,W);q.Authorization=`Bearer ${A.accessToken}`}else q.Authorization=`Bearer ${F}`}catch(F){throw console.error("[McpClient] OAuth 认证失败:",F),Error(`OAuth 认证失败: ${F instanceof Error?F.message:String(F)}`)}if(B==="stdio"){if(!G)throw Error("stdio 传输需要 command 参数");let F={};for(let[A,K]of Object.entries(process.env))if(K!==void 0)F[A]=K;return new s({command:G,args:Q||[],env:{...F,...X},stderr:"ignore"})}else if(B==="sse"){if(!Y)throw Error("sse 传输需要 url 参数");return new a(new URL(Y),{requestInit:{headers:q}})}else if(B==="http"){if(!Y)throw Error("http 传输需要 url 参数");let{StreamableHTTPClientTransport:F}=await import("@modelcontextprotocol/sdk/client/streamableHttp.js");return new F(new URL(Y),{requestInit:{headers:q}})}throw Error(`不支持的传输类型: ${B}`)}async loadTools(){if(!this.sdkClient)return;try{let B=await this.sdkClient.listTools();if(this.tools.clear(),B.tools)for(let G of B.tools)this.tools.set(G.name,G);this.emit("toolsUpdated",this.availableTools)}catch(B){throw console.error("[McpClient] 加载工具失败:",B),B}}setStatus(B){let G=this.status;this.status=B,this.emit("statusChanged",B,G)}async initialize(){return this.connect()}async destroy(){return this.disconnect()}async connectToServer(B){return this.connect()}async disconnectFromServer(B){return this.disconnect()}async listResources(B){if(!this.sdkClient)return[];try{return(await this.sdkClient.listResources()).resources||[]}catch{return[]}}async listTools(B){return this.availableTools}async readResource(B,G){if(!this.sdkClient)throw Error("客户端未连接");return(await this.sdkClient.readResource({uri:B})).contents?.[0]||{uri:B,text:""}}}class b extends r{static instance=null;servers=new Map;isDiscovering=!1;constructor(){super()}static getInstance(){if(!b.instance)b.instance=new b;return b.instance}static createIsolated(){return new b}async registerServer(B,G){if(this.servers.has(B))throw Error(`MCP服务器 "${B}" 已经注册`);let Q=new N(G,B,G.healthCheck),X={config:G,client:Q,status:"disconnected",tools:[]};this.setupClientEventHandlers(Q,X,B),this.servers.set(B,X),this.emit("serverRegistered",B,X);try{await this.connectServer(B)}catch(Y){console.warn(`MCP服务器 "${B}" 连接失败:`,Y)}}async unregisterServer(B){let G=this.servers.get(B);if(!G)return;try{await G.client.disconnect()}catch(Q){console.warn(`断开MCP服务器 "${B}" 时出错:`,Q)}this.servers.delete(B),this.emit("serverUnregistered",B)}async connectServer(B){let G=this.servers.get(B);if(!G)throw Error(`MCP服务器 "${B}" 未注册`);if(G.status==="connected")return;try{G.status="connecting",await G.client.connect(),G.connectedAt=new Date,G.lastError=void 0,G.tools=G.client.availableTools}catch(Q){throw G.lastError=Q,G.status="error",Q}}async disconnectServer(B){let G=this.servers.get(B);if(!G)return;await G.client.disconnect(),G.connectedAt=void 0}async reconnectServer(B){let G=this.servers.get(B);if(!G)throw Error(`MCP服务器 "${B}" 未注册`);if(G.status==="connected")await G.client.disconnect();try{G.status="connecting",await G.client.connect(),G.connectedAt=new Date,G.lastError=void 0,G.tools=G.client.availableTools}catch(Q){throw G.lastError=Q,G.status="error",Q}}async getAvailableTools(){let B=[],G=new Map;for(let[Q,X]of this.servers)if(X.status==="connected")for(let Y of X.tools){let $=G.get(Y.name)||0;G.set(Y.name,$+1)}for(let[Q,X]of this.servers)if(X.status==="connected")for(let Y of X.tools){let W=(G.get(Y.name)||0)>1?`${Q}__${Y.name}`:Y.name,q=U(X.client,Q,Y,W);B.push(q)}return B}async findTool(B){for(let[G,Q]of this.servers)if(Q.status==="connected"){let X=Q.tools.find((Y)=>Y.name===B);if(X)return U(Q.client,G,X)}return null}getToolsByServer(B){let G=this.servers.get(B);if(!G||G.status!=="connected")return[];return G.tools.map((Q)=>U(G.client,B,Q))}getServerStatus(B){return this.servers.get(B)||null}getAllServers(){return new Map(this.servers)}async refreshAllTools(){let B=[];for(let[G,Q]of this.servers)if(Q.status==="connected")B.push(this.refreshServerTools(G));await Promise.allSettled(B)}async refreshServerTools(B){let G=this.servers.get(B);if(!G||G.status!=="connected")return;try{let Q=G.client.availableTools,X=G.tools.length;G.tools=Q,this.emit("toolsUpdated",B,Q,X)}catch(Q){console.warn(`刷新服务器 "${B}" 工具列表失败:`,Q)}}setupClientEventHandlers(B,G,Q){B.on("connected",(X)=>{G.status="connected",G.connectedAt=new Date,G.tools=B.availableTools,this.emit("serverConnected",Q,X)}),B.on("disconnected",()=>{G.status="disconnected",G.connectedAt=void 0,G.tools=[],this.emit("serverDisconnected",Q)}),B.on("error",(X)=>{G.status="error",G.lastError=X,this.emit("serverError",Q,X)}),B.on("toolsUpdated",(X)=>{let Y=G.tools.length;G.tools=X,this.emit("toolsUpdated",Q,X,Y)}),B.on("statusChanged",(X,Y)=>{G.status=X,this.emit("serverStatusChanged",Q,X,Y)})}async discoverServers(){if(this.isDiscovering)return Array.from(this.servers.values());this.isDiscovering=!0,this.emit("discoveryStarted");try{return Array.from(this.servers.values())}finally{this.isDiscovering=!1,this.emit("discoveryCompleted")}}async registerServers(B){let G=Object.entries(B).map(([Q,X])=>this.registerServer(Q,X).catch((Y)=>{return console.warn(`注册MCP服务器 "${Q}" 失败:`,Y),Y}));await Promise.allSettled(G)}getStatistics(){let B=0,G=0,Q=0;for(let X of this.servers.values())if(X.status==="connected")B++,G+=X.tools.length;else if(X.status==="error")Q++;return{totalServers:this.servers.size,connectedServers:B,errorServers:Q,totalTools:G,isDiscovering:this.isDiscovering}}async disconnectAll(){let B=[];for(let[G,Q]of this.servers)if(Q.status==="connected")B.push(Q.client.disconnect().catch((X)=>{console.warn(`断开 MCP 服务器 "${G}" 时出错:`,X)}));await Promise.allSettled(B),this.servers.clear()}}
34
- export{k as Z,b as _};
34
+ export{k as _,b as $};
@@ -1,6 +1,6 @@
1
- import{p,q as d,r as u,s as m}from"./chunk-yaj4nmmp.js";import{t as c}from"./chunk-n969rv4v.js";import{v as z,w as g,x as v}from"./chunk-cw125vv3.js";import{y as h}from"./chunk-k4behavv.js";import{H as y,J as C,K as E,M as W,N as S}from"./chunk-8w1hd9ct.js";import"./chunk-e21htmg4.js";import"./chunk-a8znntss.js";import"./chunk-rtn0rb16.js";import"./chunk-5smacbk0.js";import"./chunk-rkhhzc4r.js";import"./chunk-jsn8476q.js";import{Va as F}from"./chunk-7pcm8vy5.js";import"./chunk-cyxb6fxe.js";import"./chunk-jf48kahn.js";import{sb as w,tb as L}from"./chunk-63dzf6hr.js";import"./chunk-98jpdmgc.js";import"./chunk-w1zb8zac.js";import"./chunk-kfg3vx5z.js";import bq from"yargs";import{hideBin as Dq}from"yargs/helpers";import{z as $}from"zod";import{z as Q}from"zod";var k=1,D=Q.object({event_version:Q.literal(k)}),o=D.extend({type:Q.literal("content_delta"),delta:Q.string()}),a=D.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),e=D.extend({type:Q.literal("thinking"),content:Q.string()}),t=D.extend({type:Q.literal("stream_end")}),qq=D.extend({type:Q.literal("content"),content:Q.string()}),Gq=D.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),Qq=D.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional(),success:Q.boolean().optional(),error_type:Q.string().optional(),error_message:Q.string().optional()}),Xq=D.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),Yq=D.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Zq=D.extend({type:Q.literal("task_update"),tasks:Q.array(W)}),$q=D.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Uq=D.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Kq=D.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Vq=D.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),_q=D.extend({type:Q.literal("error"),message:Q.string()}),Tq=Q.discriminatedUnion("type",[o,a,e,t,qq,Gq,Qq,Xq,Yq,Zq,$q,Uq,Kq,Vq,_q]);function H(G,Y){return{event_version:k,type:G,...Y}}function Aq(G){if(G?.signal)return{signal:G.signal,dispose:()=>{return}};let Y=new AbortController,Z=()=>Y.abort("interrupt");return process.once("SIGINT",Z),process.once("SIGTERM",Z),{signal:Y.signal,dispose:()=>{process.removeListener("SIGINT",Z),process.removeListener("SIGTERM",Z)}}}var Mq=$.enum(["text","jsonl"]),Rq=$.object({headless:$.boolean().optional(),message:$.string().optional(),_:$.array($.union([$.string(),$.number()])).optional(),model:$.string().optional(),systemPrompt:$.string().optional(),appendSystemPrompt:$.string().optional(),maxTurns:$.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:$.nativeEnum(w).optional(),mcpConfig:$.array($.string()).optional(),strictMcpConfig:$.boolean().optional(),sessionId:$.string().optional(),allowedTools:$.array($.string()).optional(),disallowedTools:$.array($.string()).optional(),agents:$.string().optional(),continue:$.boolean().optional(),resume:$.union([$.string(),$.boolean()]).optional(),forkSession:$.boolean().optional(),outputFormat:Mq.optional()});class l{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function jq(G){return G.issues.map((Y)=>`${Y.path.join(".")||"options"}: ${Y.message}`).join("; ")}function fq(G){let Y=Rq.safeParse(G);if(!Y.success)throw Error(`Invalid headless options: ${jq(Y.error)}`);return Y.data}function Bq(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Y)=>Y.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(Y)=>{if(!Y.headless)return;let Z=await Nq(Y);process.exit(Z)})}function A(G,Y=""){G.write(`${Y}
1
+ import{p,q as d,r as u,s as m}from"./chunk-zmndvdgb.js";import{t as c}from"./chunk-wg5nxtb2.js";import{v as z,w as g,x as v}from"./chunk-q6sj33v8.js";import{y as h}from"./chunk-h7qab07x.js";import{I as y,K as C,L as E,N as W,O as S}from"./chunk-8raa4q9y.js";import"./chunk-qyfdt8h1.js";import"./chunk-fceeqn6k.js";import"./chunk-npaj13y3.js";import"./chunk-x4fx52e7.js";import"./chunk-ebynn53v.js";import"./chunk-arwynrtf.js";import{Wa as F}from"./chunk-ve6bvba4.js";import"./chunk-ezkbqmvd.js";import"./chunk-ttf06k8y.js";import"./chunk-rhvxr82g.js";import{vb as w,wb as L}from"./chunk-cadngkwr.js";import"./chunk-cdx3hp1r.js";import"./chunk-1tzcptyb.js";import"./chunk-64x50qbc.js";import bq from"yargs";import{hideBin as Dq}from"yargs/helpers";import{z as $}from"zod";import{z as Q}from"zod";var k=1,D=Q.object({event_version:Q.literal(k)}),o=D.extend({type:Q.literal("content_delta"),delta:Q.string()}),a=D.extend({type:Q.literal("thinking_delta"),delta:Q.string()}),e=D.extend({type:Q.literal("thinking"),content:Q.string()}),t=D.extend({type:Q.literal("stream_end")}),qq=D.extend({type:Q.literal("content"),content:Q.string()}),Gq=D.extend({type:Q.literal("tool_start"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional()}),Qq=D.extend({type:Q.literal("tool_result"),tool_name:Q.string(),summary:Q.string(),target:Q.string().optional(),tool_kind:Q.enum(["readonly","write","execute"]).optional(),success:Q.boolean().optional(),error_type:Q.string().optional(),error_message:Q.string().optional()}),Xq=D.extend({type:Q.literal("phase"),phase:Q.enum(["turn","searching","inspecting","target_hit","executing","completed"]),status:Q.enum(["ongoing","hit","done"]),message:Q.string(),turn:Q.number().optional(),tool_name:Q.string().optional(),target:Q.string().optional()}),Yq=D.extend({type:Q.literal("tool_detail"),tool_name:Q.string(),detail:Q.string()}),Zq=D.extend({type:Q.literal("task_update"),tasks:Q.array(W)}),$q=D.extend({type:Q.literal("token_usage"),input_tokens:Q.number(),output_tokens:Q.number(),total_tokens:Q.number(),max_context_tokens:Q.number()}),Uq=D.extend({type:Q.literal("compacting"),state:Q.enum(["started","completed"])}),Kq=D.extend({type:Q.literal("turn_limit"),turns_count:Q.number(),action:Q.literal("continue")}),Vq=D.extend({type:Q.literal("output"),content:Q.string(),exit_code:Q.number()}),_q=D.extend({type:Q.literal("error"),message:Q.string()}),Tq=Q.discriminatedUnion("type",[o,a,e,t,qq,Gq,Qq,Xq,Yq,Zq,$q,Uq,Kq,Vq,_q]);function H(G,Y){return{event_version:k,type:G,...Y}}function Aq(G){if(G?.signal)return{signal:G.signal,dispose:()=>{return}};let Y=new AbortController,Z=()=>Y.abort("interrupt");return process.once("SIGINT",Z),process.once("SIGTERM",Z),{signal:Y.signal,dispose:()=>{process.removeListener("SIGINT",Z),process.removeListener("SIGTERM",Z)}}}var Mq=$.enum(["text","jsonl"]),Rq=$.object({headless:$.boolean().optional(),message:$.string().optional(),_:$.array($.union([$.string(),$.number()])).optional(),model:$.string().optional(),systemPrompt:$.string().optional(),appendSystemPrompt:$.string().optional(),maxTurns:$.number().int().refine((G)=>G===-1||G>0,{message:"must be -1 or a positive integer"}).optional(),permissionMode:$.nativeEnum(w).optional(),mcpConfig:$.array($.string()).optional(),strictMcpConfig:$.boolean().optional(),sessionId:$.string().optional(),allowedTools:$.array($.string()).optional(),disallowedTools:$.array($.string()).optional(),agents:$.string().optional(),continue:$.boolean().optional(),resume:$.union([$.string(),$.boolean()]).optional(),forkSession:$.boolean().optional(),outputFormat:Mq.optional()});class l{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(G){this.openedThinking=G}hasOpenThinking(){return this.openedThinking}completeStream(){let G={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,G}}function jq(G){return G.issues.map((Y)=>`${Y.path.join(".")||"options"}: ${Y.message}`).join("; ")}function fq(G){let Y=Rq.safeParse(G);if(!Y.success)throw Error(`Invalid headless options: ${jq(Y.error)}`);return Y.data}function Bq(G){return G.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Y)=>Y.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}),async(Y)=>{if(!Y.headless)return;let Z=await Nq(Y);process.exit(Z)})}function A(G,Y=""){G.write(`${Y}
2
2
  `)}function Iq(G){return`[task] [${G.status}] ${G.subject}`}function Jq(){return{requestConfirmation:async(G)=>({approved:!0,reason:"headless-auto-approved",scope:"session"})}}function xq(G){if(!(G instanceof Error))return"Unknown error";let q=G.lastError??G;if(q.responseBody)try{let V=JSON.parse(q.responseBody)?.error?.message;if(V)return q.statusCode?`${V} (HTTP ${q.statusCode})`:V}catch{}let X=G.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return G.message}function Pq(G){return G==="jsonl"?"jsonl":"text"}function T(G,Y){let Z=(...q)=>{for(let X of q){let _=Y[X];if(typeof _==="string"&&_.trim()!=="")return _}return};switch(G){case"Read":case"Edit":case"Write":case"UndoEdit":return Z("file_path");case"NotebookEdit":return Z("notebook_path");case"Grep":return Z("path","pattern");case"Glob":return Z("pattern");case"WebFetch":return Z("url");case"WebSearch":return Z("query");case"Bash":return Z("command","description");case"Task":return Z("description");case"LSP":return Z("filePath","operation");case"EnterWorktree":return Z("name");case"ExitWorktree":return Z("action");default:return}}function Lq(G,Y,Z,q){let X=new Set(["Glob","Grep","WebSearch","LS"]),_=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(G)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Y}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Z?`Working within target: ${Y}`:`Executing: ${Y}`,shouldLockTarget:!1};if(X.has(G))return{phase:"searching",status:"ongoing",message:`Still searching: ${Y}`,shouldLockTarget:!1};if(_.has(G))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Y}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Y}`,shouldLockTarget:!1}}function O(G,Y){let Z=(q,X)=>{G.stdout.write(`${JSON.stringify(H(q,X))}
3
3
  `)};return{contentDelta(q){if(Y==="jsonl"){Z("content_delta",{delta:q});return}G.stdout.write(q)},thinkingDelta(q,X){if(Y==="jsonl")return Z("thinking_delta",{delta:q}),X;if(!X)G.stderr.write("[thinking] ");return G.stderr.write(q),!0},thinking(q){if(Y==="jsonl"){Z("thinking",{content:q});return}A(G.stderr,`[thinking] ${q}`)},streamEnd(q,X){if(Y==="jsonl"){Z("stream_end",{});return}if(X)G.stderr.write(`
4
4
  `);if(q)G.stdout.write(`
5
- `)},content(q){if(Y==="jsonl"){Z("content",{content:q});return}A(G.stdout,q)},toolStart(q,X,_,V){if(Y==="jsonl"){Z("tool_start",{tool_name:q,summary:X,target:_,tool_kind:V});return}A(G.stderr,`[tool:start] ${X}`)},toolResult(q,X,_,V,M){if(Y==="jsonl"){Z("tool_result",{tool_name:q,summary:X,target:_,tool_kind:V,success:M?.success,error_type:M?.errorType,error_message:M?.errorMessage});return}A(G.stderr,`[tool:result] ${X}`)},phase(q,X,_,V={}){if(Y==="jsonl"){Z("phase",{phase:q,status:X,message:_,turn:V.turn,tool_name:V.toolName,target:V.target});return}A(G.stderr,`[phase:${q}] ${_}`)},toolDetail(q,X){if(Y==="jsonl"){Z("tool_detail",{tool_name:q,detail:X});return}A(G.stderr,X)},taskUpdate(q){if(Y==="jsonl"){Z("task_update",{tasks:q});return}for(let X of q)A(G.stderr,Iq(X))},tokenUsage(q){if(Y==="jsonl"){Z("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens});return}A(G.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){if(Y==="jsonl"){Z("compacting",{state:q?"started":"completed"});return}A(G.stderr,q?"[context] compacting started":"[context] compacting completed")},turnLimit(q){if(Y==="jsonl"){Z("turn_limit",{turns_count:q,action:"continue"});return}A(G.stderr,`[turn-limit] continuing after ${q} turns`)},output(q,X=0){if(Y==="jsonl"){Z("output",{content:q,exit_code:X});return}A(X===0?G.stdout:G.stderr,q)},error(q){if(Y==="jsonl"){Z("error",{message:q});return}A(G.stderr,q)}}}async function Nq(G,Y={stdout:process.stdout,stderr:process.stderr},Z){let q="text",X=O(Y,q),_=new l,V={targetLocked:!1},M,R=Aq(Z);try{let K=fq(G);q=Pq(K.outputFormat),X=O(Y,q),await p();let i=await d(K),j=await u(i);if(j.mode==="output"){if(j.content)X.output(j.content,j.exitCode??0);return j.exitCode??0}let N=K.permissionMode??"yolo",{sessionId:x,messages:n}=await m({sessionId:K.sessionId,continue:K.continue,resume:K.resume,forkSession:K.forkSession,fallbackSessionPrefix:"headless"}),r={messages:[...n],userId:"cli-user",sessionId:x,workspaceRoot:L(),permissionMode:N,signal:R.signal,confirmationHandler:Jq()};M=await y.create({sessionId:x,workspaceRoot:L(),modelId:K.model,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig,agents:K.agents?h(K.agents):void 0});let s=await S.createWithRuntime(M,{sessionId:x,systemPrompt:K.systemPrompt,appendSystemPrompt:K.appendSystemPrompt,maxTurns:K.maxTurns,modelId:K.model,permissionMode:N,toolWhitelist:K.allowedTools,toolBlacklist:K.disallowedTools,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig}),P=await F(s.chatStream(j.content,r,{stream:!0,signal:R.signal,maxTurns:K.maxTurns,onTurnLimitReached:async(b)=>{return X.turnLimit(b.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}),async(b)=>{switch(b.kind){case"content_delta":_.markAssistantContent(),X.contentDelta(b.delta);break;case"thinking_delta":_.setThinkingOpened(X.thinkingDelta(b.delta,_.hasOpenThinking()));break;case"stream_end":{let U=_.completeStream();X.streamEnd(U.wroteAssistantContent,U.openedThinking);break}case"tool_start":{let U=b.toolCall;if(!("function"in U))break;if(["TaskCreate","TaskUpdate","TaskList"].includes(U.function.name))break;try{let f=JSON.parse(U.function.arguments),B=C(U.function.name,f),I=T(U.function.name,f),J=Lq(U.function.name,B,I,V);if(J.shouldLockTarget)V.targetLocked=!0;X.phase(J.phase,J.status,J.message,{toolName:U.function.name,target:I}),X.toolStart(U.function.name,B,I,b.toolKind)}catch{X.phase(V.targetLocked?"executing":"searching",V.targetLocked?"hit":"ongoing",V.targetLocked?`Working within target: ${U.function.name}`:`Still searching: ${U.function.name}`,{toolName:U.function.name}),X.toolStart(U.function.name,U.function.name,void 0,b.toolKind)}break}case"tool_result":{let U=b.toolCall;if(!("function"in U))break;let f;try{let I=JSON.parse(U.function.arguments);f=T(U.function.name,I)}catch{f=void 0}let B=E(U.function.name,b.result);if(X.toolResult(U.function.name,B.summary,f,void 0,{success:b.result.success,errorType:b.result.error?.type,errorMessage:b.result.error?.message}),B.detail)X.toolDetail(U.function.name,B.detail);break}case"token_usage":X.tokenUsage(b.usage);break;case"compaction":X.compacting(b.phase==="start");break;case"task_update":X.taskUpdate(b.tasks);break;case"steering_applied":case"follow_up_started":break;case"subagent_spawned":case"subagent_completed":break;case"model_fallback":break;case"turn_start":if(b.turn===1)V.targetLocked=!1;X.phase("turn",V.targetLocked?"hit":"ongoing",`Turn ${b.turn} started`,{turn:b.turn});break;default:{let U=b}}});if(P.metadata?.outputTruncated)X.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!P.success)return X.error(`Error: ${P.error?.message??"Agent execution failed"}`),1;return X.phase("completed","done","Headless run completed"),0}catch(K){if(_.hasOpenThinking()&&q==="text")Y.stderr.write(`
5
+ `)},content(q){if(Y==="jsonl"){Z("content",{content:q});return}A(G.stdout,q)},toolStart(q,X,_,V){if(Y==="jsonl"){Z("tool_start",{tool_name:q,summary:X,target:_,tool_kind:V});return}A(G.stderr,`[tool:start] ${X}`)},toolResult(q,X,_,V,M){if(Y==="jsonl"){Z("tool_result",{tool_name:q,summary:X,target:_,tool_kind:V,success:M?.success,error_type:M?.errorType,error_message:M?.errorMessage});return}A(G.stderr,`[tool:result] ${X}`)},phase(q,X,_,V={}){if(Y==="jsonl"){Z("phase",{phase:q,status:X,message:_,turn:V.turn,tool_name:V.toolName,target:V.target});return}A(G.stderr,`[phase:${q}] ${_}`)},toolDetail(q,X){if(Y==="jsonl"){Z("tool_detail",{tool_name:q,detail:X});return}A(G.stderr,X)},taskUpdate(q){if(Y==="jsonl"){Z("task_update",{tasks:q});return}for(let X of q)A(G.stderr,Iq(X))},tokenUsage(q){if(Y==="jsonl"){Z("token_usage",{input_tokens:q.inputTokens,output_tokens:q.outputTokens,total_tokens:q.totalTokens,max_context_tokens:q.maxContextTokens});return}A(G.stderr,`[tokens] in=${q.inputTokens} out=${q.outputTokens} total=${q.totalTokens} / ${q.maxContextTokens}`)},compacting(q){if(Y==="jsonl"){Z("compacting",{state:q?"started":"completed"});return}A(G.stderr,q?"[context] compacting started":"[context] compacting completed")},turnLimit(q){if(Y==="jsonl"){Z("turn_limit",{turns_count:q,action:"continue"});return}A(G.stderr,`[turn-limit] continuing after ${q} turns`)},output(q,X=0){if(Y==="jsonl"){Z("output",{content:q,exit_code:X});return}A(X===0?G.stdout:G.stderr,q)},error(q){if(Y==="jsonl"){Z("error",{message:q});return}A(G.stderr,q)}}}async function Nq(G,Y={stdout:process.stdout,stderr:process.stderr},Z){let q="text",X=O(Y,q),_=new l,V={targetLocked:!1},M,R=Aq(Z);try{let K=fq(G);q=Pq(K.outputFormat),X=O(Y,q),await p();let i=await d(K),j=await u(i);if(j.mode==="output"){if(j.content)X.output(j.content,j.exitCode??0);return j.exitCode??0}let N=K.permissionMode??"yolo",{sessionId:x,messages:n}=await m({sessionId:K.sessionId,continue:K.continue,resume:K.resume,forkSession:K.forkSession,fallbackSessionPrefix:"headless"}),r={messages:[...n],userId:"cli-user",sessionId:x,workspaceRoot:L(),permissionMode:N,signal:R.signal,confirmationHandler:Jq()};M=await y.create({sessionId:x,workspaceRoot:L(),modelId:K.model,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig,agents:K.agents?h(K.agents):void 0});let s=await S.createWithRuntime(M,{sessionId:x,systemPrompt:K.systemPrompt,appendSystemPrompt:K.appendSystemPrompt,maxTurns:K.maxTurns,modelId:K.model,permissionMode:N,toolWhitelist:K.allowedTools,toolBlacklist:K.disallowedTools,mcpConfig:K.mcpConfig,strictMcpConfig:K.strictMcpConfig}),P=await F(s.chatStream(j.content,r,{stream:!0,signal:R.signal,maxTurns:K.maxTurns,onTurnLimitReached:async(b)=>{return X.turnLimit(b.turnsCount),{continue:!0,reason:"headless-auto-continue"}}}),async(b)=>{switch(b.kind){case"content_delta":_.markAssistantContent(),X.contentDelta(b.delta);break;case"thinking_delta":_.setThinkingOpened(X.thinkingDelta(b.delta,_.hasOpenThinking()));break;case"stream_end":{let U=_.completeStream();X.streamEnd(U.wroteAssistantContent,U.openedThinking);break}case"tool_start":{let U=b.toolCall;if(!("function"in U))break;if(["TaskCreate","TaskUpdate","TaskList"].includes(U.function.name))break;try{let f=JSON.parse(U.function.arguments),B=C(U.function.name,f),I=T(U.function.name,f),J=Lq(U.function.name,B,I,V);if(J.shouldLockTarget)V.targetLocked=!0;X.phase(J.phase,J.status,J.message,{toolName:U.function.name,target:I}),X.toolStart(U.function.name,B,I,b.toolKind)}catch{X.phase(V.targetLocked?"executing":"searching",V.targetLocked?"hit":"ongoing",V.targetLocked?`Working within target: ${U.function.name}`:`Still searching: ${U.function.name}`,{toolName:U.function.name}),X.toolStart(U.function.name,U.function.name,void 0,b.toolKind)}break}case"tool_result":{let U=b.toolCall;if(!("function"in U))break;let f;try{let I=JSON.parse(U.function.arguments);f=T(U.function.name,I)}catch{f=void 0}let B=E(U.function.name,b.result);if(X.toolResult(U.function.name,B.summary,f,void 0,{success:b.result.success,errorType:b.result.error?.type,errorMessage:b.result.error?.message}),B.detail)X.toolDetail(U.function.name,B.detail);break}case"token_usage":X.tokenUsage(b.usage);break;case"compaction":X.compacting(b.phase==="start");break;case"task_update":X.taskUpdate(b.tasks);break;case"steering_applied":case"follow_up_started":case"goal_updated":case"goal_continuation_started":break;case"subagent_spawned":case"subagent_completed":break;case"model_fallback":break;case"turn_start":if(b.turn===1)V.targetLocked=!1;X.phase("turn",V.targetLocked?"hit":"ongoing",`Turn ${b.turn} started`,{turn:b.turn});break;default:{let U=b}}});if(P.metadata?.outputTruncated)X.error("[warning] 输出因达到 token 上限被截断,部分内容可能不完整。");if(!P.success)return X.error(`Error: ${P.error?.message??"Agent execution failed"}`),1;return X.phase("completed","done","Headless run completed"),0}catch(K){if(_.hasOpenThinking()&&q==="text")Y.stderr.write(`
6
6
  `);return X.error(`Error: ${xq(K)}`),1}finally{try{await M?.dispose()}finally{R.dispose()}}}async function lq(){if(!process.argv.slice(2).includes("--headless"))return!1;let{headless:Z,"output-format":q,"system-prompt":X,"append-system-prompt":_,"max-turns":V,...M}=c,R=bq(Dq(process.argv)).scriptName("blade").strict(!1).options(M).middleware([g,z,v]);return Bq(R),await R.parse(),!0}export{Nq as runHeadless,lq as handleHeadlessMode,Rq as HeadlessOptionsSchema};
@@ -1,2 +1,2 @@
1
- import{Y as H}from"./chunk-e21htmg4.js";import{z as k}from"zod";var K=k.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),G=k.array(k.string().trim().min(1).max(200)).max(128).transform((B)=>[...new Set(B)]),Q=k.object({description:k.string().trim().min(1).max(4096),prompt:k.string().trim().min(1).max(1e5),tools:G.optional(),disallowedTools:G.optional(),model:k.string().trim().min(1).max(200).optional(),permissionMode:k.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"]).optional(),maxTurns:k.number().int().positive().max(100).optional(),isolation:k.enum(["none","worktree"]).optional()}).strict();function V(B){let w;try{w=JSON.parse(B)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let E=Object.entries(w);if(E.length>64)throw Error("--agents supports at most 64 definitions");return E.map(([x,I])=>{if(!K.safeParse(x).success)throw Error(`Invalid --agents name "${x}": use letters, numbers, hyphens, or underscores`);let F=Q.safeParse(I);if(!F.success)throw Error(`Invalid --agents definition for "${x}"`);let q=F.data;return{name:x,description:q.description,systemPrompt:q.prompt,tools:q.tools,disallowedTools:q.disallowedTools,model:q.model,permissionMode:q.permissionMode===void 0?void 0:H(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
1
+ import{Z as H}from"./chunk-qyfdt8h1.js";import{z as k}from"zod";var K=k.string().min(1).max(128).regex(/^[A-Za-z0-9][A-Za-z0-9_-]*$/),G=k.array(k.string().trim().min(1).max(200)).max(128).transform((B)=>[...new Set(B)]),Q=k.object({description:k.string().trim().min(1).max(4096),prompt:k.string().trim().min(1).max(1e5),tools:G.optional(),disallowedTools:G.optional(),model:k.string().trim().min(1).max(200).optional(),permissionMode:k.enum(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"]).optional(),maxTurns:k.number().int().positive().max(100).optional(),isolation:k.enum(["none","worktree"]).optional()}).strict();function V(B){let w;try{w=JSON.parse(B)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let E=Object.entries(w);if(E.length>64)throw Error("--agents supports at most 64 definitions");return E.map(([x,I])=>{if(!K.safeParse(x).success)throw Error(`Invalid --agents name "${x}": use letters, numbers, hyphens, or underscores`);let F=Q.safeParse(I);if(!F.success)throw Error(`Invalid --agents definition for "${x}"`);let q=F.data;return{name:x,description:q.description,systemPrompt:q.prompt,tools:q.tools,disallowedTools:q.disallowedTools,model:q.model,permissionMode:q.permissionMode===void 0?void 0:H(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
2
  export{V as y};
@@ -1,4 +1,4 @@
1
- import{na as Q}from"./chunk-5smacbk0.js";import{nb as U}from"./chunk-jf48kahn.js";import{tb as O}from"./chunk-63dzf6hr.js";import{Jb as K,Lb as N}from"./chunk-w1zb8zac.js";function Y(){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[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(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 D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.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",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{oa as Q}from"./chunk-x4fx52e7.js";import{pb as U}from"./chunk-ttf06k8y.js";import{wb as O}from"./chunk-cadngkwr.js";import{Ob as K,Qb as N}from"./chunk-1tzcptyb.js";function Y(){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[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=N("Service");function Z(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 D{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!D.instance)D.instance=new D;return D.instance}initialize(){if(this.initialized){A.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",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.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){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await K()}catch(z){}try{let z=U.getInstance();if(z.isEnabled()){let F=Q(),W=F.session?.sessionId||"unknown",X=F.config?.config?.permissionMode||"default";await z.executeSessionEndHooks(Z(b),{projectDir:O(),sessionId:W,permissionMode:X})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,V=new Promise((z,F)=>{setTimeout(()=>{F(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,V])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{Y(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var J=()=>{return D.getInstance()},H=(b)=>{return J().registerCleanup(b)},P=()=>{J().initialize()},L=(b=0)=>{J().shutdown("normal",b)};
4
4
  export{J as l,H as m,P as n,L as o};