blade-code 0.10.13 → 0.10.15

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 (54) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-j8fkhkan.js → chunk-09k2b1tw.js} +1 -1
  3. package/dist/{chunk-x9t4ryyf.js → chunk-0z7rg4f3.js} +1 -1
  4. package/dist/{chunk-ke4n1nv5.js → chunk-1amhvwmj.js} +20 -20
  5. package/dist/chunk-1c9rkm57.js +1 -0
  6. package/dist/{chunk-097zrzyy.js → chunk-25abj6rx.js} +1 -1
  7. package/dist/{chunk-c9m16hqc.js → chunk-2cqsqrxx.js} +1 -1
  8. package/dist/{chunk-hf3dwmfa.js → chunk-3m8pschr.js} +1 -1
  9. package/dist/{chunk-8p5a371t.js → chunk-5psydp1v.js} +1 -1
  10. package/dist/{chunk-zgg0y0sy.js → chunk-5tpjb8yn.js} +1 -1
  11. package/dist/{chunk-pmz455nq.js → chunk-5wecprcp.js} +1 -1
  12. package/dist/chunk-67vf8r5v.js +6 -0
  13. package/dist/{chunk-nsxkd8bq.js → chunk-6y9w5296.js} +1 -1
  14. package/dist/{chunk-5wnxafpf.js → chunk-7bq9p4ab.js} +1 -1
  15. package/dist/{chunk-cy6emyt9.js → chunk-7x5cqfy7.js} +1 -1
  16. package/dist/{chunk-0q7pvmvz.js → chunk-a170cgzr.js} +1 -1
  17. package/dist/{chunk-74wm5qnw.js → chunk-afxpp33r.js} +1 -1
  18. package/dist/{chunk-cx0tdprs.js → chunk-agdamn30.js} +1 -1
  19. package/dist/{chunk-97fyx4hr.js → chunk-csn0epd2.js} +1 -1
  20. package/dist/chunk-d7976m5f.js +5 -0
  21. package/dist/{chunk-ab4sp3m4.js → chunk-eav8jpk1.js} +2 -2
  22. package/dist/{chunk-c477j84k.js → chunk-ee7an1kq.js} +1 -1
  23. package/dist/{chunk-9ac3eajy.js → chunk-jjy8sg10.js} +1 -1
  24. package/dist/{chunk-8yypkbew.js → chunk-k47f7zqm.js} +1 -1
  25. package/dist/{chunk-k653znk8.js → chunk-m4f213hk.js} +1 -1
  26. package/dist/{chunk-p42cz164.js → chunk-mc29y7tj.js} +24 -24
  27. package/dist/{chunk-820ek28g.js → chunk-n72www7h.js} +3 -3
  28. package/dist/{chunk-4em4jxj5.js → chunk-nfqsnkbt.js} +47 -47
  29. package/dist/{chunk-kfgv64hg.js → chunk-ng8a4btc.js} +1 -1
  30. package/dist/{chunk-7s99zkve.js → chunk-qpd1jmm4.js} +1 -1
  31. package/dist/{chunk-45wpygt9.js → chunk-t6cmqsdj.js} +1 -1
  32. package/dist/{chunk-9cnm1hgp.js → chunk-wz3z8908.js} +1 -1
  33. package/dist/{chunk-nysyp11q.js → chunk-x1qw695m.js} +3 -3
  34. package/dist/{chunk-a3mwn9zj.js → chunk-zmg66vp7.js} +1 -1
  35. package/dist/{chunk-5vgjhqk9.js → chunk-zn2cec1d.js} +1 -1
  36. package/dist/{chunk-xjyctv33.js → chunk-zn7c21zj.js} +7 -7
  37. package/dist/web/assets/ChatView-rHWZ9qCy.js +7 -0
  38. package/dist/web/assets/{CodeBlockHighlighter-GS19h8wb.js → CodeBlockHighlighter-KpN8jpS4.js} +2 -2
  39. package/dist/web/assets/{FilePreview-BIjFuDdg.js → FilePreview-BbEcYewq.js} +3 -3
  40. package/dist/web/assets/{MarkdownRenderer-D-NrQgb1.js → MarkdownRenderer-Cpqkv5Ml.js} +3 -3
  41. package/dist/web/assets/{SettingsModal-BNz9vyER.js → SettingsModal-D6NZP8vM.js} +2 -2
  42. package/dist/web/assets/TaskSwitcher-cT1qKR6s.js +1 -0
  43. package/dist/web/assets/TerminalPanel-0MehdzKr.js +1 -0
  44. package/dist/web/assets/index-BYd4kNGp.js +11 -0
  45. package/dist/web/assets/session-events-BH7O5JJl.js +22 -0
  46. package/dist/web/index.html +2 -1
  47. package/package.json +1 -1
  48. package/dist/chunk-ah97bmns.js +0 -5
  49. package/dist/chunk-j4rfyz81.js +0 -6
  50. package/dist/chunk-m6sg36pw.js +0 -1
  51. package/dist/web/assets/ChatView-ucu62nNl.js +0 -7
  52. package/dist/web/assets/TaskSwitcher-HnRA3Mj8.js +0 -1
  53. package/dist/web/assets/TerminalPanel-Df2CK9n_.js +0 -1
  54. package/dist/web/assets/index-DWTihvUI.js +0 -32
@@ -1,4 +1,4 @@
1
- import{We as Zn,Xe as Jn}from"./chunk-3aqdjrtm.js";import{Ye as rn,Ze as D,_e as m}from"./chunk-kvx3sb3z.js";import{cf as pn,df as Nn}from"./chunk-f4z3gkbs.js";import{if as b}from"./chunk-5s123nbs.js";import{kf as Dn,nf as H}from"./chunk-s5666ta0.js";import{vf as fn,wf as En}from"./chunk-cy6emyt9.js";import{Af as P}from"./chunk-gav4hxcv.js";import{Kf as un}from"./chunk-363pgv1e.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((_)=>_.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ot=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),_t=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(on,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(l(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{We as Zn,Xe as Jn}from"./chunk-3aqdjrtm.js";import{Ye as rn,Ze as D,_e as m}from"./chunk-kvx3sb3z.js";import{cf as pn,df as Nn}from"./chunk-f4z3gkbs.js";import{if as b}from"./chunk-5s123nbs.js";import{kf as Dn,nf as H}from"./chunk-s5666ta0.js";import{vf as fn,wf as En}from"./chunk-7x5cqfy7.js";import{Af as P}from"./chunk-gav4hxcv.js";import{Kf as un}from"./chunk-363pgv1e.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((_)=>_.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ot=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),_t=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(on,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(l(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await A.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=Y.join(this.stateRoot,".oauth-credentials.lock"),t=Fn(),e=Date.now()+et;while(Date.now()<e)try{let r=await A.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!l(u,"ENOENT"))throw u}}}catch(r){if(!l(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((u)=>setTimeout(u,ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await A.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await A.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!it(e.pid))await A.unlink(n)}}var sn="127.0.0.1",Sn=7777,mn="/oauth/callback",mt=300000;class Q extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class cn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ft(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1,2 +1,2 @@
1
- var e={name:"blade-code",version:"0.10.13",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","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:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
1
+ var e={name:"blade-code",version:"0.10.15",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","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:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.83.0","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7","ansi-escapes":"^7.3.0",ajv:"^8.17.1","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"^2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};function i(){return{name:e.name,version:e.version,description:e.description}}function n(){return e.version}function o(){return e.name}function c(){return e.description}function a(){return`v${e.version}`}function d(){return`v${e.version} © 2025 Blade Code`}
2
2
  export{i as uf,n as vf,o as wf,c as xf,a as yf,d as zf};
@@ -1,4 +1,4 @@
1
- import{ka as H}from"./chunk-c477j84k.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as k}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ka as H}from"./chunk-ee7an1kq.js";import"./chunk-095x2ykj.js";import{Zc as $,dd as T}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as k}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1,4 +1,4 @@
1
- import{G as P}from"./chunk-nysyp11q.js";import{gb as K}from"./chunk-p42cz164.js";import{$b as B,Cb as G,Db as N,Eb as S,Fb as O,Gb as s}from"./chunk-97fyx4hr.js";import{ec as j}from"./chunk-4hawehmd.js";import{fd as q}from"./chunk-ybvdac8k.js";import{vd as v}from"./chunk-cx0tdprs.js";import{Gf as z}from"./chunk-363pgv1e.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{G as P}from"./chunk-x1qw695m.js";import{gb as K}from"./chunk-mc29y7tj.js";import{$b as B,Cb as G,Db as N,Eb as S,Fb as O,Gb as s}from"./chunk-csn0epd2.js";import{ec as j}from"./chunk-4hawehmd.js";import{fd as q}from"./chunk-ybvdac8k.js";import{vd as v}from"./chunk-agdamn30.js";import{Gf as z}from"./chunk-363pgv1e.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1,4 +1,4 @@
1
- import{Od as L1,Pd as Z0,Qd as G1}from"./chunk-9tnaads5.js";import{Ud as $O,Vd as HO}from"./chunk-heqs3xan.js";import{Yd as Y1}from"./chunk-dpt56hah.js";import{$d as M0,Zd as B0}from"./chunk-kfgv64hg.js";import{ee as h,fe as z}from"./chunk-4dq9y7zn.js";import{Ie as V0,Je as o1,Se as j0}from"./chunk-5wnxafpf.js";import{Ye as u,_e as W,bf as R1}from"./chunk-kvx3sb3z.js";import{if as b}from"./chunk-5s123nbs.js";import{vf as d0}from"./chunk-cy6emyt9.js";import{Af as T}from"./chunk-gav4hxcv.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
1
+ import{Od as L1,Pd as Z0,Qd as G1}from"./chunk-9tnaads5.js";import{Ud as $O,Vd as HO}from"./chunk-heqs3xan.js";import{Yd as Y1}from"./chunk-dpt56hah.js";import{$d as M0,Zd as B0}from"./chunk-ng8a4btc.js";import{ee as h,fe as z}from"./chunk-4dq9y7zn.js";import{Ie as V0,Je as o1,Se as j0}from"./chunk-7bq9p4ab.js";import{Ye as u,_e as W,bf as R1}from"./chunk-kvx3sb3z.js";import{if as b}from"./chunk-5s123nbs.js";import{vf as d0}from"./chunk-7x5cqfy7.js";import{Af as T}from"./chunk-gav4hxcv.js";import J1 from"node:path";import L$ from"node:path";import C0 from"node:fs";import J0 from"node:os";import R from"node:path";import jO from"yaml";var g$={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function u$(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var UO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -1,4 +1,4 @@
1
- import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-cy6emyt9.js";import{Cf as s$,Df as H0,Ff as f,Gf as m,If as s0,Jf as c,Kf as J0}from"./chunk-363pgv1e.js";import{readdir as l$,readFile as e,rm as R0,stat as oq}from"node:fs/promises";import*as F from"node:path";import{nanoid as S}from"nanoid";import{createHash as Kq,randomUUID as Bq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var X$=1;function Yq($,q){let G=Kq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==X$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function N$($){let q=await S0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),S0($)}function Nq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function F$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
1
+ import{ac as u,bc as qq,cc as e0,dc as Gq,ec as v,fc as $$,gc as Lq,hc as q$,ic as G$,jc as L$,lc as f0,oc as Z$,pc as Zq}from"./chunk-4hawehmd.js";import{od as K0}from"./chunk-8j01ssaf.js";import{Td as B0}from"./chunk-heqs3xan.js";import{ae as I$}from"./chunk-7wjy6kgt.js";import{ee as U0}from"./chunk-4dq9y7zn.js";import{cf as e$,df as $q}from"./chunk-f4z3gkbs.js";import{if as H$}from"./chunk-5s123nbs.js";import{of as V0,rf as x0}from"./chunk-dsj62dcg.js";import{vf as l}from"./chunk-7x5cqfy7.js";import{Cf as s$,Df as H0,Ff as f,Gf as m,If as s0,Jf as c,Kf as J0}from"./chunk-363pgv1e.js";import{readdir as l$,readFile as e,rm as R0,stat as oq}from"node:fs/promises";import*as F from"node:path";import{nanoid as S}from"nanoid";import{createHash as Kq,randomUUID as Bq}from"node:crypto";import*as I from"node:fs/promises";import*as X0 from"node:path";var X$=1;function Yq($,q){let G=Kq("sha256").update(q).digest("hex");return X0.join(H0($),".locks",`${G}.lock`)}function F0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function S0($){try{let q=JSON.parse(await I.readFile($,"utf8"));if(q.version!==X$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function N$($){let q=await S0($);if(q)return q;return await new Promise((G)=>setTimeout(G,10)),S0($)}function Nq($){try{return process.kill($,0),!0}catch(q){return F0(q,"EPERM")}}async function F$($,q){let G;try{return G=await I.open($,"wx",384),await G.writeFile(`${JSON.stringify(q)}
2
2
  `,"utf8"),!0}catch(L){if(F0(L,"EEXIST"))return!1;if(G)await I.unlink($).catch(()=>{return});throw L}finally{await G?.close().catch(()=>{return})}}class n extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class i{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=H$()){let G=Yq(q,$),L={version:X$,sessionId:$,ownerId:Bq(),pid:process.pid,acquiredAt:new Date().toISOString()};if(await I.mkdir(X0.dirname(G),{recursive:!0,mode:448}),await F$(G,L))return new i(G,L);let J=await N$(G);if(J&&Nq(J.pid))throw new n(J.pid);if(await I.unlink(G).catch((Z)=>{if(!F0(Z,"ENOENT"))throw Z}),await F$(G,L))return new i(G,L);throw new n((await N$(G))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await S0(this.filePath))?.ownerId!==this.record.ownerId)return;await I.unlink(this.filePath).catch((q)=>{if(!F0(q,"ENOENT"))throw q})}}function Fq($,q){for(let G of $){if(G.type!=="part_created"||G.data.partType!=="tool_result")continue;let L=G.data.payload;if(!L||typeof L!=="object"||Array.isArray(L))continue;let J=L;if(J.toolCallId===q||G.data.partId===q||G.data.messageId===q)return J}return}function W$($){let q=u($),G=new Map;for(let L of q){if(L.type==="interaction_requested"){G.set(L.data.requestId,{request:L.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(L.type==="interaction_responded"){let J=G.get(L.data.requestId);if(J)J.response=L.data;continue}if(L.type==="interaction_recovered"){let J=G.get(L.data.requestId);if(J)J.recovery=L.data}}for(let L of G.values()){let J=Fq(q,L.request.toolCallId);L.hasToolResult=J!==void 0;let Z=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;L.hasRecoveryToolResult=Z?.interactionRecovery===!0&&Z.requestId===L.request.requestId}return[...G.values()]}function T$($){return W$($).reverse().find((q)=>!q.response&&!q.recovery)}function z1($){let q=new Map;for(let G of W$($))q.set(G.request.toolCallId,G);return[...q.values()].filter((G)=>G.response&&!G.recovery&&(!G.hasToolResult||G.hasRecoveryToolResult))}function U$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function W0($){let q=new Map,G=[];for(let L of $){if(L.type==="review_started"){if(!q.has(L.data.reviewId))G.push(L.data.reviewId),q.set(L.data.reviewId,{start:L.data});continue}if(L.type!=="review_completed")continue;let J=q.get(L.data.reviewId);if(J&&J.completion===void 0)J.completion=L.data}return G.map((L)=>q.get(L)).filter((L)=>L!==void 0)}function _1($){return W0($).reverse().find((q)=>q.completion===void 0)}function m0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function O$($,q){let G=["## Code Review","",`Target: ${$.target.label}`,`Status: ${m0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)G.push("","No actionable findings.");else{G.push("","### Findings");for(let[L,J]of q.findings.entries()){let Z=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;G.push("",`${L+1}. ${J.title}`,` ${J.codeLocation.path}:L${Z} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)G.push("",`Error: ${q.error}`);return G.join(`
3
3
  `)}function C$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((G)=>({title:G.title,body:G.body,priority:G.priority,confidenceScore:G.confidenceScore,codeLocation:{...G.codeLocation}})),...q.error?{error:q.error}:{}}}var I0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Hq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Xq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";return"runtime"}function Wq($){return{code:$,...I0[$]}}function v0($){return Wq(Xq(Hq($)))}function P0($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in I0))return!1;let G=I0[q.code];return q.message===G.message&&q.retryable===G.retryable}import{promises as G0,realpathSync as Uq}from"node:fs";import T0 from"node:path";import*as o from"fs/promises";import*as O from"path";var z$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class u0{static normalize($,q){let G=O.isAbsolute($)?$:O.resolve(q,$),L=O.normalize(G),J=O.normalize(q);if(!this.isWithinWorkspace(L,J))throw new d(`Path outside workspace: ${$} (resolved to ${L}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return L}static checkRestricted($){let q=$.split(O.sep);for(let G of z$)if(q.includes(G))throw new d(`Access denied: "${G}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let G=this.normalize($,q);this.checkRestricted(G);try{await o.access(G)}catch(L){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return G}static async resolveSymlink($,q){try{let G=await o.realpath($),L=await o.realpath(q);if(!this.isWithinWorkspace(G,L))throw new d(`Symlink points outside workspace: ${$} -> ${G}`,"SYMLINK_OUTSIDE_WORKSPACE");return G}catch(G){if(G instanceof d)throw G;return $}}static getRelativePath($,q){return O.relative(q,$)}static isWithinWorkspace($,q){let G=O.resolve($),L=O.resolve(q),J=O.relative(L,G);return J===""||J!==".."&&!J.startsWith(`..${O.sep}`)&&!O.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let G=O.resolve(q),L=O.isAbsolute($)?O.resolve($):O.resolve(G,$);if(!this.isWithinWorkspace(L,G))return!1;let J;try{J=await o.realpath(G)}catch{return!1}let Z=L;while(!0){try{let V=await o.realpath(Z);return this.isWithinWorkspace(V,J)}catch(V){let B=V.code;if(B!=="ENOENT"&&B!=="ENOTDIR")return!1}let Q=O.dirname(Z);if(Q===Z)return!1;Z=Q}}static isRestricted($){let q=$.split(O.sep);return z$.some((G)=>q.includes(G))}}var L0=U0("Tool");class h{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}async recordFileRead($,q){try{let G=await G0.stat($),L={filePath:T0.resolve($),accessTime:Date.now(),mtime:G.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(L),await this.recordAliases($,L.filePath),L0.debug(`记录文件读取: ${$}`)}catch(G){L0.warn(`记录文件读取失败: ${$}`,G)}}async recordFileEdit($,q,G="edit"){try{let L=await G0.stat($),J={filePath:T0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:G};this.setRecord(J),await this.recordAliases($,J.filePath),L0.debug(`记录文件${G==="edit"?"编辑":"写入"}: ${$}`)}catch(L){L0.warn(`记录文件${G==="edit"?"编辑":"写入"}失败: ${$}`,L)}}hasFileBeenRead($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return!1;return q?G.has(q):G.size>0}async checkFileModification($,q){let G=this.getFileRecord($,q);if(!G)return{modified:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(Math.abs(L.mtimeMs-G.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(G.accessTime).toISOString()}, 当前修改时间: ${L.mtime.toISOString()})`};return{modified:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let G=this.getFileRecord($,q);if(!G)return{isExternal:!1,message:"文件未被跟踪"};try{let L=await G0.stat($);if(L.mtimeMs-G.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(G.accessTime).toISOString()} (${G.lastOperation}) 之后被外部程序修改(当前修改时间: ${L.mtime.toISOString()})`};return{isExternal:!1}}catch(L){let J=L;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return L0.warn(`检查文件外部修改失败: ${$}`,L),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let G=this.accessedFiles.get(this.resolveTrackedPath($));if(!G)return;if(q)return G.get(q);return[...G.values()].sort((L,J)=>J.accessTime-L.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let G=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(G),this.removeAliases(G);return}let L=this.accessedFiles.get(G);if(L?.delete(q),L?.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[G,L]of this.accessedFiles.entries()){if(q&&!u0.isWithinWorkspace(G,q))continue;if(L.delete($),L.size===0)this.accessedFiles.delete(G),this.removeAliases(G)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){h.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(T0.resolve($),q);let G=await G0.realpath($).catch(()=>{return});if(G)this.pathAliases.set(G,q)}resolveTrackedPath($){let q=T0.resolve($);if(this.accessedFiles.has(q))return q;let G=this.pathAliases.get(q);if(G)return G;try{let L=Uq.native(q);return this.pathAliases.get(L)??L}catch{return q}}removeAliases($){for(let[q,G]of this.pathAliases)if(G===$)this.pathAliases.delete(q)}}import*as Z0 from"node:crypto";import{promises as X}from"node:fs";import*as T from"node:path";import h0 from"write-file-atomic";var D$="missing";class O0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(f($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!T.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?T.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=J0();this.snapshotDir=T.join(q,"file-history",this.sessionId),this.manifestPath=T.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await X.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=J0(),q=await X.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),G=Z0.createHash("sha256").update(q).digest("hex").slice(0,24),L=T.join($,"file-history",this.sessionId),J=T.join($,"file-history","workspaces",G,this.sessionId),Z=T.join(J,"manifest.json");try{await X.access(Z)}catch{await this.migrateLegacySnapshotDir(L,J,q)}this.snapshotDir=J,this.manifestPath=Z}async migrateLegacySnapshotDir($,q,G){let L;try{L=JSON.parse(await X.readFile(T.join($,"manifest.json"),"utf8"))}catch{return}if(L.schemaVersion!==1||!Array.isArray(L.snapshots)||!L.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,G)))return;await X.mkdir(T.dirname(q),{recursive:!0,mode:493});try{await X.rename($,q)}catch(J){let Z=J.code;if(Z!=="ENOENT"&&Z!=="EEXIST"&&Z!=="ENOTEMPTY")throw J}}isWithinWorkspace($,q){if(!T.isAbsolute($))return!1;let G=T.relative(q,T.resolve($));return G===""||G!==".."&&!G.startsWith(`..${T.sep}`)&&!T.isAbsolute(G)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let G=await this.resolveFileIdentity($),L=!0;try{await X.access(G)}catch{L=!1}let J=this.trackedFileBackups.get(G),Z=J?J.version+1:1,Q=this.generateFileHash(G,Z),V=this.getSnapshotPath(Q,Z),B=new Date;if(L){let K=await X.readFile(G);await X.writeFile(V,K)}let x={backupFileName:Q,version:Z,backupTime:B};return this.trackedFileBackups.set(G,x),this.snapshots.push({messageId:q,backupFileName:Q,timestamp:B,filePath:G,version:Z,existedBefore:L}),await this.cleanupOldSnapshots(G),await this.persistManifest(),x}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)throw Error(`未找到待完成的快照: ${G}`);L.postEditHash=await this.hashFile(G),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let G=await this.resolveFileIdentity($),L=this.snapshots.find((J)=>J.filePath===G&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!L)return;this.removeSnapshot(L),await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),G=this.snapshots.slice().reverse().find((Z)=>Z.filePath===q&&Z.postEditHash!==void 0);if(!G?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==G.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(G.backupFileName,G.version);if(G.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(q),{recursive:!0}),await X.writeFile(q,Z)}else await X.rm(q,{force:!0});return this.removeSnapshot(G),await X.rm(J,{force:!0}),await this.persistManifest(),G}async restoreSnapshot($,q){let G=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((Z)=>Z.messageId===q&&Z.filePath===G);if(!L)throw Error(`未找到快照: messageId=${q}, filePath=${G}`);let J=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let Z=await X.readFile(J);await X.mkdir(T.dirname(G),{recursive:!0}),await X.writeFile(G,Z)}else await X.rm(G,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((G)=>G.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((G)=>G.filePath),snapshotCount:q.reduce((G,L)=>G+L.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let G=new Map;for(let J of q){let Z,Q=!0;try{Z=await X.readFile(J.filePath)}catch(B){if(B.code!=="ENOENT")throw B;Q=!1}if((Z?Z0.createHash("sha256").update(Z).digest("hex"):D$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(G.set(J.filePath,{existed:Q,content:Z}),J.target.existedBefore)await X.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let L=[...this.snapshots];try{for(let Z of q)if(Z.target.existedBefore){let Q=await X.readFile(this.getSnapshotPath(Z.target.backupFileName,Z.target.version));await X.mkdir(T.dirname(Z.filePath),{recursive:!0}),await h0(Z.filePath,Q)}else await X.rm(Z.filePath,{force:!0});let J=new Set(q.flatMap((Z)=>Z.selected));this.snapshots=this.snapshots.filter((Z)=>!J.has(Z)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((Z)=>X.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=L,this.rebuildTrackedFileBackups();let Z=[];for(let[Q,V]of G)try{if(V.existed&&V.content)await h0(Q,V.content);else await X.rm(Q,{force:!0})}catch(B){Z.push(B)}if(Z.length>0)throw AggregateError([J,...Z],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,Z)=>J+Z.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),G=new Set(q.flatMap((J)=>J.selected));if(G.size===0)return{files:[],snapshotCount:0};let L=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!G.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=L,this.rebuildTrackedFileBackups(),J}return await Promise.all([...G].map((J)=>X.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:G.size}}buildRewindPlan($){let q=new Set($),G=this.snapshots.filter((Z)=>Z.postEditHash!==void 0),L=G.filter((Z)=>q.has(Z.messageId));return[...new Set(L.map((Z)=>Z.filePath))].sort().map((Z)=>{let Q=G.filter((K)=>K.filePath===Z),V=Q.filter((K)=>q.has(K.messageId)),B=Q.indexOf(V[0]),x=Q.slice(B);if(x.length!==V.length||x.some((K)=>!q.has(K.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${Z}`);return{filePath:Z,selected:V,target:V[0],latest:V.at(-1)}})}async loadManifest(){try{let $=await X.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(G)=>({...G,filePath:await this.resolveFileIdentity(G.filePath),timestamp:new Date(G.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await X.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await h0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let G=this.snapshots.filter((L)=>L.filePath===$).slice(0,-this.maxSnapshots);for(let L of G)await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),this.removeSnapshot(L)}async cleanup($=0){let q=this.snapshots.slice().sort((L,J)=>J.timestamp.getTime()-L.timestamp.getTime()),G=new Set(q.slice(0,$));for(let L of this.snapshots)if(!G.has(L))await X.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return T.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=T.resolve($),G=[],L=q;while(!0){try{let Z=await X.realpath(L);return T.join(Z,...G.reverse())}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw Z}let J=T.dirname(L);if(J===L)return q;G.push(T.basename(L)),L=J}}async hashFile($){try{let q=await X.readFile($);return Z0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return D$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let G=Z0.createHash("md5");return G.update(`${$}:${q}`),G.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}import{createHash as Oq}from"node:crypto";import Cq from"ajv";var E$="StructuredOutput",_$=65536,R$=131072,v1=2,f$=20,M$=1000,A$=200;function r($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function b$($,q){if(!r($))throw Error(`${q} must be a JSON object`);let G;try{G=JSON.stringify($)}catch(J){throw Error(`${q} must be JSON-serializable`,{cause:J})}if(G===void 0)throw Error(`${q} must be JSON-serializable`);let L=JSON.parse(G);if(!r(L))throw Error(`${q} must be a JSON object`);return L}function zq($){let q=0,G=0,L=(J,Z)=>{if(q++,q>M$)throw Error(`Output schema exceeds the ${M$} node complexity limit`);if(Z>f$)throw Error(`Output schema exceeds the ${f$} level depth limit`);if(Array.isArray(J)){for(let Q of J)L(Q,Z+1);return}if(!r(J))return;if("$ref"in J){let Q=J.$ref;if(typeof Q!=="string"||!(Q==="#"||Q.startsWith("#/$defs/")||Q.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in J&&r(J.properties)){if(G+=Object.keys(J.properties).length,G>A$)throw Error(`Output schema exceeds the ${A$} property limit`)}for(let Q of Object.values(J))L(Q,Z+1)};L($,0)}function Dq($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function _q($){let q=new Cq({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(G){throw Error(`Invalid output schema: ${G instanceof Error?G.message:String(G)}`)}}function k$($){let q=b$($,"Output schema"),G=JSON.stringify(q);if(Buffer.byteLength(G)>_$)throw Error(`Output schema exceeds ${_$} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');zq(q);let J=_q(q),Z=Oq("sha256").update(G).digest("hex");return{schema:q,schemaDigest:Z,declaration:{name:E$,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(Q){let V;try{V=b$(Q,"Structured output")}catch(x){return{success:!1,message:x instanceof Error?x.message:String(x)}}let B=JSON.stringify(V);if(Buffer.byteLength(B)>R$)return{success:!1,message:`Structured output exceeds ${R$} bytes`};if(!J(V))return{success:!1,message:Dq(J.errors)};return{success:!0,output:V}}}}function w$($,q){if(!r($))return;let G=r($.structuredOutput)?$.structuredOutput:$;if(G.schemaDigest!==q.schemaDigest||!("output"in G))return;let L=q.validate(G.output);return L.success?L.output:void 0}function P1($,q){for(let G=$.length-1;G>=0;G--){let L=$[G];if(!L)continue;if(L.role==="user")return;if(L.role==="assistant"){let Q=w$(L.metadata,q);if(Q)return{output:Q,completed:!0};continue}if(L.role!=="tool"||L.name!==E$)continue;let J=r(L.metadata)?L.metadata:void 0,Z=w$(J?.metadata,q);if(Z)return{output:Z,completed:!1}}return}import{createHash as mq}from"node:crypto";import u$ from"node:path";import{StringDecoder as Aq}from"node:string_decoder";function Rq($,q){let G=q;while(G<$.length&&($[G]&192)===128)G+=1;return G}class c0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?Buffer.from($):Buffer.from($);if(q.length===0)return;this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),omittedBytes:this.omittedBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}trimToLimit(){while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let q=this.retainedBytes-this.maxBytes;if($.length<=q){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length;continue}let G=Rq($,q);this.chunks[0]=$.subarray(G),this.retainedBytes-=G,this.omittedBytes+=G}}}var C0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},a={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},g$={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},fq={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},Mq=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:C0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:C0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:a,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:g$},{pattern:/^git\s+(status|branch|remote)/i,config:a},{pattern:/^git\s+(log|diff|show)/i,config:g$},{pattern:/^(ls|dir|tree)\s+/i,config:a,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:a,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:C0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:C0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:a,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:a,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];class l0{static getConfigForCommand($){for(let{pattern:q,config:G,summaryTemplate:L}of Mq)if(q.test($))return{config:G,summaryTemplate:L};return{config:fq}}static truncate($,q){let{config:G,summaryTemplate:L}=this.getConfigForCommand(q);return this.truncateWithConfig($,G,L)}static truncateWithConfig($,q,G){let L=$.length,J=$.split(`
4
4
  `),Z=J.length;if(Z<=q.maxLines&&L<=q.maxChars)return{content:$,truncated:!1,originalLines:Z,originalChars:L};let Q=J.slice(0,q.keepHead),V=J.slice(-q.keepTail),B=Z-q.keepHead-q.keepTail,x=Q.join(`
@@ -0,0 +1,5 @@
1
+ import{ee as R}from"./chunk-4dq9y7zn.js";import{lf as z,nf as _}from"./chunk-s5666ta0.js";import{qf as X}from"./chunk-dsj62dcg.js";var oe={openrouter:{"HTTP-Referer":"https://github.com/echoVic/blade-code","X-Title":"Blade"},cerebras:{"X-Cerebras-3rd-Party-Integration":"blade"}},N=(e)=>oe[e]||{};var ne=new Set(["user-cancel","interrupt","sibling-error","timeout"]);function A(e){return typeof e==="string"&&ne.has(e)}function Oe(e){if(!e.aborted)return;if(A(e.reason))return e.reason;return"user-cancel"}function Ne(e){if(A(e))return!0;if(!(e instanceof Error))return!1;if(e.name==="AbortError")return!0;if(e instanceof DOMException&&e.name==="AbortError")return!0;if(e.message.includes("aborted"))return!0;return!1}function U(...e){let t=e.filter(Boolean);if(t.length===0)return new AbortController().signal;if(t.length===1)return t[0];let o=AbortSignal;if(typeof o.any==="function")return o.any(t);for(let i of t)if(i.aborted)return i;let r=new AbortController,n=new Map;for(let i of t){let a=()=>{r.abort(i.reason);for(let[u,s]of n)u.removeEventListener("abort",s)};n.set(i,a)}for(let[i,a]of n)i.addEventListener("abort",a,{once:!0});return r.signal}function P(e,t,o){let r=o?.throwOnAbort??!1;if(t?.aborted){if(r)return Promise.reject(new DOMException("Aborted","AbortError"));return Promise.resolve()}return new Promise((n,i)=>{let a,u=setTimeout(()=>{if(t&&a)t.removeEventListener("abort",a);n()},e);if(t)a=()=>{if(clearTimeout(u),r)i(new DOMException("Aborted","AbortError"));else n()},t.addEventListener("abort",a,{once:!0})})}var re=R("Chat"),ie={input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}};function E(e){if(typeof e==="string")return e;return e.filter((t)=>t.type==="text").map((t)=>t.text).join(`
2
+ `)}function se(e){if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t==="object"&&!Array.isArray(t)?t:{}}catch{return re.warn("[PiAIChatService] Invalid historical tool arguments",{value:e}),{}}}function ae(e){let t=e.match(/^data:([^;,]+);base64,(.+)$/s);return t?{mimeType:t[1],data:t[2]}:void 0}async function ue(e,t){let o=ae(e);if(o)return{type:"image",...o};if(!/^https?:\/\//i.test(e))return{type:"text",text:`[Unsupported image source: ${e}]`};let r=await fetch(e,{signal:t});if(!r.ok)throw Error(`Failed to load image ${e}: HTTP ${r.status}`);return{type:"image",mimeType:r.headers.get("content-type")?.split(";")[0]??"image/png",data:Buffer.from(await r.arrayBuffer()).toString("base64")}}async function j(e,t,o,r,n){let i=e.filter((s)=>s.role==="system").map((s)=>E(s.content)).filter(Boolean).join(`
3
+
4
+ `),a=[];for(let s of e){if(s.role==="system")continue;if(s.role==="user"){let c=t.input.includes("image"),d=typeof s.content==="string"?s.content:await Promise.all(s.content.map((l)=>l.type==="text"?Promise.resolve({type:"text",text:l.text}):c?ue(l.image_url.url,r):Promise.resolve({type:"text",text:"[Image omitted: current model does not support image input]"})));a.push({role:"user",content:d,timestamp:Date.now()});continue}if(s.role==="assistant"){let c=[];if(s.reasoningContent?.trim())c.push({type:"thinking",thinking:s.reasoningContent});let d=E(s.content);if(d)c.push({type:"text",text:d});for(let l of s.tool_calls??[]){if(!("function"in l))continue;c.push({type:"toolCall",id:l.id,name:l.function.name,arguments:se(l.function.arguments)})}a.push({role:"assistant",content:c,api:t.api,provider:t.provider,model:t.id,usage:ie,stopReason:s.tool_calls?.length?"toolUse":"stop",timestamp:Date.now()});continue}a.push({role:"toolResult",toolCallId:s.tool_call_id??"",toolName:s.name??"unknown",content:[{type:"text",text:E(s.content)}],isError:!1,timestamp:Date.now()})}let u=o?.filter((s)=>!n||s.name===n).map((s)=>({name:s.name,description:s.description,parameters:s.parameters,constrainedSampling:s.constrainedSampling}));return{...i?{systemPrompt:i}:{},messages:a,...u?.length?{tools:u}:{}}}function F(e){let t=[];for(let o=0;o<e.length;o++){let r=e[o];if(r.role==="tool")continue;let n=r.role==="assistant"&&r.tool_calls?.length?r.tool_calls:void 0;if(!n){t.push(r);continue}let i=[],a=o+1;while(a<e.length&&e[a].role==="tool")i.push(e[a++]);let u=new Set(n.map((d)=>d.id)),s=i.filter((d)=>d.tool_call_id&&u.has(d.tool_call_id)),c=new Set(s.map((d)=>d.tool_call_id));if(u.size===n.length&&s.length===u.size&&c.size===u.size)t.push(r,...s);o=a-1}return t}function q(e){return e.some((t)=>t.role==="assistant"&&Boolean(t.tool_calls?.length)&&!t.reasoningContent?.trim())}function B(e,t){return{...e,...t.baseUrl?{baseUrl:z(e.api,t.baseUrl)}:{},...t.maxOutputTokens?{maxTokens:t.maxOutputTokens}:{}}}function S(e){let t=e.modelCatalog??_();return{models:t.models,model:B(t.getModel(e.provider,e.model),e)}}function V(e,t){let o=e.modelCatalog??_();return B(o.getModel(t.provider,t.model),e)}var de=["gousagelimiterror","freeusagelimiterror","monthly usage limit reached","available balance","insufficient_quota","out of budget","quota exceeded","billing"],ce=["prompt_too_long","prompt is too long","maximum context length","context length exceeded","context_length_exceeded","request too large"],le=["econnreset","econnrefused","enotfound","eai_again","etimedout","fetch failed","network error","connection error","connection refused","connection lost","other side closed","socket hang up","socket connection was closed","upstream connect","reset before headers","websocket closed","websocket error","http2 request did not get a response"];function me(e){return(e instanceof Error?e.message:String(e)).toLowerCase()}function pe(e){return e!==null&&typeof e==="object"&&"code"in e?e.code:void 0}function fe(e){if(e===null||typeof e!=="object")return;let t=e;for(let o of["status","statusCode"]){let r=t[o];if(typeof r==="number"&&Number.isInteger(r))return r}return}function he(e){let t=e.match(/^(?:error:\s*)?(\d{3})\b/),o=e.match(/\b(?:status(?:\s+code)?|http)[:\s]+(\d{3})\b/),r=Number(t?.[1]??o?.[1]);return Number.isInteger(r)?r:void 0}function T(e,t){let o=me(e),r=pe(e);if(r==="STREAM_IDLE_TIMEOUT"||e instanceof Error&&e.name==="AbortError"||o.includes("request aborted")||o==="aborted")return{retryable:!1};if(de.some((i)=>o.includes(i))||ce.some((i)=>o.includes(i)))return{retryable:!1};if(t?.shouldRetry==="false")return{retryable:!1,statusCode:t.statusCode};let n=t?.statusCode??fe(e)??he(o);if(t?.shouldRetry==="true")return{retryable:!0,reason:n===429?"rate_limit":n===408||n===409?"timeout":"server_error",statusCode:n};if(n===429)return{retryable:!0,reason:"rate_limit",statusCode:n};if(n===408||n===409)return{retryable:!0,reason:"timeout",statusCode:n};if(n!==void 0&&n>=500&&n<=599)return{retryable:!0,reason:"server_error",statusCode:n};if(r==="PROVIDER_STREAM_CLOSED"||o.includes("stream closed before completion")||o.includes("ended without")||o.includes("stream ended before"))return{retryable:!0,reason:"stream_closed",statusCode:n};if(le.some((i)=>o.includes(i)))return{retryable:!0,reason:"transport",statusCode:n};if(o.includes("timeout")||o.includes("timed out")||o.includes("temporarily unavailable")||o.includes("upstream_error")||o.includes("overloaded")||o.includes("rate limit")||o.includes("too many requests")||o.includes("service unavailable")||o.includes("server error")||o.includes("internal error")||o.includes("please retry")||o.includes("try your request again"))return{retryable:!0,reason:o.includes("rate")||o.includes("too many")?"rate_limit":o.includes("timeout")||o.includes("timed out")?"timeout":"server_error",statusCode:n};return{retryable:!1,statusCode:n}}function ye(e,t){if(!e)return;if(e.retryAfterMs!==void 0){let n=Number.parseFloat(e.retryAfterMs);if(Number.isFinite(n))return Math.max(0,n)}if(e.retryAfter===void 0)return;let o=Number.parseFloat(e.retryAfter);if(Number.isFinite(o))return Math.max(0,o*1000);let r=Date.parse(e.retryAfter);return Number.isFinite(r)?Math.max(0,r-t):void 0}function Y(e,t,o={}){let r=o.now??Date.now(),n=o.maxDelayMs??60000,i=ye(t,r);if(i!==void 0)return Math.min(Math.ceil(i),n);let a=Math.max(0,e-1),u=Math.min(500*2**a,8000),s=Math.max(0,Math.min(1,o.random??Math.random())),c=u*(0.75+s*0.25);return Math.min(Math.round(c),n)}function G(e,t){let o=e.onPayload;e.onPayload=async(r,n)=>{let i=o?await o(r,n):r;return t(i===void 0?r:i,n)}}function ge(e){if(!e.reasoningEnabled)return;return e.reasoningEffort??e.reasoningLevel??"high"}function Ce(e){switch(e){case"minimal":return"MINIMAL";case"low":return"LOW";case"medium":return"MEDIUM";default:return"HIGH"}}function Me(e,t,o,r){let n=r?void 0:ge(o);if(!n){if(t.api==="anthropic-messages")e.thinkingEnabled=!1;if(t.api==="google-generative-ai"||t.api==="google-vertex")e.thinking={enabled:!1};return}switch(t.api){case"anthropic-messages":e.thinkingEnabled=!0,e.effort=n;break;case"google-generative-ai":case"google-vertex":e.thinking={enabled:!0,level:Ce(n)};break;case"mistral-conversations":e.reasoningEffort="high";break;case"bedrock-converse-stream":case"pi-messages":e.reasoning=n;break;default:e.reasoningEffort=n}}function be(e,t,o){if(!o)return;switch(t){case"anthropic-messages":case"bedrock-converse-stream":e.toolChoice={type:"tool",name:o};break;case"openai-completions":case"mistral-conversations":case"pi-messages":e.toolChoice={type:"function",function:{name:o}};break;case"openai-responses":case"openai-codex-responses":case"azure-openai-responses":e.toolChoice={type:"function",name:o};break;case"google-generative-ai":case"google-vertex":e.toolChoice="any";break}}function Re(e,t,o){let r=o.serviceTier;if(!r)return;if(t.api==="openai-responses"||t.api==="openai-codex-responses"||t.api==="azure-openai-responses"){e.serviceTier=r;return}if(t.api!=="openai-completions"&&!(t.api==="anthropic-messages"&&r==="fast"))return;G(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;return t.api==="anthropic-messages"?{...n,speed:"fast"}:{...n,service_tier:r}})}function xe(e,t,o){let r=o.responseVerbosity;if(!r)return;if(X(t,r),t.api==="openai-codex-responses"){e.textVerbosity=r;return}G(e,(n)=>{if(!n||typeof n!=="object"||Array.isArray(n))return n;if(t.api==="openai-completions")return{...n,verbosity:r};let i="text"in n&&n.text&&typeof n.text==="object"&&!Array.isArray(n.text)?n.text:{};return{...n,text:{...i,verbosity:r}}})}function $(e,t,o,r,n=!1){let i={apiKey:e.apiKey,headers:e.customHeaders,signal:o,temperature:r?.temperature??e.temperature??0,maxTokens:r?.maxOutputTokens??e.maxOutputTokens,timeoutMs:e.timeout,maxRetries:0,cacheRetention:e.enablePromptCaching?"short":"none"};if(Me(i,t,e,n),be(i,t.api,r?.toolChoice?.toolName),Re(i,t,e),xe(i,t,e),t.api==="azure-openai-responses")i.azureBaseUrl=e.baseUrl,i.azureApiVersion=e.apiVersion,i.azureDeploymentName=t.id;return i}function H(e,t){let o=t.get("x-should-retry");return{statusCode:e,...t.get("retry-after")!==null?{retryAfter:t.get("retry-after")??void 0}:{},...t.get("retry-after-ms")!==null?{retryAfterMs:t.get("retry-after-ms")??void 0}:{},...o==="true"||o==="false"?{shouldRetry:o}:{}}}var ve=new Set(["anthropic-messages","openai-completions","openai-responses","openai-codex-responses","azure-openai-responses","pi-messages"]);function K(e,t,o){let r=e.onResponse;if(e.onResponse=async(i,a)=>{let u=new Headers(i.headers);o(H(i.status,u)),await r?.(i,a)},!ve.has(t.api)||typeof globalThis.fetch!=="function")return;let n=typeof e.fetch==="function"?e.fetch:globalThis.fetch.bind(globalThis);e.fetch=async(i,a)=>{let u=await n(i,a);return o(H(u.status,u.headers)),u}}function J(e){return{promptTokens:e.input+e.cacheRead+e.cacheWrite,completionTokens:e.output,totalTokens:e.totalTokens,costUsd:e.cost.total,...e.reasoning!==void 0?{reasoningTokens:e.reasoning}:{},...e.cacheWrite>0?{cacheCreationInputTokens:e.cacheWrite}:{},...e.cacheRead>0?{cacheReadInputTokens:e.cacheRead}:{}}}var O=300000,Te=30000;class Z extends Error{timeoutMs;code="STREAM_IDLE_TIMEOUT";constructor(e){super(`Provider stream idle timeout after ${e}ms without an event`);this.timeoutMs=e;this.name="StreamIdleTimeoutError"}}class Q extends Error{code="PROVIDER_STREAM_CLOSED";constructor(){super("Provider stream closed before completion");this.name="ProviderStreamClosedError"}}function I(e){return e.reason instanceof Error?e.reason:new DOMException("Aborted","AbortError")}function ke(e){return e.idleTimeoutMs&&e.idleTimeoutMs>0?e.idleTimeoutMs:O}function we(e,t){if(t===0)return;let o=t!==void 0&&t>0?t:Te;return Math.max(1,Math.min(o,Math.floor(e/2)))}function Ae(e,t,o){if(o?.aborted)return Promise.reject(I(o));return new Promise((r,n)=>{let i=!1,a=()=>{clearTimeout(d),o?.removeEventListener("abort",c)},u=(l)=>{if(i)return;i=!0,a(),r(l)},s=(l)=>{if(i)return;i=!0,a(),n(l instanceof Error?l:Error(String(l)))},c=()=>{if(o)s(I(o))},d=setTimeout(()=>u({kind:"timer"}),Math.max(0,t));if(o?.addEventListener("abort",c,{once:!0}),o?.aborted){c();return}e.then((l)=>u({kind:"next",result:l}),s)})}async function*Pe(e,t,o){let r=ke(t),n=we(r,t.stallWarningMs);if(t.signal?.aborted)throw I(t.signal);let i=Date.now(),a=Promise.resolve().then(()=>e.next()),u;for(;;){let c=await Ae(a,(u?r:n??r)-(Date.now()-i),t.signal);if(c.kind==="next"){if(u)yield{...u,phase:"recovered",durationMs:Math.max(u.durationMs,Date.now()-i)};return c.result}if(!u&&n!==void 0){o.stallCount++,u={phase:"detected",stallCount:o.stallCount,durationMs:n,warningAfterMs:n,timeoutMs:r,outputStarted:o.outputStarted},yield u;continue}let d=new Z(r);throw t.abort?.(d),d}}async function*ee(e,t,o,r,n={}){let a=e.stream(t,o,r)[Symbol.asyncIterator](),u=0,s=!1,c={stallCount:0,outputStarted:!1};try{while(!0){let d=Pe(a,n,c),l=await d.next();while(!l.done)yield{providerStall:l.value},l=await d.next();let x=l.value;if(x.done)throw new Q;let f=x.value;switch(f.type){case"text_delta":c.outputStarted=!0,yield{content:f.delta};break;case"thinking_delta":c.outputStarted=!0,yield{reasoningContent:f.delta};break;case"toolcall_end":c.outputStarted=!0,yield{toolCalls:[{index:u++,id:f.toolCall.id,type:"function",function:{name:f.toolCall.name,arguments:JSON.stringify(f.toolCall.arguments)}}]};break;case"done":s=!0,yield{finishReason:f.reason,usage:J(f.message.usage)};return;case"error":throw Error(f.error.errorMessage??`Request ${f.reason==="aborted"?"aborted":"failed"}`)}}}finally{if(!s)Promise.resolve(a.return?.()).catch(()=>{return})}}var te=R("Chat");function Ee(e){return Boolean(e&&e.role==="user"&&Array.isArray(e.content)&&e.content.some((t)=>t.type==="image_url"))}class D{config;models;model;constructor(e){let t=S(e);this.config={...e,maxContextTokens:t.model.contextWindow,maxOutputTokens:e.maxOutputTokens??t.model.maxTokens},this.models=t.models,this.model=t.model,te.debug("[PiAIChatService] Initialized",{provider:this.model.provider,model:this.model.id,api:this.model.api})}async chat(e,t,o,r){let n="",i="",a=[],u,s;for await(let c of this.streamChat(e,t,o,r)){n+=c.content??"",i+=c.reasoningContent??"";for(let d of c.toolCalls??[])if(d.id&&d.type==="function"&&d.function?.name)a.push(d);u=c.usage??u,s=c.finishReason??s}return{content:n,...i?{reasoningContent:i}:{},...a.length>0?{toolCalls:a}:{},usage:u,finishReason:s}}async*streamChat(e,t,o,r){let n=r?.toolChoice?.toolName;if(n&&!t?.some((m)=>m.name===n))throw Error(`Required tool is unavailable: ${n}`);let i=F(e);if(i.some((m)=>Ee(m))&&!this.model.input.includes("image"))throw Error(`${this.model.name} does not support image input`);let a=Boolean(n)||q(i),u=await j(i,this.model,t,o,n),s,c=(m)=>{s=void 0;let C=new AbortController,h=o?U(o,C.signal):C.signal,M=$(this.config,m,h,r,a);return K(M,m,(y)=>{s=y}),ee(this.models,m,u,M,{idleTimeoutMs:this.config.streamIdleTimeout??O,signal:h,abort:(y)=>C.abort(y)})},d=this.config.maxRetries??2,l=this,x=async function*(m,C){let h,M=!1,y,v;for(let g=0;g<=d;g++)try{let b=!1;for await(let p of c(m)){if(p.providerStall){yield p;continue}if(g>0&&y&&!b)b=!0,yield{providerRetry:{phase:"recovered",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};M=!0,C(),yield p}return}catch(b){h=b,l.logIdleTimeout(b,M,m),await l.handleAbort(o);let p=T(b,s);if(M)throw b;if(!p.retryable||!p.reason){if(g>0&&y)yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:y,...v!==void 0?{statusCode:v}:{}}};throw b}if(y=p.reason,v=p.statusCode,g<d){let k=g+1,w=Y(k,s);yield{providerRetry:{phase:"scheduled",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{},delayMs:w,nextRetryAt:Date.now()+w}},await P(w,o,{throwOnAbort:!0}),yield{providerRetry:{phase:"attempt",attempt:k,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}else yield{providerRetry:{phase:"exhausted",attempt:g,maxRetries:d,reason:p.reason,...p.statusCode!==void 0?{statusCode:p.statusCode}:{}}}}throw h},f,L=!1;try{for await(let m of x(this.model,()=>{L=!0}))yield m;return}catch(m){if(f=m,L||!T(m,s).retryable)throw m}for(let m of this.config.fallbackModels??[]){yield{modelFallback:!0};let C=!1;try{let h=V(this.config,m);for await(let M of x(h,()=>{C=!0}))yield M;return}catch(h){if(f=h,C||!T(h,s).retryable)throw h}}throw f}async handleAbort(e){if(e?.aborted)await P(0,e,{throwOnAbort:!0})}logIdleTimeout(e,t,o){if(e===null||typeof e!=="object"||!("code"in e)||e.code!=="STREAM_IDLE_TIMEOUT"||!("timeoutMs"in e)||typeof e.timeoutMs!=="number")return;te.warn("[PiAIChatService] Provider stream idle timeout",{provider:o.provider,model:o.id,timeoutMs:e.timeoutMs,replayBoundaryCrossed:t})}getConfig(){return{...this.config}}updateConfig(e){let t={...this.config,...e},o=S(t);this.config={...t,maxContextTokens:o.model.contextWindow,maxOutputTokens:t.maxOutputTokens??o.model.maxTokens},this.models=o.models,this.model=o.model}}var _e=R("Service");async function ut(e){let t=e;if(t.provider){let o=N(t.provider);if(Object.keys(o).length>0)t={...t,customHeaders:{...o,...t.customHeaders}},_e.debug(`Injected ${t.provider} specific headers:`,Object.keys(o))}return Se(t)}function Se(e){return new D(e)}
5
+ export{Oe as gd,Ne as hd,U as id,D as jd,ut as kd};
@@ -1,4 +1,4 @@
1
- import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-5wnxafpf.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as L}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as F}from"./chunk-g11hq0e5.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-097zrzyy.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-vmq248m7.js";import"./chunk-4dq9y7zn.js";import{Se as Q}from"./chunk-7bq9p4ab.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as L}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import{Mf as F}from"./chunk-g11hq0e5.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-h6w3ggx9.js"),{SessionService:B}=await import("./chunk-25abj6rx.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,4 +1,4 @@
1
- import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-kfgv64hg.js";import{Ae as S,De as yn,Ee as Ht,Fe as Bt,Ge as R,He as qt,ge as xt,he as tn,ie as en,je as zt,ke as B,le as rn,me as gt,ne as mt,pe as dn,qe as En,re as U,se as on,te as pn,ue as cn,ve as lt,we as un,xe as Mn,ye as wn}from"./chunk-5wnxafpf.js";import{Ye as X,_e as x}from"./chunk-kvx3sb3z.js";import{if as vt}from"./chunk-5s123nbs.js";import{vf as nn,wf as sn}from"./chunk-cy6emyt9.js";import{Mf as ss}from"./chunk-g11hq0e5.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-ng8a4btc.js";import{Ae as S,De as yn,Ee as Ht,Fe as Bt,Ge as R,He as qt,ge as xt,he as tn,ie as en,je as zt,ke as B,le as rn,me as gt,ne as mt,pe as dn,qe as En,re as U,se as on,te as pn,ue as cn,ve as lt,we as un,xe as Mn,ye as wn}from"./chunk-7bq9p4ab.js";import{Ye as X,_e as x}from"./chunk-kvx3sb3z.js";import{if as vt}from"./chunk-5s123nbs.js";import{vf as nn,wf as sn}from"./chunk-7x5cqfy7.js";import{Mf as ss}from"./chunk-g11hq0e5.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{m as R,n as I,o as C,p as v,q as S}from"./chunk-c9m16hqc.js";import{F as y,L as w}from"./chunk-nysyp11q.js";import"./chunk-c477j84k.js";import"./chunk-p4zt7ts9.js";import{Va as x,hb as U}from"./chunk-p42cz164.js";import"./chunk-095x2ykj.js";import{$b as b,Tb as k}from"./chunk-97fyx4hr.js";import"./chunk-4hawehmd.js";import{sc as P}from"./chunk-x9t4ryyf.js";import{uc as h,vc as O,wc as M}from"./chunk-pmz455nq.js";import{xc as z}from"./chunk-632rgzcf.js";import"./chunk-ktf3bpmw.js";import{Uc as N}from"./chunk-xjyctv33.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-k653znk8.js";import"./chunk-cx0tdprs.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-kfgv64hg.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-5wnxafpf.js";import{Ue as D}from"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as E}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-cy6emyt9.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace 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"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
1
+ import{m as R,n as I,o as C,p as v,q as S}from"./chunk-2cqsqrxx.js";import{F as y,L as w}from"./chunk-x1qw695m.js";import"./chunk-ee7an1kq.js";import"./chunk-p4zt7ts9.js";import{Va as x,hb as U}from"./chunk-mc29y7tj.js";import"./chunk-095x2ykj.js";import{$b as b,Tb as k}from"./chunk-csn0epd2.js";import"./chunk-4hawehmd.js";import{sc as P}from"./chunk-0z7rg4f3.js";import{uc as h,vc as O,wc as M}from"./chunk-5wecprcp.js";import{xc as z}from"./chunk-632rgzcf.js";import"./chunk-ktf3bpmw.js";import{Uc as N}from"./chunk-zn7c21zj.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-d7976m5f.js";import"./chunk-2mzcxq6c.js";import"./chunk-8j01ssaf.js";import"./chunk-m4f213hk.js";import"./chunk-agdamn30.js";import"./chunk-9tnaads5.js";import"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-ng8a4btc.js";import"./chunk-7wjy6kgt.js";import"./chunk-4dq9y7zn.js";import"./chunk-7bq9p4ab.js";import{Ue as D}from"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import{if as E}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-7x5cqfy7.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace 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"}),async(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
2
2
  `);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSession(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
3
3
  `);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
4
4
  `);else q.stdout.write(`${k(H.record)}
@@ -1,2 +1,2 @@
1
- import{C as o}from"./chunk-nysyp11q.js";import{$b as i}from"./chunk-97fyx4hr.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
1
+ import{C as o}from"./chunk-x1qw695m.js";import{$b as i}from"./chunk-csn0epd2.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
2
  export{m as s};
@@ -1,2 +1,2 @@
1
- import{Se as F}from"./chunk-5wnxafpf.js";import{mf as D,nf as E}from"./chunk-s5666ta0.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
1
+ import{Se as F}from"./chunk-7bq9p4ab.js";import{mf as D,nf as E}from"./chunk-s5666ta0.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
2
2
  export{H as qd,Q as rd,T as sd};