blade-code 0.10.118 → 0.10.120

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 (93) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-c5wrmq2e.js → chunk-0fyy97rq.js} +1 -1
  3. package/dist/{chunk-cqqmkwvn.js → chunk-0zzh482s.js} +1 -1
  4. package/dist/{chunk-gbjk078c.js → chunk-150w9kq4.js} +3 -3
  5. package/dist/{chunk-kr8rv2b9.js → chunk-1qbq7x98.js} +2 -2
  6. package/dist/{chunk-sr10jsjs.js → chunk-207s8tns.js} +1 -1
  7. package/dist/{chunk-eyb9psbc.js → chunk-2t6b962t.js} +1 -1
  8. package/dist/{chunk-z9g2x0vm.js → chunk-2v8fyvmh.js} +2 -2
  9. package/dist/{chunk-mnkdxt1v.js → chunk-2w10er3y.js} +1 -1
  10. package/dist/chunk-36k5c6wy.js +1 -0
  11. package/dist/{chunk-jp4j9tnn.js → chunk-3jdt8kqf.js} +1 -1
  12. package/dist/{chunk-bksfg23m.js → chunk-3jqd18d8.js} +2 -2
  13. package/dist/{chunk-cxbrqnqs.js → chunk-40pzrpjc.js} +1 -1
  14. package/dist/{chunk-z8xgk0m6.js → chunk-49javhkx.js} +1 -1
  15. package/dist/{chunk-2aysvx6k.js → chunk-4de6e3am.js} +2 -2
  16. package/dist/chunk-4jaqzjtw.js +1 -0
  17. package/dist/{chunk-9n9506vy.js → chunk-56fb0ece.js} +1 -1
  18. package/dist/{chunk-53aapkv1.js → chunk-5hmeb6yk.js} +2 -2
  19. package/dist/{chunk-gjw8100g.js → chunk-6h0kgpgv.js} +2 -2
  20. package/dist/chunk-6k7s3c7y.js +1 -0
  21. package/dist/{chunk-qdv0n8yt.js → chunk-7dykmcjj.js} +2 -2
  22. package/dist/{chunk-y21nw7g1.js → chunk-7k72dxwe.js} +2 -2
  23. package/dist/{chunk-935v0gpc.js → chunk-85bamng3.js} +1 -1
  24. package/dist/{chunk-kbkdhvk7.js → chunk-8mqbaptr.js} +1 -1
  25. package/dist/{chunk-hv6hrsnk.js → chunk-8qp8v96d.js} +1 -1
  26. package/dist/{chunk-6k5k40p8.js → chunk-9fgkg1vr.js} +1 -1
  27. package/dist/{chunk-x05zyqzf.js → chunk-9jtjq50j.js} +1 -1
  28. package/dist/{chunk-z52s82k7.js → chunk-a4dmw23t.js} +1 -1
  29. package/dist/chunk-a6nz99qf.js +1 -0
  30. package/dist/{chunk-9g64g1np.js → chunk-adkpwx6c.js} +1 -1
  31. package/dist/{chunk-3pwq56je.js → chunk-anjpwev3.js} +1 -1
  32. package/dist/{chunk-76f8ms39.js → chunk-apssk1cy.js} +1 -1
  33. package/dist/{chunk-tj2efrs1.js → chunk-b41den40.js} +2 -2
  34. package/dist/chunk-c5291k2x.js +1 -0
  35. package/dist/chunk-cmcgqa1d.js +1 -0
  36. package/dist/{chunk-ypbnczjp.js → chunk-dabq8kdx.js} +2 -2
  37. package/dist/{chunk-c3jb4xg7.js → chunk-dcy8s8rz.js} +1 -1
  38. package/dist/{chunk-vnbsq6ps.js → chunk-dfcc8q87.js} +2 -2
  39. package/dist/chunk-dspjxf4c.js +1 -0
  40. package/dist/{chunk-nyhqdpb6.js → chunk-exv1nb2x.js} +1 -1
  41. package/dist/{chunk-23v8c9b8.js → chunk-fpjhg6ce.js} +2 -2
  42. package/dist/chunk-gjw3g2jd.js +1 -0
  43. package/dist/{chunk-mqekerck.js → chunk-hgrdsef7.js} +1 -1
  44. package/dist/{chunk-90q4206c.js → chunk-j2pgrrkb.js} +2 -2
  45. package/dist/chunk-j8hzgacj.js +1 -0
  46. package/dist/{chunk-y1msyved.js → chunk-jn25d5qv.js} +1 -1
  47. package/dist/{chunk-q2exry0f.js → chunk-kpqdfn9z.js} +2 -2
  48. package/dist/{chunk-qw4hh3sv.js → chunk-kvf61fb1.js} +1 -1
  49. package/dist/{chunk-4w4wjm49.js → chunk-kz15jy62.js} +1 -1
  50. package/dist/{chunk-ecd727xh.js → chunk-kzzty3v5.js} +1 -1
  51. package/dist/{chunk-1w74gwns.js → chunk-kzzw1kwk.js} +2 -2
  52. package/dist/{chunk-tf7ezqew.js → chunk-m7b779kd.js} +1 -1
  53. package/dist/{chunk-yqygarpr.js → chunk-m9vhf4dg.js} +1 -1
  54. package/dist/{chunk-vbwvsgs1.js → chunk-ncqagb27.js} +2 -2
  55. package/dist/chunk-ne40tv38.js +10 -0
  56. package/dist/{chunk-xv3a1se1.js → chunk-nq0w1j1a.js} +1 -1
  57. package/dist/chunk-p7k7hqtb.js +1 -0
  58. package/dist/chunk-pykxe413.js +2 -0
  59. package/dist/{chunk-53h87fmt.js → chunk-q265drks.js} +1 -1
  60. package/dist/chunk-qp8qcmx0.js +1 -0
  61. package/dist/{chunk-dgf2xzzd.js → chunk-r6svhe3w.js} +2 -2
  62. package/dist/{chunk-cnhw5mqv.js → chunk-sca5q3tt.js} +1 -1
  63. package/dist/chunk-scgq3g37.js +8 -0
  64. package/dist/{chunk-bxjc7pg7.js → chunk-sefdw1mm.js} +2 -2
  65. package/dist/{chunk-rkdxqx8m.js → chunk-spxb931p.js} +2 -2
  66. package/dist/{chunk-swtap0bs.js → chunk-t169d8dc.js} +3 -3
  67. package/dist/{chunk-ng96f4xd.js → chunk-twdfyk78.js} +2 -2
  68. package/dist/chunk-v1cmz2bw.js +1 -0
  69. package/dist/chunk-v6sfs4qf.js +1 -0
  70. package/dist/{chunk-kk6rg27n.js → chunk-v95hk3fw.js} +1 -1
  71. package/dist/{chunk-dvv28pkc.js → chunk-w4xqaw4h.js} +2 -2
  72. package/dist/{chunk-fys5xx87.js → chunk-x4t1v4rb.js} +4 -4
  73. package/dist/{chunk-k3tqna1w.js → chunk-y1n8nf5w.js} +2 -2
  74. package/dist/{chunk-pshyn3yy.js → chunk-ye4wyq1k.js} +1 -1
  75. package/dist/chunk-zp8d0ma8.js +1 -0
  76. package/package.json +1 -1
  77. package/dist/chunk-25ps9fxw.js +0 -1
  78. package/dist/chunk-5j419kbp.js +0 -1
  79. package/dist/chunk-74m1zc1r.js +0 -1
  80. package/dist/chunk-9aqs02va.js +0 -8
  81. package/dist/chunk-bdgq4k40.js +0 -1
  82. package/dist/chunk-bpz7a5yn.js +0 -1
  83. package/dist/chunk-fqnqeca5.js +0 -1
  84. package/dist/chunk-j3cmytrt.js +0 -1
  85. package/dist/chunk-jdm0jffr.js +0 -1
  86. package/dist/chunk-jhsdden6.js +0 -10
  87. package/dist/chunk-m56bj6c6.js +0 -1
  88. package/dist/chunk-mdczqnc0.js +0 -1
  89. package/dist/chunk-nbhgg5p2.js +0 -1
  90. package/dist/chunk-nha6m2tx.js +0 -1
  91. package/dist/chunk-p3m1jyg5.js +0 -2
  92. package/dist/chunk-scc9kbd1.js +0 -1
  93. package/dist/chunk-wyw17nfy.js +0 -1
@@ -1,4 +1,4 @@
1
- import{Dh as Y}from"./chunk-4w4wjm49.js";import{Eh as on,Fh as F,Gh as o}from"./chunk-6k5k40p8.js";import{Kh as ct,Lh as bt}from"./chunk-p3m1jyg5.js";import{Sh as x}from"./chunk-ecd727xh.js";import{$h as it,Th as Jn,Uh as Xt,Vh as pt,Zh as gt,_h as kn,ai as Rt,bi as Ct,ci as un,di as zt,ei as Bt,fi as On,gi as Kt,hi as Ut,ii as jn,ji as Ht,ki as Yt,li as qt,mi as Vt,ni as Qt,oi as Gt}from"./chunk-x05zyqzf.js";import{si as fn}from"./chunk-dvv28pkc.js";import{vi as $t,yi as J}from"./chunk-dgf2xzzd.js";import{Gi as Pn,Hi as Ln}from"./chunk-53aapkv1.js";import{Ni as h}from"./chunk-vbwvsgs1.js";import{Yi as Tn}from"./chunk-rkdxqx8m.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(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:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(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 k(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(R(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 _=t.clientId?.trim();if(_&&_.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||!Wt.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 r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=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}),nM=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(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.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 Dt("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=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.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?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(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 L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.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 L.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 L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{Eh as Y}from"./chunk-kz15jy62.js";import{Fh as on,Gh as F,Hh as o}from"./chunk-9fgkg1vr.js";import{Lh as ct,Mh as bt}from"./chunk-pykxe413.js";import{Th as x}from"./chunk-kzzty3v5.js";import{$h as kn,Uh as Jn,Vh as Xt,Wh as pt,_h as gt,ai as it,bi as Rt,ci as Ct,di as un,ei as zt,fi as Bt,gi as On,hi as Kt,ii as Ut,ji as jn,ki as Ht,li as Yt,mi as qt,ni as Vt,oi as Qt,pi as Gt}from"./chunk-9jtjq50j.js";import{ti as fn}from"./chunk-w4xqaw4h.js";import{wi as $t,zi as J}from"./chunk-r6svhe3w.js";import{Hi as Pn,Ii as Ln}from"./chunk-5hmeb6yk.js";import{Oi as h}from"./chunk-ncqagb27.js";import{Zi as Tn}from"./chunk-spxb931p.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(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:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(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 k(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(R(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 _=t.clientId?.trim();if(_&&_.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||!Wt.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 r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=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}),nM=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(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.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 Dt("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=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.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?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(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 L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.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 L.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 L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.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 L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.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 L.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(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/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 an 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">
@@ -41,4 +41,4 @@ ${M.map((e)=>` - ${e}`).join(`
41
41
  ]
42
42
  }
43
43
  `)}}function ze(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)M.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)M.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)M.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
44
- export{U as yg,k as zg,I as Ag,nn as Bg,an as Cg,$ as Dg,nt as Eg,i_ as Fg,Q as Gg,z_ as Hg,B_ as Ig,K_ as Jg,rt as Kg,PM as Lg,U_ as Mg,LM as Ng,H_ as Og,wt as Pg,V_ as Qg,Q_ as Rg,W_ as Sg,Z_ as Tg,D_ as Ug,Pt as Vg,J_ as Wg,k_ as Xg,O_ as Yg,j_ as Zg,s_ as _g,Nn as $g,$n as ah,b_ as bh,Xn as ch,pn as dh,gn as eh,Rn as fh,Cn as gh,zn as hh,x_ as ih,Bn as jh,Kn as kh,Un as lh,Hn as mh,Yn as nh,qn as oh,Vn as ph,Qn as qh,Gn as rh,Wn as sh,Zn as th,Dn as uh,A as vh,d as wh,mM as xh,B as yh,D as zh,g as Ah,ze as Bh};
44
+ export{U as zg,k as Ag,I as Bg,nn as Cg,an as Dg,$ as Eg,nt as Fg,i_ as Gg,Q as Hg,z_ as Ig,B_ as Jg,K_ as Kg,rt as Lg,PM as Mg,U_ as Ng,LM as Og,H_ as Pg,wt as Qg,V_ as Rg,Q_ as Sg,W_ as Tg,Z_ as Ug,D_ as Vg,Pt as Wg,J_ as Xg,k_ as Yg,O_ as Zg,j_ as _g,s_ as $g,Nn as ah,$n as bh,b_ as ch,Xn as dh,pn as eh,gn as fh,Rn as gh,Cn as hh,zn as ih,x_ as jh,Bn as kh,Kn as lh,Un as mh,Hn as nh,Yn as oh,qn as ph,Vn as qh,Qn as rh,Gn as sh,Wn as th,Zn as uh,Dn as vh,A as wh,d as xh,mM as yh,B as zh,D as Ah,g as Bh,ze as Ch};
@@ -1,2 +1,2 @@
1
1
  function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
2
- export{v as qg};
2
+ export{v as rg};
@@ -1,4 +1,4 @@
1
- import{s as gz,t as cz,u as Az,v as Nz,w as Pz}from"./chunk-9n9506vy.js";import{x as T}from"./chunk-mnkdxt1v.js";import{A as Uz,B as Vz,C as wz,D as Kz,y as uz,z as Gz}from"./chunk-cxbrqnqs.js";import{$ as Bz,K as b,T as Hz,U as Xz,Y as Lz,aa as jz,da as Fz,ta as Dz,ua as _z,va as Oz,wa as qz}from"./chunk-fys5xx87.js";import"./chunk-ypbnczjp.js";import{Ka as fz}from"./chunk-z9g2x0vm.js";import{Ma as Yz}from"./chunk-23v8c9b8.js";import{Gb as Qz,Pb as Wz,ub as $z}from"./chunk-gbjk078c.js";import{_b as f}from"./chunk-cnhw5mqv.js";import{Fd as g,Gd as Jz,Id as E,Ld as Zz,Qd as P,Td as U,dd as n,nd as h,od as u,pd as s,ud as t,xd as e,zd as zz}from"./chunk-bxjc7pg7.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{ye as pz}from"./chunk-k3tqna1w.js";import"./chunk-ng96f4xd.js";import{Te as Mz,Ue as kz}from"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import{df as c}from"./chunk-pshyn3yy.js";import{if as o}from"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import{tf as Iz}from"./chunk-hv6hrsnk.js";import"./chunk-gjw8100g.js";import"./chunk-90q4206c.js";import"./chunk-cqqmkwvn.js";import{lg as Cz}from"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-swtap0bs.js";import"./chunk-eyb9psbc.js";import{dh as Sz,gh as yz}from"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import{Kh as k,Lh as r,Nh as I,Oh as C}from"./chunk-p3m1jyg5.js";import{Sh as Ez}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import{si as S}from"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import{Ci as hz,zi as Tz}from"./chunk-z52s82k7.js";import"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import{Yi as a}from"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import{Readable as tz,Writable as ez}from"node:stream";import*as y from"@agentclientprotocol/sdk";import xz from"node:path";import{PROTOCOL_VERSION as nz,RequestError as sz}from"@agentclientprotocol/sdk";import{RequestError as Rz}from"@agentclientprotocol/sdk";import{nanoid as M}from"nanoid";var G=S("Agent");function i(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function vz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:i(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:i("headers"in z?z.headers:void 0)};return null}function lz(z){let Z={};for(let J of z){let Y=vz(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 iz(z){let Z=Jz(z.metadata);return Z?[{type:"text",text:g(Z)}]:bz(z.content)}function az(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as gz,t as cz,u as Az,v as Nz,w as Pz}from"./chunk-56fb0ece.js";import{x as T}from"./chunk-2w10er3y.js";import{A as Uz,B as Vz,C as wz,D as Kz,y as uz,z as Gz}from"./chunk-40pzrpjc.js";import{K as b,T as Hz,U as Xz,Z as Lz,aa as Bz,ba as jz,ea as Fz,ua as Dz,va as _z,wa as Oz,xa as qz}from"./chunk-x4t1v4rb.js";import"./chunk-dabq8kdx.js";import{La as fz}from"./chunk-2v8fyvmh.js";import{Na as Yz}from"./chunk-fpjhg6ce.js";import{Hb as Qz,Qb as Wz,vb as $z}from"./chunk-150w9kq4.js";import{$b as f}from"./chunk-sca5q3tt.js";import{Ad as zz,Gd as g,Hd as Jz,Jd as E,Md as Zz,Rd as P,Ud as U,ed as n,od as h,pd as u,qd as s,vd as t,yd as e}from"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{ze as pz}from"./chunk-y1n8nf5w.js";import"./chunk-twdfyk78.js";import{Ue as Mz,Ve as kz}from"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import{ef as c}from"./chunk-ye4wyq1k.js";import{jf as o}from"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import{uf as Iz}from"./chunk-8qp8v96d.js";import"./chunk-6h0kgpgv.js";import"./chunk-j2pgrrkb.js";import"./chunk-0zzh482s.js";import{mg as Cz}from"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import{eh as Sz,hh as yz}from"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import{Lh as k,Mh as r,Oh as I,Ph as C}from"./chunk-pykxe413.js";import{Th as Ez}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import{ti as S}from"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import{Ai as Tz,Di as hz}from"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import{Zi as a}from"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import{Readable as tz,Writable as ez}from"node:stream";import*as y from"@agentclientprotocol/sdk";import xz from"node:path";import{PROTOCOL_VERSION as nz,RequestError as sz}from"@agentclientprotocol/sdk";import{RequestError as Rz}from"@agentclientprotocol/sdk";import{nanoid as M}from"nanoid";var G=S("Agent");function i(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function vz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:i(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:i("headers"in z?z.headers:void 0)};return null}function lz(z){let Z={};for(let J of z){let Y=vz(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 iz(z){let Z=Jz(z.metadata);return Z?[{type:"text",text:g(Z)}]:bz(z.content)}function az(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function rz(z){if(!o(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...h("capacity"),resource:z.resource}}function oz(z){if(!(z instanceof Rz)||!z.data||typeof z.data!=="object")return;let Z=z.data;if(!s(Z.taskFailure)||Z.toolExecutionStarted!==!1||!Number.isInteger(Z.toolCallsCount)||Z.toolCallsCount<0||Z.outputStarted!==!1)return;return{taskFailure:Z.taskFailure,toolExecutionStarted:Z.toolExecutionStarted,toolCallsCount:Z.toolCallsCount,outputStarted:Z.outputStarted}}class x{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;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 Kz({maxPendingItems:Gz,maxPendingBytes:Uz,writeTimeoutMs:Vz,signal:J.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await J.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.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 U.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 Fz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),b.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Wz.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?lz(this.options.mcpServers):void 0,J=b.getInstance().getTerminalService(this.id);if(this.runtime=await Lz.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,B)=>{let L=await J.execute(W,{cwd:B.cwd,env:B.env,timeout:B.timeoutMs,signal:B.signal,allowLocalFallback:!1,onOutput:(j)=>B.onOutput?.("stdout",j)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await T.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await _z(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=$z.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.requestPendingResume();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.startsWith("team.")){let{teamName:B,messageId:L,content:j}=W.properties,F=W.properties.metadata;if(W.type==="team.message.received"&&typeof B==="string"&&typeof L==="string"&&typeof j==="string"&&Xz(F,{messageId:L,teamName:B}))(async()=>{let V=await this.runtime?.enqueueSteering(j,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:F});if(!V?.accepted)return;if(await new Hz(B,a()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});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(),X=this.runtime.getPendingSteeringCount()>0,Q=H?.status==="active"||H?.status==="verifying";if(X||Q)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!zz(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 iz(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.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.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{G.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 W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},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,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,j=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)j(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)j(L);return F}},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,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},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,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await T.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:W,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),L=await B.completion,j=(await T.list(this.cwd,this.id)).find((F)=>F.start.reviewId===B.reviewId);if(!j)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:n(j.start,L)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,j=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:j})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await Oz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.requestPendingResume();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 U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});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){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.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 handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=qz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let X;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:H.name,description:H.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(b.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,X=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((K)=>K.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Zz(X).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let W=Yz(H);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((K)=>K.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}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 K=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!K.accepted)throw Error(K.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${K.queued})`),K.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(Z.abortSignal?.reason)};if(Z.abortSignal?.aborted)L();else Z.abortSignal?.addEventListener("abort",L,{once:!0});let j=!1,F=!1,V=!1,m,d=new Promise((K)=>{m=K});this.pendingPrompt=B,this.pendingPromptCompletion=d;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Dz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,B.signal)}let K={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:B.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($)}}},O=await Qz(this.agent.chatStream(Y,K,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)F=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)F=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{V=!0;let w=$.toolCall,q=w.function.name;if(q===E)break;let N=this.mapToolKind($.toolKind),D=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let R=JSON.parse(w.function.arguments),_=R.resume_from??R.resume;if(typeof _==="string")D=`Resuming ${String(R.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:D,content:[],kind:N});break}case"tool_progress":{V=!0;let w=$.toolCall;if(w.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{V=!0;let w=$.toolCall;if(w.function.name===E)break;let q=$.result,N=[],D=q.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;N.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))N.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=w.function.name,mz=jz(e(Bz(_,q),t));N.push({type:"content",content:{type:"text",text:mz}})}if(w.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let R=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:R,content:N});break}case"structured_output":F=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
@@ -1,2 +1,2 @@
1
1
  import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
- export{s as tf,g as uf};
2
+ export{s as uf,g as vf};
@@ -1,2 +1,2 @@
1
1
  import d from"typebox/schema";import o from"typebox/value";class u extends Error{issues;constructor(r){super(r.map((t)=>{return`${t.path.length>0?t.path.join("."):"root"}: ${t.message}`}).join("; "));this.issues=r;this.name="SchemaValidationError"}}function p(r){if(!r)return[];return r.split("/").slice(1).map((t)=>t.replace(/~1/g,"/").replace(/~0/g,"~")).map((t)=>/^(0|[1-9]\d*)$/.test(t)?Number(t):t)}function g(r,t){let n=r;for(let e of t){if(n===null||typeof n!=="object")return;n=n[e]}return n}function i(r,t){let[,n]=d.Errors(r,t);return n.map((e)=>{let s=p(e.instancePath);return{code:e.keyword,path:s,message:e.message,value:g(t,s)}})}function a(r,t){let n=o.Default(r,o.Clone(t)),e=i(r,n);if(e.length>0)return{success:!1,error:new u(e)};let s=o.Clean(r,n),c=i(r,s);if(c.length>0)return{success:!1,error:new u(c)};return{success:!0,data:s}}function f(r,t){let n=a(r,t);if(!n.success)throw n.error;return n.data}import l from"typebox";function x(r){return Object.defineProperties(r,{parse:{value:(t)=>f(r,t),enumerable:!1},safeParse:{value:(t)=>a(r,t),enumerable:!1}}),r}function b(r,t){return l.Optional({...r,default:t})}function V(r,t={}){return l.Unsafe({type:"string",enum:[...r],...t})}
2
- export{a as Eh,f as Fh,l as Gh,x as Hh,b as Ih,V as Jh};
2
+ export{a as Fh,f as Gh,l as Hh,x as Ih,b as Jh,V as Kh};
@@ -1,2 +1,2 @@
1
1
  var I=600000,r=30000,t=3600000,o=12,O=15000,P=60000;function R(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=30000&&_<=3600000}var C=1e4,M=1000,p=300000;function E(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=300000}var T=1,s=16,n=Number.MAX_SAFE_INTEGER,D=180000,m=1000,x=600000,S=134217728,U=65536,V=134217728;function A(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=16}function w(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=1&&_<=n}function z(_){return _===0||typeof _==="number"&&Number.isSafeInteger(_)&&_>=1000&&_<=600000}function F(_){return typeof _==="number"&&Number.isSafeInteger(_)&&_>=65536&&_<=134217728}
2
- export{I as Th,r as Uh,t as Vh,o as Wh,O as Xh,P as Yh,R as Zh,C as _h,M as $h,p as ai,E as bi,T as ci,s as di,n as ei,D as fi,m as gi,x as hi,S as ii,U as ji,V as ki,A as li,w as mi,z as ni,F as oi};
2
+ export{I as Uh,r as Vh,t as Wh,o as Xh,O as Yh,P as Zh,R as _h,C as $h,M as ai,p as bi,E as ci,T as di,s as ei,n as fi,D as gi,m as hi,x as ii,S as ji,U as ki,V as li,A as mi,w as ni,z as oi,F as pi};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as zi,p as Ai,u as Bi,S as Ci,c as Di,l as Ei};
2
+ export{f as Ai,p as Bi,u as Ci,S as Di,c as Ei,l as Fi};
@@ -0,0 +1 @@
1
+ import{Mi as a,Ni as b,Oi as c}from"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
@@ -15,4 +15,4 @@ More specific user instructions about presentation take precedence for that resp
15
15
  <communication_style>
16
16
  ${h.prompt}
17
17
  </communication_style>`}
18
- export{R as lg,z as mg,H as ng,W as og,Z as pg};
18
+ export{R as mg,z as ng,H as og,W as pg,Z as qg};
@@ -1,2 +1,2 @@
1
- import{yi as o}from"./chunk-dgf2xzzd.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{zi as o}from"./chunk-r6svhe3w.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e,i as f};
@@ -1 +1 @@
1
- import"./chunk-tf7ezqew.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
1
+ import"./chunk-m7b779kd.js";var d={command:"install [target]",describe:"Install Blade native build. Use [target] to specify version (stable, latest, or specific version)",builder:(b)=>{return b.positional("target",{describe:"Version to install",type:"string",default:"stable",choices:["stable","latest"]}).option("force",{type:"boolean",describe:"Force reinstall",default:!1}).example([["$0 install","Install stable version"],["$0 install latest","Install latest version"],["$0 install --force","Force reinstall stable version"]])},handler:async(b)=>{console.log(`Installing Blade ${b.target}...`);try{if(b.force)console.log("Force reinstall enabled");console.log("Downloading..."),console.log("Installing..."),console.log("Installation completed successfully")}catch(c){console.error(`Error: Installation failed: ${c instanceof Error?c.message:"未知错误"}`),process.exit(1)}}};export{d as installCommands};
@@ -1,2 +1,2 @@
1
- import{uf as B}from"./chunk-hv6hrsnk.js";import{yi as Y}from"./chunk-dgf2xzzd.js";import{Bi as Z,Ei as $}from"./chunk-z52s82k7.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{D as qf,h as rf,j as sf};
1
+ import{vf as B}from"./chunk-8qp8v96d.js";import{zi as Y}from"./chunk-r6svhe3w.js";import{Ci as Z,Fi as $}from"./chunk-a4dmw23t.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{D as rf,h as sf,j as tf};
@@ -0,0 +1 @@
1
+ import{Od as a,Pd as b,Qd as c,Rd as d,Sd as e,Td as f,Ud as g}from"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import"./chunk-8qp8v96d.js";import"./chunk-adkpwx6c.js";import"./chunk-2t6b962t.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-w4xqaw4h.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -0,0 +1 @@
1
+ import{h as a,i as b,j as c,k as d,l as e}from"./chunk-v95hk3fw.js";import"./chunk-5hmeb6yk.js";import"./chunk-m7b779kd.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,2 +1,2 @@
1
- import{_i as K}from"./chunk-tf7ezqew.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
2
- export{P as ya,V as za,R as Aa,N as Ba};
1
+ import{$i as K}from"./chunk-m7b779kd.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
2
+ export{P as za,V as Aa,R as Ba,N as Ca};
@@ -1 +1 @@
1
- import{Na as V,Pa as W,Qa as O,gb as J}from"./chunk-23v8c9b8.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import{Sh as Q}from"./chunk-ecd727xh.js";import"./chunk-dvv28pkc.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
1
+ import{Oa as V,Qa as W,Ra as O,hb as J}from"./chunk-fpjhg6ce.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as Q}from"./chunk-kzzty3v5.js";import"./chunk-w4xqaw4h.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import F from"chalk";var K=(f)=>typeof f==="string"&&f.length>0?f:void 0;function X(f){let z=K(f.cron),G=K(f.every),H=K(f.at);if([z,G,H].filter(Boolean).length!==1)throw Error("Provide exactly one of --cron, --every, or --at");if(z)return{kind:"cron",cron:z};if(G){let P=V(G);if(!P)throw Error(`Invalid --every value "${G}" (use e.g. 30m, 2h, 1d)`);return{kind:"interval",intervalMs:P}}let N=new Date(H);if(Number.isNaN(N.getTime()))throw Error(`Invalid --at value "${H}" (use an ISO timestamp)`);return{kind:"once",runAt:N.toISOString()}}var Y={command:"create <prompt>",describe:"创建定时任务",builder:(f)=>f.positional("prompt",{type:"string",describe:"定时任务运行时发送给 Agent 的提示词",demandOption:!0}).option("cron",{type:"string",describe:"5 段 cron 表达式(本地时区)"}).option("every",{type:"string",describe:"间隔(如 30m、2h、1d)"}).option("at",{type:"string",describe:"一次性运行的 ISO 时间点"}).option("project-path",{alias:["projectPath","project"],type:"string",describe:"目标项目路径(默认当前目录)"}).option("title",{type:"string",describe:"定时任务标题"}).option("model",{alias:"m",type:"string",describe:"模型 ID"}).option("permission-mode",{type:"string",choices:["default","autoEdit","yolo","plan"],default:"default",describe:"权限模式"}).option("isolation",{type:"string",choices:["local","worktree"],default:"worktree",describe:"执行隔离方式"}).example([['$0 schedule create "跑测试并汇报失败" --every 1h',"每小时运行一次"],['$0 schedule create "生成每日站会摘要" --cron "0 9 * * 1-5"',"工作日 9 点运行"]]),handler:async(f)=>{try{let z=X(f),G=W(z);if(G)throw Error(G);let H={prompt:f.prompt,projectPath:K(f.projectPath)??Q(),title:K(f.title),trigger:z,modelId:K(f.model),isolation:K(f.isolation)??"worktree",permissionMode:K(f.permissionMode)??"default",enabled:!0},B=await J.create(H);console.log(F.green(`✓ 已创建定时任务 ${B.id}`)),console.log(` ${O(B.trigger)}`),console.log(` 项目: ${B.projectPath}`),console.log(` 下次运行: ${B.nextRunAt?new Date(B.nextRunAt).toLocaleString():"(无)"}`),process.exit(0)}catch(z){console.error(F.red(`创建定时任务失败: ${z instanceof Error?z.message:z}`)),process.exit(1)}}},Z={command:"list",aliases:["ls"],describe:"列出所有定时任务",handler:async()=>{let f=await J.list();if(f.length===0)console.log(F.dim("尚无定时任务。使用 `blade schedule create` 创建。")),process.exit(0);for(let z of f){let G=z.enabled?F.green("启用"):F.dim("停用"),H=z.nextRunAt?new Date(z.nextRunAt).toLocaleString():"—",B=z.lastRunAt?`${new Date(z.lastRunAt).toLocaleString()} (${z.lastStatus??"?"})`:"从未";console.log(`${F.cyan(z.id)} [${G}] ${z.title??z.prompt.slice(0,40)}`),console.log(` ${O(z.trigger)} · 下次: ${H} · 上次: ${B} · 运行 ${z.runCount} 次`),console.log(F.dim(` 项目: ${z.projectPath}`))}process.exit(0)}},_={command:"show <id>",describe:"查看定时任务详情",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{let z=await J.get(f.id);if(!z)console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(JSON.stringify(z,null,2)),process.exit(0)}},$={command:"remove <id>",aliases:["rm"],describe:"删除定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.remove(f.id))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已删除定时任务 ${f.id}`)),process.exit(0)}},q={command:"enable <id>",describe:"启用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!0))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已启用定时任务 ${f.id}`)),process.exit(0)}},x={command:"disable <id>",describe:"停用定时任务",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}),handler:async(f)=>{if(!await J.setEnabled(f.id,!1))console.error(F.red(`未找到定时任务 ${f.id}`)),process.exit(1);console.log(F.green(`✓ 已停用定时任务 ${f.id}`)),process.exit(0)}},D={command:"run <id>",describe:"立即运行定时任务(需要 blade serve)",builder:(f)=>f.positional("id",{type:"string",describe:"定时任务 ID",demandOption:!0}).option("server",{type:"string",default:process.env.BLADE_SERVER_URL??"http://127.0.0.1:4097",describe:"Blade server 地址"}),handler:async(f)=>{let z=f.id,G=(K(f.server)??"http://127.0.0.1:4097").replace(/\/$/,""),H={};if(process.env.BLADE_SERVER_PASSWORD){let B=process.env.BLADE_SERVER_USERNAME??"blade";H.Authorization=`Basic ${Buffer.from(`${B}:${process.env.BLADE_SERVER_PASSWORD}`).toString("base64")}`}try{let B=await fetch(`${G}/schedules/${encodeURIComponent(z)}/run`,{method:"POST",headers:H});if(!B.ok){let N=await B.json().catch(()=>{return});throw Error(N?.error?.message??`Schedule run failed (${B.status})`)}console.log(F.green(`✓ 已触发定时任务 ${z}`)),process.exit(0)}catch(B){console.error(F.red(`运行定时任务失败: ${B instanceof Error?B.message:B}`)),process.exit(1)}}},R={command:"schedule",describe:"管理定时任务",builder:(f)=>f.command(Y).command(Z).command(_).command($).command(q).command(x).command(D).demandCommand(1,"请提供子命令:create | list | show | remove | enable | disable | run"),handler:()=>{}};export{R as scheduleCommands};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{Ah as Q}from"./chunk-y21nw7g1.js";import"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import{Sh as L}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import{_i as F}from"./chunk-tf7ezqew.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-fqnqeca5.js"),{SessionService:B}=await import("./chunk-mdczqnc0.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-v508x7cg.js";import{Bh as Q}from"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as L}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import{$i as F}from"./chunk-m7b779kd.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-v1cmz2bw.js"),{SessionService:B}=await import("./chunk-c5291k2x.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -0,0 +1 @@
1
+ import{Bb as c,Fb as d,Gb as e,Hb as f,Ib as g,Jb as h,Kb as i,Lb as j,Mb as k,Tb as l,Ub as m,Vb as n,Wb as o,Yb as p,Zb as q,_b as r,yb as a,zb as b}from"./chunk-150w9kq4.js";import"./chunk-sca5q3tt.js";import"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-8qp8v96d.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1,4 +1,4 @@
1
- import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-c5wrmq2e.js";import{Y as O,da as S}from"./chunk-fys5xx87.js";import"./chunk-ypbnczjp.js";import"./chunk-z9g2x0vm.js";import"./chunk-23v8c9b8.js";import{Gb as M,Pb as E}from"./chunk-gbjk078c.js";import"./chunk-cnhw5mqv.js";import{Fd as h,Td as f}from"./chunk-bxjc7pg7.js";import"./chunk-53h87fmt.js";import"./chunk-qdv0n8yt.js";import{re as I}from"./chunk-1w74gwns.js";import{te as y,ue as R,ve as g}from"./chunk-2aysvx6k.js";import{we as C}from"./chunk-bksfg23m.js";import"./chunk-ng96f4xd.js";import{Te as w}from"./chunk-kr8rv2b9.js";import"./chunk-v508x7cg.js";import"./chunk-pshyn3yy.js";import"./chunk-q2exry0f.js";import"./chunk-tj2efrs1.js";import"./chunk-hv6hrsnk.js";import"./chunk-gjw8100g.js";import"./chunk-90q4206c.js";import"./chunk-cqqmkwvn.js";import"./chunk-9g64g1np.js";import"./chunk-935v0gpc.js";import"./chunk-swtap0bs.js";import"./chunk-eyb9psbc.js";import"./chunk-y21nw7g1.js";import{Ch as A}from"./chunk-4w4wjm49.js";import"./chunk-6k5k40p8.js";import"./chunk-p3m1jyg5.js";import{Sh as P}from"./chunk-ecd727xh.js";import"./chunk-x05zyqzf.js";import"./chunk-dvv28pkc.js";import"./chunk-dgf2xzzd.js";import"./chunk-z52s82k7.js";import"./chunk-53aapkv1.js";import"./chunk-vbwvsgs1.js";import"./chunk-sr10jsjs.js";import"./chunk-rkdxqx8m.js";import"./chunk-tf7ezqew.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
1
+ import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-0fyy97rq.js";import{Z as O,ea as S}from"./chunk-x4t1v4rb.js";import"./chunk-dabq8kdx.js";import"./chunk-2v8fyvmh.js";import"./chunk-fpjhg6ce.js";import{Hb as M,Qb as E}from"./chunk-150w9kq4.js";import"./chunk-sca5q3tt.js";import{Gd as h,Ud as f}from"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{se as I}from"./chunk-kzzw1kwk.js";import{ue as y,ve as R,we as g}from"./chunk-4de6e3am.js";import{xe as C}from"./chunk-3jqd18d8.js";import"./chunk-twdfyk78.js";import{Ue as w}from"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-6h0kgpgv.js";import"./chunk-j2pgrrkb.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import"./chunk-7k72dxwe.js";import{Dh as A}from"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import{Th as P}from"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
2
2
  `);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
3
3
  `);else j.io.stdout.write(`${j.response}
4
4
  `)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1,2 +1,2 @@
1
- import{Gh as Q,Hh as X,Ih as U,Jh as Z}from"./chunk-6k5k40p8.js";import{Kh as N,Lh as h,Nh as d}from"./chunk-p3m1jyg5.js";import{si as a}from"./chunk-dvv28pkc.js";import{Yi as i}from"./chunk-rkdxqx8m.js";var b=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],T={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D($,J,K){let B=new Set;for(let W of $.split(",")){let[Y,O]=W.split("/"),V=O?Number.parseInt(O,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${$}"`);let j=J,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,r]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(r,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<J||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${$}"`);for(let k=j;k<=H;k+=V)B.add(k)}return B}function R($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${J.length}`);let[K,B,W,Y,O]=J,V=D(O,b[4].min,b[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,b[0].min,b[0].max),hours:D(B,b[1].min,b[1].max),daysOfMonth:D(W,b[2].min,b[2].max),months:D(Y,b[3].min,b[3].max),daysOfWeek:j,domRestricted:W.trim()!=="*",dowRestricted:O.trim()!=="*"}}function y($,J){if(!J)return{minute:$.getMinutes(),hour:$.getHours(),dayOfMonth:$.getDate(),month:$.getMonth()+1,dayOfWeek:$.getDay()};let K=E.get(J);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:J,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(J,K);let B=Object.fromEntries(K.formatToParts($).filter((W)=>W.type!=="literal").map((W)=>[W.type,W.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:T[B.weekday]??-1}}function p($,J,K){let B=y(J,K);if(!$.minutes.has(B.minute))return!1;if(!$.hours.has(B.hour))return!1;if(!$.months.has(B.month))return!1;let W=$.daysOfMonth.has(B.dayOfMonth),Y=$.daysOfWeek.has(B.dayOfWeek);if($.domRestricted&&$.dowRestricted)return W||Y;if($.domRestricted)return W;if($.dowRestricted)return Y;return!0}function e($,J,K){let B=R($),W=new Date(J.getTime());W.setSeconds(0,0),W.setMinutes(W.getMinutes()+1);let Y=new Date(J.getTime());Y.setFullYear(Y.getFullYear()+4);while(W.getTime()<=Y.getTime()){if(p(B,W,K))return new Date(W.getTime());W.setMinutes(W.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function F1($){let K=$.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!K)return null;let B=Number.parseInt(K[1],10);if(!Number.isInteger(B)||B<=0)return null;let W=K[2]||"m";return B*S[W]}function Q1($){for(let J of["d","h","m","s"]){let K=S[J];if($%K===0)return`${$/K}${J}`}return`${Math.round($/1000)}s`}function F($,J,K){switch($.kind){case"cron":{if(!$.cron)return null;try{return e($.cron,J,$.timezone)}catch{return null}}case"interval":{if(!$.intervalMs||$.intervalMs<=0)return null;let W=new Date((K??J).getTime()+$.intervalMs);return W.getTime()<=J.getTime()?new Date(J.getTime()+1000):W}case"once":{if(!$.runAt)return null;let B=new Date($.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>J.getTime()?B:null}default:return null}}function z($){switch($.kind){case"cron":if(!$.cron)return"cron trigger requires a cron expression";try{if(R($.cron),$.timezone)new Intl.DateTimeFormat("en-US",{timeZone:$.timezone}).format();return null}catch(J){return J instanceof Error?J.message:"invalid cron expression"}case"interval":if(!$.intervalMs||$.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!$.runAt)return"once trigger requires runAt timestamp";let J=new Date($.runAt);if(Number.isNaN(J.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function z1($){switch($.kind){case"cron":return`cron: ${$.cron??"?"}`;case"interval":return`every ${$.intervalMs?Q1($.intervalMs):"?"}`;case"once":return`once at ${$.runAt??"?"}`;default:return"unknown"}}import{mkdir as P1,readFile as I1}from"node:fs/promises";import t from"node:path";import{nanoid as L1}from"nanoid";import D1 from"write-file-atomic";var l=16384;function v1($){let J=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec($);if(!J)return;return{question:(J[1]??"").trim()}}var w=X(Z(["default","autoEdit","yolo","plan"]));var v=X(Z(["user","assistant","system","tool"])),$1=X(Q.Union([Q.Object({type:Q.Literal("text"),text:Q.String()}),Q.Object({type:Q.Literal("image_url"),image_url:Q.Object({url:Q.String()})})])),m=Q.Union([Q.String(),Q.Array($1)]),R1=X(Q.Object({id:Q.String(),role:v,content:m,timestamp:Q.Number(),metadata:Q.Optional(Q.Record(Q.String(),Q.Unknown())),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),J1=X(Z(["queued","running","completed","failed","cancelled","interrupted"])),A=X(Z(["local","worktree"])),x=X(Z(["high","medium","low"])),C=X(Z(["feature","bug","maintenance","research"])),X1=X(Z(["applied","discarded","conflicted"])),Z1=X(Q.Object({status:X1,updatedAt:Q.String(),sourceCommit:Q.Optional(Q.String()),changedFiles:Q.Optional(Q.Integer({minimum:0})),message:Q.Optional(Q.String())})),B1=X(Q.Object({changedFiles:Q.Integer({minimum:0}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),commits:Q.Integer({minimum:0})})),K1=X(Q.Object({path:Q.String({minLength:1}),patch:Q.String({maxLength:2097152}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),binary:Q.Boolean(),truncated:Q.Boolean()})),S1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),baseCommit:Q.String(),files:Q.Array(K1,{maxItems:100}),truncated:Q.Boolean()})),W1=Q.Union([Q.String(),Q.Number(),Q.Boolean(),Q.Array(Q.String())]),Y1=X(Q.Object({name:Q.String(),type:Z(["string","number","integer","boolean","select","multi-select"]),title:Q.String(),description:Q.Optional(Q.String()),required:Q.Boolean(),defaultValue:Q.Optional(W1),options:Q.Optional(Q.Array(Q.Object({value:Q.String(),label:Q.String()}))),format:Q.Optional(Z(["date","uri","email","date-time"])),minimum:Q.Optional(Q.Number()),maximum:Q.Optional(Q.Number()),minLength:Q.Optional(Q.Number()),maxLength:Q.Optional(Q.Number()),minItems:Q.Optional(Q.Number()),maxItems:Q.Optional(Q.Number())})),l1=X(Q.Object({serverName:Q.String(),mode:Z(["form","url"]),message:Q.String(),fields:Q.Optional(Q.Array(Y1)),requestedSchema:Q.Optional(Q.Record(Q.String(),Q.Unknown())),url:Q.Optional(Q.String()),domain:Q.Optional(Q.String()),elicitationId:Q.Optional(Q.String())})),H1=X(Q.Object({type:Z(["permission","question","elicitation"]),requestId:Q.String()})),j1=X(Q.Object({code:Z(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:Q.String({minLength:1,maxLength:500}),retryable:Q.Boolean(),resource:Q.Optional(Z(["pending_count","pending_bytes","resident_runtimes"]))})),M=X(Z(["auto","off","minimal","low","medium","high","xhigh","max"])),P=X(Z(["auto","standard","fast","flex"])),I=X(Z(["auto","low","medium","high"])),G=X(Q.Union([Z(["auto","pragmatic","friendly","explanatory"]),Q.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),_=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),title:Q.Optional(Q.String()),gitBranch:Q.Optional(Q.String()),rootId:Q.String(),parentId:Q.Optional(Q.String()),relationType:Q.Optional(Z(["subagent","fork"])),resumedFrom:Q.Optional(Q.String()),rootAgentId:Q.Optional(Q.String()),resumeDepth:Q.Optional(Q.Integer({minimum:0})),taskStatus:U(J1,"completed"),taskStatusReason:Q.Optional(Q.String()),taskFailure:Q.Optional(j1),taskStartedAt:Q.Optional(Q.String()),taskCompletedAt:Q.Optional(Q.String()),taskPromptSummary:Q.Optional(Q.String()),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.String()),taskModelId:Q.Optional(Q.String()),selectedModelId:Q.Optional(Q.String()),permissionMode:Q.Optional(w),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),communicationStyleDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:Q.Optional(Q.Boolean()),taskRetriedFrom:Q.Optional(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),taskDelivery:Q.Optional(Z1),taskIsolation:Q.Optional(A),taskSourceProjectPath:Q.Optional(Q.String()),taskWorktreePath:Q.Optional(Q.String()),taskWorktreeBranch:Q.Optional(Q.String()),taskBaseCommit:Q.Optional(Q.String()),taskDiffStat:Q.Optional(B1),taskQueuePosition:Q.Optional(Q.Integer({minimum:1})),taskQueueDepth:Q.Optional(Q.Integer({minimum:0})),taskConcurrencyLimit:Q.Optional(Q.Integer({minimum:1})),archivedAt:Q.Optional(Q.String()),archivedBySessionId:Q.Optional(Q.String()),pendingInteraction:Q.Optional(H1),messageCount:Q.Number(),firstMessageTime:Q.String(),lastMessageTime:Q.String(),hasErrors:Q.Boolean()})),u1=X(Q.Object({sessions:Q.Array(_),nextCursor:Q.Optional(Q.String())})),h1=X(Q.Object({session:_,archivedSessionIds:Q.Array(Q.String())})),d1=X(Q.Object({session:_,restoredSessionIds:Q.Array(Q.String())})),m1=X(Q.Object({version:Q.Union([Q.Literal(1),Q.Literal(2)]),sessionId:Q.String(),goalId:Q.String(),objective:Q.String(),status:Z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:Q.Optional(Q.Number()),tokensUsed:Q.Number(),timeUsedSeconds:Q.Number(),continuationCount:Q.Number(),statusReason:Q.Optional(Q.String()),completionVerification:Q.Optional(Q.Object({attempt:Q.Integer({minimum:1}),status:Z(["pending","pass","fail","partial"]),requestedAt:Q.String(),completedAt:Q.Optional(Q.String()),verifierSessionId:Q.Optional(Q.String()),summary:Q.Optional(Q.String()),evidenceSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:Q.Optional(Q.Object({pattern:Q.Unsafe({type:"string"}),consecutiveCount:Q.Integer({minimum:1}),detectedAt:Q.String()})),verificationStall:Q.Optional(Q.Unsafe({type:"object"})),executionFrontier:Q.Optional(Q.Object({taskListId:Q.String({minLength:1,maxLength:256}),total:Q.Integer({minimum:0}),completed:Q.Integer({minimum:0}),inProgress:Q.Integer({minimum:0}),pending:Q.Integer({minimum:0}),blocked:Q.Integer({minimum:0}),nextTask:Q.Optional(Q.Object({id:Q.String({minLength:1}),subject:Q.String({minLength:1,maxLength:512}),priority:Z(["high","medium","low"])})),digestSha256:Q.String({pattern:"^[a-f0-9]{64}$"}),observedAt:Q.String()})),frontierStall:Q.Optional(Q.Object({category:Z(["waiting_dependency","same_task_no_effect","repeated_deferral"]),consecutiveCount:Q.Integer({minimum:1,maximum:3}),digestSha256:Q.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:Q.String()})),createdAt:Q.String(),updatedAt:Q.String()})),c=X(Q.Object({role:v,content:m,metadata:Q.Optional(Q.Unknown()),reasoningContent:Q.Optional(Q.String()),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),c1=X(Q.Object({session:_,messages:Q.Array(c)})),n=X(Z(["conversation","code","both"])),U1=X(Q.Object({messageId:Q.String(),preview:Q.String(),createdAt:Q.String(),fileCount:Q.Integer({minimum:0})})),n1=X(Q.Object({targetMessageId:Q.String({minLength:1}),mode:U(n,"conversation")})),g1=X(Q.Object({checkpoint:U1,mode:n,removedTurns:Q.Integer({minimum:1}),restoredFiles:Q.Array(Q.String()),messages:Q.Array(c)})),k1=Z(["running","completed","failed","cancelled"]),u=X(Q.Object({id:Q.String(),subagentType:Q.String(),description:Q.String(),status:k1,background:Q.Boolean(),rootAgentId:Q.String(),resumedFrom:Q.Optional(Q.String()),resumeDepth:Q.Integer({minimum:0}),createdAt:Q.Number(),lastActiveAt:Q.Number(),completedAt:Q.Optional(Q.Number()),restartRecovery:Q.Optional(Q.Object({outcome:Z(["completed","interrupted","failed"]),recoveredAt:Q.Number()})),result:Q.Optional(Q.Object({success:Q.Boolean(),message:Q.String(),error:Q.Optional(Q.String()),verificationCommands:Q.Optional(Q.Array(Q.String())),verificationVerdict:Q.Optional(Z(["pass","fail","partial"])),modifiedFiles:Q.Optional(Q.Array(Q.String()))})),stats:Q.Optional(Q.Object({tokens:Q.Optional(Q.Number()),toolCalls:Q.Optional(Q.Number()),duration:Q.Optional(Q.Number())}))})),o1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"})})),s1=X(Q.Object({source:u,session:u})),i1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),a1=X(Q.Object({path:Q.String(),name:Q.String(),gitBranch:Q.Optional(Q.String()),available:Q.Boolean(),isCurrent:Q.Boolean(),boundAt:Q.String()})),t1=X(Q.Union([Q.Object({cancelled:Q.Literal(!0)}),Q.Object({cancelled:Q.Literal(!1),path:Q.String({minLength:1})})])),r1=X(Q.Object({type:Q.String(),seq:Q.Optional(Q.Number()),properties:Q.Record(Q.String(),Q.Unknown())})),g=Q.Object({type:Z(["file","image","url"]),path:Q.Optional(Q.String()),url:Q.Optional(Q.String()),content:Q.Optional(Q.String({maxLength:h})),mimeType:Q.Optional(Q.String()),name:Q.Optional(Q.String())}),o=Q.Record(Q.String(),Q.Unknown()),T1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:U(x,"medium"),taskKind:U(C,"feature"),taskDueAt:Q.Optional(Q.String({minLength:1,maxLength:64})),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),y1=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.Union([Q.String({minLength:1,maxLength:64}),Q.Null()]))})),p1=X(Q.Object({session:_,runId:Q.String(),messageId:Q.String(),status:Z(["queued","running"]),queuePosition:Q.Optional(Q.Integer({minimum:1})),queueDepth:Q.Optional(Q.Integer({minimum:0})),maxConcurrentTasks:Q.Optional(Q.Integer({minimum:1}))})),e1=X(Q.Object({action:Z(["apply","discard"])})),q=X(Q.Object({kind:Z(["cron","interval","once"]),cron:Q.Optional(Q.String({minLength:1,maxLength:120})),intervalMs:Q.Optional(Q.Integer({minimum:60000})),runAt:Q.Optional(Q.String({minLength:1,maxLength:40})),timezone:Q.Optional(Q.String({minLength:1,maxLength:80}))})),O1=X(Q.Object({modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default")})),f=X(Q.Object({id:Q.String(),title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,dispatch:O1,enabled:Q.Boolean(),createdAt:Q.String(),updatedAt:Q.String(),nextRunAt:Q.Union([Q.String(),Q.Null()]),expiresAt:Q.Union([Q.String(),Q.Null()]),lastRunAt:Q.Optional(Q.String()),lastRunSessionId:Q.Optional(Q.String()),lastStatus:Q.Optional(Z(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:Q.Optional(Q.String()),runCount:Q.Integer({minimum:0})})),QQ=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),enabled:U(Q.Boolean(),!0)})),$Q=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.Optional(Q.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:Q.Optional(q),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:Q.Optional(A),permissionMode:Q.Optional(w),enabled:Q.Optional(Q.Boolean())})),JQ=X(Q.Object({schedules:Q.Array(f)})),XQ=X(Q.Object({content:Q.String({maxLength:d}),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),permissionMode:Q.Optional(w),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),V1=Z(["completed","failed","aborted","timed_out","spawn_error"]),b1=X(Q.Object({version:Q.Literal(1),command:Q.String(),status:V1,exitCode:Q.Union([Q.Integer(),Q.Null()]),durationMs:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),stdoutOmittedBytes:Q.Integer({minimum:0}),stderrOmittedBytes:Q.Integer({minimum:0}),binaryOutput:Q.Boolean(),truncated:Q.Boolean()})),ZQ=X(Q.Object({command:Q.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),BQ=X(Q.Object({executionId:Q.String(),messageId:Q.String(),record:b1,auxiliary:Q.Boolean(),delivery:Q.Optional(Z(["current_turn","next_turn"])),queued:Q.Optional(Q.Integer({minimum:0}))})),KQ=X(Q.Object({question:Q.String({minLength:1,maxLength:l,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),WQ=X(Q.Object({response:Q.String({minLength:1}),durationMs:Q.Number({minimum:0}),modelId:Q.Optional(Q.String()),usage:Q.Optional(Q.Object({promptTokens:Q.Number({minimum:0}),completionTokens:Q.Number({minimum:0}),totalTokens:Q.Number({minimum:0}),reasoningTokens:Q.Optional(Q.Number({minimum:0})),cacheCreationInputTokens:Q.Optional(Q.Number({minimum:0})),cacheReadInputTokens:Q.Optional(Q.Number({minimum:0})),costUsd:Q.Optional(Q.Number({minimum:0}))}))})),YQ=X(Q.Object({projectPath:Q.String(),kind:Z(["uncommitted","base","commit"]),ref:Q.Optional(Q.String({maxLength:200})),instructions:Q.Optional(Q.String({maxLength:4000})),modelId:Q.Optional(Q.String({minLength:1,maxLength:200}))})),HQ=X(Q.Object({reviewId:Q.String(),status:Q.Literal("running")})),jQ=X(Q.Object({messageId:Q.String(),role:v,content:Q.String(),timestamp:Q.String()})),UQ=X(Q.Object({approved:Q.Boolean(),remember:Q.Optional(Q.Boolean()),scope:Q.Optional(Z(["once","session","project"])),targetMode:Q.Optional(w),feedback:Q.Optional(Q.String()),answers:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String(),Q.Array(Q.String())]))),elicitation:Q.Optional(Q.Object({action:Z(["accept","decline","cancel"]),content:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String({maxLength:4000}),Q.Number(),Q.Boolean(),Q.Array(Q.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),G1=X(Q.Object({id:G,name:Q.String({minLength:1,maxLength:80}),description:Q.String({minLength:1,maxLength:256}),source:Z(["built-in","user","project","plugin"]),contentSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),kQ=X(Q.Object({id:Q.String(),displayName:Q.Optional(Q.String()),provider:Q.String(),model:Q.String(),contextWindow:Q.Optional(Q.Number()),maxTokens:Q.Optional(Q.Number()),reasoning:Q.Optional(Q.Boolean()),supportedReasoningEfforts:Q.Optional(Q.Array(Z(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:Q.Optional(Q.Array(Z(["standard","fast","flex"]))),supportedResponseVerbosities:Q.Optional(Q.Array(Z(["low","medium","high"]))),communicationStyles:Q.Optional(Q.Array(G1,{maxItems:36})),input:Q.Optional(Q.Array(Z(["text","image"]))),overrides:Q.Optional(Q.Object({baseUrl:Q.Optional(Q.String()),temperature:Q.Optional(Q.Number()),maxOutputTokens:Q.Optional(Q.Number()),timeout:Q.Optional(Q.Number()),streamIdleTimeout:Q.Optional(Q.Number({minimum:1000}))}))})),OQ=X(Z(["vs-dark","vs-light","hc-black"])),w1=X(Z(["light","dark","system"])),M1=X(Q.Object({language:Q.String(),codeTheme:Q.String(),uiTheme:w1,autoSaveSessions:Q.Boolean(),notifyBuild:Q.Boolean(),notifyErrors:Q.Boolean(),notifySounds:Q.Boolean(),privacyTelemetry:Q.Boolean(),privacyCrash:Q.Boolean(),agentTeamsEnabled:Q.Boolean(),communicationStyle:Q.Optional(G)})),VQ=X(Q.Partial(M1));var s=a("Service"),A1=1;function _1(){return t.join(i(),"schedules.json")}class L{filePath;static instance;static getInstance(){if(!L.instance)L.instance=new L;return L.instance}writeChain=Promise.resolve();constructor($=_1()){this.filePath=$}async readFile(){try{let $=await I1(this.filePath,"utf-8"),J=JSON.parse($);if(!J||!Array.isArray(J.schedules))return[];let K=[],B=0;for(let W of J.schedules){let Y=f.safeParse(W);if(Y.success)K.push(Y.data);else B+=1}if(B>0)s.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch($){let J=$;if(J.code!=="ENOENT")s.warn("[ScheduleStore] Failed to read schedules; treating as empty:",J);return[]}}async writeFile($){await P1(t.dirname(this.filePath),{recursive:!0,mode:493});let J={version:A1,schedules:$};await D1(this.filePath,JSON.stringify(J,null,2),{mode:384})}serializeWrite($){let J=this.writeChain.then($,$);return this.writeChain=J.then(()=>{return},()=>{return}),J}async list(){return this.readFile()}async get($){return(await this.readFile()).find((K)=>K.id===$)}async create($){return this.serializeWrite(async()=>{let J=$.trigger.kind==="cron"&&!$.trigger.timezone?{...$.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:$.trigger,K=z(J);if(K)throw Error(K);let B=new Date;if(J.kind==="once"&&new Date(J.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let W=B.toISOString(),Y=F(J,B),O={id:L1(10),title:$.title,prompt:$.prompt,projectPath:$.projectPath,trigger:J,dispatch:{modelId:$.modelId,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,isolation:$.isolation??"worktree",permissionMode:$.permissionMode??"default"},enabled:$.enabled??!0,createdAt:W,updatedAt:W,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(O),await this.writeFile(V),O})}async update($,J){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===$);if(B===-1)return;let W=K[B];if(J.trigger){let H=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,k=z(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");J={...J,trigger:H}}let Y={...W,...J,dispatch:J.dispatch?{...W.dispatch,...J.dispatch}:W.dispatch,updatedAt:new Date().toISOString()},O=!W.enabled,V=Y.enabled,j=J.trigger!==void 0;if((j||O&&V)&&J.nextRunAt===void 0){let H=new Date,k=F(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove($){return this.serializeWrite(async()=>{let J=await this.readFile(),K=J.filter((B)=>B.id!==$);if(K.length===J.length)return!1;return await this.writeFile(K),!0})}async setEnabled($,J){return this.update($,{enabled:J})}}var NQ=L.getInstance();
2
- export{l as La,v1 as Ma,F1 as Na,F as Oa,z as Pa,z1 as Qa,S1 as Ra,_ as Sa,n1 as Ta,o1 as Ua,T1 as Va,y1 as Wa,p1 as Xa,e1 as Ya,f as Za,QQ as _a,$Q as $a,JQ as ab,XQ as bb,ZQ as cb,KQ as db,YQ as eb,L as fb,NQ as gb};
1
+ import{Hh as Q,Ih as X,Jh as U,Kh as Z}from"./chunk-9fgkg1vr.js";import{Lh as N,Mh as h,Oh as d}from"./chunk-pykxe413.js";import{ti as a}from"./chunk-w4xqaw4h.js";import{Zi as i}from"./chunk-spxb931p.js";var b=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],T={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D($,J,K){let B=new Set;for(let W of $.split(",")){let[Y,O]=W.split("/"),V=O?Number.parseInt(O,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${$}"`);let j=J,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,r]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(r,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<J||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${$}"`);for(let k=j;k<=H;k+=V)B.add(k)}return B}function R($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${J.length}`);let[K,B,W,Y,O]=J,V=D(O,b[4].min,b[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,b[0].min,b[0].max),hours:D(B,b[1].min,b[1].max),daysOfMonth:D(W,b[2].min,b[2].max),months:D(Y,b[3].min,b[3].max),daysOfWeek:j,domRestricted:W.trim()!=="*",dowRestricted:O.trim()!=="*"}}function y($,J){if(!J)return{minute:$.getMinutes(),hour:$.getHours(),dayOfMonth:$.getDate(),month:$.getMonth()+1,dayOfWeek:$.getDay()};let K=E.get(J);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:J,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(J,K);let B=Object.fromEntries(K.formatToParts($).filter((W)=>W.type!=="literal").map((W)=>[W.type,W.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:T[B.weekday]??-1}}function p($,J,K){let B=y(J,K);if(!$.minutes.has(B.minute))return!1;if(!$.hours.has(B.hour))return!1;if(!$.months.has(B.month))return!1;let W=$.daysOfMonth.has(B.dayOfMonth),Y=$.daysOfWeek.has(B.dayOfWeek);if($.domRestricted&&$.dowRestricted)return W||Y;if($.domRestricted)return W;if($.dowRestricted)return Y;return!0}function e($,J,K){let B=R($),W=new Date(J.getTime());W.setSeconds(0,0),W.setMinutes(W.getMinutes()+1);let Y=new Date(J.getTime());Y.setFullYear(Y.getFullYear()+4);while(W.getTime()<=Y.getTime()){if(p(B,W,K))return new Date(W.getTime());W.setMinutes(W.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function F1($){let K=$.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!K)return null;let B=Number.parseInt(K[1],10);if(!Number.isInteger(B)||B<=0)return null;let W=K[2]||"m";return B*S[W]}function Q1($){for(let J of["d","h","m","s"]){let K=S[J];if($%K===0)return`${$/K}${J}`}return`${Math.round($/1000)}s`}function F($,J,K){switch($.kind){case"cron":{if(!$.cron)return null;try{return e($.cron,J,$.timezone)}catch{return null}}case"interval":{if(!$.intervalMs||$.intervalMs<=0)return null;let W=new Date((K??J).getTime()+$.intervalMs);return W.getTime()<=J.getTime()?new Date(J.getTime()+1000):W}case"once":{if(!$.runAt)return null;let B=new Date($.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>J.getTime()?B:null}default:return null}}function z($){switch($.kind){case"cron":if(!$.cron)return"cron trigger requires a cron expression";try{if(R($.cron),$.timezone)new Intl.DateTimeFormat("en-US",{timeZone:$.timezone}).format();return null}catch(J){return J instanceof Error?J.message:"invalid cron expression"}case"interval":if(!$.intervalMs||$.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!$.runAt)return"once trigger requires runAt timestamp";let J=new Date($.runAt);if(Number.isNaN(J.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function z1($){switch($.kind){case"cron":return`cron: ${$.cron??"?"}`;case"interval":return`every ${$.intervalMs?Q1($.intervalMs):"?"}`;case"once":return`once at ${$.runAt??"?"}`;default:return"unknown"}}import{mkdir as P1,readFile as I1}from"node:fs/promises";import t from"node:path";import{nanoid as L1}from"nanoid";import D1 from"write-file-atomic";var l=16384;function v1($){let J=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec($);if(!J)return;return{question:(J[1]??"").trim()}}var w=X(Z(["default","autoEdit","yolo","plan"]));var v=X(Z(["user","assistant","system","tool"])),$1=X(Q.Union([Q.Object({type:Q.Literal("text"),text:Q.String()}),Q.Object({type:Q.Literal("image_url"),image_url:Q.Object({url:Q.String()})})])),m=Q.Union([Q.String(),Q.Array($1)]),R1=X(Q.Object({id:Q.String(),role:v,content:m,timestamp:Q.Number(),metadata:Q.Optional(Q.Record(Q.String(),Q.Unknown())),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),J1=X(Z(["queued","running","completed","failed","cancelled","interrupted"])),A=X(Z(["local","worktree"])),x=X(Z(["high","medium","low"])),C=X(Z(["feature","bug","maintenance","research"])),X1=X(Z(["applied","discarded","conflicted"])),Z1=X(Q.Object({status:X1,updatedAt:Q.String(),sourceCommit:Q.Optional(Q.String()),changedFiles:Q.Optional(Q.Integer({minimum:0})),message:Q.Optional(Q.String())})),B1=X(Q.Object({changedFiles:Q.Integer({minimum:0}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),commits:Q.Integer({minimum:0})})),K1=X(Q.Object({path:Q.String({minLength:1}),patch:Q.String({maxLength:2097152}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),binary:Q.Boolean(),truncated:Q.Boolean()})),S1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),baseCommit:Q.String(),files:Q.Array(K1,{maxItems:100}),truncated:Q.Boolean()})),W1=Q.Union([Q.String(),Q.Number(),Q.Boolean(),Q.Array(Q.String())]),Y1=X(Q.Object({name:Q.String(),type:Z(["string","number","integer","boolean","select","multi-select"]),title:Q.String(),description:Q.Optional(Q.String()),required:Q.Boolean(),defaultValue:Q.Optional(W1),options:Q.Optional(Q.Array(Q.Object({value:Q.String(),label:Q.String()}))),format:Q.Optional(Z(["date","uri","email","date-time"])),minimum:Q.Optional(Q.Number()),maximum:Q.Optional(Q.Number()),minLength:Q.Optional(Q.Number()),maxLength:Q.Optional(Q.Number()),minItems:Q.Optional(Q.Number()),maxItems:Q.Optional(Q.Number())})),l1=X(Q.Object({serverName:Q.String(),mode:Z(["form","url"]),message:Q.String(),fields:Q.Optional(Q.Array(Y1)),requestedSchema:Q.Optional(Q.Record(Q.String(),Q.Unknown())),url:Q.Optional(Q.String()),domain:Q.Optional(Q.String()),elicitationId:Q.Optional(Q.String())})),H1=X(Q.Object({type:Z(["permission","question","elicitation"]),requestId:Q.String()})),j1=X(Q.Object({code:Z(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:Q.String({minLength:1,maxLength:500}),retryable:Q.Boolean(),resource:Q.Optional(Z(["pending_count","pending_bytes","resident_runtimes"]))})),M=X(Z(["auto","off","minimal","low","medium","high","xhigh","max"])),P=X(Z(["auto","standard","fast","flex"])),I=X(Z(["auto","low","medium","high"])),G=X(Q.Union([Z(["auto","pragmatic","friendly","explanatory"]),Q.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),_=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),title:Q.Optional(Q.String()),gitBranch:Q.Optional(Q.String()),rootId:Q.String(),parentId:Q.Optional(Q.String()),relationType:Q.Optional(Z(["subagent","fork"])),resumedFrom:Q.Optional(Q.String()),rootAgentId:Q.Optional(Q.String()),resumeDepth:Q.Optional(Q.Integer({minimum:0})),taskStatus:U(J1,"completed"),taskStatusReason:Q.Optional(Q.String()),taskFailure:Q.Optional(j1),taskStartedAt:Q.Optional(Q.String()),taskCompletedAt:Q.Optional(Q.String()),taskPromptSummary:Q.Optional(Q.String()),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.String()),taskModelId:Q.Optional(Q.String()),selectedModelId:Q.Optional(Q.String()),permissionMode:Q.Optional(w),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),communicationStyleDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:Q.Optional(Q.Boolean()),taskRetriedFrom:Q.Optional(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),taskDelivery:Q.Optional(Z1),taskIsolation:Q.Optional(A),taskSourceProjectPath:Q.Optional(Q.String()),taskWorktreePath:Q.Optional(Q.String()),taskWorktreeBranch:Q.Optional(Q.String()),taskBaseCommit:Q.Optional(Q.String()),taskDiffStat:Q.Optional(B1),taskQueuePosition:Q.Optional(Q.Integer({minimum:1})),taskQueueDepth:Q.Optional(Q.Integer({minimum:0})),taskConcurrencyLimit:Q.Optional(Q.Integer({minimum:1})),archivedAt:Q.Optional(Q.String()),archivedBySessionId:Q.Optional(Q.String()),pendingInteraction:Q.Optional(H1),messageCount:Q.Number(),firstMessageTime:Q.String(),lastMessageTime:Q.String(),hasErrors:Q.Boolean()})),u1=X(Q.Object({sessions:Q.Array(_),nextCursor:Q.Optional(Q.String())})),h1=X(Q.Object({session:_,archivedSessionIds:Q.Array(Q.String())})),d1=X(Q.Object({session:_,restoredSessionIds:Q.Array(Q.String())})),m1=X(Q.Object({version:Q.Union([Q.Literal(1),Q.Literal(2)]),sessionId:Q.String(),goalId:Q.String(),objective:Q.String(),status:Z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:Q.Optional(Q.Number()),tokensUsed:Q.Number(),timeUsedSeconds:Q.Number(),continuationCount:Q.Number(),statusReason:Q.Optional(Q.String()),completionVerification:Q.Optional(Q.Object({attempt:Q.Integer({minimum:1}),status:Z(["pending","pass","fail","partial"]),requestedAt:Q.String(),completedAt:Q.Optional(Q.String()),verifierSessionId:Q.Optional(Q.String()),summary:Q.Optional(Q.String()),evidenceSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:Q.Optional(Q.Object({pattern:Q.Unsafe({type:"string"}),consecutiveCount:Q.Integer({minimum:1}),detectedAt:Q.String()})),verificationStall:Q.Optional(Q.Unsafe({type:"object"})),executionFrontier:Q.Optional(Q.Object({taskListId:Q.String({minLength:1,maxLength:256}),total:Q.Integer({minimum:0}),completed:Q.Integer({minimum:0}),inProgress:Q.Integer({minimum:0}),pending:Q.Integer({minimum:0}),blocked:Q.Integer({minimum:0}),nextTask:Q.Optional(Q.Object({id:Q.String({minLength:1}),subject:Q.String({minLength:1,maxLength:512}),priority:Z(["high","medium","low"])})),digestSha256:Q.String({pattern:"^[a-f0-9]{64}$"}),observedAt:Q.String()})),frontierStall:Q.Optional(Q.Object({category:Z(["waiting_dependency","same_task_no_effect","repeated_deferral"]),consecutiveCount:Q.Integer({minimum:1,maximum:3}),digestSha256:Q.String({pattern:"^[a-f0-9]{64}$"}),detectedAt:Q.String()})),createdAt:Q.String(),updatedAt:Q.String()})),c=X(Q.Object({role:v,content:m,metadata:Q.Optional(Q.Unknown()),reasoningContent:Q.Optional(Q.String()),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),c1=X(Q.Object({session:_,messages:Q.Array(c)})),n=X(Z(["conversation","code","both"])),U1=X(Q.Object({messageId:Q.String(),preview:Q.String(),createdAt:Q.String(),fileCount:Q.Integer({minimum:0})})),n1=X(Q.Object({targetMessageId:Q.String({minLength:1}),mode:U(n,"conversation")})),g1=X(Q.Object({checkpoint:U1,mode:n,removedTurns:Q.Integer({minimum:1}),restoredFiles:Q.Array(Q.String()),messages:Q.Array(c)})),k1=Z(["running","completed","failed","cancelled"]),u=X(Q.Object({id:Q.String(),subagentType:Q.String(),description:Q.String(),status:k1,background:Q.Boolean(),rootAgentId:Q.String(),resumedFrom:Q.Optional(Q.String()),resumeDepth:Q.Integer({minimum:0}),createdAt:Q.Number(),lastActiveAt:Q.Number(),completedAt:Q.Optional(Q.Number()),restartRecovery:Q.Optional(Q.Object({outcome:Z(["completed","interrupted","failed"]),recoveredAt:Q.Number()})),result:Q.Optional(Q.Object({success:Q.Boolean(),message:Q.String(),error:Q.Optional(Q.String()),verificationCommands:Q.Optional(Q.Array(Q.String())),verificationVerdict:Q.Optional(Z(["pass","fail","partial"])),modifiedFiles:Q.Optional(Q.Array(Q.String()))})),stats:Q.Optional(Q.Object({tokens:Q.Optional(Q.Number()),toolCalls:Q.Optional(Q.Number()),duration:Q.Optional(Q.Number())}))})),o1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"})})),s1=X(Q.Object({source:u,session:u})),i1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),a1=X(Q.Object({path:Q.String(),name:Q.String(),gitBranch:Q.Optional(Q.String()),available:Q.Boolean(),isCurrent:Q.Boolean(),boundAt:Q.String()})),t1=X(Q.Union([Q.Object({cancelled:Q.Literal(!0)}),Q.Object({cancelled:Q.Literal(!1),path:Q.String({minLength:1})})])),r1=X(Q.Object({type:Q.String(),seq:Q.Optional(Q.Number()),properties:Q.Record(Q.String(),Q.Unknown())})),g=Q.Object({type:Z(["file","image","url"]),path:Q.Optional(Q.String()),url:Q.Optional(Q.String()),content:Q.Optional(Q.String({maxLength:h})),mimeType:Q.Optional(Q.String()),name:Q.Optional(Q.String())}),o=Q.Record(Q.String(),Q.Unknown()),T1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:U(x,"medium"),taskKind:U(C,"feature"),taskDueAt:Q.Optional(Q.String({minLength:1,maxLength:64})),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),y1=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.Union([Q.String({minLength:1,maxLength:64}),Q.Null()]))})),p1=X(Q.Object({session:_,runId:Q.String(),messageId:Q.String(),status:Z(["queued","running"]),queuePosition:Q.Optional(Q.Integer({minimum:1})),queueDepth:Q.Optional(Q.Integer({minimum:0})),maxConcurrentTasks:Q.Optional(Q.Integer({minimum:1}))})),e1=X(Q.Object({action:Z(["apply","discard"])})),q=X(Q.Object({kind:Z(["cron","interval","once"]),cron:Q.Optional(Q.String({minLength:1,maxLength:120})),intervalMs:Q.Optional(Q.Integer({minimum:60000})),runAt:Q.Optional(Q.String({minLength:1,maxLength:40})),timezone:Q.Optional(Q.String({minLength:1,maxLength:80}))})),O1=X(Q.Object({modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default")})),f=X(Q.Object({id:Q.String(),title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,dispatch:O1,enabled:Q.Boolean(),createdAt:Q.String(),updatedAt:Q.String(),nextRunAt:Q.Union([Q.String(),Q.Null()]),expiresAt:Q.Union([Q.String(),Q.Null()]),lastRunAt:Q.Optional(Q.String()),lastRunSessionId:Q.Optional(Q.String()),lastStatus:Q.Optional(Z(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:Q.Optional(Q.String()),runCount:Q.Integer({minimum:0})})),QQ=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),enabled:U(Q.Boolean(),!0)})),$Q=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.Optional(Q.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:Q.Optional(q),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:Q.Optional(A),permissionMode:Q.Optional(w),enabled:Q.Optional(Q.Boolean())})),JQ=X(Q.Object({schedules:Q.Array(f)})),XQ=X(Q.Object({content:Q.String({maxLength:d}),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),permissionMode:Q.Optional(w),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),V1=Z(["completed","failed","aborted","timed_out","spawn_error"]),b1=X(Q.Object({version:Q.Literal(1),command:Q.String(),status:V1,exitCode:Q.Union([Q.Integer(),Q.Null()]),durationMs:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),stdoutOmittedBytes:Q.Integer({minimum:0}),stderrOmittedBytes:Q.Integer({minimum:0}),binaryOutput:Q.Boolean(),truncated:Q.Boolean()})),ZQ=X(Q.Object({command:Q.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),BQ=X(Q.Object({executionId:Q.String(),messageId:Q.String(),record:b1,auxiliary:Q.Boolean(),delivery:Q.Optional(Z(["current_turn","next_turn"])),queued:Q.Optional(Q.Integer({minimum:0}))})),KQ=X(Q.Object({question:Q.String({minLength:1,maxLength:l,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),WQ=X(Q.Object({response:Q.String({minLength:1}),durationMs:Q.Number({minimum:0}),modelId:Q.Optional(Q.String()),usage:Q.Optional(Q.Object({promptTokens:Q.Number({minimum:0}),completionTokens:Q.Number({minimum:0}),totalTokens:Q.Number({minimum:0}),reasoningTokens:Q.Optional(Q.Number({minimum:0})),cacheCreationInputTokens:Q.Optional(Q.Number({minimum:0})),cacheReadInputTokens:Q.Optional(Q.Number({minimum:0})),costUsd:Q.Optional(Q.Number({minimum:0}))}))})),YQ=X(Q.Object({projectPath:Q.String(),kind:Z(["uncommitted","base","commit"]),ref:Q.Optional(Q.String({maxLength:200})),instructions:Q.Optional(Q.String({maxLength:4000})),modelId:Q.Optional(Q.String({minLength:1,maxLength:200}))})),HQ=X(Q.Object({reviewId:Q.String(),status:Q.Literal("running")})),jQ=X(Q.Object({messageId:Q.String(),role:v,content:Q.String(),timestamp:Q.String()})),UQ=X(Q.Object({approved:Q.Boolean(),remember:Q.Optional(Q.Boolean()),scope:Q.Optional(Z(["once","session","project"])),targetMode:Q.Optional(w),feedback:Q.Optional(Q.String()),answers:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String(),Q.Array(Q.String())]))),elicitation:Q.Optional(Q.Object({action:Z(["accept","decline","cancel"]),content:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String({maxLength:4000}),Q.Number(),Q.Boolean(),Q.Array(Q.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),G1=X(Q.Object({id:G,name:Q.String({minLength:1,maxLength:80}),description:Q.String({minLength:1,maxLength:256}),source:Z(["built-in","user","project","plugin"]),contentSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),kQ=X(Q.Object({id:Q.String(),displayName:Q.Optional(Q.String()),provider:Q.String(),model:Q.String(),contextWindow:Q.Optional(Q.Number()),maxTokens:Q.Optional(Q.Number()),reasoning:Q.Optional(Q.Boolean()),supportedReasoningEfforts:Q.Optional(Q.Array(Z(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:Q.Optional(Q.Array(Z(["standard","fast","flex"]))),supportedResponseVerbosities:Q.Optional(Q.Array(Z(["low","medium","high"]))),communicationStyles:Q.Optional(Q.Array(G1,{maxItems:36})),input:Q.Optional(Q.Array(Z(["text","image"]))),overrides:Q.Optional(Q.Object({baseUrl:Q.Optional(Q.String()),temperature:Q.Optional(Q.Number()),maxOutputTokens:Q.Optional(Q.Number()),timeout:Q.Optional(Q.Number()),streamIdleTimeout:Q.Optional(Q.Number({minimum:1000}))}))})),OQ=X(Z(["vs-dark","vs-light","hc-black"])),w1=X(Z(["light","dark","system"])),M1=X(Q.Object({language:Q.String(),codeTheme:Q.String(),uiTheme:w1,autoSaveSessions:Q.Boolean(),notifyBuild:Q.Boolean(),notifyErrors:Q.Boolean(),notifySounds:Q.Boolean(),privacyTelemetry:Q.Boolean(),privacyCrash:Q.Boolean(),agentTeamsEnabled:Q.Boolean(),communicationStyle:Q.Optional(G)})),VQ=X(Q.Partial(M1));var s=a("Service"),A1=1;function _1(){return t.join(i(),"schedules.json")}class L{filePath;static instance;static getInstance(){if(!L.instance)L.instance=new L;return L.instance}writeChain=Promise.resolve();constructor($=_1()){this.filePath=$}async readFile(){try{let $=await I1(this.filePath,"utf-8"),J=JSON.parse($);if(!J||!Array.isArray(J.schedules))return[];let K=[],B=0;for(let W of J.schedules){let Y=f.safeParse(W);if(Y.success)K.push(Y.data);else B+=1}if(B>0)s.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch($){let J=$;if(J.code!=="ENOENT")s.warn("[ScheduleStore] Failed to read schedules; treating as empty:",J);return[]}}async writeFile($){await P1(t.dirname(this.filePath),{recursive:!0,mode:493});let J={version:A1,schedules:$};await D1(this.filePath,JSON.stringify(J,null,2),{mode:384})}serializeWrite($){let J=this.writeChain.then($,$);return this.writeChain=J.then(()=>{return},()=>{return}),J}async list(){return this.readFile()}async get($){return(await this.readFile()).find((K)=>K.id===$)}async create($){return this.serializeWrite(async()=>{let J=$.trigger.kind==="cron"&&!$.trigger.timezone?{...$.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:$.trigger,K=z(J);if(K)throw Error(K);let B=new Date;if(J.kind==="once"&&new Date(J.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let W=B.toISOString(),Y=F(J,B),O={id:L1(10),title:$.title,prompt:$.prompt,projectPath:$.projectPath,trigger:J,dispatch:{modelId:$.modelId,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,isolation:$.isolation??"worktree",permissionMode:$.permissionMode??"default"},enabled:$.enabled??!0,createdAt:W,updatedAt:W,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(O),await this.writeFile(V),O})}async update($,J){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===$);if(B===-1)return;let W=K[B];if(J.trigger){let H=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,k=z(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");J={...J,trigger:H}}let Y={...W,...J,dispatch:J.dispatch?{...W.dispatch,...J.dispatch}:W.dispatch,updatedAt:new Date().toISOString()},O=!W.enabled,V=Y.enabled,j=J.trigger!==void 0;if((j||O&&V)&&J.nextRunAt===void 0){let H=new Date,k=F(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove($){return this.serializeWrite(async()=>{let J=await this.readFile(),K=J.filter((B)=>B.id!==$);if(K.length===J.length)return!1;return await this.writeFile(K),!0})}async setEnabled($,J){return this.update($,{enabled:J})}}var NQ=L.getInstance();
2
+ export{l as Ma,v1 as Na,F1 as Oa,F as Pa,z as Qa,z1 as Ra,S1 as Sa,_ as Ta,n1 as Ua,o1 as Va,T1 as Wa,y1 as Xa,p1 as Ya,e1 as Za,f as _a,QQ as $a,$Q as ab,JQ as bb,XQ as cb,ZQ as db,KQ as eb,YQ as fb,L as gb,NQ as hb};
@@ -0,0 +1 @@
1
+ import{a,b as i,c as l,d as m}from"./chunk-scgq3g37.js";import"./chunk-anjpwev3.js";import"./chunk-nq0w1j1a.js";import"./chunk-56fb0ece.js";import"./chunk-2w10er3y.js";import"./chunk-40pzrpjc.js";import"./chunk-x4t1v4rb.js";import"./chunk-dabq8kdx.js";import"./chunk-2v8fyvmh.js";import"./chunk-fpjhg6ce.js";import"./chunk-150w9kq4.js";import"./chunk-sca5q3tt.js";import"./chunk-sefdw1mm.js";import"./chunk-q265drks.js";import"./chunk-7dykmcjj.js";import{ze as n}from"./chunk-y1n8nf5w.js";import"./chunk-twdfyk78.js";import{Ve as s}from"./chunk-1qbq7x98.js";import"./chunk-v508x7cg.js";import"./chunk-ye4wyq1k.js";import"./chunk-kpqdfn9z.js";import"./chunk-b41den40.js";import"./chunk-8qp8v96d.js";import"./chunk-6h0kgpgv.js";import"./chunk-j2pgrrkb.js";import"./chunk-0zzh482s.js";import"./chunk-adkpwx6c.js";import"./chunk-85bamng3.js";import"./chunk-t169d8dc.js";import"./chunk-2t6b962t.js";import"./chunk-7k72dxwe.js";import"./chunk-kz15jy62.js";import"./chunk-9fgkg1vr.js";import"./chunk-pykxe413.js";import"./chunk-kzzty3v5.js";import"./chunk-9jtjq50j.js";import"./chunk-w4xqaw4h.js";import"./chunk-r6svhe3w.js";import"./chunk-a4dmw23t.js";import"./chunk-5hmeb6yk.js";import"./chunk-ncqagb27.js";import"./chunk-207s8tns.js";import"./chunk-spxb931p.js";import"./chunk-m7b779kd.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 +1 @@
1
- import{Aa as f,Ba as k,ya as h}from"./chunk-ypbnczjp.js";import"./chunk-tf7ezqew.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{Ba as f,Ca as k,za as h}from"./chunk-dabq8kdx.js";import"./chunk-m7b779kd.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -1,4 +1,4 @@
1
- import{$f as L0,_f as b1,ag as z1,fg as N0}from"./chunk-cqqmkwvn.js";import{mg as jO,ng as wO}from"./chunk-9g64g1np.js";import{qg as A1}from"./chunk-935v0gpc.js";import{rg as b0,tg as J0}from"./chunk-swtap0bs.js";import{Ah as I0,vh as S0,wh as GO}from"./chunk-y21nw7g1.js";import{Eh as u,Gh as L,Jh as c1}from"./chunk-6k5k40p8.js";import{Sh as M}from"./chunk-ecd727xh.js";import{si as k,ti as S}from"./chunk-dvv28pkc.js";import{Gi as u0}from"./chunk-53aapkv1.js";import{Ni as N}from"./chunk-vbwvsgs1.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
1
+ import{$f as b1,ag as L0,bg as z1,gg as N0}from"./chunk-0zzh482s.js";import{ng as jO,og as wO}from"./chunk-adkpwx6c.js";import{rg as A1}from"./chunk-85bamng3.js";import{sg as b0,ug as J0}from"./chunk-t169d8dc.js";import{Bh as I0,wh as S0,xh as GO}from"./chunk-7k72dxwe.js";import{Fh as u,Hh as L,Kh as c1}from"./chunk-9fgkg1vr.js";import{Th as M}from"./chunk-kzzty3v5.js";import{ti as k,ui as S}from"./chunk-w4xqaw4h.js";import{Hi as u0}from"./chunk-5hmeb6yk.js";import{Oi as N}from"./chunk-ncqagb27.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
2
2
  ${J.map((K)=>`- ${K}`).join(`
3
3
  `)}`:""].filter(Boolean).join(`
4
4
 
@@ -730,4 +730,4 @@ ${Z.join(`
730
730
  </${Q}>`:"";return{content:K,files:[...O],references:O.map(O4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:w0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
731
731
  `))}}function AO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(L1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
732
732
  `))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=c$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&G1(J.scopeDirectory,Q));return q0(AO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=l$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>W1(z.relative(this.projectRoot,K1(G)))).filter(Y1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!G1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>xO(U,{dot:!0})(X)))continue}else if(G1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=AO([...q.values()].sort(L1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(L1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=W1(z.relative(this.projectRoot,K1(O)));if($&&!Y1($))throw Error("Project instruction source is outside the catalog root");return $}}async function $4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>zO)throw Error(`Project rule exceeds ${zO} bytes`);let Z=await d.realpath($),J=W1(z.relative(O,Z));if(!Y1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(TO(K))throw Error("Project rule contains hidden control characters");let q=u$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=r$(q.data.paths),Y=e$(J),X=w0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${w0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function _O(O,$){let Q=t$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=g$.stream([...o$],{cwd:Z,absolute:!0,dot:!0,deep:s$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...a$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>SO)throw Error(`Project rule catalog exceeds ${SO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await $4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>MO)throw Error(`Project rule catalog exceeds ${MO} bytes`);W.push(X)}catch(X){i$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var DO=32,D0=64;class CO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,X1=0,NO=[];async function Q4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await q1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function Z4(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function J5(O){NO=[...new Set(O.map(($)=>H1.resolve($)))]}function EO(O,$){YO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),T.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function vO(O){EO(O.workspaceRoot,O)}function K0(){while(x.size>DO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),vO(Q.resources),O=!0;break}if(!O)return}}function J4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function q4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=T.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??NO])]),A0(O),await Z1(O);let W=await q1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await _O(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw EO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function K4(O,$){let Q={generation:X1,users:0};return Q.promise=q4(O,$).then((Z)=>{if(Q.generation!==X1||x.get(O)!==Q)return vO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function RO(O,$){let Q=H1.resolve(O),Z=x.get(Q);if(!Z){if(K0(),x.size>=D0)throw new CO;Z=K4(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function yO(O,$){if(!$)return;A0(O.workspaceRoot),await Z1(O.workspaceRoot),await Q4(O)}async function q5(O,$={}){let Q=await RO(O,$);try{return await yO(Q.resources,$.reconcilePlugins),Q.resources}finally{J4(Q.entry)}}async function K5(O,$,Q={}){let Z=await RO(O,Q);try{return await yO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function G5(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:DO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function L5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:H1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??wO.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:Z4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function W5(){X1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),T.resetInstance(),D.resetInstance()}
733
- export{Y4 as yf,X4 as zf,H4 as Af,M1 as Bf,B4 as Cf,S4 as Df,o as Ef,y4 as Ff,w1 as Gf,g as Hf,T as If,r0 as Jf,M0 as Kf,D as Lf,Q0 as Mf,Z1 as Nf,A0 as Of,m as Pf,DO as Qf,D0 as Rf,CO as Sf,Q4 as Tf,J5 as Uf,q5 as Vf,K5 as Wf,G5 as Xf,L5 as Yf,W5 as Zf};
733
+ export{Y4 as zf,X4 as Af,H4 as Bf,M1 as Cf,B4 as Df,S4 as Ef,o as Ff,y4 as Gf,w1 as Hf,g as If,T as Jf,r0 as Kf,M0 as Lf,D as Mf,Q0 as Nf,Z1 as Of,A0 as Pf,m as Qf,DO as Rf,D0 as Sf,CO as Tf,Q4 as Uf,J5 as Vf,q5 as Wf,K5 as Xf,G5 as Yf,L5 as Zf,W5 as _f};
@@ -0,0 +1 @@
1
+ import{Gi as a,Hi as b,Ii as c,Ji as d,Ki as e,Li as f}from"./chunk-5hmeb6yk.js";import"./chunk-m7b779kd.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};