blade-code 0.10.69 → 0.10.70

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 (70) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-g324ww9d.js → chunk-0kmrvxsz.js} +262 -263
  3. package/dist/{chunk-ypqp368c.js → chunk-0p0e70cy.js} +1 -1
  4. package/dist/{chunk-crkkpx3m.js → chunk-0p95nha3.js} +1 -1
  5. package/dist/{chunk-2da7j2sw.js → chunk-1bcp0qc4.js} +1 -1
  6. package/dist/{chunk-6pkyc8r6.js → chunk-1z9k5dmz.js} +1 -1
  7. package/dist/{chunk-bbcb9jzb.js → chunk-20vj0npz.js} +1 -1
  8. package/dist/chunk-2z75emht.js +1 -0
  9. package/dist/{chunk-2e7sedzn.js → chunk-31k6x4kn.js} +2 -2
  10. package/dist/chunk-3j413cgh.js +1 -0
  11. package/dist/chunk-4aam3qhk.js +8 -0
  12. package/dist/{chunk-efemjy9y.js → chunk-4md4sd4j.js} +1 -1
  13. package/dist/{chunk-kwv6vyst.js → chunk-5wnx38ze.js} +1 -1
  14. package/dist/{chunk-1z9wct9w.js → chunk-63121s4r.js} +1 -1
  15. package/dist/{chunk-n6rgqmf7.js → chunk-728anavt.js} +1 -1
  16. package/dist/{chunk-dfrgc84s.js → chunk-7b5s752s.js} +1 -1
  17. package/dist/{chunk-c8h3c8an.js → chunk-832va1mp.js} +1 -1
  18. package/dist/{chunk-b793bj62.js → chunk-83b4vfjs.js} +7 -7
  19. package/dist/chunk-8bsyhr4v.js +1 -0
  20. package/dist/{chunk-ppsvzgs5.js → chunk-8wea3qty.js} +2 -2
  21. package/dist/{chunk-yvg961q3.js → chunk-b2p4kd07.js} +1 -1
  22. package/dist/{chunk-kf070906.js → chunk-b39p4f5r.js} +1 -1
  23. package/dist/{chunk-7cm6tfnn.js → chunk-bkajr86v.js} +1 -1
  24. package/dist/{chunk-16n849z3.js → chunk-brdxkp0y.js} +1 -1
  25. package/dist/chunk-c0qm0wwk.js +1 -0
  26. package/dist/{chunk-xjse24zd.js → chunk-cmpj3a5a.js} +1 -1
  27. package/dist/chunk-cx5s0rf3.js +1 -0
  28. package/dist/{chunk-1xjzd1jn.js → chunk-d2vrbbvd.js} +1 -1
  29. package/dist/{chunk-98n2rxmq.js → chunk-d808m826.js} +1 -1
  30. package/dist/chunk-e3asq942.js +1 -0
  31. package/dist/{chunk-zdxxqchm.js → chunk-f7yfcw8s.js} +1 -1
  32. package/dist/{chunk-8gd0ksz7.js → chunk-ffym3kf3.js} +1 -1
  33. package/dist/{chunk-50jthhfq.js → chunk-g28pgqyn.js} +1 -1
  34. package/dist/{chunk-ftmbgtnk.js → chunk-h94vfh7s.js} +1 -1
  35. package/dist/{chunk-5d2cdvdy.js → chunk-jrr361h1.js} +1 -1
  36. package/dist/{chunk-hcv17986.js → chunk-k6shq7rk.js} +1 -1
  37. package/dist/chunk-nea4rcdf.js +1 -0
  38. package/dist/{chunk-qd9vk8t1.js → chunk-p9vaaayr.js} +6 -6
  39. package/dist/{chunk-68zek95f.js → chunk-pw87f92g.js} +1 -1
  40. package/dist/chunk-q919ypcz.js +5 -0
  41. package/dist/{chunk-asgyyv1s.js → chunk-qm5c9wew.js} +2 -2
  42. package/dist/{chunk-jj0b6n20.js → chunk-qstf0gpe.js} +1 -1
  43. package/dist/{chunk-nxek5ev2.js → chunk-r9n8y8m1.js} +1 -1
  44. package/dist/{chunk-qjg390mv.js → chunk-rpfa4a56.js} +1 -1
  45. package/dist/{chunk-v712dqde.js → chunk-sch01e04.js} +1 -1
  46. package/dist/{chunk-a0j0xwt1.js → chunk-sh17gjxv.js} +1 -1
  47. package/dist/{chunk-rpmmy3qs.js → chunk-smjkx71w.js} +1 -1
  48. package/dist/chunk-v3kkv21n.js +1 -0
  49. package/dist/{chunk-z9p0by31.js → chunk-w2gr97qt.js} +1 -1
  50. package/dist/{chunk-ptcb5fb7.js → chunk-wahhwjp9.js} +1 -1
  51. package/dist/{chunk-5147jh26.js → chunk-wepvrnmh.js} +1 -1
  52. package/dist/chunk-wj6t3tv2.js +3 -0
  53. package/dist/chunk-wkpacysr.js +166 -0
  54. package/dist/{chunk-4ge1jkf8.js → chunk-y9d9nqnn.js} +1 -1
  55. package/dist/{chunk-dktrankr.js → chunk-ypgjqg23.js} +1 -1
  56. package/dist/{chunk-kmarzy98.js → chunk-ysmqje92.js} +1 -1
  57. package/dist/{chunk-mgv3qr9b.js → chunk-z77c18j5.js} +1 -1
  58. package/package.json +1 -1
  59. package/dist/chunk-0f8nn2h1.js +0 -5
  60. package/dist/chunk-8gzm51m8.js +0 -1
  61. package/dist/chunk-bvyydst6.js +0 -166
  62. package/dist/chunk-e7pssnr9.js +0 -1
  63. package/dist/chunk-eym0bdee.js +0 -1
  64. package/dist/chunk-hsgcdk2a.js +0 -1
  65. package/dist/chunk-m65pse74.js +0 -1
  66. package/dist/chunk-q9y9hxnt.js +0 -1
  67. package/dist/chunk-qz0pe10c.js +0 -1
  68. package/dist/chunk-t2gq918a.js +0 -3
  69. package/dist/chunk-w3fy09rw.js +0 -8
  70. package/dist/chunk-w67k19a1.js +0 -1
@@ -1,3 +1,3 @@
1
- import{yh as $,zh as F}from"./chunk-ppsvzgs5.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{Ah as F,zh as $}from"./chunk-8wea3qty.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as l};
@@ -1,4 +1,4 @@
1
- import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-98n2rxmq.js";import{_g as $t,bh as J}from"./chunk-ypqp368c.js";import{jh as an,kh as xn}from"./chunk-4ge1jkf8.js";import{ph as h}from"./chunk-t2gq918a.js";import{zh as mn}from"./chunk-ppsvzgs5.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-d808m826.js";import{_g as $t,bh as J}from"./chunk-0p0e70cy.js";import{jh as an,kh as xn}from"./chunk-y9d9nqnn.js";import{qh as h}from"./chunk-wj6t3tv2.js";import{Ah as mn}from"./chunk-8wea3qty.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=y.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+kt;while(Date.now()<M)try{let e=await P.open(n,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!nM(M.pid))await P.unlink(n)}}var cn="127.0.0.1",bn=7777,wn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Pn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -1,2 +1,2 @@
1
- import{jh as d,lh as h}from"./chunk-4ge1jkf8.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
1
+ import{jh as d,lh as h}from"./chunk-y9d9nqnn.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is disposed",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
2
2
  export{q as jd,w as kd};
@@ -1,4 +1,4 @@
1
- import{f as T,g as W,h as X,i as Y}from"./chunk-w3fy09rw.js";import"./chunk-dktrankr.js";import"./chunk-yvg961q3.js";import"./chunk-rpmmy3qs.js";import"./chunk-z9p0by31.js";import"./chunk-1xjzd1jn.js";import"./chunk-g324ww9d.js";import"./chunk-b793bj62.js";import"./chunk-5147jh26.js";import"./chunk-bvyydst6.js";import"./chunk-th4jjfgm.js";import"./chunk-6pkyc8r6.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as R}from"./chunk-n6rgqmf7.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-qd9vk8t1.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-c8h3c8an.js";import"./chunk-ptcb5fb7.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-asgyyv1s.js";import"./chunk-m57w4p91.js";import"./chunk-kf070906.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-4ge1jkf8.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import m from"chalk";import K from"open";var A=`
1
+ import{f as T,g as W,h as X,i as Y}from"./chunk-4aam3qhk.js";import"./chunk-ypgjqg23.js";import"./chunk-b2p4kd07.js";import"./chunk-smjkx71w.js";import"./chunk-w2gr97qt.js";import"./chunk-d2vrbbvd.js";import"./chunk-0kmrvxsz.js";import"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import"./chunk-wkpacysr.js";import"./chunk-th4jjfgm.js";import"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{qd as R}from"./chunk-728anavt.js";import"./chunk-bjqjdw34.js";import{Md as Q}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import{jh as M}from"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import m from"chalk";import K from"open";var A=`
2
2
  ____ _ _
3
3
  | __ )| | __ _ __| | ___
4
4
  | _ \\| |/ _\` |/ _\` |/ _ \\
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e}from"./chunk-sch01e04.js";import"./chunk-y9d9nqnn.js";import"./chunk-k6shq7rk.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,4 +1,4 @@
1
- import{s as Pz,t as xz}from"./chunk-rpmmy3qs.js";import{u as E}from"./chunk-z9p0by31.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-1xjzd1jn.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-g324ww9d.js";import{wa as qz}from"./chunk-b793bj62.js";import"./chunk-5147jh26.js";import{db as n,pb as t,yb as s}from"./chunk-bvyydst6.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-6pkyc8r6.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{qd as Ez}from"./chunk-n6rgqmf7.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-qd9vk8t1.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-0f8nn2h1.js";import"./chunk-efemjy9y.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-c8h3c8an.js";import"./chunk-ptcb5fb7.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-asgyyv1s.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-kf070906.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-98n2rxmq.js";import"./chunk-ypqp368c.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-4ge1jkf8.js";import"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as Pz,t as xz}from"./chunk-smjkx71w.js";import{u as E}from"./chunk-w2gr97qt.js";import{A as Hz,v as Nz,w as $z,x as Qz,y as Wz,z as Yz}from"./chunk-d2vrbbvd.js";import{E as N,N as e,Q as zz,R as Jz,V as Zz,ja as jz,ka as Xz,la as Dz,ma as Lz}from"./chunk-0kmrvxsz.js";import{wa as qz}from"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import{db as n,pb as t,yb as s}from"./chunk-wkpacysr.js";import{Hb as M}from"./chunk-th4jjfgm.js";import{Ac as a,Cc as x,Fc as o,Kc as R,Nc as F,_b as m,ic as d,jc as v,oc as l,rc as i,tc as r,zc as k}from"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{qd as Ez}from"./chunk-728anavt.js";import"./chunk-bjqjdw34.js";import{Ld as _z,Md as Oz}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import{Xd as I}from"./chunk-0j22w4wh.js";import{$d as p}from"./chunk-q919ypcz.js";import"./chunk-4md4sd4j.js";import{ie as Az}from"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import{Te as Rz}from"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import{Lf as wz,Of as Kz}from"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as h,rg as c,sg as S}from"./chunk-xz6y0w4n.js";import{wg as Fz}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Xg as T}from"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import{ch as Uz,fh as Vz}from"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import{Readable as uz,Writable as gz}from"node:stream";import*as b from"@agentclientprotocol/sdk";import Gz from"node:path";import{PROTOCOL_VERSION as Cz,RequestError as fz}from"@agentclientprotocol/sdk";import{RequestError as yz}from"@agentclientprotocol/sdk";import{nanoid as y}from"nanoid";var B=T("Agent");function g(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function hz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:g(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:g("headers"in z?z.headers:void 0)};return null}function Sz(z){let Z={};for(let J of z){let Y=hz(J);if(Y)Z[J.name]=Y}return Z}function Bz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function Mz(z){let Z=a(z.metadata);return Z?[{type:"text",text:k(Z)}]:Bz(z.content)}function kz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function Iz(z){if(!p(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...d("capacity"),resource:z.resource}}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Hz({maxPendingItems:$z,maxPendingBytes:Qz,writeTimeoutMs:Wz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([F.loadSession(this.id,this.cwd),F.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await F.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Zz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(B.debug(`[AcpSession ${this.id}] Initializing...`),await F.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),B.debug(`[AcpSession ${this.id}] ACP service context initialized`),await s.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?Sz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await e.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(X)=>Q.onOutput?.("stdout",X)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Xz(this.cwd),B.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=n.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!r(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of Mz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);B.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{B.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,D,G=(U)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:U.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:U.result?.message||U.result?.error||`Subagent ${U.status}`}}]})},L=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(U)=>{if(X)G(U);else D=U}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,D)G(D);return L}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,X)},complete:async(Q,j,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,X)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),D=await X.completion,G=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!G)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:D.status,findings:D.findings.length,content:m(G.start,D)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,X)=>{let D=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,G=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:G})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Dz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await F.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){return B.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let z=Lz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});B.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),B.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){B.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((L)=>L.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=o(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let L=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!L.accepted)throw Error(L.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(B.debug(`[AcpSession ${this.id}] Queued steering for active turn (${L.queued})`),L.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let j=new AbortController,X=!1,D,G=new Promise((L)=>{D=L});this.pendingPrompt=j,this.pendingPromptCompletion=G;try{if(B.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),jz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,j.signal)}let L={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},U=await t(this.agent.chatStream(Y,L,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let A=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let q=JSON.parse(V.function.arguments),K=q.resume_from??q.resume;if(typeof K==="string")w=`Resuming ${String(q.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:A});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,A=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;A.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))A.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,Tz=Jz(i(zz(K,O),l));A.push({type:"content",content:{type:"text",text:Tz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))A.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let q=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:q,content:A});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
@@ -0,0 +1 @@
1
+ import{f as a,g as i,h as l,i as m}from"./chunk-4aam3qhk.js";import"./chunk-ypgjqg23.js";import"./chunk-b2p4kd07.js";import"./chunk-smjkx71w.js";import"./chunk-w2gr97qt.js";import"./chunk-d2vrbbvd.js";import"./chunk-0kmrvxsz.js";import"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import"./chunk-wkpacysr.js";import"./chunk-th4jjfgm.js";import"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{qd as n}from"./chunk-728anavt.js";import"./chunk-bjqjdw34.js";import{Md as s}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,2 +1,2 @@
1
- import{K as I}from"./chunk-g324ww9d.js";import{Nc as M}from"./chunk-6pkyc8r6.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{K as I}from"./chunk-0kmrvxsz.js";import{Nc as M}from"./chunk-1z9k5dmz.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -1,3 +1,3 @@
1
- import{zh as j}from"./chunk-ppsvzgs5.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
1
+ import{Ah as j}from"./chunk-8wea3qty.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
2
2
  `)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
3
3
  export{m as Ug,I as Vg,M as Wg,V as Xg,h as Yg};
@@ -0,0 +1 @@
1
+ import{ke as a,le as b,me as c}from"./chunk-832va1mp.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1,4 +1,4 @@
1
- import{Xg as r}from"./chunk-98n2rxmq.js";import{Ah as i,rh as d,th as x,vh as j,zh as u}from"./chunk-ppsvzgs5.js";import{Bh as y}from"./chunk-hcv17986.js";import{stat as a}from"node:fs/promises";import k from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let M=W===void 0?e:W;if(!Number.isInteger(M)||M<1||M>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:M,includeSubagents:$,archived:H}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let H of W){if(typeof H!=="string"||!E.has(H))throw Error(`Invalid session ${R} filter`);$.add(H)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((M)=>Y_(M,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:m(_,E),createdAt:R.data.createdAt}}function m(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function h(_,E){N(_,E);let R=_.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((M)=>M.type==="turn_started"&&$&&M.data.inputMessageIds?.includes($)?[M.data.turnId]:[]));return _.filter((M,Q)=>{if((M.type==="turn_started"||M.type==="turn_completed"||M.type==="turn_aborted")&&H.has(M.data.turnId))return!1;return Q<R||!G_(M)})}function D(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=h(E,R.data.targetMessageId)}return E}function j_(_){let E=D(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=D(_),W=N(R,E),$=R.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:H.filter(O).length,snapshotMessageIds:H.flatMap((M)=>M.type==="part_created"&&M.data.partType==="tool_call"?[M.data.partId]:[])}}import*as I from"node:fs";import{createReadStream as T_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as Z_}from"node:readline";var b=65536;function w(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function g_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
1
+ import{Xg as r}from"./chunk-d808m826.js";import{Ah as u,Bh as i,sh as d,uh as x,wh as j}from"./chunk-8wea3qty.js";import{Ch as y}from"./chunk-k6shq7rk.js";import{stat as a}from"node:fs/promises";import k from"node:path";import*as U from"node:path";var e=50,__=100,E_=new Set(["queued","running","completed","failed","cancelled","interrupted"]),R_=new Set(["high","medium","low"]),W_=/^[A-Za-z0-9_-]+$/,$_=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function H_(_){return typeof _==="string"&&$_.test(_)&&Number.isFinite(Date.parse(_))}function v(_){return typeof _==="string"&&U.isAbsolute(_)}function M_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function Q_(_){try{if(!W_.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||v(R.cwd))||!H_(R.lastMessageTime)||!v(R.projectPath)||!x(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function J(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function V_(_){if(!_.cursor)return;let E=Q_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function O_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let M=W===void 0?e:W;if(!Number.isInteger(M)||M<1||M>__)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:M,includeSubagents:$,archived:H}}function N_(_={}){let E=c(_.taskStatus,E_,"task status"),R=c(_.taskPriority,R_,"task priority"),W=S(_.taskDueAfter,"taskDueAfter"),$=S(_.taskDueBefore,"taskDueBefore");return X_(W,$),{...E?{taskStatuses:E}:{},...R?{taskPriorities:R}:{},...W?{taskDueAfter:W}:{},...$?{taskDueBefore:$}:{}}}function c(_,E,R){if(_===void 0)return;let W=Array.isArray(_)?_:[_];if(W.length===0)return;let $=new Set;for(let H of W){if(typeof H!=="string"||!E.has(H))throw Error(`Invalid session ${R} filter`);$.add(H)}return[...$].sort()}function S(_,E){if(_===void 0)return;if(typeof _!=="string"||!Number.isFinite(Date.parse(_)))throw Error(`Invalid session ${E} filter`);return new Date(_).toISOString()}function X_(_,E){if(_!==void 0&&E!==void 0&&_>E)throw Error("Session task due range is inverted")}function Y_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function f_(_,E){let R=[..._],W=V_(E);if(W)R=R.filter((M)=>Y_(M,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:M_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function G_(_){return _.type==="message_created"||_.type==="token_budget_handoff_recorded"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function O(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function N(_,E){let R=_.find((W)=>O(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:m(_,E),createdAt:R.data.createdAt}}function m(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function h(_,E){N(_,E);let R=_.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((M)=>M.type==="turn_started"&&$&&M.data.inputMessageIds?.includes($)?[M.data.turnId]:[]));return _.filter((M,Q)=>{if((M.type==="turn_started"||M.type==="turn_completed"||M.type==="turn_aborted")&&H.has(M.data.turnId))return!1;return Q<R||!G_(M)})}function D(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(N(E,R.data.targetMessageId),R.data.mode!=="code")E=h(E,R.data.targetMessageId)}return E}function j_(_){let E=D(_);return E.filter(O).map((R)=>({messageId:R.data.messageId,preview:m(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function u_(_,E){let R=D(_),W=N(R,E),$=R.findIndex((M)=>M.type==="message_created"&&M.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:h(R,E),removedTurns:H.filter(O).length,snapshotMessageIds:H.flatMap((M)=>M.type==="part_created"&&M.data.partType==="tool_call"?[M.data.partId]:[])}}import*as I from"node:fs";import{createReadStream as T_}from"node:fs";import*as X from"node:fs/promises";import*as f from"node:path";import{createInterface as Z_}from"node:readline";var b=65536;function w(_){let E=_.data;if(E===null||typeof E!=="object"||Array.isArray(E))throw Error("Session event data must be a JSON object");return JSON.stringify(_)}function g_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function z(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
3
  `),$=[];for(let[H,M]of R.entries())try{let Q=g_(M,H+1,E);if(Q){if(typeof Q.seq!=="number")Q.seq=$.length+1;$.push(Q)}}catch(Q){if(W&&H===R.length-1)break;throw Q}return $}class G{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return G.stampSeqFrom(_,G.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(f.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=G.stampSeqFrom(_,W),H=`${$.map(w).join(`
4
4
  `)}
@@ -1,4 +1,4 @@
1
- import{b as QY,c as JY,d as YY}from"./chunk-v712dqde.js";import{j as _J,k as NJ}from"./chunk-dktrankr.js";import{u as c8}from"./chunk-z9p0by31.js";import{$ as vJ,B as w6,D as HY,F as s2,G as a2,H as O6,N as h1,P as V4,Q as j4,V as Y8,W as fJ,X as kJ,_ as SJ,da as $4,ea as D6,ga as k6,ha as S6,ia as WY,ja as d4,la as r4,na as b6}from"./chunk-g324ww9d.js";import{ra as x9,sa as u9,ta as l9,wa as FY}from"./chunk-b793bj62.js";import"./chunk-5147jh26.js";import{cb as e4,db as $6,pb as Q6,yb as u2}from"./chunk-bvyydst6.js";import{Hb as K8}from"./chunk-th4jjfgm.js";import{Ac as m4,Cc as V8,Kc as J8,Nc as P0,_b as a4,mc as v4,rc as D4,yc as g4,zc as x2}from"./chunk-6pkyc8r6.js";import"./chunk-0wxkymqv.js";import"./chunk-zdxxqchm.js";import{od as eJ}from"./chunk-s7jsadnc.js";import{pd as G8,qd as x8,sd as f1}from"./chunk-n6rgqmf7.js";import"./chunk-bjqjdw34.js";import{Ad as v$,Bd as j8,Cd as z9,Dd as uQ,Ed as ZJ,Fd as _9,Gd as f$,Hd as $1,Id as _Y,Jd as a0,Kd as sJ,Ld as P2,Md as Z8,Pd as u4,Wd as m0,wd as C$,xd as r0,yd as Q$,zd as yQ}from"./chunk-qd9vk8t1.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-0f8nn2h1.js";import{he as lQ}from"./chunk-efemjy9y.js";import"./chunk-yn51162x.js";import"./chunk-c8h3c8an.js";import{Ae as TJ,Je as NY,se as I6,ve as uJ}from"./chunk-ptcb5fb7.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import{$e as z1,Ze as CQ}from"./chunk-asgyyv1s.js";import"./chunk-m57w4p91.js";import{bg as OY,gg as IJ,hg as zY}from"./chunk-kf070906.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as D$,rg as h8,sg as IQ}from"./chunk-xz6y0w4n.js";import{wg as l0}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Ug as UY,Xg as e1}from"./chunk-98n2rxmq.js";import{Zg as UJ,_g as OJ,bh as E1}from"./chunk-ypqp368c.js";import"./chunk-t8xmh4w2.js";import{nh as e9}from"./chunk-4ge1jkf8.js";import{ph as eQ}from"./chunk-t2gq918a.js";import"./chunk-5d2cdvdy.js";import"./chunk-ppsvzgs5.js";import{Bh as MQ}from"./chunk-hcv17986.js";import{useMemoizedFn as v2}from"ahooks";import{useEffect as J7,useState as D2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as oX,useRef as f2}from"react";import{useShallow as BY}from"zustand/react/shallow";import{useStore as LY}from"zustand";function t($){return LY(f$,$)}var wY=[],k$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),Q4=()=>t(($)=>$.session.messages),J4=()=>t(($)=>$.session.clearCount),Y4=()=>t(($)=>$.session.isCompacting),Z4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return $4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),K4=()=>t(($)=>$.session.providerCircuit),G4=()=>t(($)=>$.session.providerAdmission),q4=()=>t(($)=>$.session.providerRetry),U4=()=>t(($)=>$.session.providerStall),O4=()=>t(($)=>$.session.actionStationarity),n1=()=>t(($)=>$.session.actions),z4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),_4=()=>t(($)=>$.app.initializationStatus),N4=()=>t(($)=>$.app.initializationError),y8=()=>t(($)=>$.app.activeModal),F4=()=>t(($)=>$.app.tasks),H4=()=>t(($)=>$.app.modelEditorTarget),W4=()=>t(($)=>$.app.sessionSelectorData),L4=()=>t(($)=>$.app.awaitingSecondCtrlC),t1=()=>t(($)=>$.app.actions),R8=()=>t(($)=>$.app.initializationStatus==="ready"),B4=()=>t(($)=>$.app.tasks.length>0),S$=()=>t(($)=>$.config.config?.permissionMode||"default"),w4=()=>t(($)=>$.config.config?.models??wY),M8=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),C8=()=>t(($)=>$.config.config?.currentModelId),A0=()=>t(($)=>{return r0.getTheme()}),b4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),A4=()=>t(($)=>$.focus.actions),s1=()=>t(($)=>$.command.isProcessing),P4=()=>t(($)=>$.command.actions),I8=()=>t(($)=>$.command.pendingCommands),y4=()=>t(($)=>$.command.recoveredSteeringCount),T8=()=>t(($)=>$.app.thinkingModeEnabled),f8=()=>t(($)=>$.app.reasoningEffort),k8=()=>t(($)=>$.app.serviceTier),S8=()=>t(($)=>$.app.responseVerbosity),v8=()=>t(($)=>$.app.communicationStyle),R4=()=>t(($)=>$.session.currentThinkingContent),M4=()=>t(($)=>$.session.thinkingExpanded),C4=()=>t(($)=>$.session.currentStreamingMessageId),I4=()=>t(BY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),T4=()=>t(($)=>$.session.finalizingStreamingMessageId),f4=()=>t(($)=>$.session.historyExpanded),k4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as j$}from"ahooks";import{useEffect as l8,useRef as t4}from"react";function bY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function AY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function PY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function D8($){let Q=AY($),Y=PY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=bY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as yY,mkdirSync as RY,writeFileSync as MY}from"node:fs";import CY from"node:os";import h2 from"node:path";var S4=null;function IY(){let $=process.env.BLADE_STORAGE_ROOT||h2.join(CY.homedir(),".blade");return h2.join($,"logs","stream-debug.log")}function TY($){if(S4===$)return;let Q=h2.dirname($);RY(Q,{recursive:!0,mode:493}),MY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
1
+ import{b as QY,c as JY,d as YY}from"./chunk-sch01e04.js";import{j as _J,k as NJ}from"./chunk-ypgjqg23.js";import{u as c8}from"./chunk-w2gr97qt.js";import{$ as vJ,B as w6,D as HY,F as s2,G as a2,H as O6,N as h1,P as V4,Q as j4,V as Y8,W as fJ,X as kJ,_ as SJ,da as $4,ea as D6,ga as k6,ha as S6,ia as WY,ja as d4,la as r4,na as b6}from"./chunk-0kmrvxsz.js";import{ra as x9,sa as u9,ta as l9,wa as FY}from"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import{cb as e4,db as $6,pb as Q6,yb as u2}from"./chunk-wkpacysr.js";import{Hb as K8}from"./chunk-th4jjfgm.js";import{Ac as m4,Cc as V8,Kc as J8,Nc as P0,_b as a4,mc as v4,rc as D4,yc as g4,zc as x2}from"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{od as eJ}from"./chunk-s7jsadnc.js";import{pd as G8,qd as x8,sd as f1}from"./chunk-728anavt.js";import"./chunk-bjqjdw34.js";import{Ad as v$,Bd as j8,Cd as z9,Dd as uQ,Ed as ZJ,Fd as _9,Gd as f$,Hd as $1,Id as _Y,Jd as a0,Kd as sJ,Ld as P2,Md as Z8,Pd as u4,Wd as m0,wd as C$,xd as r0,yd as Q$,zd as yQ}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import{he as lQ}from"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import{Ae as TJ,Je as NY,se as I6,ve as uJ}from"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import{$e as z1,Ze as CQ}from"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import{bg as OY,gg as IJ,hg as zY}from"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import{qg as D$,rg as h8,sg as IQ}from"./chunk-xz6y0w4n.js";import{wg as l0}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import{Ug as UY,Xg as e1}from"./chunk-d808m826.js";import{Zg as UJ,_g as OJ,bh as E1}from"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import{nh as e9}from"./chunk-y9d9nqnn.js";import{qh as eQ}from"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import{Ch as MQ}from"./chunk-k6shq7rk.js";import{useMemoizedFn as v2}from"ahooks";import{useEffect as J7,useState as D2}from"react";import{useMemoizedFn as t0}from"ahooks";import{Box as z$}from"ink";import{useEffect as _$,useMemo as oX,useRef as f2}from"react";import{useShallow as BY}from"zustand/react/shallow";import{useStore as LY}from"zustand";function t($){return LY(f$,$)}var wY=[],k$=()=>t(($)=>$.session.sessionId),T1=()=>t(($)=>$.session.workspaceRoot),Q4=()=>t(($)=>$.session.messages),J4=()=>t(($)=>$.session.clearCount),Y4=()=>t(($)=>$.session.isCompacting),Z4=()=>t(($)=>$.session.tokenUsage.estimatedCostUsd),X4=()=>t(($)=>{let{totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}=$.session.tokenUsage;return $4({totalInputTokens:Q,cacheReadTokens:Y,cacheWriteTokens:J}).hitRate}),K4=()=>t(($)=>$.session.providerCircuit),G4=()=>t(($)=>$.session.providerAdmission),q4=()=>t(($)=>$.session.providerRetry),U4=()=>t(($)=>$.session.providerStall),O4=()=>t(($)=>$.session.actionStationarity),n1=()=>t(($)=>$.session.actions),z4=()=>t(($)=>{let{inputTokens:Q,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let J=Math.max(0,100-Q/Y*100);return Math.round(J)}),_4=()=>t(($)=>$.app.initializationStatus),N4=()=>t(($)=>$.app.initializationError),y8=()=>t(($)=>$.app.activeModal),F4=()=>t(($)=>$.app.tasks),H4=()=>t(($)=>$.app.modelEditorTarget),W4=()=>t(($)=>$.app.sessionSelectorData),L4=()=>t(($)=>$.app.awaitingSecondCtrlC),t1=()=>t(($)=>$.app.actions),R8=()=>t(($)=>$.app.initializationStatus==="ready"),B4=()=>t(($)=>$.app.tasks.length>0),S$=()=>t(($)=>$.config.config?.permissionMode||"default"),w4=()=>t(($)=>$.config.config?.models??wY),M8=()=>t(($)=>{let Q=$.config.config;if(!Q)return;let Y=Q.currentModelId;return Q.models.find((Z)=>Z.id===Y)??Q.models[0]}),C8=()=>t(($)=>$.config.config?.currentModelId),A0=()=>t(($)=>{return r0.getTheme()}),b4=()=>t(($)=>$.config.config?.codeTheme??"default"),e0=()=>t(($)=>$.focus.currentFocus),A4=()=>t(($)=>$.focus.actions),s1=()=>t(($)=>$.command.isProcessing),P4=()=>t(($)=>$.command.actions),I8=()=>t(($)=>$.command.pendingCommands),y4=()=>t(($)=>$.command.recoveredSteeringCount),T8=()=>t(($)=>$.app.reasoningEffort!=="off"),f8=()=>t(($)=>$.app.reasoningEffort),k8=()=>t(($)=>$.app.serviceTier),S8=()=>t(($)=>$.app.responseVerbosity),v8=()=>t(($)=>$.app.communicationStyle),R4=()=>t(($)=>$.session.currentThinkingContent),M4=()=>t(($)=>$.session.thinkingExpanded),C4=()=>t(($)=>$.session.currentStreamingMessageId),I4=()=>t(BY(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),T4=()=>t(($)=>$.session.finalizingStreamingMessageId),f4=()=>t(($)=>$.session.historyExpanded),k4=()=>t(($)=>$.session.expandedMessageCount);import{useMemoizedFn as j$}from"ahooks";import{useEffect as l8,useRef as t4}from"react";function bY($){if(!($ instanceof Error))return"未知错误";let J=$.lastError??$;if(J.responseBody)try{let K=JSON.parse(J.responseBody)?.error?.message;if(K){let q=J.statusCode?` (HTTP ${J.statusCode})`:"";return`${K}${q}`}}catch{}let Z=$.message.match(/Last error:\s*(.+)$/);if(Z)return Z[1];return $.message}function AY($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function PY($){if(!($ instanceof Error))return!1;let Q=$.message;return Q.includes("can only concatenate str")||Q.includes("image_url")||Q.includes("multimodal")||Q.includes("vision")||Q.includes("does not support images")}function D8($){let Q=AY($),Y=PY($),J;if(Y)J="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else J=bY($);return{displayMessage:J,isAbort:Q,isVisionNotSupported:Y}}import{appendFileSync as yY,mkdirSync as RY,writeFileSync as MY}from"node:fs";import CY from"node:os";import h2 from"node:path";var S4=null;function IY(){let $=process.env.BLADE_STORAGE_ROOT||h2.join(CY.homedir(),".blade");return h2.join($,"logs","stream-debug.log")}function TY($){if(S4===$)return;let Q=h2.dirname($);RY(Q,{recursive:!0,mode:493}),MY($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
2
2
  `),S4=$}function E2($,Q,Y){try{let J=IY();TY(J);let Z=new Date().toISOString(),X=Y?` | ${JSON.stringify(Y)}`:"",K=`[${Z}] [${$}] ${Q}${X}
3
3
  `;yY(J,K)}catch{}}var Q8=e1("UI");function h4($,Q){let Y=!1;return(J)=>{switch(J.kind){case"content_delta":if(Y||$.signal.aborted)break;Q.contentDeltaCount++,Q.contentDeltaTotalLen+=J.delta.length,E2("loopEventHandler","onContentDelta",{callCount:Q.contentDeltaCount,deltaLen:J.delta.length,totalLen:Q.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(J.delta);break;case"thinking_delta":if(Y||$.signal.aborted)break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(J.delta);break;case"stream_end":{if($.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Q8.debug("[loopEventHandler] stream_end",{contentDeltaCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),E2("loopEventHandler","onStreamEnd",{contentDeltaCallCount:Q.contentDeltaCount,contentDeltaTotalLen:Q.contentDeltaTotalLen,streamFinalized:Y,signalAborted:$.signal.aborted}),Y||$.signal.aborted){Y=!0;break}let{extraContent:Z,extraThinking:X}=$.streamingBuffer.drainPendingBuffers(),K=$.getStreamingMessageId();if(K){if(Z)v$(K,Z);j8(K)}$.sessionActions.finalizeStreamingMessage(Z,X),Y=!0;break}case"model_fallback":Y=!0,$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),$.streamingBuffer.resetStreamingBuffers(),$.sessionActions.discardStreamingMessage(),$.sessionActions.setCurrentThinkingContent(null);break;case"provider_admission":{let{kind:Z,...X}=J;$.sessionActions.setProviderAdmission(J.phase==="queued"?X:null);break}case"provider_circuit":{let{kind:Z,...X}=J;$.sessionActions.setProviderCircuit(J.phase==="closed"?null:X);break}case"provider_retry":{let{kind:Z,...X}=J;$.sessionActions.setProviderRetry(J.phase==="recovered"?null:X);break}case"provider_stall":{let{kind:Z,...X}=J;$.sessionActions.setProviderStall(J.phase==="detected"?X:null);break}case"action_stationarity":{let{kind:Z,...X}=J;$.sessionActions.setActionStationarity(J.phase==="recovered"?null:X);break}case"tool_start":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===V8)break;if(Q8.debug("[loopEventHandler] tool_start",{toolName:Z.function.name,toolKind:J.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Z.function.name))break;try{let X=JSON.parse(Z.function.arguments),K=V4(Z.function.name,X);$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"start",summary:K,params:X})}catch(X){Q8.error("[loopEventHandler] onToolStart error:",X)}break}case"tool_progress":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===V8)break;let X=J.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((J.update.progress??0)/J.update.total*100)))}%`:"",K=`${Z.function.name}${X}: ${J.update.message}`;$.sessionActions.addToolMessage(K,{toolCallId:Z.id,toolName:Z.function.name,phase:"progress",summary:K,...J.update.admission?{admission:J.update.admission}:{}});break}case"tool_result":{let Z=J.toolCall;if(!("function"in Z))break;if(Z.function.name===V8)break;Q8.debug("[loopEventHandler] tool_result",{toolName:Z.function.name,success:J.result.success});let X=D4(j4(Z.function.name,J.result),v4);$.sessionActions.addToolMessage(X.summary,{toolCallId:Z.id,toolName:Z.function.name,phase:"complete",summary:X.summary,detail:X.detail});break}case"structured_output":$.sessionActions.replaceLastAssistantMessage(JSON.stringify(J.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(J.usage);break;case"compaction":if($.sessionActions.setCompacting(J.phase==="start"),J.phase==="end"){if($.sessionActions.resetContextUsage(),J.outcome!=="failed")Q.compactionCount=(Q.compactionCount??0)+1}break;case"turn_start":Q8.debug("[loopEventHandler] turn_start",{turn:J.turn,maxTurns:J.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:J.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y=!1;break;case"task_update":$.appActions.setTasks(J.tasks);break;case"mcp_catalog_changed":{let Z=`MCP catalog r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Catalog",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
4
4
  `)});break}case"mcp_content_changed":{let Z=`MCP ${J.contentKind} r${J.revision}: +${J.added.length} -${J.removed.length} ~${J.updated.length}`;$.sessionActions.addToolMessage(Z,{toolName:"MCP Content",phase:"complete",summary:Z,detail:[J.added.length>0?`Added: ${J.added.join(", ")}`:"",J.removed.length>0?`Removed: ${J.removed.join(", ")}`:"",J.updated.length>0?`Updated: ${J.updated.join(", ")}`:""].filter(Boolean).join(`
@@ -1,3 +1,3 @@
1
- import{l as i}from"./chunk-yvg961q3.js";import{wg as s}from"./chunk-k0pa8874.js";import"./chunk-ppsvzgs5.js";import"./chunk-hcv17986.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
1
+ import{l as i}from"./chunk-b2p4kd07.js";import{wg as s}from"./chunk-k0pa8874.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import m from"node:path";var r={registry:i,currentWorkspace:s,inputCwd:()=>process.cwd(),write:console.log};function c(t,e){return m.resolve(e.inputCwd(),t)}function p(t){return t.map((e)=>{let o=e.isCurrent?"*":" ",n=e.gitBranch?` · ${e.gitBranch}`:"",d=e.available?"":" · unavailable";return`${o} ${e.name}${n}${d}
2
2
  ${e.path}`}).join(`
3
3
  `)}async function l(t,e=r){let o=await e.registry.list(e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):p(o)),o}async function u(t,e=r){let o=await e.registry.bind(c(t.path,e),e.currentWorkspace());return e.write(t.json?JSON.stringify(o,null,2):`Bound project: ${o.path}`),o}async function j(t,e=r){let o=c(t.path,e),n=await e.registry.unbind(o);return e.write(t.json?JSON.stringify({path:o,removed:n},null,2):n?`Unbound project: ${o}`:`Project was not bound: ${o}`),n}var a={type:"boolean",default:!1,describe:"Print machine-readable JSON"},P={command:"list",aliases:["ls"],describe:"List bound projects",builder:(t)=>t.option("json",a),handler:async(t)=>{await l(t)}},b={command:"add <path>",aliases:["bind"],describe:"Bind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await u(t)}},h={command:"remove <path>",aliases:["rm","unbind"],describe:"Unbind a project folder",builder:(t)=>t.positional("path",{type:"string",demandOption:!0,describe:"Absolute or relative project folder"}).option("json",a),handler:async(t)=>{await j(t)}},y={command:"projects",aliases:["project"],describe:"Manage project bindings shared with Blade Web",builder:(t)=>t.command(P).command(b).command(h).demandCommand(1,"Choose list, add, or remove"),handler:()=>{return}};export{j as runProjectsRemove,l as runProjectsList,u as runProjectsAdd,y as projectsCommands,p as formatProjectList};
@@ -1 +1 @@
1
- import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-4ge1jkf8.js";import"./chunk-hcv17986.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{ih as a,jh as b,kh as c,lh as d,mh as e,nh as f}from"./chunk-y9d9nqnn.js";import"./chunk-k6shq7rk.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,2 +1,2 @@
1
1
  import{promises as A}from"node:fs";import q from"node:path";var J=new Map;async function L(B){let b=B;while(!0){try{return await A.lstat(q.join(b,".git")),b}catch(H){if(H.code!=="ENOENT")return}let E=q.dirname(b);if(E===b)return;b=E}}async function M(B){let b=q.join(B,".git"),E=await A.lstat(b);if(E.isDirectory())return B;if(!E.isFile())return;let H=await A.readFile(b,"utf8"),F=/^gitdir:\s*(.+)\s*$/im.exec(H);if(!F)return;let z=await A.realpath(q.isAbsolute(F[1])?F[1]:q.resolve(B,F[1])),I=z;try{let x=(await A.readFile(q.join(z,"commondir"),"utf8")).trim();if(x)I=await A.realpath(q.resolve(z,x))}catch(x){if(x.code!=="ENOENT")throw x}return q.basename(I)===".git"?A.realpath(q.dirname(I)):void 0}async function S(B){if(!q.isAbsolute(B))throw Error("Workspace path must be absolute");let b=await A.realpath(B),E=J.get(b);if(E)return E;let H=b;try{let z=await L(b);if(z){let I=await M(z),x=q.relative(z,b);if(I&&(x===""||!x.startsWith(`..${q.sep}`)&&x!==".."&&!q.isAbsolute(x))){let K=q.resolve(I,x);H=await A.realpath(K).catch(()=>K)}}}catch{}let F={projectPath:b,trustRoot:H};if(J.size>=512){let z=J.keys().next().value;if(z)J.delete(z)}return J.set(b,F),F}
2
- export{S as qh};
2
+ export{S as rh};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as Bh};
2
+ export{c as Ch};
@@ -0,0 +1 @@
1
+ import{ld as a,md as b,nd as c}from"./chunk-r9n8y8m1.js";import"./chunk-s7jsadnc.js";import"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zvz2cnt4.js";import"./chunk-b39p4f5r.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};