blade-code 0.10.70 → 0.10.71

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 (68) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-31k6x4kn.js → chunk-0tm20v38.js} +2 -2
  3. package/dist/{chunk-728anavt.js → chunk-0vrgrw71.js} +1 -1
  4. package/dist/{chunk-p9vaaayr.js → chunk-1je1xw6v.js} +1 -1
  5. package/dist/{chunk-g28pgqyn.js → chunk-1pjkgfez.js} +1 -1
  6. package/dist/{chunk-qstf0gpe.js → chunk-1w83z8j0.js} +1 -1
  7. package/dist/{chunk-r9n8y8m1.js → chunk-2428hhvj.js} +1 -1
  8. package/dist/{chunk-0p0e70cy.js → chunk-2px6hzdc.js} +1 -1
  9. package/dist/chunk-3as0bkqy.js +1 -0
  10. package/dist/{chunk-bkajr86v.js → chunk-3hy06st1.js} +1 -1
  11. package/dist/{chunk-qm5c9wew.js → chunk-4ke8k0xw.js} +2 -2
  12. package/dist/{chunk-ffym3kf3.js → chunk-4pexpa3h.js} +1 -1
  13. package/dist/{chunk-63121s4r.js → chunk-5te2jqt3.js} +1 -1
  14. package/dist/{chunk-b39p4f5r.js → chunk-82htkvz8.js} +1 -1
  15. package/dist/chunk-8j568nm6.js +1 -0
  16. package/dist/{chunk-wepvrnmh.js → chunk-92x15fzx.js} +1 -1
  17. package/dist/{chunk-4aam3qhk.js → chunk-93tvxmqg.js} +1 -1
  18. package/dist/{chunk-1z9k5dmz.js → chunk-97aywyzn.js} +1 -1
  19. package/dist/{chunk-ypgjqg23.js → chunk-9hchc346.js} +1 -1
  20. package/dist/{chunk-8wea3qty.js → chunk-9q852bsc.js} +2 -2
  21. package/dist/{chunk-w2gr97qt.js → chunk-ahg9vjb6.js} +1 -1
  22. package/dist/{chunk-wahhwjp9.js → chunk-axtzde5k.js} +1 -1
  23. package/dist/{chunk-y9d9nqnn.js → chunk-azw0jckv.js} +1 -1
  24. package/dist/{chunk-sch01e04.js → chunk-be30r8an.js} +1 -1
  25. package/dist/{chunk-d2vrbbvd.js → chunk-byqxaa9v.js} +1 -1
  26. package/dist/{chunk-7b5s752s.js → chunk-cff9gphh.js} +1 -1
  27. package/dist/{chunk-5wnx38ze.js → chunk-ckqpt15b.js} +1 -1
  28. package/dist/{chunk-0kmrvxsz.js → chunk-d3ttqmyt.js} +3 -3
  29. package/dist/{chunk-pw87f92g.js → chunk-dwb2nmms.js} +1 -1
  30. package/dist/{chunk-brdxkp0y.js → chunk-fcmgwzrj.js} +1 -1
  31. package/dist/{chunk-832va1mp.js → chunk-fcv8b6ny.js} +1 -1
  32. package/dist/{chunk-z77c18j5.js → chunk-gtcxybv5.js} +1 -1
  33. package/dist/chunk-gvbx0t4j.js +1 -0
  34. package/dist/{chunk-ysmqje92.js → chunk-j0p54tqt.js} +1 -1
  35. package/dist/{chunk-20vj0npz.js → chunk-j9q1wyxg.js} +1 -1
  36. package/dist/chunk-jzntxp7f.js +3 -0
  37. package/dist/{chunk-f7yfcw8s.js → chunk-mtphps19.js} +1 -1
  38. package/dist/chunk-n827nys9.js +1 -0
  39. package/dist/{chunk-cmpj3a5a.js → chunk-nwzpnx7m.js} +1 -1
  40. package/dist/{chunk-wkpacysr.js → chunk-nx31fkkf.js} +2 -2
  41. package/dist/{chunk-83b4vfjs.js → chunk-qgrq04hb.js} +1 -1
  42. package/dist/chunk-qnsvae10.js +1 -0
  43. package/dist/chunk-r9d4mjxj.js +2 -0
  44. package/dist/{chunk-b2p4kd07.js → chunk-rm9hbew3.js} +1 -1
  45. package/dist/{chunk-smjkx71w.js → chunk-s77sbxr7.js} +1 -1
  46. package/dist/chunk-sp3bn8qh.js +1 -0
  47. package/dist/{chunk-d808m826.js → chunk-t2wgf9tq.js} +1 -1
  48. package/dist/{chunk-1bcp0qc4.js → chunk-trn6r1g3.js} +1 -1
  49. package/dist/{chunk-0p95nha3.js → chunk-v7p533ff.js} +1 -1
  50. package/dist/{chunk-h94vfh7s.js → chunk-vthgpdbd.js} +1 -1
  51. package/dist/{chunk-k6shq7rk.js → chunk-wfy851et.js} +1 -1
  52. package/dist/chunk-wneeq8cr.js +1 -0
  53. package/dist/{chunk-4md4sd4j.js → chunk-wrfay5r3.js} +1 -1
  54. package/dist/{chunk-sh17gjxv.js → chunk-x9tvjkjv.js} +1 -1
  55. package/dist/{chunk-rpfa4a56.js → chunk-xdz5zrjt.js} +1 -1
  56. package/dist/chunk-xzz69esf.js +1 -0
  57. package/dist/{chunk-q919ypcz.js → chunk-zdnk7qtn.js} +1 -1
  58. package/package.json +1 -1
  59. package/dist/chunk-2z75emht.js +0 -1
  60. package/dist/chunk-3j413cgh.js +0 -1
  61. package/dist/chunk-8bsyhr4v.js +0 -1
  62. package/dist/chunk-c0qm0wwk.js +0 -1
  63. package/dist/chunk-cx5s0rf3.js +0 -1
  64. package/dist/chunk-e3asq942.js +0 -1
  65. package/dist/chunk-jrr361h1.js +0 -2
  66. package/dist/chunk-nea4rcdf.js +0 -1
  67. package/dist/chunk-v3kkv21n.js +0 -1
  68. package/dist/chunk-wj6t3tv2.js +0 -3
@@ -1,4 +1,4 @@
1
- import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-d808m826.js";import{_g as $t,bh as J}from"./chunk-0p0e70cy.js";import{jh as an,kh as xn}from"./chunk-y9d9nqnn.js";import{qh as h}from"./chunk-wj6t3tv2.js";import{Ah as mn}from"./chunk-8wea3qty.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{jg as Y}from"./chunk-h0ft81a3.js";import{kg as Tn,lg as F,mg as o}from"./chunk-v0rsz1rt.js";import{qg as ct,rg as bt}from"./chunk-xz6y0w4n.js";import{wg as a}from"./chunk-k0pa8874.js";import{Dg as gt,Eg as Jn,Fg as it,Gg as Ct,Hg as Rt,Ig as On,Jg as zt,Kg as Bt,Lg as kn,Mg as Ut,Ng as Kt,Og as yn,Pg as Ht,Qg as Yt,Rg as qt,Sg as Vt,Tg as Gt,xg as Zn,yg as Xt,zg as pt}from"./chunk-6pyktfa4.js";import{Xg as dn}from"./chunk-t2wgf9tq.js";import{_g as $t,bh as J}from"./chunk-2px6hzdc.js";import{jh as an,kh as xn}from"./chunk-azw0jckv.js";import{qh as h}from"./chunk-jzntxp7f.js";import{Bh as mn}from"./chunk-9q852bsc.js";var Qt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Dt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function C(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Dt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var K=async(n,t)=>{C(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function O(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(C(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let r=t.clientId?.trim();if(r&&r.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Qt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let _=t.callbackPort;if(_!==void 0&&(!Number.isInteger(_)||_<1024||_>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...r?{clientId:r}:{},...S?.length?{scopes:S}:{},..._!==void 0?{callbackPort:_}:{}}}import{randomUUID as v}from"node:crypto";import tM from"node:http";import{auth as An}from"@modelcontextprotocol/sdk/client/auth.js";import MM from"open";import{createHash as Wt,randomUUID as Zt}from"node:crypto";import{constants as k,promises as P}from"node:fs";import y from"node:path";import Jt from"write-file-atomic";var on=1,Ot=1048576,kt=5000,yt=50,jt=/^[a-f0-9]{64}$/,Ft=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),lt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),vt=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(Ft),tokens:o.Optional(lt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(vt),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),un=o.Object({version:o.Literal(on),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function nM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function j(n){return structuredClone(n)}function En(n){if(Object.keys(n.credentials).some((t)=>!jt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Wt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=mn()){this.stateRoot=y.join(n,"mcp"),this.tokenFilePath=y.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?j(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],r=await t(e?j(e):null);if(r)M.credentials[n]=F(sn,r);else delete M.credentials[n];return r?j(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=Tn(un,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return En(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:on,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(un,n);En(t),await Jt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=y.join(this.stateRoot,".oauth-credentials.lock"),t=Zt(),M=Date.now()+kt;while(Date.now()<M)try{let e=await P.open(n,k.O_CREAT|k.O_EXCL|k.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(r){if(!H(r,"ENOENT"))throw r}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((r)=>setTimeout(r,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!nM(M.pid))await P.unlink(n)}}var cn="127.0.0.1",bn=7777,wn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class Pn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -0,0 +1 @@
1
+ import{oh as a,ph as b,qh as c}from"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";export{b as isWorkspaceTrusted,c as WorkspaceTrustService,a as MAX_RESIDENT_WORKSPACE_TRUST_STATUSES};
@@ -1,2 +1,2 @@
1
- import{mg as J,ng as $,og as U,pg as B}from"./chunk-v0rsz1rt.js";import{qg as v,rg as h,sg as u}from"./chunk-xz6y0w4n.js";import{Xg as i}from"./chunk-d808m826.js";import{Ah as s}from"./chunk-8wea3qty.js";var O=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],r={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D(Q,Z,W){let K=new Set;for(let X of Q.split(",")){let[Y,V]=X.split("/"),G=V?Number.parseInt(V,10):1;if(!Number.isInteger(G)||G<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,t]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(t,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let k=j;k<=H;k+=G)K.add(k)}return K}function R(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,K,X,Y,V]=Z,G=D(V,O[4].min,O[4].max),j=new Set([...G].map((H)=>H===7?0:H));return{minutes:D(W,O[0].min,O[0].max),hours:D(K,O[1].min,O[1].max),daysOfMonth:D(X,O[2].min,O[2].max),months:D(Y,O[3].min,O[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:V.trim()!=="*"}}function T(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=E.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(Z,W);let K=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(K.minute),hour:Number(K.hour),dayOfMonth:Number(K.day),month:Number(K.month),dayOfWeek:r[K.weekday]??-1}}function y(Q,Z,W){let K=T(Z,W);if(!Q.minutes.has(K.minute))return!1;if(!Q.hours.has(K.hour))return!1;if(!Q.months.has(K.month))return!1;let X=Q.daysOfMonth.has(K.dayOfMonth),Y=Q.daysOfWeek.has(K.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function p(Q,Z,W){let K=R(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(y(K,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function zJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let K=Number.parseInt(W[1],10);if(!Number.isInteger(K)||K<=0)return null;let X=W[2]||"m";return K*S[X]}function e(Q){for(let Z of["d","h","m","s"]){let W=S[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return p(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let K=new Date(Q.runAt);if(Number.isNaN(K.getTime()))return null;return K.getTime()>Z.getTime()?K:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(R(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function AJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?e(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as LJ,readFile as PJ}from"node:fs/promises";import a from"node:path";import{nanoid as MJ}from"nanoid";import IJ from"write-file-atomic";var w=$(B(["default","autoEdit","yolo","plan"]));var N=$(B(["user","assistant","system","tool"])),JJ=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),d=J.Union([J.String(),J.Array(JJ)]),xJ=$(J.Object({id:J.String(),role:N,content:d,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),QJ=$(B(["queued","running","completed","failed","cancelled","interrupted"])),F=$(B(["local","worktree"])),q=$(B(["high","medium","low"])),x=$(B(["feature","bug","maintenance","research"])),ZJ=$(B(["applied","discarded","conflicted"])),$J=$(J.Object({status:ZJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),BJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),KJ=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),fJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array(KJ,{maxItems:100}),truncated:J.Boolean()})),WJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),XJ=$(J.Object({name:J.String(),type:B(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(WJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(B(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),CJ=$(J.Object({serverName:J.String(),mode:B(["form","url"]),message:J.String(),fields:J.Optional(J.Array(XJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),YJ=$(J.Object({type:B(["permission","question","elicitation"]),requestId:J.String()})),HJ=$(J.Object({code:B(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean(),resource:J.Optional(B(["pending_count","pending_bytes","resident_runtimes"]))})),L=$(B(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(B(["auto","standard","fast","flex"])),M=$(B(["auto","low","medium","high"])),b=$(J.Union([B(["auto","pragmatic","friendly","explanatory"]),J.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})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(B(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:U(QJ,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(HJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional($J),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(BJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(YJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),EJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),RJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),SJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),lJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:B(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:B(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),m=$(J.Object({role:N,content:d,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),hJ=$(J.Object({session:z,messages:J.Array(m)})),c=$(B(["conversation","code","both"])),jJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),uJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:U(c,"conversation")})),dJ=$(J.Object({checkpoint:jJ,mode:c,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(m)})),UJ=B(["running","completed","failed","cancelled"]),l=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:UJ,background:J.Boolean(),rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:B(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(B(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),mJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),cJ=$(J.Object({source:l,session:l})),gJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),nJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),oJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),sJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),g=J.Object({type:B(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:h})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),n=J.Record(J.String(),J.Unknown()),iJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:U(q,"medium"),taskKind:U(x,"feature"),taskDueAt:J.Optional(J.String({minLength:1,maxLength:64})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.Union([J.String({minLength:1,maxLength:64}),J.Null()]))})),tJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:B(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),rJ=$(J.Object({action:B(["apply","discard"])})),f=$(J.Object({kind:B(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),kJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default")})),C=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,dispatch:kJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(B(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),TJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),enabled:U(J.Boolean(),!0)})),yJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(f),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),pJ=$(J.Object({schedules:J.Array(C)})),eJ=$(J.Object({content:J.String({maxLength:u}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),VJ=B(["completed","failed","aborted","timed_out","spawn_error"]),GJ=$(J.Object({version:J.Literal(1),command:J.String(),status:VJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),JQ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),QQ=$(J.Object({executionId:J.String(),messageId:J.String(),record:GJ,auxiliary:J.Boolean(),delivery:J.Optional(B(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),ZQ=$(J.Object({projectPath:J.String(),kind:B(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),$Q=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),BQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),KQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(B(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:B(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),OJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:B(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),WQ=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(B(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(B(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(B(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(OJ,{maxItems:36})),input:J.Optional(J.Array(B(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),XQ=$(B(["vs-dark","vs-light","hc-black"])),bJ=$(B(["light","dark","system"])),wJ=$(J.Object({language:J.String(),codeTheme:J.String(),uiTheme:bJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),YQ=$(J.Partial(wJ));var o=i("Service"),DJ=1;function FJ(){return a.join(s(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=FJ()){this.filePath=Q}async readFile(){try{let Q=await PJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],K=0;for(let X of Z.schedules){let Y=C.safeParse(X);if(Y.success)W.push(Y.data);else K+=1}if(K>0)o.warn(`[ScheduleStore] Ignored ${K} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")o.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await LJ(a.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:DJ,schedules:Q};await IJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let K=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=K.getTime())throw Error("once trigger runAt must be in the future");let X=K.toISOString(),Y=A(Z,K),V={id:MJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},G=await this.readFile();return G.push(V),await this.writeFile(G),V})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),K=W.findIndex((H)=>H.id===Q);if(K===-1)return;let X=W[K];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,k=_(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");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},V=!X.enabled,G=Y.enabled,j=Z.trigger!==void 0;if((j||V&&G)&&Z.nextRunAt===void 0){let H=new Date,k=A(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return W[K]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((K)=>K.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var IQ=I.getInstance();
1
+ import{mg as J,ng as $,og as U,pg as B}from"./chunk-v0rsz1rt.js";import{qg as v,rg as h,sg as u}from"./chunk-xz6y0w4n.js";import{Xg as i}from"./chunk-t2wgf9tq.js";import{Bh as s}from"./chunk-9q852bsc.js";var O=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],r={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D(Q,Z,W){let K=new Set;for(let X of Q.split(",")){let[Y,V]=X.split("/"),G=V?Number.parseInt(V,10):1;if(!Number.isInteger(G)||G<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,t]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(t,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let k=j;k<=H;k+=G)K.add(k)}return K}function R(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,K,X,Y,V]=Z,G=D(V,O[4].min,O[4].max),j=new Set([...G].map((H)=>H===7?0:H));return{minutes:D(W,O[0].min,O[0].max),hours:D(K,O[1].min,O[1].max),daysOfMonth:D(X,O[2].min,O[2].max),months:D(Y,O[3].min,O[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:V.trim()!=="*"}}function T(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=E.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(Z,W);let K=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(K.minute),hour:Number(K.hour),dayOfMonth:Number(K.day),month:Number(K.month),dayOfWeek:r[K.weekday]??-1}}function y(Q,Z,W){let K=T(Z,W);if(!Q.minutes.has(K.minute))return!1;if(!Q.hours.has(K.hour))return!1;if(!Q.months.has(K.month))return!1;let X=Q.daysOfMonth.has(K.dayOfMonth),Y=Q.daysOfWeek.has(K.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function p(Q,Z,W){let K=R(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(y(K,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function zJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let K=Number.parseInt(W[1],10);if(!Number.isInteger(K)||K<=0)return null;let X=W[2]||"m";return K*S[X]}function e(Q){for(let Z of["d","h","m","s"]){let W=S[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return p(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let K=new Date(Q.runAt);if(Number.isNaN(K.getTime()))return null;return K.getTime()>Z.getTime()?K:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(R(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function AJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?e(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as LJ,readFile as PJ}from"node:fs/promises";import a from"node:path";import{nanoid as MJ}from"nanoid";import IJ from"write-file-atomic";var w=$(B(["default","autoEdit","yolo","plan"]));var N=$(B(["user","assistant","system","tool"])),JJ=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),d=J.Union([J.String(),J.Array(JJ)]),xJ=$(J.Object({id:J.String(),role:N,content:d,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),QJ=$(B(["queued","running","completed","failed","cancelled","interrupted"])),F=$(B(["local","worktree"])),q=$(B(["high","medium","low"])),x=$(B(["feature","bug","maintenance","research"])),ZJ=$(B(["applied","discarded","conflicted"])),$J=$(J.Object({status:ZJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),BJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),KJ=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),fJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array(KJ,{maxItems:100}),truncated:J.Boolean()})),WJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),XJ=$(J.Object({name:J.String(),type:B(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(WJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(B(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),CJ=$(J.Object({serverName:J.String(),mode:B(["form","url"]),message:J.String(),fields:J.Optional(J.Array(XJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),YJ=$(J.Object({type:B(["permission","question","elicitation"]),requestId:J.String()})),HJ=$(J.Object({code:B(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean(),resource:J.Optional(B(["pending_count","pending_bytes","resident_runtimes"]))})),L=$(B(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(B(["auto","standard","fast","flex"])),M=$(B(["auto","low","medium","high"])),b=$(J.Union([B(["auto","pragmatic","friendly","explanatory"]),J.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})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(B(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:U(QJ,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(HJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional($J),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(BJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(YJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),EJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),RJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),SJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),lJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:B(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:B(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),m=$(J.Object({role:N,content:d,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),hJ=$(J.Object({session:z,messages:J.Array(m)})),c=$(B(["conversation","code","both"])),jJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),uJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:U(c,"conversation")})),dJ=$(J.Object({checkpoint:jJ,mode:c,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(m)})),UJ=B(["running","completed","failed","cancelled"]),l=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:UJ,background:J.Boolean(),rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:B(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(B(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),mJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),cJ=$(J.Object({source:l,session:l})),gJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),nJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),oJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),sJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),g=J.Object({type:B(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:h})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),n=J.Record(J.String(),J.Unknown()),iJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:U(q,"medium"),taskKind:U(x,"feature"),taskDueAt:J.Optional(J.String({minLength:1,maxLength:64})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),taskPriority:J.Optional(q),taskKind:J.Optional(x),taskDueAt:J.Optional(J.Union([J.String({minLength:1,maxLength:64}),J.Null()]))})),tJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:B(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),rJ=$(J.Object({action:B(["apply","discard"])})),f=$(J.Object({kind:B(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),kJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default")})),C=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,dispatch:kJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(B(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),TJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:f,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:U(F,"worktree"),permissionMode:U(w,"default"),enabled:U(J.Boolean(),!0)})),yJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(f),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),pJ=$(J.Object({schedules:J.Array(C)})),eJ=$(J.Object({content:J.String({maxLength:u}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(g,{maxItems:v})),outputSchema:J.Optional(n)})),VJ=B(["completed","failed","aborted","timed_out","spawn_error"]),GJ=$(J.Object({version:J.Literal(1),command:J.String(),status:VJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),JQ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),QQ=$(J.Object({executionId:J.String(),messageId:J.String(),record:GJ,auxiliary:J.Boolean(),delivery:J.Optional(B(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),ZQ=$(J.Object({projectPath:J.String(),kind:B(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),$Q=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),BQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),KQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(B(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:B(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),OJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:B(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),WQ=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(B(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(B(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(B(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(OJ,{maxItems:36})),input:J.Optional(J.Array(B(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),XQ=$(B(["vs-dark","vs-light","hc-black"])),bJ=$(B(["light","dark","system"])),wJ=$(J.Object({language:J.String(),codeTheme:J.String(),uiTheme:bJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),YQ=$(J.Partial(wJ));var o=i("Service"),DJ=1;function FJ(){return a.join(s(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=FJ()){this.filePath=Q}async readFile(){try{let Q=await PJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],K=0;for(let X of Z.schedules){let Y=C.safeParse(X);if(Y.success)W.push(Y.data);else K+=1}if(K>0)o.warn(`[ScheduleStore] Ignored ${K} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")o.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await LJ(a.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:DJ,schedules:Q};await IJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let K=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=K.getTime())throw Error("once trigger runAt must be in the future");let X=K.toISOString(),Y=A(Z,K),V={id:MJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},G=await this.readFile();return G.push(V),await this.writeFile(G),V})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),K=W.findIndex((H)=>H.id===Q);if(K===-1)return;let X=W[K];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,k=_(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");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},V=!X.enabled,G=Y.enabled,j=Z.trigger!==void 0;if((j||V&&G)&&Z.nextRunAt===void 0){let H=new Date,k=A(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return W[K]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((K)=>K.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var IQ=I.getInstance();
2
2
  export{zJ as xa,A as ya,_ as za,AJ as Aa,fJ as Ba,z as Ca,uJ as Da,mJ as Ea,iJ as Fa,aJ as Ga,tJ as Ha,rJ as Ia,C as Ja,TJ as Ka,yJ as La,pJ as Ma,eJ as Na,JQ as Oa,ZQ as Pa,I as Qa,IQ as Ra};
@@ -1,4 +1,4 @@
1
- import{j as X4,k as V4}from"./chunk-ypgjqg23.js";import{l as nO}from"./chunk-b2p4kd07.js";import{s as JO,t as g1}from"./chunk-smjkx71w.js";import{u as a0}from"./chunk-w2gr97qt.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as OO}from"./chunk-d2vrbbvd.js";import{$ as e1,C as w4,F as R1,G as XO,H as A$,I as cO,J as W$,K as E0,L as F$,M as f0,N as jO,Q as kO,R as IO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-0kmrvxsz.js";import{qa as Q1,wa as U0}from"./chunk-83b4vfjs.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-wepvrnmh.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-wkpacysr.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as ZO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as iO,pc as EO,qc as D$,rc as qO,tc as j1,zc as T1}from"./chunk-1z9k5dmz.js";import{Ld as x0,Pd as G1,Wd as L0}from"./chunk-p9vaaayr.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as lO}from"./chunk-832va1mp.js";import{Be as wO,Ce as MO,Ge as d4,Je as T0,Ke as AO,Ne as l4,ue as D4,xe as a1}from"./chunk-wahhwjp9.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as xO,_e as O1}from"./chunk-qm5c9wew.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as LO,rf as J1}from"./chunk-b39p4f5r.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as y,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as aO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-d808m826.js";import{bh as c0}from"./chunk-0p0e70cy.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as $O}from"./chunk-y9d9nqnn.js";import{qh as E$}from"./chunk-wj6t3tv2.js";import{vh as uO,zh as n$}from"./chunk-8wea3qty.js";import{Ch as C$}from"./chunk-k6shq7rk.js";var a5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as fO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var e0=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;e0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,e0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){e0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),e0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),e0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let G=Q instanceof Error?Q.message:String(Q);e0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Q0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends Q0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Q0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Q0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Q0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Q0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Q0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Q0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=x0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=y(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:G}=J.data;return await L0().updateConfig(Q,G),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=x0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
1
+ import{j as X4,k as V4}from"./chunk-9hchc346.js";import{l as nO}from"./chunk-rm9hbew3.js";import{s as JO,t as g1}from"./chunk-s77sbxr7.js";import{u as a0}from"./chunk-ahg9vjb6.js";import{A as a$,v as S1,w as l$,x as c$,y as i$,z as OO}from"./chunk-byqxaa9v.js";import{$ as e1,C as w4,F as R1,G as XO,H as A$,I as cO,J as W$,K as E0,L as F$,M as f0,N as jO,Q as kO,R as IO,T as q1,U as k1,V as I1,W as o1,X as n1,Y as t1,Z as s1,_ as r1,aa as O4,ba as $4,ca as x4,fa as G4,ia as y4,na as M4}from"./chunk-d3ttqmyt.js";import{qa as Q1,wa as U0}from"./chunk-qgrq04hb.js";import{Ba as j4,Ca as j$,Da as P1,Ea as f1,Fa as T4,Ga as C4,Ha as T$,Ia as b4,Ja as t0,Ka as K4,La as W4,Ma as F4,Na as y1,Oa as m1,Pa as h1,Qa as u$,Ra as q$,ya as x$}from"./chunk-92x15fzx.js";import{ab as m0,bb as g,db as R,eb as E1,pb as K$,yb as o0}from"./chunk-nx31fkkf.js";import{Hb as M1}from"./chunk-th4jjfgm.js";import{Ac as C1,Cc as ZO,Fc as X$,Kc as b1,Lc as V$,Mc as N$,Nc as E,_b as A1,jc as iO,pc as EO,qc as D$,rc as qO,tc as j1,zc as T1}from"./chunk-97aywyzn.js";import{Ld as x0,Pd as G1,Wd as L0}from"./chunk-1je1xw6v.js";import{Xd as G$}from"./chunk-0j22w4wh.js";import{je as L1}from"./chunk-yn51162x.js";import{le as lO}from"./chunk-fcv8b6ny.js";import{Be as wO,Ce as MO,Ge as d4,Je as T0,Ke as AO,Ne as l4,ue as D4,xe as a1}from"./chunk-axtzde5k.js";import{Ve as X1,We as w1}from"./chunk-cdy9efgm.js";import{$e as xO,_e as O1}from"./chunk-4ke8k0xw.js";import{Lf as D1,Of as H1,Qf as B1,bg as $1,gg as LO,rf as J1}from"./chunk-82htkvz8.js";import{jg as z$}from"./chunk-h0ft81a3.js";import{kg as y,mg as U,pg as F0}from"./chunk-v0rsz1rt.js";import{rg as aO}from"./chunk-xz6y0w4n.js";import{wg as c}from"./chunk-k0pa8874.js";import{Xg as a}from"./chunk-t2wgf9tq.js";import{bh as c0}from"./chunk-2px6hzdc.js";import{dh as Y1,eh as U1,gh as z1,hh as _1}from"./chunk-t8xmh4w2.js";import{jh as $O}from"./chunk-azw0jckv.js";import{qh as E$}from"./chunk-jzntxp7f.js";import{Ah as n$,wh as uO}from"./chunk-9q852bsc.js";import{Dh as C$}from"./chunk-wfy851et.js";var a5={port:{type:"number",describe:"Port to listen on (0 for auto)",default:0},hostname:{type:"string",describe:"Hostname to listen on",default:"127.0.0.1"},cors:{type:"array",describe:"Additional domains to allow for CORS",default:[]}};function o5(O){return{port:O.port??0,hostname:O.hostname??"127.0.0.1",cors:O.cors??[]}}import{existsSync as k$,readFileSync as fO}from"node:fs";import{createServer as j5}from"node:http";import{networkInterfaces as T5}from"node:os";import{dirname as C5,extname as b5,join as u0}from"node:path";import{fileURLToPath as R5}from"node:url";import{brotliCompressSync as E5,gzipSync as q5,constants as k5}from"node:zlib";import{Hono as I5}from"hono";import{cors as S5}from"hono/cors";import{WebSocketServer as P5}from"ws";var e0=a("Service"),a4=30000,o4=new Set(["completed","failed","cancelled","interrupted"]);class J${dispatch;store;tickMs;timer;unsubscribeBus;ticking=!1;inFlight=new Set;constructor(O){this.dispatch=O.dispatch,this.store=O.store??u$.getInstance(),this.tickMs=O.tickMs??a4}start(){if(this.timer)return;e0.info("[TaskScheduler] Starting scheduler tick loop"),this.timer=setInterval(()=>{this.tick()},this.tickMs),this.timer.unref?.(),this.unsubscribeBus=R.subscribe((O)=>{if(O.type!=="task.status")return;let $=O.properties.taskStatus;if(typeof $!=="string"||!o4.has($))return;this.recordTerminalStatus(O.sessionId,$,typeof O.properties.taskStatusReason==="string"?O.properties.taskStatusReason:void 0)}),this.tick()}stop(){if(this.timer)clearInterval(this.timer),this.timer=void 0,this.unsubscribeBus?.(),this.unsubscribeBus=void 0,e0.info("[TaskScheduler] Stopped scheduler tick loop")}async tick(O=new Date){if(this.ticking)return;this.ticking=!0;try{let $=await this.store.list();for(let x of $)await this.evaluate(x,O)}catch($){e0.warn("[TaskScheduler] Tick failed:",$)}finally{this.ticking=!1}}async evaluate(O,$){if(!O.enabled)return;if(this.inFlight.has(O.id))return;if(O.expiresAt&&new Date(O.expiresAt).getTime()<=$.getTime()){await this.store.update(O.id,{enabled:!1,nextRunAt:null}),e0.info(`[TaskScheduler] Schedule ${O.id} expired; disabled`);return}if(!O.nextRunAt)return;if(!(new Date(O.nextRunAt).getTime()<=$.getTime()))return;await this.fire(O,$)}async fire(O,$=new Date,x={}){if(this.inFlight.has(O.id))throw Error(`Schedule ${O.id} is already dispatching`);this.inFlight.add(O.id);let J=$.toISOString();try{let Q=await this.dispatch({prompt:O.prompt,title:O.title??n4(O),sourceProjectPath:O.projectPath,isolation:O.dispatch.isolation??"worktree",permissionMode:O.dispatch.permissionMode??"default",modelId:O.dispatch.modelId,reasoningEffort:O.dispatch.reasoningEffort,serviceTier:O.dispatch.serviceTier,responseVerbosity:O.dispatch.responseVerbosity,communicationStyle:O.dispatch.communicationStyle}),G=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastRunSessionId:Q.session.sessionId,lastStatus:Q.status,lastError:void 0,runCount:O.runCount+1,nextRunAt:G?G.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled}),R.publish({sessionId:Q.session.sessionId,projectPath:O.projectPath},"schedule.fired",{scheduleId:O.id,firedAt:J,sessionId:Q.session.sessionId,runId:Q.runId,status:Q.status}),e0.info(`[TaskScheduler] Fired schedule ${O.id} -> session ${Q.session.sessionId} (${Q.status})`)}catch(Q){let G=Q instanceof Error?Q.message:String(Q);e0.warn(`[TaskScheduler] Schedule ${O.id} dispatch failed:`,Q);let z=O.trigger.kind==="once"?null:x.manual?O.nextRunAt?new Date(O.nextRunAt):null:x$(O.trigger,$,$);await this.store.update(O.id,{lastRunAt:J,lastStatus:"error",lastError:G,nextRunAt:z?z.toISOString():null,enabled:O.trigger.kind==="once"?!1:O.enabled})}finally{this.inFlight.delete(O.id)}}async recordTerminalStatus(O,$,x){let Q=(await this.store.list()).find((G)=>G.lastRunSessionId===O);if(!Q)return;await this.store.update(Q.id,{lastStatus:$,...x?{lastError:x}:{lastError:void 0}})}}function n4(O){return`Scheduled: ${O.prompt.trim().replace(/\s+/g," ").slice(0,60)}`}class Q0 extends Error{code;statusCode;details;constructor(O,$,x=500,J){super($);this.code=O;this.statusCode=x;this.details=J;this.name="BladeServerError"}toObject(){return{error:{code:this.code,message:this.message,...this.details?{details:this.details}:{}}}}}class f extends Q0{constructor(O,$){super("NOT_FOUND",$?`${O} not found: ${$}`:`${O} not found`,404)}}class H extends Q0{constructor(O){super("BAD_REQUEST",O,400)}}class q extends Q0{constructor(O){super("CONFLICT",O,409)}}class k0 extends Q0{constructor(O,$){super("TOO_MANY_REQUESTS",O,429,$)}}class l0 extends Q0{constructor(O="Server is shutting down"){super("SERVICE_UNAVAILABLE",O,503)}}class B0 extends Q0{constructor(){super("AMBIGUOUS_SESSION","Multiple workspaces contain this session ID; projectPath is required",409)}}class r extends Q0{constructor(O="Internal server error"){super("INTERNAL_ERROR",O,500)}}var x3=U.Object({error:U.Object({code:U.String(),message:U.String(),details:U.Optional(U.Record(U.String(),U.Unknown()))})});import{Hono as t4}from"hono";var Q$=a("Service"),s4=U.Object({updates:U.Record(U.String(),U.Any()),options:U.Optional(U.Object({scope:U.Optional(F0(["local","project","global"])),immediate:U.Optional(U.Boolean())}))});function r4(O){return{currentModelId:O.currentModelId,permissionMode:O.permissionMode,language:O.language,codeTheme:O.codeTheme,uiTheme:O.uiTheme,autoSaveSessions:O.autoSaveSessions,notifyBuild:O.notifyBuild,notifyErrors:O.notifyErrors,notifySounds:O.notifySounds,privacyTelemetry:O.privacyTelemetry,privacyCrash:O.privacyCrash,communicationStyle:O.communicationStyle,maxConcurrentTasks:O.maxConcurrentTasks,maxQueuedTasks:O.maxQueuedTasks,maxQueuedTaskBytes:O.maxQueuedTaskBytes,maxResidentSessionRuntimes:O.maxResidentSessionRuntimes,sessionRuntimeIdleMs:O.sessionRuntimeIdleMs}}var p$=()=>{let O=new t4;return O.get("/",async($)=>{try{let x=x0();return $.json(x?r4(x):{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get config:",x),$.json({})}}),O.put("/",async($)=>{try{let x=await $.req.json(),J=y(s4,x);if(!J.success)throw new H("Invalid config update format");let{updates:Q,options:G}=J.data;return await L0().updateConfig(Q,G),$.json({success:!0,updates:Q})}catch(x){throw Q$.error("[ConfigRoutes] Failed to update config:",x),x}}),O.get("/permissions",async($)=>{try{let x=x0();return $.json(x?.permissions||{})}catch(x){return Q$.error("[ConfigRoutes] Failed to get permissions:",x),$.json({})}}),O};import{Hono as e4}from"hono";import{streamSSE as O2}from"hono/streaming";function d$(O){let $="";if(O.id!==void 0)$+=`id: ${O.id}
2
2
  `;if(O.event!==void 0)$+=`event: ${O.event}
3
3
  `;for(let x of O.data.split(/\r\n|\r|\n/))$+=`data: ${x}
4
4
  `;if(O.retry!==void 0)$+=`retry: ${O.retry}
@@ -1,4 +1,4 @@
1
- import{$c as F$,Sc as u,Tc as I1,Uc as O$,Vc as v1,Wc as I,Xc as N$,Yc as u1,Zc as U$,_c as P1,ad as R$,cd as g0,fd as x$,gd as h1}from"./chunk-f7yfcw8s.js";import{ie as H0}from"./chunk-yn51162x.js";import{Te as K0}from"./chunk-cdy9efgm.js";import{df as V1}from"./chunk-m57w4p91.js";import{qg as j1,rg as m1}from"./chunk-xz6y0w4n.js";import{wg as v$}from"./chunk-k0pa8874.js";import{Xg as D0}from"./chunk-d808m826.js";import{ch as Y0,fh as W0}from"./chunk-t8xmh4w2.js";import{jh as i}from"./chunk-y9d9nqnn.js";import{Ah as G0,sh as k1,th as B0,uh as S1,vh as b,wh as m,yh as V0,zh as p}from"./chunk-8wea3qty.js";import{readdir as H$,readFile as s,rm as q0,stat as y0}from"node:fs/promises";import*as H from"node:path";import{nanoid as j}from"nanoid";import{createHash as e1,randomUUID as $q}from"node:crypto";import*as v from"node:fs/promises";import*as F0 from"node:path";import{execFileSync as d1}from"node:child_process";import{createHash as r1}from"node:crypto";import{readFileSync as o1}from"node:fs";var t1=/^[a-f0-9]{64}$/;function k$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&t1.test(q.fingerprint)}var S$={readFile:($)=>o1($,"utf8"),execFile:($,q)=>d1($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},a1=($)=>{try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}};function l0($,q){return{platform:$,fingerprint:r1("sha256").update(`${$}\x00${q}`).digest("hex")}}function s1($,q){let L=q.readFile(`/proc/${$}/stat`).trim(),f=L.lastIndexOf(")");if(f<0)throw Error("Invalid /proc process stat");let B=L.slice(f+2).split(/\s+/)[19];if(!B||!/^\d+$/.test(B))throw Error("Missing process start ticks");return B}function N0($,q=process.platform,L=S$){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return l0(q,s1($,L));if(q==="darwin"){let f=L.execFile("ps",["-o","lstart=","-p",String($)]).trim();return f?l0(q,f):void 0}if(q==="win32"){let f=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,J=L.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",f]).trim();return J?l0(q,J):void 0}}catch{return}return}function j$($,q){return N0($,q.platform)?.fingerprint===q.fingerprint}function wL($,q,L=S$,f=a1){if(!Number.isInteger($)||$<=1)return!1;let J=N0($,q.platform,L);if(J)return J.fingerprint===q.fingerprint;return!f($)}var u$=1;function qq($,q){let L=e1("sha256").update(q).digest("hex");return F0.join(B0($),".locks",`${L}.lock`)}function U0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function p0($){try{let q=JSON.parse(await v.readFile($,"utf8"));if(q.version!==u$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!k$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function m$($){let q=await p0($);if(q)return q;return await new Promise((L)=>setTimeout(L,10)),p0($)}function Lq($){try{return process.kill($,0),!0}catch(q){return U0(q,"EPERM")}}async function I$($,q){let L;try{return L=await v.open($,"wx",384),await L.writeFile(`${JSON.stringify(q)}
1
+ import{$c as F$,Sc as u,Tc as I1,Uc as O$,Vc as v1,Wc as I,Xc as N$,Yc as u1,Zc as U$,_c as P1,ad as R$,cd as g0,fd as x$,gd as h1}from"./chunk-mtphps19.js";import{ie as H0}from"./chunk-yn51162x.js";import{Te as K0}from"./chunk-cdy9efgm.js";import{df as V1}from"./chunk-m57w4p91.js";import{qg as j1,rg as m1}from"./chunk-xz6y0w4n.js";import{wg as v$}from"./chunk-k0pa8874.js";import{Xg as D0}from"./chunk-t2wgf9tq.js";import{ch as Y0,fh as W0}from"./chunk-t8xmh4w2.js";import{jh as i}from"./chunk-azw0jckv.js";import{Ah as p,Bh as G0,th as k1,uh as B0,vh as S1,wh as b,xh as m,zh as V0}from"./chunk-9q852bsc.js";import{readdir as H$,readFile as s,rm as q0,stat as y0}from"node:fs/promises";import*as H from"node:path";import{nanoid as j}from"nanoid";import{createHash as e1,randomUUID as $q}from"node:crypto";import*as v from"node:fs/promises";import*as F0 from"node:path";import{execFileSync as d1}from"node:child_process";import{createHash as r1}from"node:crypto";import{readFileSync as o1}from"node:fs";var t1=/^[a-f0-9]{64}$/;function k$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&t1.test(q.fingerprint)}var S$={readFile:($)=>o1($,"utf8"),execFile:($,q)=>d1($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},a1=($)=>{try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}};function l0($,q){return{platform:$,fingerprint:r1("sha256").update(`${$}\x00${q}`).digest("hex")}}function s1($,q){let L=q.readFile(`/proc/${$}/stat`).trim(),f=L.lastIndexOf(")");if(f<0)throw Error("Invalid /proc process stat");let B=L.slice(f+2).split(/\s+/)[19];if(!B||!/^\d+$/.test(B))throw Error("Missing process start ticks");return B}function N0($,q=process.platform,L=S$){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return l0(q,s1($,L));if(q==="darwin"){let f=L.execFile("ps",["-o","lstart=","-p",String($)]).trim();return f?l0(q,f):void 0}if(q==="win32"){let f=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,J=L.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",f]).trim();return J?l0(q,J):void 0}}catch{return}return}function j$($,q){return N0($,q.platform)?.fingerprint===q.fingerprint}function wL($,q,L=S$,f=a1){if(!Number.isInteger($)||$<=1)return!1;let J=N0($,q.platform,L);if(J)return J.fingerprint===q.fingerprint;return!f($)}var u$=1;function qq($,q){let L=e1("sha256").update(q).digest("hex");return F0.join(B0($),".locks",`${L}.lock`)}function U0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function p0($){try{let q=JSON.parse(await v.readFile($,"utf8"));if(q.version!==u$||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!k$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function m$($){let q=await p0($);if(q)return q;return await new Promise((L)=>setTimeout(L,10)),p0($)}function Lq($){try{return process.kill($,0),!0}catch(q){return U0(q,"EPERM")}}async function I$($,q){let L;try{return L=await v.open($,"wx",384),await L.writeFile(`${JSON.stringify(q)}
2
2
  `,"utf8"),!0}catch(f){if(U0(f,"EEXIST"))return!1;if(L)await v.unlink($).catch(()=>{return});throw f}finally{await L?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class c{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=v$()){let L=qq(q,$),f={version:u$,sessionId:$,ownerId:$q(),pid:process.pid,processIdentity:N0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(F0.dirname(L),{recursive:!0,mode:448}),await I$(L,f))return new c(L,f);let J=await m$(L);if(J&&Lq(J.pid)&&(!J.processIdentity||j$(J.pid,J.processIdentity)))throw new h(J.pid);if(await v.unlink(L).catch((B)=>{if(!U0(B,"ENOENT"))throw B}),await I$(L,f))return new c(L,f);throw new h((await m$(L))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await p0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((q)=>{if(!U0(q,"ENOENT"))throw q})}}var mL=1;function i0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function fq($){if(!i0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&i0($.image_url)&&typeof $.image_url.url==="string"}function Bq($){if(!i0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(fq)}function P$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let L=JSON.parse(q);if(!Array.isArray(L)||!L.every(Bq))return;return L}function IL($){let q=P$($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function R0($){return P$($)}function Jq($,q){for(let L of $){if(L.type!=="part_created"||L.data.partType!=="tool_result")continue;let f=L.data.payload;if(!f||typeof f!=="object"||Array.isArray(f))continue;let J=f;if(J.toolCallId===q||L.data.partId===q||L.data.messageId===q)return J}return}function h$($){let q=u($),L=new Map;for(let f of q){if(f.type==="interaction_requested"){L.set(f.data.requestId,{request:f.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(f.type==="interaction_responded"){let J=L.get(f.data.requestId);if(J)J.response=f.data;continue}if(f.type==="interaction_recovered"){let J=L.get(f.data.requestId);if(J)J.recovery=f.data}}for(let f of L.values()){let J=Jq(q,f.request.toolCallId);f.hasToolResult=J!==void 0;let B=J?.metadata&&typeof J.metadata==="object"?J.metadata:void 0;f.hasRecoveryToolResult=B?.interactionRecovery===!0&&B.requestId===f.request.requestId}return[...L.values()]}function c$($){return h$($).reverse().find((q)=>!q.response&&!q.recovery)}function PL($){let q=new Map;for(let L of h$($))q.set(L.request.toolCallId,L);return[...q.values()].filter((L)=>L.response&&!L.recovery&&(!L.hasToolResult||L.hasRecoveryToolResult))}function n$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function x0($){let q=new Map,L=[];for(let f of $){if(f.type==="review_started"){if(!q.has(f.data.reviewId))L.push(f.data.reviewId),q.set(f.data.reviewId,{start:f.data});continue}if(f.type!=="review_completed")continue;let J=q.get(f.data.reviewId);if(J&&J.completion===void 0)J.completion=f.data}return L.map((f)=>q.get(f)).filter((f)=>f!==void 0)}function cL($){return x0($).reverse().find((q)=>q.completion===void 0)}function d0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function l$($,q){let L=["## Code Review","",`Target: ${$.target.label}`,`Status: ${d0(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)L.push("","No actionable findings.");else{L.push("","### Findings");for(let[f,J]of q.findings.entries()){let B=J.codeLocation.lineStart===J.codeLocation.lineEnd?`${J.codeLocation.lineStart}`:`${J.codeLocation.lineStart}-${J.codeLocation.lineEnd}`;L.push("",`${f+1}. ${J.title}`,` ${J.codeLocation.path}:L${B} · confidence ${J.confidenceScore.toFixed(2)}`,` ${J.body}`)}}if(q.error)L.push("",`Error: ${q.error}`);return L.join(`
3
3
  `)}function p$($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((L)=>({title:L.title,body:L.body,priority:L.priority,confidenceScore:L.confidenceScore,codeLocation:{...L.codeLocation}})),...q.error?{error:q.error}:{}}}var a0=1;var r0=2000,Zq='<token-budget-handoff version="1">',pL="handoff-message-",Cq=128,Gq=["version","messageId","observedPromptTokens","availableForInput","handoffThreshold","compactionThreshold","createdAt"],Qq=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,Vq=/(?:^|\n)Remaining prompt-token headroom before compaction: (\d+)\.$/;function n($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function s0($){return n($)&&$>0}function Xq($){for(let q=0;q<$.length;q+=1){let L=$.charCodeAt(q);if(L<=31||L===127)return!0}return!1}function i$($){return typeof $==="string"&&$.length>=1&&$.length<=Cq&&!Xq($)}function o0($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let q=Object.getPrototypeOf($);return q===Object.prototype||q===null}function T0($,q){let L=Math.floor($/10),f=$%10;return L*q+Math.floor(f*q/10)}function Yq($){if(typeof $!=="string"||!Qq.test($))return!1;try{let q=new Date($);return Number.isFinite(q.getTime())&&q.toISOString()===$}catch{return!1}}function d$($){if(!n($))throw Error("Token budget handoff headroom must be a safe nonnegative integer");return[Zq,"Context rollover is approaching. Continue the user task from this state only.","Make objective, decisions, mutations, verification, background work, blockers, and the exact next action explicit.","For pending work, preserve exact commands, tool arguments, and required final-response constraints when they are known.","Do not claim success or completion unless it is already proven in the transcript.","Do not create bookkeeping files the user did not request.",`Remaining prompt-token headroom before compaction: ${$}.`].join(`
4
4
  `)}function Wq($){let q=d$($);if(new TextEncoder().encode(q).length>r0)throw Error(`Token budget handoff reminder exceeds ${r0} bytes`);return q}function t0($,q){let L=Object.keys($).sort(),f=[...q].sort();return L.length===f.length&&L.every((J,B)=>J===f[B])}function iL($){let{maxContextTokens:q,maxOutputTokens:L,configuredMaxOutputTokens:f}=$,J=L??f??void 0;if(J!==void 0)return J;if(!s0(q))return;return Math.min(Math.max(Math.floor(q*0.1),8192),32768)}function dL($){let{actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f}=$;if(!s0(L)||!n(f)||f>=L)return{phase:"unknown"};let J=L-f;if(J<=0)return{phase:"unknown"};let B=T0(J,7),Z=T0(J,8);if(!n(q))return{phase:"unknown",maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z};if(q<B)return{phase:"below_handoff",actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z};if(q<Z)return{phase:"handoff_band",actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z};return{phase:"compaction_due",actualPromptTokens:q,maxContextTokens:L,maxOutputTokens:f,availableForInput:J,handoffThreshold:B,compactionThreshold:Z}}function r$($){if($.type!=="token_budget_handoff_recorded"||!o0($.data))return;let q=$.data;if(!t0(q,Gq)||q.version!==a0||!i$(q.messageId)||!n(q.observedPromptTokens)||!s0(q.availableForInput)||!n(q.handoffThreshold)||!n(q.compactionThreshold)||!Yq(q.createdAt))return;let L=T0(q.availableForInput,7),f=T0(q.availableForInput,8);if(q.handoffThreshold!==L||q.compactionThreshold!==f||q.observedPromptTokens<q.handoffThreshold||q.observedPromptTokens>=q.compactionThreshold)return;return $}function Hq($){return $.type==="token_budget_handoff_recorded"}function o$($){let q=$.findLastIndex((B)=>{if(B.type!=="part_created"||B.data.partType!=="summary")return!1;let Z=B.data.payload;return Z!==null&&typeof Z==="object"&&!Array.isArray(Z)&&R0(Z.replacementMessages)!==void 0}),L=$.slice(q+1).filter(Hq);if(L.length===0)return{kind:"none"};let f=L.at(-1);if(!f)return{kind:"none"};if(L.length!==1)return{kind:"suppressed",recordId:f.id};let J=r$(f);return J?{kind:"valid",event:J}:{kind:"suppressed",recordId:f.id}}function t$($){let q=r$($);if(!q)return;let L={clientVisible:!1,tokenBudgetHandoff:{version:a0,messageId:q.data.messageId}};return{id:q.data.messageId,role:"user",content:Wq(Math.max(0,q.data.compactionThreshold-q.data.observedPromptTokens)),metadata:L}}function Kq($){if(typeof $.id!=="string"||$.role!=="user"||typeof $.content!=="string"||!o0($.metadata)||$.metadata.clientVisible!==!1)return!1;let q=$.metadata;if(!t0(q,["clientVisible","tokenBudgetHandoff"]))return!1;let L=q.tokenBudgetHandoff;if(!o0(L))return!1;if(!t0(L,["messageId","version"]))return!1;if(L.version!==a0||!i$(L.messageId)||L.messageId!==$.id)return!1;if(new TextEncoder().encode($.content).length>r0)return!1;let J=Vq.exec($.content);if(!J)return!1;let B=Number(J[1]);return n(B)&&$.content===d$(B)}function rL($){return $.filter((q)=>!Kq(q))}var e0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},capacity:{message:"Task admission capacity is full. Retry after running tasks complete.",retryable:!0},runtime:{message:"Agent execution failed.",retryable:!0}};function _q($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function Oq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";if(/\btask admission\b.*\b(capacity|queue)\b/.test(q))return"capacity";return"runtime"}function Nq($){try{if(!$||typeof $!=="object"||!("name"in $)||$.name!=="TaskAdmissionQueueFullError"&&$.name!=="SessionRuntimeCapacityError"||!("resource"in $))return;return $.resource==="pending_count"||$.resource==="pending_bytes"||$.resource==="resident_runtimes"?$.resource:void 0}catch{return}}function a$($){return{code:$,...e0[$]}}function $$($){let q=Nq($);if(q)return{...a$("capacity"),resource:q};return a$(Oq(_q($)))}function q$($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in e0))return!1;let L=e0[q.code],f=q.resource===void 0||q.resource==="pending_count"||q.resource==="pending_bytes"||q.resource==="resident_runtimes";return q.message===L.message&&q.retryable===L.retryable&&f&&(q.code==="capacity"||q.resource===void 0)}import{promises as J0,realpathSync as Fq}from"node:fs";import z0 from"node:path";import*as o from"fs/promises";import*as x from"path";var s$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class r extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class L${static normalize($,q){let L=x.isAbsolute($)?$:x.resolve(q,$),f=x.normalize(L),J=x.normalize(q);if(!this.isWithinWorkspace(f,J))throw new r(`Path outside workspace: ${$} (resolved to ${f}, workspace: ${J})`,"PATH_OUTSIDE_WORKSPACE");return f}static checkRestricted($){let q=$.split(x.sep);for(let L of s$)if(q.includes(L))throw new r(`Access denied: "${L}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new r(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let L=this.normalize($,q);this.checkRestricted(L);try{await o.access(L)}catch(f){throw new r(`Path not found: ${$}`,"PATH_NOT_FOUND")}return L}static async resolveSymlink($,q){try{let L=await o.realpath($),f=await o.realpath(q);if(!this.isWithinWorkspace(L,f))throw new r(`Symlink points outside workspace: ${$} -> ${L}`,"SYMLINK_OUTSIDE_WORKSPACE");return L}catch(L){if(L instanceof r)throw L;return $}}static getRelativePath($,q){return x.relative(q,$)}static isWithinWorkspace($,q){let L=x.resolve($),f=x.resolve(q),J=x.relative(f,L);return J===""||J!==".."&&!J.startsWith(`..${x.sep}`)&&!x.isAbsolute(J)}static async isWithinWorkspaceResolved($,q){let L=x.resolve(q),f=x.isAbsolute($)?x.resolve($):x.resolve(L,$);if(!this.isWithinWorkspace(f,L))return!1;let J;try{J=await o.realpath(L)}catch{return!1}let B=f;while(!0){try{let C=await o.realpath(B);return this.isWithinWorkspace(C,J)}catch(C){let Q=C.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")return!1}let Z=x.dirname(B);if(Z===B)return!1;B=Z}}static isRestricted($){let q=$.split(x.sep);return s$.some((L)=>q.includes(L))}}var Z0=D0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,q){try{let L=await J0.stat($),f={filePath:z0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(f),await this.recordAliases($,f.filePath),Z0.debug(`记录文件读取: ${$}`)}catch(L){Z0.warn(`记录文件读取失败: ${$}`,L)}}async recordFileEdit($,q,L="edit"){try{let f=await J0.stat($),J={filePath:z0.resolve($),accessTime:Date.now(),mtime:f.mtimeMs,sessionId:q,lastOperation:L};this.setRecord(J),await this.recordAliases($,J.filePath),Z0.debug(`记录文件${L==="edit"?"编辑":"写入"}: ${$}`)}catch(f){Z0.warn(`记录文件${L==="edit"?"编辑":"写入"}失败: ${$}`,f)}}hasFileBeenRead($,q){let L=this.accessedFiles.get(this.resolveTrackedPath($));if(!L)return!1;return q?L.has(q):L.size>0}async checkFileModification($,q){let L=this.getFileRecord($,q);if(!L)return{modified:!1,message:"文件未被跟踪"};try{let f=await J0.stat($);if(Math.abs(f.mtimeMs-L.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(L.accessTime).toISOString()}, 当前修改时间: ${f.mtime.toISOString()})`};return{modified:!1}}catch(f){let J=f;if(J.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${J.message}`}}}async checkExternalModification($,q){let L=this.getFileRecord($,q);if(!L)return{isExternal:!1,message:"文件未被跟踪"};try{let f=await J0.stat($);if(f.mtimeMs-L.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(L.accessTime).toISOString()} (${L.lastOperation}) 之后被外部程序修改(当前修改时间: ${f.mtime.toISOString()})`};return{isExternal:!1}}catch(f){let J=f;if(J.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return Z0.warn(`检查文件外部修改失败: ${$}`,f),{isExternal:!1,message:`无法检查文件状态: ${J.message}`}}}getFileRecord($,q){let L=this.accessedFiles.get(this.resolveTrackedPath($));if(!L)return;if(q)return L.get(q);return[...L.values()].sort((f,J)=>J.accessTime-f.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let L=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(L),this.removeAliases(L);return}let f=this.accessedFiles.get(L);if(f?.delete(q),f?.size===0)this.accessedFiles.delete(L),this.removeAliases(L)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[L,f]of this.accessedFiles.entries()){if(q&&!L$.isWithinWorkspace(L,q))continue;if(f.delete($),f.size===0)this.accessedFiles.delete(L),this.removeAliases(L)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(z0.resolve($),q);let L=await J0.realpath($).catch(()=>{return});if(L)this.pathAliases.set(L,q)}resolveTrackedPath($){let q=z0.resolve($);if(this.accessedFiles.has(q))return q;let L=this.pathAliases.get(q);if(L)return L;try{let f=Fq.native(q);return this.pathAliases.get(f)??f}catch{return q}}removeAliases($){for(let[q,L]of this.pathAliases)if(L===$)this.pathAliases.delete(q)}}import*as C0 from"node:crypto";import{promises as _}from"node:fs";import*as N from"node:path";import f$ from"write-file-atomic";var e$="missing";class A0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(b($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!N.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?N.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=G0();this.snapshotDir=N.join(q,"file-history",this.sessionId),this.manifestPath=N.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await _.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=G0(),q=await _.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),L=C0.createHash("sha256").update(q).digest("hex").slice(0,24),f=N.join($,"file-history",this.sessionId),J=N.join($,"file-history","workspaces",L,this.sessionId),B=N.join(J,"manifest.json");try{await _.access(B)}catch{await this.migrateLegacySnapshotDir(f,J,q)}this.snapshotDir=J,this.manifestPath=B}async migrateLegacySnapshotDir($,q,L){let f;try{f=JSON.parse(await _.readFile(N.join($,"manifest.json"),"utf8"))}catch{return}if(f.schemaVersion!==1||!Array.isArray(f.snapshots)||!f.snapshots.every((J)=>this.isWithinWorkspace(J.filePath,L)))return;await _.mkdir(N.dirname(q),{recursive:!0,mode:493});try{await _.rename($,q)}catch(J){let B=J.code;if(B!=="ENOENT"&&B!=="EEXIST"&&B!=="ENOTEMPTY")throw J}}isWithinWorkspace($,q){if(!N.isAbsolute($))return!1;let L=N.relative(q,N.resolve($));return L===""||L!==".."&&!L.startsWith(`..${N.sep}`)&&!N.isAbsolute(L)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let L=await this.resolveFileIdentity($),f=!0;try{await _.access(L)}catch{f=!1}let J=this.trackedFileBackups.get(L),B=J?J.version+1:1,Z=this.generateFileHash(L,B),C=this.getSnapshotPath(Z,B),Q=new Date;if(f){let Y=await _.readFile(L);await _.writeFile(C,Y)}let X={backupFileName:Z,version:B,backupTime:Q};return this.trackedFileBackups.set(L,X),this.snapshots.push({messageId:q,backupFileName:Z,timestamp:Q,filePath:L,version:B,existedBefore:f}),await this.cleanupOldSnapshots(L),await this.persistManifest(),X}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let L=await this.resolveFileIdentity($),f=this.snapshots.find((J)=>J.filePath===L&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!f)throw Error(`未找到待完成的快照: ${L}`);f.postEditHash=await this.hashFile(L),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let L=await this.resolveFileIdentity($),f=this.snapshots.find((J)=>J.filePath===L&&J.backupFileName===q.backupFileName&&J.version===q.version);if(!f)return;this.removeSnapshot(f),await _.rm(this.getSnapshotPath(f.backupFileName,f.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((B)=>B.filePath===q&&B.postEditHash!==void 0);if(!L?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==L.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let J=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let B=await _.readFile(J);await _.mkdir(N.dirname(q),{recursive:!0}),await _.writeFile(q,B)}else await _.rm(q,{force:!0});return this.removeSnapshot(L),await _.rm(J,{force:!0}),await this.persistManifest(),L}async restoreSnapshot($,q){let L=await this.resolveFileIdentity($),f=this.snapshots.slice().reverse().find((B)=>B.messageId===q&&B.filePath===L);if(!f)throw Error(`未找到快照: messageId=${q}, filePath=${L}`);let J=this.getSnapshotPath(f.backupFileName,f.version);if(f.existedBefore){let B=await _.readFile(J);await _.mkdir(N.dirname(L),{recursive:!0}),await _.writeFile(L,B)}else await _.rm(L,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((L)=>L.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((L)=>L.filePath),snapshotCount:q.reduce((L,f)=>L+f.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let L=new Map;for(let J of q){let B,Z=!0;try{B=await _.readFile(J.filePath)}catch(Q){if(Q.code!=="ENOENT")throw Q;Z=!1}if((B?C0.createHash("sha256").update(B).digest("hex"):e$)!==J.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${J.filePath}`);if(L.set(J.filePath,{existed:Z,content:B}),J.target.existedBefore)await _.access(this.getSnapshotPath(J.target.backupFileName,J.target.version))}let f=[...this.snapshots];try{for(let B of q)if(B.target.existedBefore){let Z=await _.readFile(this.getSnapshotPath(B.target.backupFileName,B.target.version));await _.mkdir(N.dirname(B.filePath),{recursive:!0}),await f$(B.filePath,Z)}else await _.rm(B.filePath,{force:!0});let J=new Set(q.flatMap((B)=>B.selected));this.snapshots=this.snapshots.filter((B)=>!J.has(B)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...J].map((B)=>_.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return})))}catch(J){this.snapshots=f,this.rebuildTrackedFileBackups();let B=[];for(let[Z,C]of L)try{if(C.existed&&C.content)await f$(Z,C.content);else await _.rm(Z,{force:!0})}catch(Q){B.push(Q)}if(B.length>0)throw AggregateError([J,...B],"快照回退失败且无法完整恢复回退前状态");throw J}return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,B)=>J+B.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),L=new Set(q.flatMap((J)=>J.selected));if(L.size===0)return{files:[],snapshotCount:0};let f=[...this.snapshots];this.snapshots=this.snapshots.filter((J)=>!L.has(J)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(J){throw this.snapshots=f,this.rebuildTrackedFileBackups(),J}return await Promise.all([...L].map((J)=>_.rm(this.getSnapshotPath(J.backupFileName,J.version),{force:!0}).catch(()=>{return}))),{files:q.map((J)=>J.filePath),snapshotCount:L.size}}buildRewindPlan($){let q=new Set($),L=this.snapshots.filter((B)=>B.postEditHash!==void 0),f=L.filter((B)=>q.has(B.messageId));return[...new Set(f.map((B)=>B.filePath))].sort().map((B)=>{let Z=L.filter((Y)=>Y.filePath===B),C=Z.filter((Y)=>q.has(Y.messageId)),Q=Z.indexOf(C[0]),X=Z.slice(Q);if(X.length!==C.length||X.some((Y)=>!q.has(Y.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${B}`);return{filePath:B,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await _.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(L)=>({...L,filePath:await this.resolveFileIdentity(L.filePath),timestamp:new Date(L.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await _.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await f$(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let L=this.snapshots.filter((f)=>f.filePath===$).slice(0,-this.maxSnapshots);for(let f of L)await _.rm(this.getSnapshotPath(f.backupFileName,f.version),{force:!0}),this.removeSnapshot(f)}async cleanup($=0){let q=this.snapshots.slice().sort((f,J)=>J.timestamp.getTime()-f.timestamp.getTime()),L=new Set(q.slice(0,$));for(let f of this.snapshots)if(!L.has(f))await _.rm(this.getSnapshotPath(f.backupFileName,f.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return N.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=N.resolve($),L=[],f=q;while(!0){try{let B=await _.realpath(f);return N.join(B,...L.reverse())}catch(B){let Z=B.code;if(Z!=="ENOENT"&&Z!=="ENOTDIR")throw B}let J=N.dirname(f);if(J===f)return q;L.push(N.basename(f)),f=J}}async hashFile($){try{let q=await _.readFile($);return C0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return e$;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let L=C0.createHash("md5");return L.update(`${$}:${q}`),L.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var Q2=1200,V2=2000,X2=2000,Y2=2000;function q1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function Rq($){if(typeof $==="string"&&$.length>0)return $;if(q1($)&&typeof $.message==="string")return $.message;return}function xq($,q){if($===null||$===void 0)return q??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function L1($){let q=$.error!==null&&$.error!==void 0,L=q?Rq($.error)??"Tool execution failed":void 0,f=q1($.metadata)?$.metadata:void 0;return{success:!q,llmContent:xq($.output,L),...L?{error:{type:"execution_error",message:L}}:{},...f?{metadata:f}:{}}}function J$($,q){if($.length<=q)return $;let L=Math.max(0,q);if(L>0&&L<$.length&&/[\uD800-\uDBFF]/.test($.charAt(L-1)))L-=1;return $.slice(0,L)}function $1($,q){if($.length<=q)return $;let L=Math.max(0,$.length-q);if(L<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(L)))L+=1;return $.slice(L)}function B$($,q){if($.length<=q)return $;if(q<=0)return"";let L=`
@@ -1,2 +1,2 @@
1
- import{bh as o}from"./chunk-0p0e70cy.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
1
+ import{bh as o}from"./chunk-2px6hzdc.js";async function e(){return o().listProviders()}async function i(r){return o().listModels(r)}
2
2
  export{e as j,i as k};
@@ -1,2 +1,2 @@
1
- import{Ch as F}from"./chunk-k6shq7rk.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
2
- export{M as sh,z as th,J as uh,A as vh,N as wh,O as xh,Q as yh,T as zh,E as Ah,U as Bh};
1
+ import{Dh as F}from"./chunk-wfy851et.js";import{execSync as G}from"node:child_process";import*as C from"node:os";import*as v from"node:path";function H(k){return v.resolve(k).replace(/[/\\]/g,"-").replace(/:/g,"_")}function M(k){let q=k.replace(/_/g,":");if(q.startsWith("-"))q="/"+q.slice(1);return q.replace(/-/g,"/")}function z(k){let q=H(k);return v.join(E(),"projects",q)}function J(k){return typeof k==="string"&&k!=="."&&k!==".."&&/^[A-Za-z0-9_-][A-Za-z0-9._-]{0,199}$/.test(k)}function A(k){if(!J(k))throw Error(`Invalid session ID: ${k}`)}function N(k,q){return A(q),v.join(z(k),`${q}.jsonl`)}function O(k,q){return A(q),v.join(z(k),`${q}.inbox.json`)}function Q(k,q){return A(q),v.join(z(k),`${q}.goal.json`)}function T(k){try{return G("git rev-parse --abbrev-ref HEAD",{cwd:k,encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim()||void 0}catch{return}}function E(){return process.env.BLADE_STORAGE_ROOT||v.join(C.homedir(),".blade")}async function U(){let{readdir:k}=await import("node:fs/promises");try{let q=v.join(E(),"projects");return(await k(q,{withFileTypes:!0})).filter((w)=>w.isDirectory()).map((w)=>w.name)}catch{return[]}}
2
+ export{M as th,z as uh,J as vh,A as wh,N as xh,O as yh,Q as zh,T as Ah,E as Bh,U as Ch};
@@ -1,4 +1,4 @@
1
- import{O as P}from"./chunk-0kmrvxsz.js";import{fb as K}from"./chunk-wkpacysr.js";import{$b as s,Nc as B,Xb as G,Yb as N,Zb as S,_b as O}from"./chunk-1z9k5dmz.js";import{Wc as j}from"./chunk-f7yfcw8s.js";import{Xd as q}from"./chunk-0j22w4wh.js";import{pe as v}from"./chunk-wahhwjp9.js";import{wh as z}from"./chunk-8wea3qty.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
1
+ import{O as P}from"./chunk-d3ttqmyt.js";import{fb as K}from"./chunk-nx31fkkf.js";import{$b as s,Nc as B,Xb as G,Yb as N,Zb as S,_b as O}from"./chunk-97aywyzn.js";import{Wc as j}from"./chunk-mtphps19.js";import{Xd as q}from"./chunk-0j22w4wh.js";import{pe as v}from"./chunk-axtzde5k.js";import{xh as z}from"./chunk-9q852bsc.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
3
3
  `).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
4
4
  `)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
@@ -1,4 +1,4 @@
1
- import{Oe as j1,Pe as L0,Qe as F1}from"./chunk-hat9v5c5.js";import{Ue as WO,Ve as IO}from"./chunk-cdy9efgm.js";import{Ye as B1}from"./chunk-zvz2cnt4.js";import{$e as J0,Ze as b0}from"./chunk-qm5c9wew.js";import{bg as z0,cg as $O,gg as I0}from"./chunk-b39p4f5r.js";import{kg as u,mg as L,pg as P1}from"./chunk-v0rsz1rt.js";import{wg as M}from"./chunk-k0pa8874.js";import{Xg as k,Yg as z}from"./chunk-d808m826.js";import{jh as g0}from"./chunk-y9d9nqnn.js";import{qh as N}from"./chunk-wj6t3tv2.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
1
+ import{Oe as j1,Pe as L0,Qe as F1}from"./chunk-hat9v5c5.js";import{Ue as WO,Ve as IO}from"./chunk-cdy9efgm.js";import{Ye as B1}from"./chunk-zvz2cnt4.js";import{$e as J0,Ze as b0}from"./chunk-4ke8k0xw.js";import{bg as z0,cg as $O,gg as I0}from"./chunk-82htkvz8.js";import{kg as u,mg as L,pg as P1}from"./chunk-v0rsz1rt.js";import{wg as M}from"./chunk-k0pa8874.js";import{Xg as k,Yg as z}from"./chunk-t2wgf9tq.js";import{jh as g0}from"./chunk-azw0jckv.js";import{qh as N}from"./chunk-jzntxp7f.js";import Y1 from"node:path";import QO from"node:path";import R0 from"node:fs";import X0 from"node:os";import R from"node:path";import EO from"yaml";var Q4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:2000},findings:{type:"array",maxItems:50,items:{type:"string",minLength:1,maxLength:1000}}},required:["verdict","summary","findings"],additionalProperties:!1};function Z4(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O.verdict;return $==="pass"||$==="fail"||$==="partial"?$:void 0}var NO=`# Goal Completion Verifier
2
2
 
3
3
  You are a fresh, independent, adversarial verifier. The parent Agent has claimed
4
4
  that a persisted goal is complete. Your job is to refute that claim unless the
@@ -1,2 +1,2 @@
1
- import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.70",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
1
+ import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.71",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",playwright:"1.62.1",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
2
2
  export{y as ih,p as jh,v as kh,g as lh,f as mh,w as nh};
@@ -1,2 +1,2 @@
1
- import{jh as S}from"./chunk-y9d9nqnn.js";import{Ch as f}from"./chunk-k6shq7rk.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
1
+ import{jh as S}from"./chunk-azw0jckv.js";import{Dh as f}from"./chunk-wfy851et.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
2
2
  export{_ as a,u as b,g as c,C as d,V as e};
@@ -1,2 +1,2 @@
1
- import{K as I}from"./chunk-0kmrvxsz.js";import{Nc as M}from"./chunk-1z9k5dmz.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
1
+ import{K as I}from"./chunk-d3ttqmyt.js";import{Nc as M}from"./chunk-97aywyzn.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
2
2
  export{C as v,$ as w,V as x,x as y,i as z,K as A};
@@ -1,4 +1,4 @@
1
- import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-z77c18j5.js";import{N as M,V as y}from"./chunk-0kmrvxsz.js";import"./chunk-83b4vfjs.js";import"./chunk-wepvrnmh.js";import{pb as h,yb as A}from"./chunk-wkpacysr.js";import"./chunk-th4jjfgm.js";import{Nc as U,zc as w}from"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import{jd as C}from"./chunk-bkajr86v.js";import{ld as I,md as S,nd as v}from"./chunk-r9n8y8m1.js";import{od as O}from"./chunk-s7jsadnc.js";import"./chunk-bjqjdw34.js";import{Ld as P}from"./chunk-p9vaaayr.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import"./chunk-4md4sd4j.js";import"./chunk-yn51162x.js";import"./chunk-832va1mp.js";import"./chunk-wahhwjp9.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import"./chunk-b39p4f5r.js";import{ig as F}from"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as z}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-wj6t3tv2.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(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 R,n as c,o as g,p as d,q as m,r as l}from"./chunk-gtcxybv5.js";import{N as M,V as y}from"./chunk-d3ttqmyt.js";import"./chunk-qgrq04hb.js";import"./chunk-92x15fzx.js";import{pb as h,yb as A}from"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import{Nc as U,zc as w}from"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import{jd as C}from"./chunk-3hy06st1.js";import{ld as I,md as S,nd as v}from"./chunk-2428hhvj.js";import{od as O}from"./chunk-s7jsadnc.js";import"./chunk-bjqjdw34.js";import{Ld as P}from"./chunk-1je1xw6v.js";import"./chunk-v508x7cg.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-wrfay5r3.js";import"./chunk-yn51162x.js";import"./chunk-fcv8b6ny.js";import"./chunk-axtzde5k.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-zvz2cnt4.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-82htkvz8.js";import{ig as F}from"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import{wg as z}from"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-jzntxp7f.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(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 i(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 n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
@@ -1 +1 @@
1
- import{Ab as m,Bb as n,Cb as o,Eb as p,Fb as q,Gb as r,gb as a,hb as b,jb as c,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,zb as l}from"./chunk-wkpacysr.js";import"./chunk-th4jjfgm.js";import"./chunk-1z9k5dmz.js";import"./chunk-0wxkymqv.js";import"./chunk-f7yfcw8s.js";import"./chunk-0j22w4wh.js";import"./chunk-q919ypcz.js";import"./chunk-yn51162x.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-qm5c9wew.js";import"./chunk-m57w4p91.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-d808m826.js";import"./chunk-0p0e70cy.js";import"./chunk-t8xmh4w2.js";import"./chunk-y9d9nqnn.js";import"./chunk-jrr361h1.js";import"./chunk-8wea3qty.js";import"./chunk-k6shq7rk.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
+ import{Ab as m,Bb as n,Cb as o,Eb as p,Fb as q,Gb as r,gb as a,hb as b,jb as c,nb as d,ob as e,pb as f,qb as g,rb as h,sb as i,tb as j,ub as k,zb as l}from"./chunk-nx31fkkf.js";import"./chunk-th4jjfgm.js";import"./chunk-97aywyzn.js";import"./chunk-0wxkymqv.js";import"./chunk-mtphps19.js";import"./chunk-0j22w4wh.js";import"./chunk-zdnk7qtn.js";import"./chunk-yn51162x.js";import"./chunk-hat9v5c5.js";import"./chunk-cdy9efgm.js";import"./chunk-4ke8k0xw.js";import"./chunk-m57w4p91.js";import"./chunk-h0ft81a3.js";import"./chunk-v0rsz1rt.js";import"./chunk-xz6y0w4n.js";import"./chunk-k0pa8874.js";import"./chunk-6pyktfa4.js";import"./chunk-t2wgf9tq.js";import"./chunk-2px6hzdc.js";import"./chunk-t8xmh4w2.js";import"./chunk-azw0jckv.js";import"./chunk-r9d4mjxj.js";import"./chunk-9q852bsc.js";import"./chunk-wfy851et.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};