blade-code 0.10.96 → 0.10.97

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 (116) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/chunk-0p6qkcft.js +1 -0
  3. package/dist/chunk-0pdkfzgc.js +1 -0
  4. package/dist/{chunk-t48zm299.js → chunk-0v74fhhc.js} +1 -1
  5. package/dist/{chunk-9318pj5k.js → chunk-21ycnzsv.js} +1 -1
  6. package/dist/{chunk-50em9ww2.js → chunk-23qhbq46.js} +1 -1
  7. package/dist/{chunk-hrfh7wck.js → chunk-2c2cxrc0.js} +1 -1
  8. package/dist/{chunk-ax8tta9d.js → chunk-2mwgykjs.js} +1 -1
  9. package/dist/chunk-2vt67deg.js +1 -0
  10. package/dist/{chunk-0eqk29xr.js → chunk-31g86axj.js} +2 -2
  11. package/dist/{chunk-bss2kc28.js → chunk-3229684w.js} +1 -1
  12. package/dist/{chunk-zj4kfyer.js → chunk-3saxqsn7.js} +1 -1
  13. package/dist/{chunk-5vg1dwh1.js → chunk-630jj776.js} +1 -1
  14. package/dist/chunk-64kpbdpc.js +1 -0
  15. package/dist/chunk-6qxzcx0a.js +118 -0
  16. package/dist/chunk-6tzphr1p.js +10 -0
  17. package/dist/{chunk-4jbpvete.js → chunk-7bhk8qk5.js} +2 -2
  18. package/dist/chunk-7t2nf0rz.js +1 -0
  19. package/dist/{chunk-gbsxnvgg.js → chunk-7wtbhnfr.js} +1 -1
  20. package/dist/{chunk-1t097t5f.js → chunk-825r9sfe.js} +248 -248
  21. package/dist/{chunk-z6xfknxe.js → chunk-88mf53ak.js} +1 -1
  22. package/dist/{chunk-xzzrtwjx.js → chunk-88ykfsbv.js} +2 -2
  23. package/dist/{chunk-ya5p7mx7.js → chunk-8hprmrd5.js} +1 -1
  24. package/dist/{chunk-c9zd429t.js → chunk-8htbttg5.js} +1 -1
  25. package/dist/{chunk-rsh4rw9k.js → chunk-9mnspb2d.js} +1 -1
  26. package/dist/{chunk-rxbxvq67.js → chunk-a1vhp8sa.js} +2 -2
  27. package/dist/chunk-ah15z613.js +1 -0
  28. package/dist/chunk-b9thsjxh.js +2 -0
  29. package/dist/{chunk-wbfa6xce.js → chunk-bztsz28c.js} +2 -2
  30. package/dist/{chunk-rzja9zza.js → chunk-c6p5mj1k.js} +2 -2
  31. package/dist/chunk-cp9mj5he.js +1 -0
  32. package/dist/{chunk-kpxz0hbg.js → chunk-csr9d8yx.js} +2 -2
  33. package/dist/{chunk-wj403wry.js → chunk-cvpvncza.js} +2 -2
  34. package/dist/{chunk-4cvmfne8.js → chunk-dretwm9j.js} +1 -1
  35. package/dist/{chunk-va1exak5.js → chunk-dsnz4a1d.js} +1 -1
  36. package/dist/{chunk-bfxj0w4r.js → chunk-fbs90qgx.js} +1 -1
  37. package/dist/{chunk-w63dfcx5.js → chunk-fm93hym6.js} +2 -2
  38. package/dist/{chunk-b12wtvac.js → chunk-g2hxj68b.js} +3 -3
  39. package/dist/{chunk-nh45xp7r.js → chunk-g2yaghbk.js} +1 -1
  40. package/dist/chunk-g7yfjy30.js +1 -0
  41. package/dist/{chunk-na1cney5.js → chunk-h5xw792m.js} +2 -2
  42. package/dist/{chunk-z5rtzcm4.js → chunk-j1t2qedg.js} +2 -2
  43. package/dist/{chunk-ztp2ff01.js → chunk-jy4s51bt.js} +2 -2
  44. package/dist/{chunk-0r4bnnr4.js → chunk-krym2q8y.js} +1 -1
  45. package/dist/{chunk-dwttn5xg.js → chunk-m67hdwk8.js} +1 -1
  46. package/dist/{chunk-qa4efys0.js → chunk-mybhqpc7.js} +1 -1
  47. package/dist/chunk-n407vvwt.js +2 -0
  48. package/dist/{chunk-qstdm5xh.js → chunk-n7p994w1.js} +1 -1
  49. package/dist/{chunk-36tgee8v.js → chunk-nxmn37zx.js} +1 -1
  50. package/dist/{chunk-721g4w9f.js → chunk-p5ewrebt.js} +1 -1
  51. package/dist/{chunk-epmxrw4f.js → chunk-p87j2g40.js} +1 -1
  52. package/dist/chunk-perp57h6.js +1 -0
  53. package/dist/{chunk-7k5v52ct.js → chunk-ps2rv1gg.js} +1 -1
  54. package/dist/chunk-pxmfnkf3.js +1 -0
  55. package/dist/{chunk-yjh47zv6.js → chunk-q5t2rnx0.js} +1 -1
  56. package/dist/{chunk-srqfz4rw.js → chunk-qeznbnd1.js} +2 -2
  57. package/dist/{chunk-gnffwz1c.js → chunk-qhsmhx0y.js} +2 -2
  58. package/dist/chunk-qkmsw3km.js +1 -0
  59. package/dist/{chunk-am66822r.js → chunk-qm83ezt6.js} +1 -1
  60. package/dist/{chunk-7dqh8bqm.js → chunk-s36efnxd.js} +1 -1
  61. package/dist/{chunk-q74xmdkf.js → chunk-s47ypj8n.js} +3 -3
  62. package/dist/chunk-s91r4emx.js +1 -0
  63. package/dist/{chunk-4n4a3vm2.js → chunk-sdvfyzv0.js} +2 -2
  64. package/dist/{chunk-n4gtzx4x.js → chunk-t5es94zk.js} +1 -1
  65. package/dist/chunk-t5y1ebdn.js +8 -0
  66. package/dist/{chunk-5j0b62sr.js → chunk-v2bvrk83.js} +2 -2
  67. package/dist/{chunk-ggf76jxn.js → chunk-vchv2x9y.js} +2 -2
  68. package/dist/chunk-wgg7ysqn.js +1 -0
  69. package/dist/{chunk-9vp2qgt2.js → chunk-xjyr40bn.js} +2 -2
  70. package/dist/{chunk-74yge4ka.js → chunk-xtm0sp0k.js} +1 -1
  71. package/dist/{chunk-g9m309s9.js → chunk-ycr6tsfs.js} +2 -2
  72. package/dist/{chunk-0vkk338p.js → chunk-z6we2tr8.js} +1 -1
  73. package/dist/chunk-zr27h1p0.js +1 -0
  74. package/dist/{chunk-h4j0nve8.js → chunk-zvms9ap7.js} +2 -2
  75. package/dist/{chunk-dd99sgf8.js → chunk-zyfacwgn.js} +1 -1
  76. package/dist/web/assets/{ChatView-EtPiVi9S.js → ChatView-DRfyX8iK.js} +5 -5
  77. package/dist/web/assets/{CodeBlockHighlighter-CJJQKiYA.js → CodeBlockHighlighter-DAFduwex.js} +1 -1
  78. package/dist/web/assets/{FilePreview-p9GkBrrr.js → FilePreview-DP5FG_5E.js} +1 -1
  79. package/dist/web/assets/{KanbanBoard-B3HgXU0l.js → KanbanBoard-CWMPGJNx.js} +1 -1
  80. package/dist/web/assets/{MarkdownRenderer-DQd1r_NH.js → MarkdownRenderer-Dp8ahj7G.js} +3 -3
  81. package/dist/web/assets/{SettingsModal-CJ8604CG.js → SettingsModal-BR_98FMD.js} +1 -1
  82. package/dist/web/assets/{TaskSwitcher-zfuhsPf1.js → TaskSwitcher-D5WijUhR.js} +1 -1
  83. package/dist/web/assets/{TerminalPanel-BF6GORqQ.js → TerminalPanel-CE33pxwb.js} +1 -1
  84. package/dist/web/assets/{arrow-left-BSNY0aTj.js → arrow-left-Cv-KDeEq.js} +1 -1
  85. package/dist/web/assets/{calendar-clock-BizCOffP.js → calendar-clock-Cv_w0wjo.js} +1 -1
  86. package/dist/web/assets/{chevrons-up-down-CN8I3dkY.js → chevrons-up-down-BAdiQ6sx.js} +1 -1
  87. package/dist/web/assets/{clock-3-D5q6Flxt.js → clock-3-wrrODhWr.js} +1 -1
  88. package/dist/web/assets/{external-link-Dw5epjDt.js → external-link-CBEu1rS8.js} +1 -1
  89. package/dist/web/assets/{folder-Dcq3CYVD.js → folder-aphP4iXp.js} +1 -1
  90. package/dist/web/assets/index-rQ1P5u3I.js +271 -0
  91. package/dist/web/assets/{pause-DhspNLAg.js → pause-Bp8TFDGG.js} +1 -1
  92. package/dist/web/assets/{play-B4wnlOAa.js → play-CuOkQMyB.js} +1 -1
  93. package/dist/web/assets/{session-events-Ci1823tS.js → session-events-C95VE6d2.js} +10 -10
  94. package/dist/web/assets/{teamService-DelV4FvL.js → teamService-BXTinwSE.js} +1 -1
  95. package/dist/web/index.html +2 -2
  96. package/package.json +1 -1
  97. package/dist/chunk-46shzdny.js +0 -1
  98. package/dist/chunk-4p6q87bp.js +0 -1
  99. package/dist/chunk-4pamygxp.js +0 -1
  100. package/dist/chunk-54qgtz5s.js +0 -1
  101. package/dist/chunk-729bsa9b.js +0 -1
  102. package/dist/chunk-7jg5d0bz.js +0 -1
  103. package/dist/chunk-8eh0vp98.js +0 -2
  104. package/dist/chunk-brs43rma.js +0 -10
  105. package/dist/chunk-d45gd36e.js +0 -1
  106. package/dist/chunk-d83bfr0b.js +0 -2
  107. package/dist/chunk-gf2vdsx3.js +0 -1
  108. package/dist/chunk-jrjaente.js +0 -1
  109. package/dist/chunk-jzc7ez35.js +0 -1
  110. package/dist/chunk-p3nqvg65.js +0 -1
  111. package/dist/chunk-qrj0d6a5.js +0 -8
  112. package/dist/chunk-tw63vfgh.js +0 -118
  113. package/dist/chunk-vdfwj5fy.js +0 -1
  114. package/dist/chunk-vy4dz3yz.js +0 -1
  115. package/dist/chunk-x9t8340h.js +0 -1
  116. package/dist/web/assets/index-CpHES-wJ.js +0 -271
@@ -1,3 +1,3 @@
1
- import{qi as N,ti as M}from"./chunk-n4gtzx4x.js";import{Oi as H}from"./chunk-na1cney5.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
1
+ import{ri as N,ui as M}from"./chunk-t5es94zk.js";import{Pi as H}from"./chunk-h5xw792m.js";import{createModels as _,createProvider as Y,envApiKeyAuth as x,getSupportedThinkingLevels as E}from"@earendil-works/pi-ai";import{anthropicMessagesApi as F}from"@earendil-works/pi-ai/api/anthropic-messages.lazy";import{openAICompletionsApi as U}from"@earendil-works/pi-ai/api/openai-completions.lazy";import{builtinProviders as P}from"@earendil-works/pi-ai/providers/all";var K=/^[a-z][a-z0-9._-]{0,63}$/,z=/^[A-Z_][A-Z0-9_]*$/,s=new Set(["openai-completions","anthropic-messages"]);function B(u){return typeof u==="string"&&s.has(u)}function X(u,$){let h=`modelProviders.${u}`,b=[];if(!K.test(u))b.push(`${h}: id must match ${K.source}`);if(!$.name?.trim())b.push(`${h}: name must not be empty`);if(!B($.wireApi))b.push(`${h}: wireApi must be openai-completions or anthropic-messages`);try{let w=new URL($.baseUrl);if(!["http:","https:"].includes(w.protocol))b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}catch{b.push(`${h}: baseUrl must be an absolute HTTP(S) URL`)}if($.apiKeyEnv!==void 0&&!z.test($.apiKeyEnv))b.push(`${h}: apiKeyEnv must be a valid environment variable name`);if("apiKey"in $)b.push(`${h}: API keys must be stored separately in auth.json`);return b}function J(u,$){let h=$.trim().replace(/\/+$/,"");if(u==="anthropic-messages"&&/\/v1$/i.test(h))return h.slice(0,-3);return h}import{promises as Z}from"node:fs";import j from"node:path";import{Mutex as R}from"async-mutex";import T from"write-file-atomic";class Q{filePath;mutex=new R;constructor(u=j.join(H(),"auth.json")){this.filePath=u}async read(u){return(await this.readAll())[u]}async list(){let u=await this.readAll();return Object.entries(u).map(([$,h])=>({providerId:$,type:h.type}))}async modify(u,$){return this.mutex.runExclusive(async()=>{let h=await this.readAll(),b=h[u],w=await $(b);if(w===void 0)return b;return h[u]=w,await this.writeAll(h),w})}async delete(u){await this.mutex.runExclusive(async()=>{let $=await this.readAll();if(!(u in $))return;delete $[u],await this.writeAll($)})}async readAll(){try{let u=await Z.readFile(this.filePath,"utf8"),$=JSON.parse(u);return $&&typeof $==="object"&&!Array.isArray($)?$:{}}catch(u){if(u.code==="ENOENT")return{};throw u}}async writeAll(u){let $=j.dirname(this.filePath);await Z.mkdir($,{recursive:!0,mode:448}),await Z.chmod($,448),await T(this.filePath,`${JSON.stringify(u,null,2)}
2
2
  `,{mode:384}),await Z.chmod(this.filePath,384)}}var q="openai-compatible",G="anthropic-compatible",D="https://api.openai.com/v1",V="https://api.anthropic.com",A=128000,C=32768,t={input:0,output:0,cacheRead:0,cacheWrite:0},f=["openai","anthropic","deepseek","google","moonshotai","moonshotai-cn","zai","zai-coding-cn"];class L{credentials;models;compatibleModels=new Map;anthropicCompatibleModels=new Map;customProviderConfigs=new Map;customProviderModels=new Map;reservedProviderIds=new Set;constructor(u=new Q){this.credentials=u,this.models=_({credentials:u});for(let $ of P())this.models.setProvider($);this.installOpenAICompatibleProvider(),this.installAnthropicCompatibleProvider();for(let $ of this.models.getProviders())this.reservedProviderIds.add($.id)}async listProviders(){return Promise.all(this.models.getProviders().map(async(u)=>{let $=u.getModels(),h=this.customProviderConfigs.get(u.id),b=this.getFactoryWireApi(u.id);return{id:u.id,name:u.name,modelCount:$.length,defaultBaseUrl:u.baseUrl??$[0]?.baseUrl,supportsApiKey:Boolean(u.auth.apiKey),supportsOAuth:Boolean(u.auth.oauth),configured:b?!1:Boolean(await this.models.checkAuth(u.id)),custom:Boolean(h),factoryWireApi:b,wireApi:h?.wireApi,apiKeyEnv:h?.apiKeyEnv}}))}listModels(u){return this.models.getModels(u).map(($)=>this.toCatalogEntry($))}getModel(u,$){let h=this.models.getModel(u,$);if(!h&&u===q)this.registerOpenAICompatibleModel($),h=this.models.getModel(u,$);if(!h&&u===G)this.registerAnthropicCompatibleModel($),h=this.models.getModel(u,$);if(!h&&this.customProviderConfigs.has(u))this.registerCustomProviderModel(u,$),h=this.models.getModel(u,$);if(!h)throw Error(`Unknown pi-ai model: ${u}/${$}`);return h}resolveConfig(u){let $=this.getModel(u.provider,u.model),h=u.overrides;return{...$,...h?.baseUrl?{baseUrl:J($.api,h.baseUrl)}:{},...h?.maxOutputTokens?{maxTokens:h.maxOutputTokens}:{}}}async setApiKey(u,$){this.requireProvider(u),await this.credentials.modify(u,async()=>({type:"api_key",key:$}))}async clearCredential(u){this.requireProvider(u),await this.credentials.delete(u)}async isConfigured(u){return this.requireProvider(u),Boolean(await this.models.checkAuth(u))}isReservedProviderId(u){return this.reservedProviderIds.has(u)}configureModelProviders(u,$){for(let h of this.customProviderConfigs.keys())this.models.deleteProvider(h);this.customProviderConfigs.clear(),this.customProviderModels.clear();for(let[h,b]of Object.entries(u)){let w=$.filter((k)=>k.provider===h).map((k)=>k.model);this.registerModelProvider(h,b,w)}}registerModelProvider(u,$,h=[]){if(this.isReservedProviderId(u))throw Error(`modelProviders.${u}: built-in provider ids cannot be overridden`);let b=X(u,$);if(b.length>0)throw Error(b.join("; "));let w={...$,name:$.name.trim(),baseUrl:J($.wireApi,$.baseUrl),...$.apiKeyEnv?{apiKeyEnv:$.apiKeyEnv.trim()}:{}};this.customProviderConfigs.set(u,w);let k=new Map;for(let y of new Set(h)){let W=y.trim();if(!W)continue;k.set(W,this.createCompatibleModel(u,W,w.wireApi,w.baseUrl))}this.customProviderModels.set(u,k),this.installCustomProvider(u)}unregisterModelProvider(u){if(!this.customProviderConfigs.has(u))return;this.customProviderConfigs.delete(u),this.customProviderModels.delete(u),this.models.deleteProvider(u)}requireProvider(u){if(!this.models.getProvider(u))throw Error(`Unknown pi-ai provider: ${u}`)}registerOpenAICompatibleModel(u){let $=u.trim();if(!$)throw Error("OpenAI-compatible model ID must not be empty");if(this.compatibleModels.has($))return;let h=this.createCompatibleModel(q,$,"openai-completions",D);this.compatibleModels.set($,h),this.installOpenAICompatibleProvider()}registerAnthropicCompatibleModel(u){let $=u.trim();if(!$)throw Error("Anthropic-compatible model ID must not be empty");if(this.anthropicCompatibleModels.has($))return;let h=this.createCompatibleModel(G,$,"anthropic-messages",V);this.anthropicCompatibleModels.set($,h),this.installAnthropicCompatibleProvider()}registerCustomProviderModel(u,$){let h=$.trim();if(!h)throw Error("Custom provider model ID must not be empty");let b=this.customProviderConfigs.get(u),w=this.customProviderModels.get(u);if(!b||!w||w.has(h))return;w.set(h,this.createCompatibleModel(u,h,b.wireApi,b.baseUrl)),this.installCustomProvider(u)}createCompatibleModel(u,$,h,b){let w=this.models.getModels().filter((y)=>y.provider!==u&&!this.customProviderConfigs.has(y.provider)&&y.id===$),k=f.flatMap((y)=>w.filter((W)=>W.provider===y))[0]??w[0];return{id:$,name:k?.name??$,api:h,provider:u,baseUrl:b,reasoning:k?.reasoning??!1,input:k?[...k.input]:["text"],cost:{...t},contextWindow:k?.contextWindow??A,maxTokens:k?.maxTokens??C,...k?.thinkingLevelMap?{thinkingLevelMap:{...k.thinkingLevelMap}}:{}}}installOpenAICompatibleProvider(){this.models.setProvider(Y({id:q,name:"Custom OpenAI Endpoint",baseUrl:D,auth:{apiKey:x("OpenAI-compatible API key",["OPENAI_COMPATIBLE_API_KEY","BLADE_API_KEY"])},models:[...this.compatibleModels.values()],api:U()}))}installAnthropicCompatibleProvider(){this.models.setProvider(Y({id:G,name:"Custom Anthropic Endpoint",baseUrl:V,auth:{apiKey:x("Anthropic-compatible API key",["ANTHROPIC_API_KEY","BLADE_API_KEY"])},models:[...this.anthropicCompatibleModels.values()],api:F()}))}installCustomProvider(u){let $=this.customProviderConfigs.get(u),h=this.customProviderModels.get(u);if(!$||!h)return;let b=$.apiKeyEnv?[$.apiKeyEnv]:[];this.models.setProvider(Y({id:u,name:$.name,baseUrl:$.baseUrl,auth:{apiKey:x(`${$.name} API key`,b)},models:[...h.values()],api:$.wireApi==="anthropic-messages"?F():U()}))}getFactoryWireApi(u){if(u===q)return"openai-completions";if(u===G)return"anthropic-messages";return}toCatalogEntry(u){return{id:u.id,name:u.name,provider:u.provider,api:u.api,baseUrl:u.baseUrl,reasoning:u.reasoning,supportedReasoningEfforts:E(u),supportedServiceTiers:M(u),supportedResponseVerbosities:N(u),input:[...u.input],contextWindow:u.contextWindow,maxTokens:u.maxTokens,cost:{...u.cost}}}}var S;function hu(){return S??=new L,S}
3
- export{K as ki,X as li,J as mi,L as ni,hu as oi};
3
+ export{K as li,X as mi,J as ni,L as oi,hu as pi};
@@ -1,4 +1,4 @@
1
- import{_b as E4}from"./chunk-ya5p7mx7.js";import{Cd as I0,Ed as V6,Fd as R1,Gd as K6,Nd as n$,Rc as kJ,Tc as CJ,Uc as vJ,Vc as d2,Wc as m2,ac as X$,ad as IJ,bd as S4,cd as T4,dd as v2,ed as x1,fd as M4,gd as R4,hd as E1,kd as UJ,sd as V1}from"./chunk-tw63vfgh.js";import{Sd as F0,Vd as _J,Wd as k0}from"./chunk-4jbpvete.js";import{Xe as tJ}from"./chunk-zj4kfyer.js";import{$e as HJ,Ye as _4,Ze as i0,_e as O4,cf as b1,df as Y6,ef as zJ,ff as BJ,hf as jJ}from"./chunk-0eqk29xr.js";import{Sf as J$,Tf as r0,Wf as b4,_f as X4}from"./chunk-yjh47zv6.js";import{jg as A$}from"./chunk-q74xmdkf.js";import{th as rJ}from"./chunk-t48zm299.js";import{Ih as H0}from"./chunk-qa4efys0.js";import{ii as h0}from"./chunk-h4j0nve8.js";import{wi as xJ}from"./chunk-5j0b62sr.js";import{Hi as _$,Ji as i6,Ki as y0,Li as M1,Ni as MJ,Oi as RJ,Pi as hJ}from"./chunk-na1cney5.js";import{Qi as G8}from"./chunk-nh45xp7r.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],k6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},Y5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},V5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],z5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",L5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function N5($){let J=$;for(let X of A5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
1
+ import{$b as E4}from"./chunk-8hprmrd5.js";import{Dd as I0,Fd as V6,Gd as R1,Hd as K6,Od as n$,Sc as kJ,Uc as CJ,Vc as vJ,Wc as d2,Xc as m2,bc as X$,bd as IJ,cd as S4,dd as T4,ed as v2,fd as x1,gd as M4,hd as R4,id as E1,ld as UJ,td as V1}from"./chunk-6qxzcx0a.js";import{Td as F0,Wd as _J,Xd as k0}from"./chunk-7bhk8qk5.js";import{Ye as tJ}from"./chunk-3saxqsn7.js";import{$e as O4,Ze as _4,_e as i0,af as HJ,df as b1,ef as Y6,ff as zJ,gf as BJ,if as jJ}from"./chunk-31g86axj.js";import{$f as X4,Tf as J$,Uf as r0,Xf as b4}from"./chunk-q5t2rnx0.js";import{kg as A$}from"./chunk-s47ypj8n.js";import{uh as rJ}from"./chunk-0v74fhhc.js";import{Jh as H0}from"./chunk-mybhqpc7.js";import{ji as h0}from"./chunk-zvms9ap7.js";import{xi as xJ}from"./chunk-v2bvrk83.js";import{Ii as _$,Ki as i6,Li as y0,Mi as M1,Oi as MJ,Pi as RJ,Qi as hJ}from"./chunk-h5xw792m.js";import{Ri as G8}from"./chunk-g2yaghbk.js";function f$($){return $.role==="system"&&Array.isArray($.content)}function O$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class f1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,J){this.context=$;let Z=$.messages.find(f$);if(this._contextualSystemMessages=$.messages.filter(O$),Z)this.systemMessages=[Z,...this._contextualSystemMessages];else if(J)this.systemMessages=[{role:"system",content:[{type:"text",text:J,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!f$(W)&&!O$(W))}get historyLength(){return this._history.length}get history(){return this._history}get pending(){return this._pending}get contextRevision(){return this._contextRevision}toLLMMessages(){return[...this.systemMessages,...this._history,...this._pending]}getMessagesForLLM(){return this.toLLMMessages()}getHistory(){return this._history}appendPending($){this._pending.push($)}appendUser($){this._pending.push($)}appendAssistant($){this._pending.push($)}appendToolResult($){this._pending.push($)}appendContextualProjectInstructions($){if(!O$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(f$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,J){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push(J)}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((J)=>J.id===$.id))return;this._history.push($)}appendToHistory($){this._history.push($)}commitPending(){if(this._pending.length>0)this._history.push(...this._pending),this._pending=[]}replaceHistory($){this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(O$),this._history=$.filter((J)=>!f$(J)&&!O$(J)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let J=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((Z)=>!$(Z)),this._pending=this._pending.filter((Z)=>!$(Z)),this._contextualSystemMessages=this._contextualSystemMessages.filter((Z)=>!$(Z)),this.syncContextualSystemMessages(),this._history.length!==J[0]||this._pending.length!==J[1]||this._contextualSystemMessages.length!==J[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function _6($){if($.isSubagent)return"continue";if(!$.budget||$.budget<=0)return"continue";if($.consecutiveContinuations>=3&&$.lastOutputDelta<500)return"stop";if($.usage/$.budget>=0.9)return"stop";return"continue"}function b6($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function E6($,J,Z){return{...$,usage:$.usage+J,lastOutputDelta:J,consecutiveContinuations:Z?$.consecutiveContinuations+1:0}}import Q$ from"node:path";var d4=new Set(["GOEXPERIMENT","GOOS","GOARCH","CGO_ENABLED","GO111MODULE","RUST_BACKTRACE","RUST_LOG","NODE_ENV","PYTHONUNBUFFERED","PYTHONDONTWRITEBYTECODE","GIT_TERMINAL_PROMPT","LANG","LANGUAGE","LC_ALL","LC_CTYPE","LC_TIME","CHARSET","TERM","COLORTERM","NO_COLOR","FORCE_COLOR","TZ","LS_COLORS","LSCOLORS","GREP_COLOR","GREP_COLORS"]),m4=/^(LD_.+|DYLD_.+|PATH)$/,S6=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function c$($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(!d4.has(K))break;J=Y}return J}function vZ($){let J=$;while(!0){let Z=J.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!Z)break;let W=Z[1],Y=Z[2],V=W.match(S6);if(!V)break;let K=V[1];if(m4.test(K))break;J=Y}return J}var c4=[/^timeout[ \t]+(?:--foreground[ \t]+|--preserve-status[ \t]+|-v[ \t]+|--verbose[ \t]+|-k[ \t]+\S+[ \t]+|--kill-after[= ]\S+[ \t]+|-s[ \t]+\S+[ \t]+|--signal[= ]\S+[ \t]+)*\S+[ \t]+/,/^time[ \t]+/,/^nice[ \t]+(?:-n[ \t]+\d+[ \t]+|-\d+[ \t]+)?/,/^nohup[ \t]+/];function U2($){let J=$,Z=!0;while(Z){Z=!1;for(let W of c4){let Y=J.match(W);if(Y){J=J.slice(Y[0].length),Z=!0;break}}if(J.startsWith("-- "))J=J.slice(3),Z=!0}return J}function l$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){Z+=Q,V=!0;continue}if(Q==="'"&&!Y){W=!W,Z+=Q;continue}if(Q==='"'&&!W){Y=!Y,Z+=Q;continue}if(W||Y){Z+=Q;continue}if(Q==="|"){if(K+1<$.length&&$[K+1]==="|"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&K+1<$.length&&$[K+1]==="&"){if(Z.trim())J.push(Z.trim());Z="",K++;continue}if(Q==="&")return null;if(Q===";"){if(Z.trim())J.push(Z.trim());Z="";continue}Z+=Q}if(Z.trim())J.push(Z.trim());return J.length>0?J:null}function T6($){let J=!1,Z=!1,W=!1;for(let Y=0;Y<$.length;Y++){let V=$[Y];if(W){W=!1;continue}if(V==="\\"&&!J){W=!0;continue}if(V==="'"&&!Z){J=!J;continue}if(V==='"'&&!J){Z=!Z;continue}if(J)continue;if(V==="$"){let K=$[Y+1];if(K&&/[A-Za-z_@*#?!$0-9({]/.test(K))return!0}if(V==="`")return!0;if(Z)continue;if(V==="|")return!0;if(V===">"||V==="<")return!0;if(V==="{"){let K=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(K)||/^\{[^}]*\.\.[^}]*\}/.test(K))return!0}}return!1}function K$($){let J=[],Z="",W=!1,Y=!1,V=!1;for(let K=0;K<$.length;K++){let Q=$[K];if(V){Z+=Q,V=!1;continue}if(Q==="\\"&&!W){if(V=!0,Y){let X=$[K+1];if(X&&'$`"\\'.includes(X))continue;Z+=Q,V=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(Z)J.push(Z),Z="";continue}Z+=Q}if(Z)J.push(Z);return J}var l4=new Set(["npm","pnpm","yarn","bun"]),M6=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),i4=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),r4=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function n4($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function R6($){return $.replace(/\s+2>&1\s*$/,"").trim()}function o4($,J,Z){if(!Z||J.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=K$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let V=Y[1];if(!V||V==="-")return;let K=Q$.isAbsolute(V)?Q$.resolve(V):Q$.resolve(Z,V);if(!X$.isWithinWorkspace(K,Z))return;return W[2]?.trim()||void 0}function a4($){let J=[],Z=!1,W=!1,Y=!1;for(let V=0;V<$.length;V++){let K=$[V];if(Y){Y=!1;continue}if(K==="\\"&&!Z){Y=!0;continue}if(K==="'"&&!W){Z=!Z;continue}if(K==='"'&&!Z){W=!W;continue}if(K!=="|"||Z||W)continue;if($[V+1]==="|")return;J.push(V)}return J}function s4($){let J=K$($),[Z,W,Y]=J;if(Z!=="head"&&Z!=="tail")return!1;if(J.length===1)return!0;let V=(K)=>K!==void 0&&/^[1-9]\d{0,4}$/.test(K);if(J.length===2)return W?.startsWith("--lines=")&&V(W.slice(8))||W?.startsWith("-")&&V(W.slice(1));return J.length===3&&(W==="-n"||W==="--lines")&&V(Y)}function t4($){let J=R6($.replace(r4,"").trim()),Z=a4(J);if(!Z)return;if(Z.length===0)return h6(J);if(Z.length!==1)return;let W=Z[0];if(W===void 0)return;let Y=R6(J.slice(0,W).trim()),V=J.slice(W+1).trim();if(!Y||!s4(V))return;return h6(Y)}function h6($){let Z=l$($)?.at(-1);if(!Z)return $;let W=K$(Z),[Y,V]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&V==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function y$($,J){let Z=t4($);if(!Z)return!1;let W=c$(Z),Y=l$(W);if(!Y||T6(W)||/[\r\n]/.test(W))return!1;let V=Y.length===1?Y[0]:o4(W,Y,J);if(!V)return!1;let K=K$(V);if(K.length===0||K.some((B)=>[...i4].some((j)=>B===j||B.startsWith(`${j}=`))))return!1;let[Q,X,H]=K;if(l4.has(Q??""))return n4(X==="run"?H:X)||X==="--test";if((Q==="npx"||Q==="bunx")&&M6.has(X??""))return!0;if(M6.has(Q??""))return!0;if(Q==="node"&&X==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(X??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(X??"")}function dZ($,J){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!J)return!Q$.isAbsolute($);let Z=Q$.isAbsolute($)?Q$.resolve($):Q$.resolve(J,$);return X$.isWithinWorkspace(Z,J)}var D2=h0("Agent"),e4=3;function w2($,J,Z){if($!=="length")return{action:"none"};if(J>=e4)return{action:"truncated"};if(_6(Z)==="stop")return D2.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var $5=[/:\s*$/,/:\s*$/,/\.\.\.\s*$/,/让我(先|来|开始|查看|检查|修复)/,/Let me (first|start|check|look|fix)/i,/I('ll| will) (now |)(create|write|edit|update|modify|fix|add|implement)/i,/我(现在就|来|要)(创建|写入|编辑|修改|修复|添加|实现)/,/\d+\.\s+(First|Next|Then|Finally)/i],J5=/```[\s\S]{50,}```/,x6="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",Z5=2;function q2($,J,Z=!0){if(!$||J>=Z5)return{action:"none"};if(!Z&&J5.test($))return{action:"retry",prompt:x6};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if($5.some((K)=>K.test(W)))return{action:"retry",prompt:x6};return{action:"none"}}var W5=[/\b(?:run|execute|rerun|re-run)\b[\s\S]{0,60}\b(?:tests?|test suite|lint|type-?check|build)\b/i,/\b(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?(?:test|lint|build|type-?check)\b/i,/(?:运行|执行|跑|重新运行).{0,30}(?:测试|单测|集成测试|检查|构建)/],k6={test:/\b(?:tests?|test suite)\b|(?:测试|单测|集成测试)/i,lint:/\blint(?:ing)?\b/i,"type-check":/\btype[\s-]?check(?:ing)?\b|\btsc\b|类型检查/i,build:/\bbuild\b|构建/i},Y5={test:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?test\b|(?:^|\s)(?:node|bun)\s+--test\b|(?:^|\s)(?:vitest|jest|pytest|go\s+test|cargo\s+test)\b/i,lint:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?lint\b/i,"type-check":/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?type-?check\b|(?:^|\s)tsc\b/i,build:/(?:^|\s)(?:npm|pnpm|yarn|bun)\s+(?:run\s+)?build\b/i},V5="The user explicitly required verification, but it has not run successfully. Do not finish or explain. Your next action must be a Bash tool call that runs the requested test, lint, type-check, or build command. Inspect the command result and fix any failure before finishing.",K5="Required verification did not run successfully before the retry limit.",Q5=3;function v6($,J,Z,W){if(!Z.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(J)){$.clear();return}if(J==="Bash"&&typeof Z.metadata?.command==="string"&&Z.metadata.exit_code===0&&y$(Z.metadata.command,W)){$.add(Z.metadata.command);return}if(!["Task","TaskOutput"].includes(J))return;let Y=Z.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let V of Y)if(typeof V==="string"&&y$(V,W))$.add(V)}function G2($,J,Z){if(!$||!W5.some((X)=>X.test($)))return{action:"none"};let W=Object.keys(k6).filter((X)=>k6[X].test($)),Y=[...J],V=W.filter((X)=>!Y.some((H)=>Y5[X].test(H)));if(W.length>0?V.length===0:Y.some((X)=>y$(X)))return{action:"none"};if(Z>=Q5)return{action:"fail",message:K5};let Q=W.length>1&&V.length>0?` Missing successful verification categories: ${V.join(", ")}.`:"";return{action:"retry",prompt:`${V5}${Q}`}}var X5=[/\bdelegate\b[\s\S]{0,120}\b(?:Task tool|subagent|agent)\b/i,/\b(?:call|use|invoke)\b[\s\S]{0,80}\bTask tool\b/i,/(?:委派|交给|调用|使用).{0,60}(?:Task|子代理|子智能体)/],I6=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function u6($){return typeof $==="string"&&I6.some((J)=>J.test($))}var H5=[/\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b[\s\S]{0,30}\bexactly once\b/i,/\bexactly once\b[\s\S]{0,30}\b(?:call|use|invoke)\b[\s\S]{0,30}\bTask(?: tool)?\b/i,/\bexactly one\b[\s\S]{0,30}\bTask(?: tool)? calls?\b/i,/(?:Task|子代理).{0,20}(?:恰好|仅|只)(?:调用|使用)?一次/,/(?:恰好|仅|只)(?:调用|使用)?一次.{0,20}(?:Task|子代理)/],z5=[/\b(?:do not|don't|never)\s+(?:call|use|invoke)\s+(?:the\s+)?Task\b[\s\S]{0,30}\bexactly once\b/i,/\bTask\b[\s\S]{0,30}\b(?:does not|doesn't|need not)\b[\s\S]{0,30}\bexactly once\b/i,/\bmultiple\s+Task(?: tool)?\s+calls?\s+(?:are\s+)?allowed\b/i,/(?:不要|禁止).{0,12}(?:Task|子代理).{0,12}(?:恰好|仅|只)(?:调用|使用)?一次/];function B5($){if(typeof $!=="string")return;if(z5.some((J)=>J.test($)))return"multiple-allowed";return H5.some((J)=>J.test($))?"required":void 0}function i$($){for(let J of $){let Z=B5(J);if(Z!==void 0)return Z==="required"}return!1}var j5="The user explicitly required delegation, but no Task tool call completed successfully. Do not solve the task directly or explain. Your next action must be a Task tool call using the requested subagent.",U5="Required delegation did not complete before the retry limit.",D5=3;function g6($,J,Z){let W=(typeof $==="string"?[$]:$??[]).map((K)=>K.trim()).filter(Boolean),Y=i$(W),V=!1;if(!Y)for(let K of W){if(I6.some((Q)=>Q.test(K)))break;if(X5.some((Q)=>Q.test(K))){V=!0;break}}if(W.length===0||!Y&&!V||J.has("Task"))return{action:"none"};if(Z>=D5)return{action:"fail",message:U5};return{action:"retry",prompt:j5}}var w5=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],q5=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],G5=[/\b(?:do not|don't|never|must not|should not)\b[^.!?;\n]{0,80}\b(?:git\s+)?worktree\b/gi,/\bwithout\b[^.!?;\n]{0,60}\b(?:git\s+)?worktree\b/gi,/(?:不要|禁止|不得|无需)[^。!?;\n]{0,50}(?:worktree|工作树)/gi];function p6($){return G5.reduce((J,Z)=>J.replace(Z," "),$)}function A1($){if(typeof $!=="string")return!1;let J=p6($);return w5.some((Z)=>Z.test(J))}var F5="The user explicitly required git worktree isolation, but EnterWorktree has not completed successfully. Do not continue in the original workspace. Your next action must be an EnterWorktree tool call. Wait for its result before using file or Bash tools.",L5="The user explicitly required leaving the managed worktree, but ExitWorktree has not completed successfully. Do not finish or explain. Your next action must be an ExitWorktree tool call using the action requested by the user.",O5="Required worktree lifecycle did not complete before the retry limit.",f5=3;function d6($,J,Z){if(!$)return{action:"none"};let W=p6($);if(!A1(W))return{action:"none"};let Y=q5.some((K)=>K.test(W));if(J.has("TaskWorktree"))return{action:"none"};let V=!J.has("EnterWorktree")?"EnterWorktree":Y&&!J.has("ExitWorktree")?"ExitWorktree":void 0;if(!V)return{action:"none"};if(Z>=f5)return{action:"fail",message:O5};return{action:"retry",tool:V,prompt:V==="EnterWorktree"?F5:L5}}var C6=30000;async function F2($){try{let Z=A$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??H0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((V)=>{W=setTimeout(()=>V("timeout"),C6)});try{let V=await Promise.race([Z,Y]);if(V==="timeout")return D2.warn(`[Loop] Stop hook 超时 (${C6}ms),按 shouldStop: true 处理`),{action:"stop"};let K=V;if(!K.shouldStop)return{action:"continue",reason:K.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(J){return D2.warn("[Loop] Stop hook execution failed:",J),{action:"stop"}}}async function y5($,J){let Z;while(!(Z=await $.next()).done)if(J)await J(Z.value);return Z.value}var A5=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function P5($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((J)=>{if(typeof J==="string")return J;if(J&&typeof J==="object"&&"text"in J){let Z=J.text;return typeof Z==="string"?Z:""}return""}).join(" ");return""}function N5($){let J=$;for(let X of A5)J=J.replace(X," ");J=J.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let Z=J.replace(/\s+/g," ").trim();if(!Z)return"";let W=Z.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:Z;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let V=Y.slice(0,60),K=V.lastIndexOf(" ");return`${(K>36?V.slice(0,K):V).trimEnd()}…`}function m6($){return N5(P5($))}import{EventEmitter as _5}from"events";import c6 from"node:path";function L2($){if(i6($.sessionId),!c6.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:c6.resolve($.projectPath)}}function l6($){let J=L2($);return JSON.stringify([J.projectPath,J.sessionId])}function $3($,J){return l6($)===l6(J)}class P$ extends _5{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!P$.instance)P$.instance=new P$;return P$.instance}publish($,J,Z,W){let Y=L2($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:J,...W!==void 0?{seq:W}:{},properties:Z})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var r$=P$.getInstance();var t0=h0("Agent"),P1=new Set;async function b5($,J){let Z=$.sessionId;if(!Z||$.subagentInfo)return;if(P1.has(Z))return;if(P1.size>=5000)P1.clear();P1.add(Z);try{let W=$.workspaceRoot,Y=await n$.findSessionMetadata(Z,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let V=m6(J);if(!V)return;await n$.updateSessionMetadata(Z,Y.projectPath,{title:V}),r$.publish({sessionId:Z,projectPath:Y.projectPath},"session.updated",{title:V})}catch(W){t0.debug?.("[Loop] 自动生成会话标题失败:",W)}}var O2=`<turn_aborted>
2
2
  The previous turn was interrupted. Commands or tool calls may have partially completed; inspect the workspace and running processes before retrying.
3
3
  </turn_aborted>`,H$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",r6="Tool execution completed, but its durable result record could not be committed. Further model and tool execution was stopped. The operation may have completed; inspect external state before retrying.";class N$ extends Error{phase;constructor($,J){super($==="user_message"?"Conversation input could not be committed. No further model request was started.":"Model output could not be committed. The run was stopped before any further model request or successful completion.",J);this.phase=$;this.name="DurableConversationPersistenceError"}}function z$($){return $.executionEngine?.getContextManager()}async function l0($,J,Z,W=null,Y,V={}){let K=V.required??$.executionEngine!==void 0;try{let Q=z$($),X=typeof Z==="string"?Z.trim()!=="":Z.some((H)=>H.type==="text"?H.text.trim()!=="":!0);if(Q&&J.sessionId&&X){let H=await Q.saveMessage(J.sessionId,"user",Z,W,Y,J.subagentInfo);if(K&&!H)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)b5(J,Z);return H}if(K&&J.sessionId&&X)throw Error("Durable user-message storage is unavailable")}catch(Q){if(t0.warn("[Loop] 保存用户消息失败:",Q),K)throw new N$("user_message",{cause:Q})}return null}async function x0($,J,Z,W,Y,V,K={}){let Q=K.required??$.executionEngine!==void 0;try{let X=z$($),H=Boolean(Z.trim()||Y?.trim());if(X&&J.sessionId&&H){let B=await X.saveMessage(J.sessionId,"assistant",Z,W,V,J.subagentInfo,Y);if(Q&&!B)throw Error("Durable assistant-message commit returned no identity");return B}if(Q&&J.sessionId&&H)throw Error("Durable assistant-message storage is unavailable")}catch(X){if(t0.warn("[Loop] 保存助手消息失败:",X),Q)throw new N$("assistant_message",{cause:X})}return null}async function n6($,J,Z){try{let W=z$($);if(W&&J.sessionId)return await W.saveMessage(J.sessionId,"system",O2,Z,void 0,J.subagentInfo)}catch(W){t0.warn("[Loop] 保存中断边界失败:",W)}return null}async function o6($,J,Z,W,Y){try{let V=z$($);if(!V||!J.sessionId||Z.length===0)return null;return await V.saveMessage(J.sessionId,"system",`<contextual-project-instructions-ref count="${Z.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(Z.map((K)=>({...K})))),triggerPaths:[...W]},J.subagentInfo)}catch(V){t0.warn("[Loop] 保存 contextual project rules provenance 失败:",V)}return null}async function f2($,J,Z,W,Y,V={}){try{let K=z$($);if(K&&J.sessionId){let Q=await K.saveToolUse(J.sessionId,Z,W,Y,J.subagentInfo,V.providerToolCallId);if(V.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(V.required&&J.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(K){if(t0.warn("[Loop] 保存工具调用失败:",K),V.required)throw K}return null}async function N1($,J,Z,W,Y,V,K,Q,X,H={}){try{let B=z$($);if(B&&J.sessionId){let j=await B.saveToolResult(J.sessionId,Z,W,Y,V,K,J.subagentInfo,Q,X);if(H.required&&!j)throw Error("Durable tool-result commit returned no identity");return j}if(H.required&&J.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(B){if(t0.warn("[Loop] 保存工具结果失败:",B),H.required)throw B}return null}async function o$($,J,Z,W,Y={}){try{let V=z$($);if(V&&J.sessionId){let K=await V.saveCompaction(J.sessionId,Z,W,null);if(Y.required&&!K)throw Error("Compaction checkpoint commit returned no identity");return K||null}if(Y.required&&J.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(V){if(t0.warn("[Loop] 保存压缩数据失败:",V),Y.required)throw V}return null}async function U0($){let{deps:J,context:Z,state:W,assistantContent:Y,assistantReasoningContent:V,lastMessageUuid:K,controlPrompt:Q,controlMetadata:X}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:V});let H=K,B=await x0(J,Z,Y,H,V);if(B)H=B;if(Q!==void 0){let j={role:"user",content:Q};if(X)j.metadata=X;W.appendControl("user",j);let z=await l0(J,Z,j.content,H,X);if(z)H=z}return H}import{createHash as Q6}from"node:crypto";import{promises as m5}from"node:fs";import c5 from"node:path";import{nanoid as e0}from"nanoid";import*as J0 from"node:fs/promises";import*as B$ from"node:path";var a6={enabled:!0,maxIndexLines:200};var E5="memory",s6="MEMORY.md";class y2{memoryDir;config;initialized=!1;constructor($,J,Z){if(Z)this.memoryDir=Z;else{let W=_$($);this.memoryDir=B$.join(W,E5)}this.config={...a6,...J}}async initialize(){if(this.initialized)return;await J0.mkdir(this.memoryDir,{recursive:!0}),this.initialized=!0}async loadIndex(){if(!this.config.enabled)return null;await this.initialize();let $=B$.join(this.memoryDir,s6);try{let J=await J0.readFile($,"utf-8");if(!J.trim())return null;let Z=J.split(`
4
4
  `),Y=Z.slice(0,this.config.maxIndexLines).join(`
@@ -83,7 +83,7 @@ Full output saved to: ${Q}`}catch{return`${J}
83
83
 
84
84
  ${Y}`}}import E8 from"node:path";import{nanoid as S8}from"nanoid";import*as M0 from"node:fs/promises";import*as bJ from"node:path";import{Mutex as j8}from"async-mutex";import U8 from"write-file-atomic";var PJ=120,k2=128;function $1($){if(!Array.isArray($)||$.length>120||!$.every((J)=>typeof J==="string"&&J.length>0&&J.length<=128))return;return[...new Set($)]}function B8($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let J=$.recovery;if(typeof J!=="object"||Array.isArray(J))return[];if(!("version"in J)||J.version!==1||!("inputMessageIds"in J)||!("hadSuccessfulToolResult"in J)||typeof J.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in J)||typeof J.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];let Z=$1(J.inputMessageIds),W=$1($.acknowledgedInputMessageIds);if(!Z||!W)return[];let Y=new Set(Z);return W.filter((V)=>Y.has(V))}function S1($,J){let Z=$[J];if(Z?.type!=="turn_aborted")return[];let W=B8(Z.data);if(W.length===0)return[];let Y=-1;for(let K=J-1;K>=0;K--){let Q=$[K];if(Q.type==="turn_started"){if(Q.data.turnId!==Z.data.turnId)return[];Y=K;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let V=new Set;for(let K=Y+1;K<J;K++){let Q=$[K];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let X=Q.data.metadata,H=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:X!==null&&typeof X==="object"&&!Array.isArray(X)?X.inboxMessageId:void 0;if(typeof H==="string"&&H.length>0&&H.length<=128)V.add(H)}return W.filter((K)=>V.has(K))}var T1=1,J1=8388608;function NJ($,J){let Z={version:T1,sessionId:$,messages:J.map(({recovered:W,...Y})=>Y)};return`${JSON.stringify(Z)}
85
85
  `}function C2($,J){return $ instanceof Error&&"code"in $&&$.code===J}function D8($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((J)=>{if(!J||typeof J!=="object"||!("type"in J))return!1;if(J.type==="text")return"text"in J&&typeof J.text==="string";return J.type==="image_url"&&"image_url"in J&&typeof J.image_url==="object"&&J.image_url!==null&&"url"in J.image_url&&typeof J.image_url.url==="string"})}function w8($,J,Z){let W;try{W=JSON.parse($)}catch(V){throw Error(`Invalid steering inbox JSON: ${J}`,{cause:V})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==T1||!("sessionId"in W)||W.sessionId!==Z||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${J}`);let Y=W.messages.map((V)=>{if(!V||typeof V!=="object"||!("id"in V)||typeof V.id!=="string"||!("content"in V)||!D8(V.content)||!("queuedAt"in V)||typeof V.queuedAt!=="number"||"persisted"in V&&typeof V.persisted!=="boolean"||"origin"in V&&V.origin!=="user"&&V.origin!=="background_subagent"&&V.origin!=="team_message"||"metadata"in V&&(V.metadata===null||typeof V.metadata!=="object"||Array.isArray(V.metadata))||"outputSchema"in V&&V.outputSchema!==void 0&&(!V.outputSchema||typeof V.outputSchema!=="object"||Array.isArray(V.outputSchema)))throw Error(`Invalid steering inbox message: ${J}`);let K="outputSchema"in V&&V.outputSchema!==void 0?R1(V.outputSchema).schema:void 0;return{id:V.id,content:V.content,queuedAt:V.queuedAt,..."persisted"in V&&V.persisted===!0?{persisted:!0}:{},..."origin"in V&&V.origin?{origin:V.origin}:{},..."metadata"in V&&V.metadata?{metadata:JSON.parse(JSON.stringify(V.metadata))}:{},...K?{outputSchema:K}:{}}});return{version:T1,sessionId:Z,messages:Y}}function q8($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return S1($,Z);return[]}))}class h1{workspaceRoot;sessionId;filePath;mutex=new j8;messages=[];constructor($,J,Z){this.workspaceRoot=$;this.sessionId=J;this.filePath=Z}static async open($,J){let Z=new h1($,J,M1($,J));return await Z.loadAndReconcile(),Z}async enqueue($,J){return this.mutex.runExclusive(async()=>{if(J&&!J(this.messages))return!1;let Z=[...this.messages,{...$,recovered:!1}],W=NJ(this.sessionId,Z);if(Buffer.byteLength(W)>J1)return!1;return await this.persist(Z,W),this.messages=Z,!0})}async acknowledge($){if($.length===0)return;let J=new Set($);await this.mutex.runExclusive(async()=>{let Z=this.messages.filter((W)=>!J.has(W.id));this.messages=Z,await this.persist(Z)})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((J)=>J.type==="text"?{...J}:{...J,image_url:{...J.image_url}}),...$.outputSchema?{outputSchema:JSON.parse(JSON.stringify($.outputSchema))}:{},...$.metadata?{metadata:JSON.parse(JSON.stringify($.metadata))}:{}}))}count(){return this.messages.length}recoveredCount(){return this.messages.filter(($)=>$.recovered).length}async loadAndReconcile(){await this.mutex.runExclusive(async()=>{let $={version:T1,sessionId:this.sessionId,messages:[]};try{if((await M0.stat(this.filePath)).size>J1)throw Error(`Steering inbox exceeds ${J1} bytes: ${this.filePath}`);await M0.chmod(this.filePath,384),$=w8(await M0.readFile(this.filePath,"utf8"),this.filePath,this.sessionId)}catch(Y){if(!C2(Y,"ENOENT"))throw Y}let J=y0(this.workspaceRoot,this.sessionId),Z=new Set;try{Z=q8(_J(await M0.readFile(J,"utf8"),J))}catch(Y){if(!C2(Y,"ENOENT"))throw Y}let W=$.messages.filter((Y)=>!Z.has(Y.id)).map((Y)=>({...Y,recovered:!0}));if(this.messages=W,W.length!==$.messages.length)await this.persist(W)})}async persist($,J){if(await M0.mkdir(bJ.dirname(this.filePath),{recursive:!0,mode:448}),$.length===0){await M0.unlink(this.filePath).catch((W)=>{if(!C2(W,"ENOENT"))throw W});return}let Z=J??NJ(this.sessionId,$);if(Buffer.byteLength(Z)>J1)throw Error(`Steering inbox exceeds ${J1} bytes: ${this.filePath}`);await U8(this.filePath,Z,{encoding:"utf8",mode:384,fsync:!0})}}import*as v0 from"node:fs/promises";import*as uJ from"node:path";import{nanoid as K0}from"nanoid";var EJ=256;class D0{sessionId;projectPath;static instances=new Map;store;subscribers=new Set;highestSeq=0;constructor($,J){this.sessionId=$;this.projectPath=J;this.store=new k0(y0(J,$))}static for($,J){let Z=`${J}\x00${$}`,W=D0.instances.get(Z);if(!W)W=new D0($,J),D0.instances.set(Z,W),D0.pruneIdleInstances(Z);else D0.instances.delete(Z),D0.instances.set(Z,W);return W}static release($,J){D0.instances.delete(`${J}\x00${$}`)}static pruneIdleInstances($){if(D0.instances.size<=EJ)return;for(let[J,Z]of D0.instances){if(J===$||Z.subscribers.size>0)continue;if(D0.instances.delete(J),D0.instances.size<=EJ)return}}get lastSeq(){return this.highestSeq}async commit($){let J=await this.store.append($);return this.record(J),J}async commitBatch($){if($.length===0)return[];let J=await this.store.appendBatch($);for(let Z of J)this.record(Z);return J}async commitValidated($){let J=await this.store.appendValidated($);return this.record(J),J}async commitValidatedBatch($){let J=await this.store.appendValidatedBatch($);for(let Z of J)this.record(Z);return J}emitDelta($){for(let J of this.subscribers)J.onDelta?.($);r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,J){if(this.subscribers.add($),J?.fromSeq!==void 0)this.replay($,J.fromSeq);return()=>{this.subscribers.delete($),D0.pruneIdleInstances()}}async replay($,J){let Z=await this.store.readFromSeq(J);for(let W of Z){if(v2(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(v2($))return;for(let J of this.subscribers){let Z=J.onCommitted($);if(Z)Promise.resolve(Z).catch(()=>{return})}r$.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}}function M$($){let J=null,Z=null;for(let W of $){if(W.type==="turn_started"){J=W.data;continue}if(W.type==="turn_completed")Z={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")Z={type:"turn_aborted",data:W.data};else continue;if(J?.turnId===Z.data.turnId)J=null}return{active:J,lastTerminal:Z}}class C0 extends Error{}var F8="Tool execution was interrupted by a process restart. The operation may have partially completed. Inspect the workspace, running processes, and external state before deciding whether to retry it.";function I2($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return!1;return $.slice(Z+1).some((W)=>{if(W.type!=="message_created"||W.data.role!=="user")return!1;let Y=W.data.metadata;return Y!==null&&typeof Y==="object"&&!Array.isArray(Y)&&Y.clientVisible===!1&&Y.emptyFinalCorrection===!0})}function SJ($,J){let Z=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===J);if(Z<0)return[];let W=[];for(let Y of $.slice(Z+1)){if(Y.type==="turn_started"&&Y.data.turnId!==J||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===J)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let V=Y.data.metadata,K=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:V!==null&&typeof V==="object"&&!Array.isArray(V)?V.inboxMessageId:void 0;if(typeof K==="string"&&K.length>0&&K.length<=k2)W.push(K)}return[...new Set(W)]}function gJ($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1)return;let J="inputMessageIds"in $?$1($.inputMessageIds):void 0;if(!J||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;return{inputMessageIds:J,hadSuccessfulToolResult:$.hadSuccessfulToolResult,emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function pJ($){return new Set($.flatMap((J,Z)=>{if(J.type==="inbox_acknowledged")return J.data.messageIds;if(J.type==="turn_aborted")return S1($,Z);return[]}))}function dJ($,J,Z=[]){let W=gJ(J.data.recovery);if(!W)return;let Y=pJ($);for(let K of Z)Y.add(K);let V=W.inputMessageIds.filter((K)=>!Y.has(K));if(V.length===0)return;return{turnId:J.data.turnId,outcome:"aborted",inputMessageIds:V,hadSuccessfulToolResult:W.hadSuccessfulToolResult,emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function u2($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z.type!=="turn_aborted")continue;let W=dJ($,Z);if(W)return W}return}var L8=1e4,O8=1e5,f8=2592000000,TJ=128,y8=1e6,A8=256;function P8($){if(!$||typeof $!=="object"||Array.isArray($))return;let J=$;if(typeof J.goalId!=="string"||J.goalId.length===0||J.goalId.length>TJ||typeof J.verificationAttempt!=="number"||!Number.isSafeInteger(J.verificationAttempt)||J.verificationAttempt<1||J.verificationAttempt>y8||typeof J.verifierSessionId!=="string"||J.verifierSessionId.length===0||J.verifierSessionId.length>TJ||typeof J.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(J.evidenceSha256)||typeof J.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(J.goalUpdatedAt)))return;return{goalId:J.goalId,verificationAttempt:J.verificationAttempt,verifierSessionId:J.verifierSessionId,evidenceSha256:J.evidenceSha256,goalUpdatedAt:J.goalUpdatedAt}}function mJ($,J){let Z=$.data.metadata;if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let W=Z.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,V=Y.turnId,K=Y.inputMessageIds,Q=Y.turnsCount,X=Y.toolCallsCount,H=Y.durationMs,B=Array.isArray(K)?K.filter((z)=>typeof z==="string"&&z.length>0&&z.length<=k2):[];if(typeof V!=="string"||V.length===0||V.length>128||J!==void 0&&V!==J||!Array.isArray(K)||K.length>PJ||B.length!==K.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>L8||typeof X!=="number"||!Number.isSafeInteger(X)||X<0||X>O8||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>f8)return;let j;if("goalFinalization"in Y){if(j=P8(Y.goalFinalization),!j)return}return{turnId:V,inputMessageIds:[...new Set(B)],turnsCount:Q,toolCallsCount:X,durationMs:H,...j?{goalFinalization:j}:{}}}function N8($,J){let Z=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===J);if(Z<0)return;for(let W=$.length-1;W>Z;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let V=mJ(Y,J);if(V)return V}return}function _8($){for(let J=$.length-1;J>=0;J--){let Z=$[J];if(Z?.type!=="message_created")continue;let W=mJ(Z);if(!W?.goalFinalization)continue;if(!$.slice(0,J).some((V)=>V.type==="turn_started"&&V.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function Z1($,J){let Z=J?$.findLastIndex((X)=>X.type==="turn_started"&&X.data.turnId===J):-1;if(J&&Z<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,V=new Set,K=new Set;for(let X of $.slice(Z+1)){if(X.type==="interaction_requested"){K.add(X.data.toolCallId);continue}if(X.type!=="part_created")continue;let H=X.data.payload&&typeof X.data.payload==="object"&&!Array.isArray(X.data.payload)?X.data.payload:{},B=typeof H.toolCallId==="string"?H.toolCallId:X.data.partId;if(X.data.partType==="tool_call")W.set(B,{toolCallId:B,messageId:X.data.messageId,toolName:typeof H.toolName==="string"?H.toolName:"unknown",input:H.input??null});else if(X.data.partType==="tool_result"){if(Y.add(B),Y.add(X.data.partId),Y.add(X.data.messageId),W.has(B)&&H.error===null)V.add(B)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((X)=>!Y.has(X.toolCallId)&&!K.has(X.toolCallId)),hadSuccessfulResult:Q.some((X)=>V.has(X.toolCallId))}}class A0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;initializedSessions=new Set;constructor($=H0(),J=100,Z=xJ()){this.projectPath=$,this.maxSessions=J,this.version=Z}createEvent($,J,Z){return{id:K0(),sessionId:J,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,gitBranch:MJ(this.projectPath),version:this.version,data:Z}}log($){return D0.for($,this.projectPath)}async ensureSessionCreated($,J){let Z=y0(this.projectPath,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=A0.sessionInitializationRuns.get(Z);if(!W)W=this.initializeSessionFile($,Z,J),A0.sessionInitializationRuns.set(Z,W);try{await W,this.rememberInitializedSession($)}finally{if(A0.sessionInitializationRuns.get(Z)===W)A0.sessionInitializationRuns.delete(Z)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>A8){let J=this.initializedSessions.values().next().value;if(J===void 0)return;this.initializedSessions.delete(J)}}async initializeSessionFile($,J,Z){if((await new k0(J).readAll()).length>0)return;let V=new Date().toISOString(),K={sessionId:$,rootId:Z?.parentSessionId??$,parentId:Z?.parentSessionId,relationType:Z?"subagent":void 0,resumedFrom:Z?.resumedFrom,rootAgentId:Z?.rootAgentId,resumeDepth:Z?.resumeDepth,title:void 0,status:"running",taskStatus:Z?"running":"queued",taskFailure:null,agentType:Z?.subagentType,model:void 0,permission:void 0,createdAt:V,updatedAt:V},Q=this.createEvent("session_created",$,K);await this.log($).commit(Q)}buildCompactionMetadata($){let J={trigger:$.trigger,preTokens:$.preTokens};if($.reason)J.reason=$.reason;if($.strategy)J.strategy=$.strategy;if($.preTokenSource)J.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)J.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)J.postTokens=$.postTokens;if($.sampleAttempts!==void 0)J.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)J.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)J.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)J.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)J.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)J.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)J.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)J.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)J.failureReason=$.failureReason;if($.filesIncluded)J.filesIncluded=$.filesIncluded;if($.replacementMessages)J.checkpointVersion=CJ;return J}async initialize(){try{let $=_$(this.projectPath);await v0.mkdir($,{recursive:!0,mode:493}),console.log(`[PersistentStore] 初始化存储目录: ${$}`)}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,J,Z,W=null,Y,V,K){try{await this.ensureSessionCreated($,V);let Q=new Date().toISOString(),X=K0(),H={messageId:X,role:J,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},B=this.createEvent("message_created",$,H),j=J==="assistant"&&K?.trim()?[this.createEvent("part_created",$,{partId:K0(),messageId:X,partType:"reasoning",payload:{text:K},createdAt:Q})]:[],z=typeof Z==="string"?[this.createEvent("part_created",$,{partId:K0(),messageId:X,partType:"text",payload:{text:Z},createdAt:Q})]:Z.map((U)=>this.createEvent("part_created",$,{partId:K0(),messageId:X,partType:U.type==="text"?"text":"image",payload:U.type==="text"?{text:U.text}:{mimeType:b8(U.image_url.url)??"image/png",dataUrl:U.image_url.url},createdAt:Q}));return await this.log($).commitBatch([B,...j,...z]),X}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,J){if(J.length===0)return;await this.ensureSessionCreated($);let Z=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...J],acknowledgedAt:Z}))}async persistBackgroundSubagentCompletion($,J){if(J.inboxMessageId!==`background-subagent-completion:${J.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let Z={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),V=Y.some((z)=>z.type==="inbox_acknowledged"&&z.data.messageIds.includes(J.inboxMessageId)),K=Y.find((z)=>z.type==="message_created"&&z.data.inboxMessageId===J.inboxMessageId),Q=Y.findLast((z)=>{if(z.type!=="part_created"||z.data.partType!=="tool_call"||!z.data.payload||typeof z.data.payload!=="object"||Array.isArray(z.data.payload))return!1;let U=z.data.payload;if(U.toolName!=="Task"||!U.input||typeof U.input!=="object"||Array.isArray(U.input))return!1;let A=U.input,b=A.resume_from??A.resume;return A.run_in_background===!0&&A.subagent_session_id===J.childSessionId&&A.description===J.subagentRef.subagentDescription&&(A.subagent_type===void 0||A.subagent_type===J.subagentRef.subagentType)&&(A.resume_from===void 0||A.resume===void 0||A.resume_from===A.resume)&&(b===void 0?J.subagentRef.subagentResumedFrom===void 0:b===J.subagentRef.subagentResumedFrom)});if(!Q)return Z={eligible:!1,acknowledged:V,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];if(V)return Z={eligible:!0,acknowledged:!0,persisted:!1,...K?{messageId:K.data.messageId}:{}},[];let X=Y.find((z)=>z.type==="part_created"&&z.data.partType==="subtask_ref"&&z.data.payload!==null&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)&&z.data.payload.childSessionId===J.childSessionId&&z.data.payload.status===J.subagentRef.subagentStatus);if(K&&X)return Z={eligible:!0,acknowledged:!1,persisted:!1,messageId:K.data.messageId},[];let H=new Date().toISOString(),B=K?.data.messageId??K0(),j=[];if(!K){let z={messageId:B,role:"user",inboxMessageId:J.inboxMessageId,createdAt:H,metadata:JSON.parse(JSON.stringify(J.metadata))};j.push(this.createEvent("message_created",$,z)),j.push(this.createEvent("part_created",$,{partId:K0(),messageId:B,partType:"text",payload:{text:J.content},createdAt:H}))}if(!X){let z=Y.findLast((A)=>A.type==="part_created"&&A.data.partType==="subtask_ref"&&A.data.messageId===Q.data.messageId&&A.data.payload!==null&&typeof A.data.payload==="object"&&!Array.isArray(A.data.payload)&&A.data.payload.childSessionId===J.childSessionId),U=z?.data.payload&&typeof z.data.payload==="object"&&!Array.isArray(z.data.payload)?z.data.payload:void 0;j.push(this.createEvent("part_created",$,{partId:K0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:J.subagentRef.subagentSessionId,agentType:J.subagentRef.subagentType,description:J.subagentRef.subagentDescription??"",status:J.subagentRef.subagentStatus,summary:J.subagentRef.subagentSummary??"",resumedFrom:J.subagentRef.subagentResumedFrom??null,rootAgentId:J.subagentRef.subagentRootId??J.subagentRef.subagentSessionId,resumeDepth:J.subagentRef.subagentResumeDepth??0,verificationVerdict:J.subagentRef.verificationVerdict??null,startedAt:typeof U?.startedAt==="string"?U.startedAt:H,finishedAt:H},createdAt:H}))}return Z={eligible:!0,acknowledged:!1,persisted:j.length>0,messageId:B},j}),Z}async saveTurnStart($,J){await this.ensureSessionCreated($);try{await this.log($).commitValidated((Z)=>{let W=F0(Z);if(W.some((V)=>V.type==="turn_started"&&V.data.turnId===J.turnId))throw new C0;let Y=M$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,J)})}catch(Z){if(!(Z instanceof C0))throw Z}}async saveTurnCompletion($,J,Z=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),V=new Set(Y.flatMap((H)=>H.type==="inbox_acknowledged"?H.data.messageIds:[])),K=[...new Set(Z)].filter((H)=>!V.has(H)),Q=Y.findLast((H)=>(H.type==="turn_completed"||H.type==="turn_aborted")&&H.data.turnId===J.turnId);if(Q){if(Q.type==="turn_aborted"||K.length===0)throw new C0;return[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]}let X=M$(Y).active;if(!X||X.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);return[...K.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:K,acknowledgedAt:J.completedAt})]:[],this.createEvent("turn_completed",$,J)]})}catch(W){if(!(W instanceof C0))throw W}}async saveTurnAbort($,J,Z={}){let W=Z.acknowledgeInputMessageIds??[],Y=$1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let V=Y;await this.ensureSessionCreated($);let K,Q=[];try{await this.log($).commitValidatedBatch((X)=>{let H=F0(X),B=pJ(H),j=H.findLast((g)=>(g.type==="turn_completed"||g.type==="turn_aborted")&&g.data.turnId===J.turnId);if(j){if(j.type==="turn_completed")throw K=void 0,Q=[],new C0;let g=gJ(j.data.recovery),Z0=g?V.filter((w0)=>g.inputMessageIds.includes(w0)):[],P0=Z0.filter((w0)=>!B.has(w0));if(Q=Z0,K=dJ(H,j,Z0),P0.length===0)throw new C0;return[this.createEvent("inbox_acknowledged",$,{messageIds:P0,acknowledgedAt:J.abortedAt})]}let z=M$(H).active;if(!z||z.turnId!==J.turnId)throw Error(`Turn is not active: ${J.turnId}`);let U=Z1(H,z.turnId),A=SJ(H,z.turnId),b=u2(H),M=new Set(J.recovery?.inputMessageIds??[]),R=b?b.inputMessageIds.filter((g)=>M.has(g)):[],x=[...new Set([...A,...R])],P={version:1,inputMessageIds:x,hadSuccessfulToolResult:U.hadSuccessfulResult||J.recovery?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:I2(H,z.turnId)||J.recovery?.emptyFinalCorrectionSpent===!0};K={turnId:J.turnId,outcome:"aborted",inputMessageIds:P.inputMessageIds,hadSuccessfulToolResult:P.hadSuccessfulToolResult,emptyFinalCorrectionSpent:P.emptyFinalCorrectionSpent};let v=V.filter((g)=>x.includes(g)),u=v.filter((g)=>!B.has(g));Q=v;let q=new Set(B);for(let g of v)q.add(g);let d=P.inputMessageIds.filter((g)=>!q.has(g));K=d.length>0?{turnId:J.turnId,outcome:"aborted",inputMessageIds:d,hadSuccessfulToolResult:P.hadSuccessfulToolResult,emptyFinalCorrectionSpent:P.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:u0,...Q0}=J;return[this.createEvent("turn_aborted",$,{...Q0,...v.length>0?{acknowledgedInputMessageIds:v}:{},recovery:P}),...u.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:u,acknowledgedAt:J.abortedAt})]:[]]})}catch(X){if(!(X instanceof C0))throw X}return{...K?{recovery:K}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let J=await this.loadEvents($);if(!J)return[];let Z=F0(J),W=M$(Z).active;return W?Z1(Z,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async loadBackgroundTaskChildIds($){let J=await this.loadEvents($);if(!J)return new Set;let Z=F0(J).flatMap((W)=>{if(W.type!=="part_created"||W.data.partType!=="tool_call"||!W.data.payload||typeof W.data.payload!=="object"||Array.isArray(W.data.payload))return[];let Y=W.data.payload;if(Y.toolName!=="Task"||!Y.input||typeof Y.input!=="object"||Array.isArray(Y.input))return[];let V=Y.input;return V.run_in_background===!0&&typeof V.subagent_session_id==="string"?[V.subagent_session_id]:[]});return new Set(Z)}async recoverInterruptedTurn($,J={}){await this.ensureSessionCreated($);let Z;try{await this.log($).commitValidatedBatch((W)=>{let Y=F0(W),V=M$(Y).active,K=Z1(Y);if(!V&&K.orphaned.length===0){if(Z=u2(Y),Z)return[];throw new C0}let Q=V?N8(Y,V.turnId):void 0;if(V&&Q&&K.orphaned.length===0){let P=Z1(Y,V.turnId);Z={turnId:V.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:P.hadSuccessfulResult,emptyFinalCorrectionSpent:I2(Y,V.turnId),finalization:Q};let v=new Set(Y.flatMap((d)=>d.type==="inbox_acknowledged"?d.data.messageIds:[])),u=Q.inputMessageIds.filter((d)=>!v.has(d)),q=new Date().toISOString();return[...u.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:u,acknowledgedAt:q})]:[],this.createEvent("turn_completed",$,{turnId:V.turnId,completedAt:q,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let X=V?Z1(Y,V.turnId):void 0,H=X?.orphaned.some((P)=>{let v=J.adoptedToolResults?.get(P.toolCallId);return v?.toolCallId===P.toolCallId&&v.toolName===P.toolName&&v.error===void 0})??!1,B=new Set(V?.inputMessageIds??[]),j=V?u2(Y):void 0,z=j?j.inputMessageIds.filter((P)=>B.has(P)):[],U=z.length>0,A=V?SJ(Y,V.turnId):[];Z=V?{turnId:V.turnId,outcome:"aborted",inputMessageIds:[...new Set([...A,...z])],hadSuccessfulToolResult:(X?.hadSuccessfulResult??!1)||H||U&&j?.hadSuccessfulToolResult===!0,emptyFinalCorrectionSpent:I2(Y,V.turnId)||U&&j?.emptyFinalCorrectionSpent===!0}:void 0;let b=V?X?.all.length??0:0,M=new Date().toISOString(),R=V?Date.parse(V.startedAt):Number.NaN,x=K.orphaned.flatMap((P)=>{let v=J.adoptedToolResults?.get(P.toolCallId),u=v?.toolCallId===P.toolCallId&&v.toolName===P.toolName?v:void 0,q=this.createEvent("part_created",$,{partId:P.toolCallId,messageId:u?P.messageId:P.toolCallId,partType:"tool_result",payload:u?{toolCallId:P.toolCallId,toolName:P.toolName,output:u.output,error:u.error??null,...u.metadata===void 0?{}:{metadata:u.metadata}}:{toolCallId:P.toolCallId,toolName:P.toolName,output:null,error:F8,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:M});if(!u?.subagentRef)return[q];let d=u.subagentRef;return[q,this.createEvent("part_created",$,{partId:K0(),messageId:P.messageId,partType:"subtask_ref",payload:{childSessionId:d.subagentSessionId,agentType:d.subagentType,description:d.subagentDescription??"",status:d.subagentStatus,summary:d.subagentSummary??"",resumedFrom:d.subagentResumedFrom??null,rootAgentId:d.subagentRootId??d.subagentSessionId,resumeDepth:d.subagentResumeDepth??0,verificationVerdict:d.verificationVerdict??null,startedAt:M,finishedAt:M},createdAt:M})]});return V?[...x,this.createEvent("turn_aborted",$,{turnId:V.turnId,cause:"process_restart",abortedAt:M,turnsCount:0,toolCallsCount:b,durationMs:Number.isFinite(R)?Math.max(0,Date.now()-R):0,recovery:Z?{version:1,inputMessageIds:Z.inputMessageIds,hadSuccessfulToolResult:Z.hadSuccessfulToolResult,emptyFinalCorrectionSpent:Z.emptyFinalCorrectionSpent}:void 0})]:x})}catch(W){if(!(W instanceof C0))throw W}return Z}async loadLatestGoalFinalization($){let J=await this.loadEvents($);return J?_8(J):void 0}async saveInteractionRequest($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===J.requestId))throw Error(`Interaction request already exists: ${J.requestId}`);return this.createEvent("interaction_requested",$,J)})}async saveInteractionResponse($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_requested"&&V.data.requestId===J.requestId))throw Error(`Interaction request not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction already responded: ${J.requestId}`);return this.createEvent("interaction_responded",$,J)})}async saveInteractionRecovery($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="interaction_responded"&&V.data.requestId===J.requestId))throw Error(`Interaction response not found: ${J.requestId}`);if(Z.some((V)=>V.type==="interaction_recovered"&&V.data.requestId===J.requestId))throw Error(`Interaction already recovered: ${J.requestId}`);return this.createEvent("interaction_recovered",$,J)})}async saveReviewStart($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review already exists: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_started"&&!Z.some((K)=>K.type==="review_completed"&&K.data.reviewId===V.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,J)})}async saveReviewCompletion($,J){await this.ensureSessionCreated($),await this.log($).commitValidated((Z)=>{if(!Z.some((V)=>V.type==="review_started"&&V.data.reviewId===J.reviewId))throw Error(`Review not found: ${J.reviewId}`);if(Z.some((V)=>V.type==="review_completed"&&V.data.reviewId===J.reviewId))throw Error(`Review already completed: ${J.reviewId}`);return this.createEvent("review_completed",$,J)})}async saveToolUse($,J,Z,W=null,Y,V){try{if(V!==void 0&&(V.length===0||V.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let K=new Date().toISOString(),Q=W??K0(),X=[];if(!W){let j={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:K};X.push(this.createEvent("message_created",$,j))}let H=V??K0(),B={partId:H,messageId:Q,partType:"tool_call",payload:{toolCallId:H,toolName:J,input:Z},createdAt:K};if(X.push(this.createEvent("part_created",$,B)),J==="Task"&&Z&&typeof Z==="object"){let j=Z,z=typeof j.subagent_session_id==="string"?j.subagent_session_id:void 0,U=typeof j.subagent_type==="string"?j.subagent_type:void 0;if(z&&U){let A={partId:K0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:z,agentType:U,status:"running",summary:typeof j.description==="string"?j.description:"",startedAt:K},createdAt:K};X.push(this.createEvent("part_created",$,A))}}return await this.log($).commitBatch(X),H}catch(K){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,K),K}}async saveToolResult($,J,Z,W,Y=null,V,K,Q,X){try{await this.ensureSessionCreated($,K);let H=new Date().toISOString(),B=Y??K0();return await this.log($).commitValidatedBatch((j)=>{let z=Q?.subagentStatus==="running"?F0(j).findLast((x)=>x.type==="part_created"&&x.data.partType==="subtask_ref"&&x.data.payload!==null&&typeof x.data.payload==="object"&&!Array.isArray(x.data.payload)&&x.data.payload.childSessionId===Q.subagentSessionId&&(x.data.payload.status==="completed"||x.data.payload.status==="failed"||x.data.payload.status==="cancelled")):void 0,U=z?.data.payload,A=X&&typeof X==="object"&&!Array.isArray(X)?X:{},b=U?{...A,subagentSessionId:U.childSessionId,subagentType:U.agentType,description:U.description,subagentStatus:U.status,subagentSummary:U.summary,subagentResumedFrom:U.resumedFrom,subagentRootId:U.rootAgentId,subagentResumeDepth:U.resumeDepth,verificationVerdict:U.verificationVerdict}:X,M=[];if(!Y){let x={messageId:B,role:"assistant",parentMessageId:void 0,createdAt:H};M.push(this.createEvent("message_created",$,x))}let R={partId:J,messageId:B,partType:"tool_result",payload:{toolCallId:J,toolName:Z,output:W,error:V??null,...b===void 0?{}:{metadata:b}},createdAt:H};if(M.push(this.createEvent("part_created",$,R)),Q&&!z){let x=Q.subagentStatus==="running"?null:H,P={partId:K0(),messageId:B,partType:"subtask_ref",payload:{childSessionId:Q.subagentSessionId,agentType:Q.subagentType,description:Q.subagentDescription??"",status:Q.subagentStatus,summary:Q.subagentSummary??"",resumedFrom:Q.subagentResumedFrom??null,rootAgentId:Q.subagentRootId??Q.subagentSessionId,resumeDepth:Q.subagentResumeDepth??0,verificationVerdict:Q.verificationVerdict??null,startedAt:H,finishedAt:x},createdAt:H};M.push(this.createEvent("part_created",$,P))}return M}),J}catch(H){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,H),H}}async saveCompaction($,J,Z,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),V=K0(),K={messageId:V,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(Z),X={partId:K0(),messageId:V,partType:"summary",payload:{text:J,metadata:Q,...Z.replacementMessages?{replacementMessages:vJ(Z.replacementMessages)}:{}},createdAt:Y},H=[this.createEvent("message_created",$,K),this.createEvent("part_created",$,X)];return await this.log($).commitBatch(H),V}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,J){await this.ensureSessionCreated($);let Z=x1([]),W=await this.log($).commitValidatedBatch((V)=>{if(Z=x1(F0(V)),Z.kind!=="none")return[];let K=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...J,messageId:`${IJ}${K0()}`,createdAt:K})]});if(Z.kind==="valid")return{outcome:"existing",event:Z.event};if(Z.kind==="suppressed")return{outcome:"suppressed",recordId:Z.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=x1(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,J){await this.ensureSessionCreated($,J)}async loadEvents($){try{let J=y0(this.projectPath,$),W=await new k0(J).readAll();return W.length>0?F0(W):null}catch{return null}}async loadSession($){try{let J=y0(this.projectPath,$),Z=new k0(J),W=F0(await Z.readAll());if(W.length===0)return null;let Y=W.find((V)=>V.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(Y?.timestamp??W[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let J=y0(this.projectPath,$),Z=new k0(J),W=F0(await Z.readAll());if(W.length===0)return null;let Y=new Map;for(let X of W){if(X.type==="message_created")Y.set(X.data.messageId,{id:X.data.messageId,role:X.data.role,content:"",timestamp:new Date(X.timestamp).getTime()});if(X.type==="part_created"&&X.data.partType==="text"){let H=Y.get(X.data.messageId);if(H){let B=X.data.payload;H.content=B.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let H=Y.get(X.data.messageId);if(H)H.content=H.content?`${H.content}
86
- [Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=_$(this.projectPath);return(await v0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=y0(this.projectPath,$),Z=new k0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=F0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=y0(this.projectPath,$);await new k0(J).delete(),await v0.unlink(M1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await kJ(this.projectPath,$,RJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-vy4dz3yz.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=y0(this.projectPath,Z),V=await new k0(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=_$(this.projectPath);await v0.mkdir($,{recursive:!0,mode:493});let J=uJ.join($,".health-check");return await v0.writeFile(J,"test","utf-8"),await v0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return hJ()}}function b8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var cJ=131072,g2=new rJ;function p2($,J){return`${E8.resolve($)}\x00${J}`}function c2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>cJ)throw Error(`${J} exceeds ${cJ} bytes`);return JSON.parse(Z)}function lJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function T8($,J){return JSON.stringify($)===JSON.stringify(J)}function M8($,J){if($.request.interactionType!=="elicitation")return c2(J,"Interaction response");return c2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function iJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function R8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function h8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
86
+ [Image]`:"[Image]"}}let V=Array.from(Y.values()),K=W[W.length-1],Q=new Date(K.timestamp).getTime();return{messages:V,topics:[],lastActivity:Q}}catch{return null}}async listSessions(){try{let $=_$(this.projectPath);return(await v0.readdir($)).filter((Z)=>Z.endsWith(".jsonl")).map((Z)=>Z.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){try{let J=y0(this.projectPath,$),Z=new k0(J);if(!(await Z.getStats()).exists)return null;let Y=await Z.readAll();if(Y.length===0)return null;let V=F0(Y),K=Y[Y.length-1],Q=V.filter((X)=>X.type==="message_created"&&["user","assistant"].includes(X.data.role)).length;return{sessionId:$,lastActivity:new Date(K.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){this.initializedSessions.delete($);try{let J=y0(this.projectPath,$);await new k0(J).delete(),await v0.unlink(M1(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await kJ(this.projectPath,$,RJ());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-0p6qkcft.js"),V=await W();if(V)Y(V,$,this.projectPath)}catch{}}catch(J){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,J)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){try{let $=await this.listSessions();if($.length<=this.maxSessions)return;let W=(await Promise.all($.map((Y)=>this.getSessionSummary(Y)))).filter((Y)=>Y!==null).sort((Y,V)=>V.lastActivity-Y.lastActivity).slice(this.maxSessions).map((Y)=>Y.sessionId);await Promise.all(W.map((Y)=>this.deleteSession(Y))),console.log(`[PersistentStore] 已清理 ${W.length} 个旧会话`)}catch($){console.error("[PersistentStore] 清理旧会话失败:",$)}}async getStorageStats(){try{let $=await this.listSessions(),J=0;for(let Z of $){let W=y0(this.projectPath,Z),V=await new k0(W).getStats();J+=V.size}return{totalSessions:$.length,totalSize:J,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){try{let $=_$(this.projectPath);await v0.mkdir($,{recursive:!0,mode:493});let J=uJ.join($,".health-check");return await v0.writeFile(J,"test","utf-8"),await v0.unlink(J),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return hJ()}}function b8($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var cJ=131072,g2=new rJ;function p2($,J){return`${E8.resolve($)}\x00${J}`}function c2($,J){let Z=JSON.stringify($);if(Z===void 0)throw Error(`${J} is not JSON serializable`);if(Buffer.byteLength(Z,"utf8")>cJ)throw Error(`${J} exceeds ${cJ} bytes`);return JSON.parse(Z)}function lJ($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function T8($,J){return JSON.stringify($)===JSON.stringify(J)}function M8($,J){if($.request.interactionType!=="elicitation")return c2(J,"Interaction response");return c2({approved:J.approved,...J.reason?{reason:J.reason}:{},...J.elicitation?{elicitation:{action:J.elicitation.action}}:{},...J.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function iJ($){let J=$.request.details;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return J}function R8($){let J=$.response?.response;if(!J||typeof J!=="object"||Array.isArray(J))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return J}function h8($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([J,Z])=>{let W=Array.isArray(Z)?Z.join(", "):Z;return`${J}: ${W}`}).join(`
87
87
  `)}function x8($,J){let{request:Z}=$;if(Z.interactionType==="question"){let K=h8(J);return{toolOutput:`User answers:
88
88
  ${K}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
89
89
  ${K}
@@ -168,4 +168,4 @@ ${N}`}if(typeof k==="object"&&k!==null)k=JSON.stringify(k,null,2);if(typeof k===
168
168
  ${sJ(V$)}
169
169
  </system-reminder>`,metadata:V1};q.appendControl("user",w);let D=await l0($,Z,w.content,X,V1);if(D)X=D}}if(W?.signal?.aborted)return B(K,Q.length,W.signal);if(K>=w0&&(P0||Q0)){if(l.info(`Warning: 达到轮次上限 ${w0} 轮`),W?.onTurnLimitReached){let w=await W.onTurnLimitReached({turnsCount:K});if(w?.continue){q.writeback();let D="failed",_,y,c,E,f,p,k,L0,V0,C,N,a,n,j0;yield{kind:"compaction",phase:"start",reason:"turn_limit"};try{let O=$.chatService.getConfig(),O0=A(),G0=G$&&i$(q$)?O0.filter((j2)=>j2.name!=="Task"):O0,X0=p0?G0.filter((j2)=>j2.name===p0):G0,T=T2(q.systemMessages,X0,O.model),S0=F$.project({history:q.getHistory(),contextRevision:q.contextRevision,modelName:O.model,requestProfile:T});c=S0.source,E=S0.estimatedPendingTokens;let I=await E$.compact(Z.messages,{trigger:"auto",modelName:O.model,modelProvider:O.provider,maxContextTokens:O.maxContextTokens??0,apiKey:O.apiKey,baseURL:O.baseUrl,actualPreTokens:S0.contextTokens,signal:W?.signal,activeTask:b0,workspaceRoot:Z.workspaceRoot||H0(),sessionId:Z.sessionId});if(I.usage)yield{kind:"token_usage",usage:m1(I.usage,O.maxContextTokens??0)};let p4={role:"user",content:`This session is being continued from a previous conversation. The conversation is summarized above.
170
170
 
171
- Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},N6=[...I.compactedMessages,p4];_=I.success?"llm":"fallback",y=I.preTokens,f=I.postTokens,p=I.sampleAttempts,k=I.inputReductions,L0=I.messagesOmitted,V0=I.filesOmitted,C=I.imagesOmitted,N=I.fallbackTargetTokens,a=I.fallbackMessagesOmitted,n=I.fallbackMessagesTruncated,j0=I.failureReason,await o$($,Z,I.summary,{trigger:"auto",reason:"turn_limit",strategy:_,preTokens:I.preTokens,preTokenSource:S0.source,...S0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:S0.estimatedPendingTokens}:{},postTokens:I.postTokens,sampleAttempts:I.sampleAttempts,inputReductions:I.inputReductions,messagesOmitted:I.messagesOmitted,filesOmitted:I.filesOmitted,imagesOmitted:I.imagesOmitted,fallbackTargetTokens:I.fallbackTargetTokens,fallbackMessagesOmitted:I.fallbackMessagesOmitted,fallbackMessagesTruncated:I.fallbackMessagesTruncated,failureReason:I.failureReason,filesIncluded:I.filesIncluded,replacementMessages:N6},{required:$.executionEngine!==void 0}),Z.messages=N6,q.replaceHistory(Z.messages),F$.reset(),D=I.success?"completed":"fallback"}catch(O){throw l.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:_,preTokens:y,preTokenSource:c,estimatedPendingTokens:E,postTokens:f,sampleAttempts:p,inputReductions:k,messagesOmitted:L0,filesOmitted:V0,imagesOmitted:C,fallbackTargetTokens:N,fallbackMessagesOmitted:a,fallbackMessagesTruncated:n,failureReason:j0}}K=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:h}}}return{success:!1,error:{type:"max_turns_exceeded",message:Q0?`子代理已达到轮次上限 (${w0} 轮)。`:`已达到轮次上限 (${w0} 轮)。`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:h}}}}}catch(L){if(L instanceof N$)try{let F=Z.sessionId?await n$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):u;q.restoreDurableHistory(F)}catch(F){l.error("[Loop] Failed to reload durable context after message commit failure:",F),q.restoreDurableHistory(u)}throw L}finally{if(W?.transientInput==="goal_continuation")q.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});q.writeback()}}catch(j){if(i0(j))return B(K,Q.length,W?.signal);if(j instanceof N$)return{success:!1,error:{type:"message_persistence_failed",message:j.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let z=LZ(j);return l.error(`API 调用失败: ${z}`),{success:!1,error:{type:"api_error",message:z,details:j},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:O2}),await n6($,Z,X)}}export{y2 as db,c$ as eb,vZ as fb,U2 as gb,l$ as hb,R6 as ib,t4 as jb,y$ as kb,dZ as lb,M$ as mb,L2 as nb,l6 as ob,$3 as pb,r$ as qb,D0 as rb,A0 as sb,w2 as tb,q2 as ub,v6 as vb,F2 as wb,U4 as xb,D4 as yb,q4 as zb,f$ as Ab,f1 as Bb,y5 as Cb,l0 as Db,x0 as Eb,f2 as Fb,N1 as Gb,o$ as Hb,i as Ib,E$ as Jb,h1 as Kb,z0 as Lb,J9 as Mb,L4 as Nb,d1 as Ob,f4 as Pb,y4 as Qb,A4 as Rb,qZ as Sb,Z6 as Tb,h4 as Ub,RZ as Vb};
171
+ Please continue the conversation from where we left it off without asking the user any further questions. Continue with the last task that you were asked to work on.`},N6=[...I.compactedMessages,p4];_=I.success?"llm":"fallback",y=I.preTokens,f=I.postTokens,p=I.sampleAttempts,k=I.inputReductions,L0=I.messagesOmitted,V0=I.filesOmitted,C=I.imagesOmitted,N=I.fallbackTargetTokens,a=I.fallbackMessagesOmitted,n=I.fallbackMessagesTruncated,j0=I.failureReason,await o$($,Z,I.summary,{trigger:"auto",reason:"turn_limit",strategy:_,preTokens:I.preTokens,preTokenSource:S0.source,...S0.estimatedPendingTokens!==void 0?{estimatedPendingTokens:S0.estimatedPendingTokens}:{},postTokens:I.postTokens,sampleAttempts:I.sampleAttempts,inputReductions:I.inputReductions,messagesOmitted:I.messagesOmitted,filesOmitted:I.filesOmitted,imagesOmitted:I.imagesOmitted,fallbackTargetTokens:I.fallbackTargetTokens,fallbackMessagesOmitted:I.fallbackMessagesOmitted,fallbackMessagesTruncated:I.fallbackMessagesTruncated,failureReason:I.failureReason,filesIncluded:I.filesIncluded,replacementMessages:N6},{required:$.executionEngine!==void 0}),Z.messages=N6,q.replaceHistory(Z.messages),F$.reset(),D=I.success?"completed":"fallback"}catch(O){throw l.error("[Loop] 轮次上限压缩失败,停止继续执行:",O),O}finally{yield{kind:"compaction",phase:"end",reason:"turn_limit",outcome:D,strategy:_,preTokens:y,preTokenSource:c,estimatedPendingTokens:E,postTokens:f,sampleAttempts:p,inputReductions:k,messagesOmitted:L0,filesOmitted:V0,imagesOmitted:C,fallbackTargetTokens:N,fallbackMessagesOmitted:a,fallbackMessagesTruncated:n,failureReason:j0}}K=0;continue}return{success:!0,finalMessage:w?.reason||"已达到对话轮次上限,用户选择停止",metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:h}}}return{success:!1,error:{type:"max_turns_exceeded",message:Q0?`子代理已达到轮次上限 (${w0} 轮)。`:`已达到轮次上限 (${w0} 轮)。`},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V,tokensUsed:h}}}}}catch(L){if(L instanceof N$)try{let F=Z.sessionId?await n$.loadSessionModelContext(Z.sessionId,Z.workspaceRoot):u;q.restoreDurableHistory(F)}catch(F){l.error("[Loop] Failed to reload durable context after message commit failure:",F),q.restoreDurableHistory(u)}throw L}finally{if(W?.transientInput==="goal_continuation")q.removeMessages((L)=>{let F=L.metadata;return F!==null&&typeof F==="object"&&!Array.isArray(F)&&F.transientGoalContinuation===!0});q.writeback()}}catch(j){if(i0(j))return B(K,Q.length,W?.signal);if(j instanceof N$)return{success:!1,error:{type:"message_persistence_failed",message:j.message},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}};let z=LZ(j);return l.error(`API 调用失败: ${z}`),{success:!1,error:{type:"api_error",message:z,details:j},metadata:{turnsCount:K,toolCallsCount:Q.length,duration:Date.now()-V}}}finally{if(H)Z.messages.push({role:"system",content:O2}),await n6($,Z,X)}}export{y2 as eb,c$ as fb,vZ as gb,U2 as hb,l$ as ib,R6 as jb,t4 as kb,y$ as lb,dZ as mb,M$ as nb,L2 as ob,l6 as pb,$3 as qb,r$ as rb,D0 as sb,A0 as tb,w2 as ub,q2 as vb,v6 as wb,F2 as xb,U4 as yb,D4 as zb,q4 as Ab,f$ as Bb,f1 as Cb,y5 as Db,l0 as Eb,x0 as Fb,f2 as Gb,N1 as Hb,o$ as Ib,i as Jb,E$ as Kb,h1 as Lb,z0 as Mb,J9 as Nb,L4 as Ob,d1 as Pb,f4 as Qb,y4 as Rb,A4 as Sb,qZ as Tb,Z6 as Ub,h4 as Vb,RZ as Wb};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as Qi};
2
+ export{c as Ri};
@@ -0,0 +1 @@
1
+ import{He as a,Ie as b,Je as c,Ke as d,Le as e,Me as f,Ne as g,Oe as h,Pe as i,Qe as j,Re as k,Se as l,Te as m,Ue as n,Ve as o,We as p,Xe as q}from"./chunk-vchv2x9y.js";import"./chunk-v508x7cg.js";import"./chunk-3saxqsn7.js";import"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import"./chunk-b9thsjxh.js";import"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,2 +1,2 @@
1
- import{Qi as F}from"./chunk-nh45xp7r.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 Gi,z as Hi,J as Ii,A as Ji,N as Ki,O as Li,Q as Mi,T as Ni,E as Oi,U as Pi};
1
+ import{Ri as F}from"./chunk-g2yaghbk.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 Hi,z as Ii,J as Ji,A as Ki,N as Li,O as Mi,Q as Ni,T as Oi,E as Pi,U as Qi};
@@ -1,2 +1,2 @@
1
- import{Qi as K}from"./chunk-nh45xp7r.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
2
- export{P as ua,V as va,R as wa,N as xa};
1
+ import{Ri as K}from"./chunk-g2yaghbk.js";import{spawn as Y}from"node:child_process";import{constants as j}from"node:fs";import{access as x,readFile as B}from"node:fs/promises";import{createRequire as L}from"node:module";import C from"node:path";var P="blade browser install";var D=["PATH","Path","PATHEXT","HOME","USERPROFILE","LOCALAPPDATA","PROGRAMDATA","TMPDIR","TMP","TEMP","LANG","LC_ALL","LC_CTYPE","TZ","SystemRoot","SYSTEMROOT","WINDIR","COMSPEC","XDG_RUNTIME_DIR","CHROME_DEVEL_SANDBOX"],A=[...D,"PLAYWRIGHT_BROWSERS_PATH","PLAYWRIGHT_DOWNLOAD_CONNECTION_TIMEOUT","PLAYWRIGHT_DOWNLOAD_HOST","PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST","HTTP_PROXY","HTTPS_PROXY","NO_PROXY","http_proxy","https_proxy","no_proxy","NODE_EXTRA_CA_CERTS","SSL_CERT_FILE","SSL_CERT_DIR"],J=32768,M=4096;function U(f,F){let $={};for(let Z of F){let q=f[Z];if(q!==void 0&&q.length<=J)$[Z]=q}return $}function V(f=process.env){return U(f,D)}function S(f=process.env){return U(f,A)}function W(){return L(import.meta.url).resolve("playwright/package.json")}function y(f=W){return C.join(C.dirname(f()),"cli.js")}async function T(){return await import("playwright")}async function m(f){let F=JSON.parse(await B(f,"utf8"));if(typeof F.version!=="string"||F.version.length===0)throw Error("Playwright package version is invalid");return F.version}function I(f){return(f instanceof Error?f.message:String(f)).replace(/[\r\n]+/g," ").slice(0,M)}async function R(f={}){let $=(f.resolvePackageJson??W)(),Z=await m($),q=await(f.loadPlaywright??T)(),G=q.chromium.executablePath(),H=f.access??x,z;try{await H(G,j.X_OK),z=await q.chromium.launch({executablePath:G,headless:!0,chromiumSandbox:!0,env:V(f.environment)});let Q=z.version();return await z.close(),z=void 0,{playwrightVersion:Z,executablePath:G,installed:!0,browserVersion:Q}}catch(Q){return{playwrightVersion:Z,executablePath:G,installed:!1,error:I(Q)}}finally{await z?.close().catch(()=>{return})}}async function N(f={}){let F=f.resolvePackageJson??W,$=y(F),Z=f.spawn??((q,G,H)=>Y(q,[...G],H));await new Promise((q,G)=>{let H=Z(f.execPath??process.execPath,[$,"install","chromium"],{env:S(f.environment),shell:!1,stdio:"inherit"}),z=!1;H.once("error",(Q)=>{if(z)return;z=!0,G(Q)}),H.once("close",(Q,X)=>{if(z)return;if(z=!0,Q===0){q();return}G(Error(X?`Playwright browser installer stopped by ${X}`:`Playwright browser installer exited with code ${Q??1}`))})})}
2
+ export{P as va,V as wa,R as xa,N as ya};
@@ -1,4 +1,4 @@
1
- import{Fh as L,Ih as _}from"./chunk-qa4efys0.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
1
+ import{Gh as L,Jh as _}from"./chunk-mybhqpc7.js";import{execSync as F}from"child_process";import{existsSync as Q,readFileSync as O,realpathSync as b}from"fs";import*as V from"os";import*as H from"path";import{basename as J,isAbsolute as j,resolve as R}from"path";function G(z=_()){let q=z,M=f(q);return{workingDirectory:q,projectRoot:M,platform:`${V.platform()} (${V.arch()})`,nodeVersion:process.version,currentDate:new Date().toISOString().split("T")[0],homeDirectory:V.homedir()}}function Y(z,q){try{return F(q,{cwd:z,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()}catch{return null}}function v(z={}){let{includeGitSnapshot:q=!0,includeDirectoryListing:M=!0,workingDirectory:W}=z,B=G(W),$=Q(H.join(B.projectRoot,".git")),T=J(process.env.SHELL||"unknown"),A=["package.json","tsconfig.json","BLADE.md",".env.example"].filter((K)=>Q(H.join(B.projectRoot,K))).map((K)=>`- \`${H.join(B.projectRoot,K)}\``),N=`# Environment
2
2
  You have been invoked in the following environment:
3
3
  - Primary working directory: ${B.workingDirectory}
4
4
  - Is a git repository: ${$?"true":"false"}
@@ -25,4 +25,4 @@ ${I.join(`
25
25
 
26
26
  Project root directory listing:
27
27
  ${K}`}return N}function f(z){let q=z,M=null;while(q!==H.dirname(q)){if(Q(H.join(q,".git")))return q;if(Q(H.join(q,".blade")))return q;if(Q(H.join(q,".claude")))return q;if(!M&&Q(H.join(q,"package.json")))M=q;q=H.dirname(q)}return M??z}function x(z,q){let M=j(z)?z:R(q||process.cwd(),z),W;try{W=b(M)}catch{W=M}L(W)}
28
- export{v as te,f as ue,x as ve};
28
+ export{v as ue,f as ve,x as we};
@@ -1,4 +1,4 @@
1
- import{s as hz,t as Sz}from"./chunk-bss2kc28.js";import{u as b}from"./chunk-c9zd429t.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-ax8tta9d.js";import{$ as jz,G as N,O as $z,P as Qz,T as Wz,W as Yz,X as Hz,pa as Fz,qa as Uz,ra as Vz,sa as wz}from"./chunk-1t097t5f.js";import"./chunk-z5rtzcm4.js";import{Ga as Tz}from"./chunk-wj403wry.js";import{Ia as Zz}from"./chunk-8eh0vp98.js";import{Cb as zz,Lb as Jz,qb as e}from"./chunk-b12wtvac.js";import{Wb as I}from"./chunk-ya5p7mx7.js";import{Ad as s,Cd as x,Fd as t,Kd as q,Nd as U,_c as l,id as i,jd as r,od as a,rd as o,td as n,zd as C}from"./chunk-tw63vfgh.js";import"./chunk-gbsxnvgg.js";import"./chunk-4jbpvete.js";import{qe as Mz}from"./chunk-4n4a3vm2.js";import"./chunk-ztp2ff01.js";import{Le as Nz,Me as Ez}from"./chunk-ggf76jxn.js";import"./chunk-v508x7cg.js";import{Xe as f}from"./chunk-zj4kfyer.js";import{af as v}from"./chunk-0eqk29xr.js";import"./chunk-rxbxvq67.js";import{lf as xz}from"./chunk-z6xfknxe.js";import"./chunk-gnffwz1c.js";import"./chunk-kpxz0hbg.js";import"./chunk-yjh47zv6.js";import{bg as bz}from"./chunk-rsh4rw9k.js";import"./chunk-4cvmfne8.js";import"./chunk-q74xmdkf.js";import"./chunk-74yge4ka.js";import{Vg as qz,Yg as Pz}from"./chunk-xzzrtwjx.js";import"./chunk-t48zm299.js";import"./chunk-7dqh8bqm.js";import{Ah as S,Bh as d,Dh as M,Eh as k}from"./chunk-d83bfr0b.js";import{Ih as Oz}from"./chunk-qa4efys0.js";import"./chunk-hrfh7wck.js";import{ii as T}from"./chunk-h4j0nve8.js";import"./chunk-w63dfcx5.js";import{pi as Az,si as Rz}from"./chunk-n4gtzx4x.js";import"./chunk-5j0b62sr.js";import"./chunk-rzja9zza.js";import"./chunk-dd99sgf8.js";import{Oi as m}from"./chunk-na1cney5.js";import"./chunk-nh45xp7r.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
1
+ import{s as hz,t as Sz}from"./chunk-3229684w.js";import{u as b}from"./chunk-8htbttg5.js";import{A as Gz,v as yz,w as Xz,x as Dz,y as Lz,z as Bz}from"./chunk-2mwgykjs.js";import{G as N,P as $z,Q as Qz,U as Wz,X as Yz,Y as Hz,aa as jz,qa as Fz,ra as Uz,sa as Vz,ta as wz}from"./chunk-825r9sfe.js";import"./chunk-j1t2qedg.js";import{Ha as Tz}from"./chunk-cvpvncza.js";import{Ja as Zz}from"./chunk-n407vvwt.js";import{Db as zz,Mb as Jz,rb as e}from"./chunk-g2hxj68b.js";import{Xb as I}from"./chunk-8hprmrd5.js";import{$c as l,Ad as C,Bd as s,Dd as x,Gd as t,Ld as q,Od as U,jd as i,kd as r,pd as a,sd as o,ud as n}from"./chunk-6qxzcx0a.js";import"./chunk-7wtbhnfr.js";import"./chunk-7bhk8qk5.js";import{re as Mz}from"./chunk-sdvfyzv0.js";import"./chunk-jy4s51bt.js";import{Me as Nz,Ne as Ez}from"./chunk-vchv2x9y.js";import"./chunk-v508x7cg.js";import{Ye as f}from"./chunk-3saxqsn7.js";import{bf as v}from"./chunk-31g86axj.js";import"./chunk-a1vhp8sa.js";import{mf as xz}from"./chunk-88mf53ak.js";import"./chunk-qhsmhx0y.js";import"./chunk-csr9d8yx.js";import"./chunk-q5t2rnx0.js";import{cg as bz}from"./chunk-9mnspb2d.js";import"./chunk-dretwm9j.js";import"./chunk-s47ypj8n.js";import"./chunk-xtm0sp0k.js";import{Wg as qz,Zg as Pz}from"./chunk-88ykfsbv.js";import"./chunk-0v74fhhc.js";import"./chunk-s36efnxd.js";import{Bh as S,Ch as d,Eh as M,Fh as k}from"./chunk-b9thsjxh.js";import{Jh as Oz}from"./chunk-mybhqpc7.js";import"./chunk-2c2cxrc0.js";import{ji as T}from"./chunk-zvms9ap7.js";import"./chunk-fm93hym6.js";import{qi as Az,ti as Rz}from"./chunk-t5es94zk.js";import"./chunk-v2bvrk83.js";import"./chunk-c6p5mj1k.js";import"./chunk-zyfacwgn.js";import{Pi as m}from"./chunk-h5xw792m.js";import"./chunk-g2yaghbk.js";import{Readable as vz,Writable as lz}from"node:stream";import*as y from"@agentclientprotocol/sdk";import _z from"node:path";import{PROTOCOL_VERSION as mz,RequestError as dz}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=T("Agent");function p(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function fz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:p(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:p("headers"in z?z.headers:void 0)};return null}function uz(z){let Z={};for(let J of z){let Y=fz(J);if(Y)Z[J.name]=Y}return Z}function Kz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function gz(z){let Z=s(z.metadata);return Z?[{type:"text",text:C(Z)}]:Kz(z.content)}function cz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
2
2
  `)}function pz(z){if(!v(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...i("capacity"),resource:z.resource}}class E{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,Y,H={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode),this.updateEgress=new Gz({maxPendingItems:Xz,maxPendingBytes:Dz,writeTimeoutMs:Lz,signal:J.signal,sizeOf:(W)=>Buffer.byteLength(JSON.stringify(W)),write:async(W)=>{await J.sessionUpdate(W)},onFailure:(W)=>this.handleUpdateEgressFailure(W)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([U.loadSession(this.id,this.cwd),U.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await U.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...z]}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return jz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await U.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?uz(this.options.mcpServers):void 0,J=N.getInstance().getTerminalService(this.id);if(this.runtime=await Wz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(W,Q)=>{let j=await J.execute(W,{cwd:Q.cwd,env:Q.env,timeout:Q.timeoutMs,signal:Q.signal,allowLocalFallback:!1,onOutput:(D)=>Q.onOutput?.("stdout",D)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await b.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Uz(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=e.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.schedulePendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:Q,messageId:j,content:D}=W.properties,X=W.properties.metadata;if(W.type==="team.message.received"&&typeof Q==="string"&&typeof j==="string"&&typeof D==="string"&&Qz(X,{messageId:j,teamName:Q}))(async()=>{let L=await this.runtime?.enqueueSteering(D,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:X});if(!L?.accepted)return;if(await new $z(Q,m()).markDelivered([j]),L.delivery==="next_turn")this.schedulePendingResume()})().catch((L)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,L)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!n(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let Y of gz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await this.runtime.rewindSession(Q);return this.messages=[...j.messages],this.contextMessages=await this.loadModelContextOr(j.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),j}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=!1,X,L=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},F=this.runtime.resumeSubagent({agentId:Q,prompt:j,onCompleted:(B)=>{if(D)L(B);else X=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.session.id,status:"in_progress",title:`Resuming ${F.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${F.source.id} at depth ${F.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),D=!0,X)L(X);return F}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,j,D)},complete:async(Q,j,D)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,j,D)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,j)},getLogs:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,j)},setLoggingLevel:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,j)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:j})}},codeReview:{run:async(Q,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let D=await b.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:j,onEvent:(F)=>{if(F.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.toolCall.id,status:"in_progress",title:`Review: ${F.toolCall.function.name}`,content:[],kind:this.mapToolKind(F.toolKind)});else if(F.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.toolCall.id,status:F.result.success?"completed":"failed",content:[]})}}),X=await D.completion,L=(await b.list(this.cwd,this.id)).find((F)=>F.start.reviewId===D.reviewId);if(!L)throw Error(`Review not found: ${D.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:D.reviewId,status:X.status,findings:X.findings.length,content:l(L.start,X)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,j,D)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(D);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(j,null,2)}}],kind:L})},sendToolResult:(Q,j)=>{if(j.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:j.summary}})}}},Y=await Vz(z,J),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await U.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let W=Y.content||Y.message;if(W)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,Y=new Promise((H)=>{J=H});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,Z.signal)}catch(H){if(Z.signal.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};throw H}finally{if(J(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z)this.pendingSideConversation=null}}async sendAvailableCommands(){try{let z=wz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],Y=z.filter((H)=>!Z.includes(H.name)&&(H.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((H)=>{let W;if(H.usage){let Q=H.usage.replace(/^\/\w+\s*/,"").trim();if(Q)W=Q}if(H.aliases?.length){let Q=`Aliases: ${H.aliases.join(", ")}`;W=W?`${W} | ${Q}`:Q}return{name:H.name,description:H.description,input:W?{hint:W}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),Y=J.content,H=J.displayText,W=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((B)=>B.outputSchema)?.outputSchema:void 0),Q;if(W!==void 0)Q=t(W).schema;if(H.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}let j=Zz(H);if(j){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((B)=>B.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(j.question?`/btw ${j.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let B=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!B.accepted)throw Error(B.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${B.queued})`),B.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let D=new AbortController,X=!1,L,F=new Promise((B)=>{L=B});this.pendingPrompt=D,this.pendingPromptCompletion=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),Fz(H)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,D.signal)}let B={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:D.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},A=await zz(this.agent.chatStream(Y,B,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{let V=$.toolCall,O=V.function.name;if(O===x)break;let R=this.mapToolKind($.toolKind),w=`Executing ${O}`;if(O==="Task"&&"function"in V)try{let P=JSON.parse(V.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")w=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:R});break}case"tool_progress":{let V=$.toolCall;if(V.function.name===x)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{let V=$.toolCall;if(V.function.name===x)break;let O=$.result,R=[],w=O.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let K of w.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;R.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))R.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let K=V.function.name,kz=Hz(o(Yz(K,O),a));R.push({type:"content",content:{type:"text",text:kz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))R.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let P=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:P,content:R});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
@@ -1 +1 @@
1
- import{ua as h,wa as f,xa as k}from"./chunk-z5rtzcm4.js";import"./chunk-nh45xp7r.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
1
+ import{va as h,xa as f,ya as k}from"./chunk-j1t2qedg.js";import"./chunk-g2yaghbk.js";var p={command:"status",describe:"Check the pinned Playwright Chromium installation",handler:async()=>{let c=await f();if(console.log(`Playwright: ${c.playwrightVersion}`),console.log(`Chromium executable: ${c.executablePath}`),!c.installed){console.error(`Chromium: unavailable (${c.error??"unknown error"})`),console.error(`Install with: ${h}`),process.exitCode=1;return}console.log(`Chromium: ${c.browserVersion}`),console.log("Status: ready")}},q={command:"install",describe:"Install Chromium for the pinned Playwright runtime",handler:async()=>{try{await k();let c=await f();if(!c.installed)throw Error(c.error??"Chromium is not runnable after installation");console.log(`Chromium installed: Playwright ${c.playwrightVersion}, ${c.browserVersion}`)}catch(c){console.error(`Browser installation failed: ${c instanceof Error?c.message:String(c)}`),process.exitCode=1}}},x={command:"browser",describe:"Manage the native Browser Tool runtime",builder:(c)=>c.command(p).command(q).demandCommand(1).strict(),handler:()=>{return}};export{p as browserStatusCommand,q as browserInstallCommand,x as browserCommands};
@@ -1,2 +1,2 @@
1
1
  import{realpathSync as z}from"fs";import{cwd as F}from"process";var u=null;function G(){let m="";if(typeof process<"u"&&typeof process.cwd==="function"&&typeof z==="function"){let x=F();try{m=z(x).normalize("NFC")}catch{m=x.normalize("NFC")}}return{cwd:m,originalCwd:m,projectRoot:m}}function q(){if(!u)u=G();return u}function B(){return q().cwd}function N(m){q().cwd=m.normalize("NFC")}function D(){return q().originalCwd}function P(m){q().projectRoot=m.normalize("NFC")}import{AsyncLocalStorage as H}from"async_hooks";var I=new H;function J(){return I.getStore()??B()}function V(){try{return J()}catch{return D()}}
2
- export{N as Fh,D as Gh,P as Hh,V as Ih};
2
+ export{N as Gh,D as Hh,P as Ih,V as Jh};
@@ -0,0 +1,2 @@
1
+ import{Ah as Z,xh as Q,yh as X,zh as U}from"./chunk-s36efnxd.js";import{Bh as N,Ch as h,Eh as d}from"./chunk-b9thsjxh.js";import{ji as a}from"./chunk-zvms9ap7.js";import{Pi as i}from"./chunk-h5xw792m.js";var b=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],T={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},E=new Map;function D($,J,K){let B=new Set;for(let W of $.split(",")){let[Y,O]=W.split("/"),V=O?Number.parseInt(O,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${$}"`);let j=J,H=K;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[k,r]=Y.split("-");j=Number.parseInt(k,10),H=Number.parseInt(r,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<J||H>K||j>H)throw Error(`Invalid cron range "${Y}" in field "${$}"`);for(let k=j;k<=H;k+=V)B.add(k)}return B}function R($){let J=$.trim().split(/\s+/);if(J.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${J.length}`);let[K,B,W,Y,O]=J,V=D(O,b[4].min,b[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(K,b[0].min,b[0].max),hours:D(B,b[1].min,b[1].max),daysOfMonth:D(W,b[2].min,b[2].max),months:D(Y,b[3].min,b[3].max),daysOfWeek:j,domRestricted:W.trim()!=="*",dowRestricted:O.trim()!=="*"}}function y($,J){if(!J)return{minute:$.getMinutes(),hour:$.getHours(),dayOfMonth:$.getDate(),month:$.getMonth()+1,dayOfWeek:$.getDay()};let K=E.get(J);if(!K)K=new Intl.DateTimeFormat("en-US",{timeZone:J,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),E.set(J,K);let B=Object.fromEntries(K.formatToParts($).filter((W)=>W.type!=="literal").map((W)=>[W.type,W.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:T[B.weekday]??-1}}function p($,J,K){let B=y(J,K);if(!$.minutes.has(B.minute))return!1;if(!$.hours.has(B.hour))return!1;if(!$.months.has(B.month))return!1;let W=$.daysOfMonth.has(B.dayOfMonth),Y=$.daysOfWeek.has(B.dayOfWeek);if($.domRestricted&&$.dowRestricted)return W||Y;if($.domRestricted)return W;if($.dowRestricted)return Y;return!0}function e($,J,K){let B=R($),W=new Date(J.getTime());W.setSeconds(0,0),W.setMinutes(W.getMinutes()+1);let Y=new Date(J.getTime());Y.setFullYear(Y.getFullYear()+4);while(W.getTime()<=Y.getTime()){if(p(B,W,K))return new Date(W.getTime());W.setMinutes(W.getMinutes()+1)}return null}var S={s:1000,m:60000,h:3600000,d:86400000};function F1($){let K=$.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!K)return null;let B=Number.parseInt(K[1],10);if(!Number.isInteger(B)||B<=0)return null;let W=K[2]||"m";return B*S[W]}function Q1($){for(let J of["d","h","m","s"]){let K=S[J];if($%K===0)return`${$/K}${J}`}return`${Math.round($/1000)}s`}function F($,J,K){switch($.kind){case"cron":{if(!$.cron)return null;try{return e($.cron,J,$.timezone)}catch{return null}}case"interval":{if(!$.intervalMs||$.intervalMs<=0)return null;let W=new Date((K??J).getTime()+$.intervalMs);return W.getTime()<=J.getTime()?new Date(J.getTime()+1000):W}case"once":{if(!$.runAt)return null;let B=new Date($.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>J.getTime()?B:null}default:return null}}function z($){switch($.kind){case"cron":if(!$.cron)return"cron trigger requires a cron expression";try{if(R($.cron),$.timezone)new Intl.DateTimeFormat("en-US",{timeZone:$.timezone}).format();return null}catch(J){return J instanceof Error?J.message:"invalid cron expression"}case"interval":if(!$.intervalMs||$.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!$.runAt)return"once trigger requires runAt timestamp";let J=new Date($.runAt);if(Number.isNaN(J.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function z1($){switch($.kind){case"cron":return`cron: ${$.cron??"?"}`;case"interval":return`every ${$.intervalMs?Q1($.intervalMs):"?"}`;case"once":return`once at ${$.runAt??"?"}`;default:return"unknown"}}import{mkdir as P1,readFile as I1}from"node:fs/promises";import t from"node:path";import{nanoid as L1}from"nanoid";import D1 from"write-file-atomic";var l=16384;function v1($){let J=/^\s*\/btw(?:\s+([\s\S]*))?\s*$/iu.exec($);if(!J)return;return{question:(J[1]??"").trim()}}var w=X(Z(["default","autoEdit","yolo","plan"]));var v=X(Z(["user","assistant","system","tool"])),$1=X(Q.Union([Q.Object({type:Q.Literal("text"),text:Q.String()}),Q.Object({type:Q.Literal("image_url"),image_url:Q.Object({url:Q.String()})})])),m=Q.Union([Q.String(),Q.Array($1)]),R1=X(Q.Object({id:Q.String(),role:v,content:m,timestamp:Q.Number(),metadata:Q.Optional(Q.Record(Q.String(),Q.Unknown())),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),J1=X(Z(["queued","running","completed","failed","cancelled","interrupted"])),A=X(Z(["local","worktree"])),x=X(Z(["high","medium","low"])),C=X(Z(["feature","bug","maintenance","research"])),X1=X(Z(["applied","discarded","conflicted"])),Z1=X(Q.Object({status:X1,updatedAt:Q.String(),sourceCommit:Q.Optional(Q.String()),changedFiles:Q.Optional(Q.Integer({minimum:0})),message:Q.Optional(Q.String())})),B1=X(Q.Object({changedFiles:Q.Integer({minimum:0}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),commits:Q.Integer({minimum:0})})),K1=X(Q.Object({path:Q.String({minLength:1}),patch:Q.String({maxLength:2097152}),additions:Q.Integer({minimum:0}),deletions:Q.Integer({minimum:0}),binary:Q.Boolean(),truncated:Q.Boolean()})),S1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),baseCommit:Q.String(),files:Q.Array(K1,{maxItems:100}),truncated:Q.Boolean()})),W1=Q.Union([Q.String(),Q.Number(),Q.Boolean(),Q.Array(Q.String())]),Y1=X(Q.Object({name:Q.String(),type:Z(["string","number","integer","boolean","select","multi-select"]),title:Q.String(),description:Q.Optional(Q.String()),required:Q.Boolean(),defaultValue:Q.Optional(W1),options:Q.Optional(Q.Array(Q.Object({value:Q.String(),label:Q.String()}))),format:Q.Optional(Z(["date","uri","email","date-time"])),minimum:Q.Optional(Q.Number()),maximum:Q.Optional(Q.Number()),minLength:Q.Optional(Q.Number()),maxLength:Q.Optional(Q.Number()),minItems:Q.Optional(Q.Number()),maxItems:Q.Optional(Q.Number())})),l1=X(Q.Object({serverName:Q.String(),mode:Z(["form","url"]),message:Q.String(),fields:Q.Optional(Q.Array(Y1)),requestedSchema:Q.Optional(Q.Record(Q.String(),Q.Unknown())),url:Q.Optional(Q.String()),domain:Q.Optional(Q.String()),elicitationId:Q.Optional(Q.String())})),H1=X(Q.Object({type:Z(["permission","question","elicitation"]),requestId:Q.String()})),j1=X(Q.Object({code:Z(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","workspace_unavailable","capacity","runtime"]),message:Q.String({minLength:1,maxLength:500}),retryable:Q.Boolean(),resource:Q.Optional(Z(["pending_count","pending_bytes","resident_runtimes"]))})),M=X(Z(["auto","off","minimal","low","medium","high","xhigh","max"])),P=X(Z(["auto","standard","fast","flex"])),I=X(Z(["auto","low","medium","high"])),G=X(Q.Union([Z(["auto","pragmatic","friendly","explanatory"]),Q.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),_=X(Q.Object({sessionId:Q.String(),projectPath:Q.String(),title:Q.Optional(Q.String()),gitBranch:Q.Optional(Q.String()),rootId:Q.String(),parentId:Q.Optional(Q.String()),relationType:Q.Optional(Z(["subagent","fork"])),resumedFrom:Q.Optional(Q.String()),rootAgentId:Q.Optional(Q.String()),resumeDepth:Q.Optional(Q.Integer({minimum:0})),taskStatus:U(J1,"completed"),taskStatusReason:Q.Optional(Q.String()),taskFailure:Q.Optional(j1),taskStartedAt:Q.Optional(Q.String()),taskCompletedAt:Q.Optional(Q.String()),taskPromptSummary:Q.Optional(Q.String()),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.String()),taskModelId:Q.Optional(Q.String()),selectedModelId:Q.Optional(Q.String()),permissionMode:Q.Optional(w),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),communicationStyleDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:Q.Optional(Q.Boolean()),taskRetriedFrom:Q.Optional(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),taskDelivery:Q.Optional(Z1),taskIsolation:Q.Optional(A),taskSourceProjectPath:Q.Optional(Q.String()),taskWorktreePath:Q.Optional(Q.String()),taskWorktreeBranch:Q.Optional(Q.String()),taskBaseCommit:Q.Optional(Q.String()),taskDiffStat:Q.Optional(B1),taskQueuePosition:Q.Optional(Q.Integer({minimum:1})),taskQueueDepth:Q.Optional(Q.Integer({minimum:0})),taskConcurrencyLimit:Q.Optional(Q.Integer({minimum:1})),archivedAt:Q.Optional(Q.String()),archivedBySessionId:Q.Optional(Q.String()),pendingInteraction:Q.Optional(H1),messageCount:Q.Number(),firstMessageTime:Q.String(),lastMessageTime:Q.String(),hasErrors:Q.Boolean()})),u1=X(Q.Object({sessions:Q.Array(_),nextCursor:Q.Optional(Q.String())})),h1=X(Q.Object({session:_,archivedSessionIds:Q.Array(Q.String())})),d1=X(Q.Object({session:_,restoredSessionIds:Q.Array(Q.String())})),m1=X(Q.Object({version:Q.Literal(1),sessionId:Q.String(),goalId:Q.String(),objective:Q.String(),status:Z(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:Q.Optional(Q.Number()),tokensUsed:Q.Number(),timeUsedSeconds:Q.Number(),continuationCount:Q.Number(),statusReason:Q.Optional(Q.String()),completionVerification:Q.Optional(Q.Object({attempt:Q.Integer({minimum:1}),status:Z(["pending","pass","fail","partial"]),requestedAt:Q.String(),completedAt:Q.Optional(Q.String()),verifierSessionId:Q.Optional(Q.String()),summary:Q.Optional(Q.String()),evidenceSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),prematureStop:Q.Optional(Q.Object({pattern:Q.Unsafe({type:"string"}),consecutiveCount:Q.Integer({minimum:1}),detectedAt:Q.String()})),verificationStall:Q.Optional(Q.Unsafe({type:"object"})),createdAt:Q.String(),updatedAt:Q.String()})),c=X(Q.Object({role:v,content:m,metadata:Q.Optional(Q.Unknown()),reasoningContent:Q.Optional(Q.String()),thinkingContent:Q.Optional(Q.String()),tool_call_id:Q.Optional(Q.String()),name:Q.Optional(Q.String()),tool_calls:Q.Optional(Q.Unknown())})),c1=X(Q.Object({session:_,messages:Q.Array(c)})),n=X(Z(["conversation","code","both"])),U1=X(Q.Object({messageId:Q.String(),preview:Q.String(),createdAt:Q.String(),fileCount:Q.Integer({minimum:0})})),n1=X(Q.Object({targetMessageId:Q.String({minLength:1}),mode:U(n,"conversation")})),g1=X(Q.Object({checkpoint:U1,mode:n,removedTurns:Q.Integer({minimum:1}),restoredFiles:Q.Array(Q.String()),messages:Q.Array(c)})),k1=Z(["running","completed","failed","cancelled"]),u=X(Q.Object({id:Q.String(),subagentType:Q.String(),description:Q.String(),status:k1,background:Q.Boolean(),rootAgentId:Q.String(),resumedFrom:Q.Optional(Q.String()),resumeDepth:Q.Integer({minimum:0}),createdAt:Q.Number(),lastActiveAt:Q.Number(),completedAt:Q.Optional(Q.Number()),restartRecovery:Q.Optional(Q.Object({outcome:Z(["completed","interrupted","failed"]),recoveredAt:Q.Number()})),result:Q.Optional(Q.Object({success:Q.Boolean(),message:Q.String(),error:Q.Optional(Q.String()),verificationCommands:Q.Optional(Q.Array(Q.String())),verificationVerdict:Q.Optional(Z(["pass","fail","partial"])),modifiedFiles:Q.Optional(Q.Array(Q.String()))})),stats:Q.Optional(Q.Object({tokens:Q.Optional(Q.Number()),toolCalls:Q.Optional(Q.Number()),duration:Q.Optional(Q.Number())}))})),o1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"})})),s1=X(Q.Object({source:u,session:u})),i1=X(Q.Object({sessionId:Q.String(),projectPath:Q.String()})),a1=X(Q.Object({path:Q.String(),name:Q.String(),gitBranch:Q.Optional(Q.String()),available:Q.Boolean(),isCurrent:Q.Boolean(),boundAt:Q.String()})),t1=X(Q.Union([Q.Object({cancelled:Q.Literal(!0)}),Q.Object({cancelled:Q.Literal(!1),path:Q.String({minLength:1})})])),r1=X(Q.Object({type:Q.String(),seq:Q.Optional(Q.Number()),properties:Q.Record(Q.String(),Q.Unknown())})),g=Q.Object({type:Z(["file","image","url"]),path:Q.Optional(Q.String()),url:Q.Optional(Q.String()),content:Q.Optional(Q.String({maxLength:h})),mimeType:Q.Optional(Q.String()),name:Q.Optional(Q.String())}),o=Q.Record(Q.String(),Q.Unknown()),T1=X(Q.Object({prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:U(x,"medium"),taskKind:U(C,"feature"),taskDueAt:Q.Optional(Q.String({minLength:1,maxLength:64})),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),y1=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),taskPriority:Q.Optional(x),taskKind:Q.Optional(C),taskDueAt:Q.Optional(Q.Union([Q.String({minLength:1,maxLength:64}),Q.Null()]))})),p1=X(Q.Object({session:_,runId:Q.String(),messageId:Q.String(),status:Z(["queued","running"]),queuePosition:Q.Optional(Q.Integer({minimum:1})),queueDepth:Q.Optional(Q.Integer({minimum:0})),maxConcurrentTasks:Q.Optional(Q.Integer({minimum:1}))})),e1=X(Q.Object({action:Z(["apply","discard"])})),q=X(Q.Object({kind:Z(["cron","interval","once"]),cron:Q.Optional(Q.String({minLength:1,maxLength:120})),intervalMs:Q.Optional(Q.Integer({minimum:60000})),runAt:Q.Optional(Q.String({minLength:1,maxLength:40})),timezone:Q.Optional(Q.String({minLength:1,maxLength:80}))})),O1=X(Q.Object({modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default")})),f=X(Q.Object({id:Q.String(),title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,dispatch:O1,enabled:Q.Boolean(),createdAt:Q.String(),updatedAt:Q.String(),nextRunAt:Q.Union([Q.String(),Q.Null()]),expiresAt:Q.Union([Q.String(),Q.Null()]),lastRunAt:Q.Optional(Q.String()),lastRunSessionId:Q.Optional(Q.String()),lastStatus:Q.Optional(Z(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:Q.Optional(Q.String()),runCount:Q.Integer({minimum:0})})),QQ=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:Q.String({minLength:1}),trigger:q,modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:U(A,"worktree"),permissionMode:U(w,"default"),enabled:U(Q.Boolean(),!0)})),$Q=X(Q.Object({title:Q.Optional(Q.String({minLength:1,maxLength:200})),prompt:Q.Optional(Q.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:Q.Optional(q),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),isolation:Q.Optional(A),permissionMode:Q.Optional(w),enabled:Q.Optional(Q.Boolean())})),JQ=X(Q.Object({schedules:Q.Array(f)})),XQ=X(Q.Object({content:Q.String({maxLength:d}),projectPath:Q.Optional(Q.String()),modelId:Q.Optional(Q.String({minLength:1,maxLength:500})),reasoningEffort:Q.Optional(M),serviceTier:Q.Optional(P),responseVerbosity:Q.Optional(I),communicationStyle:Q.Optional(G),permissionMode:Q.Optional(w),attachments:Q.Optional(Q.Array(g,{maxItems:N})),outputSchema:Q.Optional(o)})),V1=Z(["completed","failed","aborted","timed_out","spawn_error"]),b1=X(Q.Object({version:Q.Literal(1),command:Q.String(),status:V1,exitCode:Q.Union([Q.Integer(),Q.Null()]),durationMs:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),stdoutOmittedBytes:Q.Integer({minimum:0}),stderrOmittedBytes:Q.Integer({minimum:0}),binaryOutput:Q.Boolean(),truncated:Q.Boolean()})),ZQ=X(Q.Object({command:Q.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),BQ=X(Q.Object({executionId:Q.String(),messageId:Q.String(),record:b1,auxiliary:Q.Boolean(),delivery:Q.Optional(Z(["current_turn","next_turn"])),queued:Q.Optional(Q.Integer({minimum:0}))})),KQ=X(Q.Object({question:Q.String({minLength:1,maxLength:l,pattern:"^(?![\\s\\S]*\\x00)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:Q.Optional(Q.String())})),WQ=X(Q.Object({response:Q.String({minLength:1}),durationMs:Q.Number({minimum:0}),modelId:Q.Optional(Q.String()),usage:Q.Optional(Q.Object({promptTokens:Q.Number({minimum:0}),completionTokens:Q.Number({minimum:0}),totalTokens:Q.Number({minimum:0}),reasoningTokens:Q.Optional(Q.Number({minimum:0})),cacheCreationInputTokens:Q.Optional(Q.Number({minimum:0})),cacheReadInputTokens:Q.Optional(Q.Number({minimum:0})),costUsd:Q.Optional(Q.Number({minimum:0}))}))})),YQ=X(Q.Object({projectPath:Q.String(),kind:Z(["uncommitted","base","commit"]),ref:Q.Optional(Q.String({maxLength:200})),instructions:Q.Optional(Q.String({maxLength:4000})),modelId:Q.Optional(Q.String({minLength:1,maxLength:200}))})),HQ=X(Q.Object({reviewId:Q.String(),status:Q.Literal("running")})),jQ=X(Q.Object({messageId:Q.String(),role:v,content:Q.String(),timestamp:Q.String()})),UQ=X(Q.Object({approved:Q.Boolean(),remember:Q.Optional(Q.Boolean()),scope:Q.Optional(Z(["once","session","project"])),targetMode:Q.Optional(w),feedback:Q.Optional(Q.String()),answers:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String(),Q.Array(Q.String())]))),elicitation:Q.Optional(Q.Object({action:Z(["accept","decline","cancel"]),content:Q.Optional(Q.Record(Q.String(),Q.Union([Q.String({maxLength:4000}),Q.Number(),Q.Boolean(),Q.Array(Q.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),G1=X(Q.Object({id:G,name:Q.String({minLength:1,maxLength:80}),description:Q.String({minLength:1,maxLength:256}),source:Z(["built-in","user","project","plugin"]),contentSha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))})),kQ=X(Q.Object({id:Q.String(),displayName:Q.Optional(Q.String()),provider:Q.String(),model:Q.String(),contextWindow:Q.Optional(Q.Number()),maxTokens:Q.Optional(Q.Number()),reasoning:Q.Optional(Q.Boolean()),supportedReasoningEfforts:Q.Optional(Q.Array(Z(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:Q.Optional(Q.Array(Z(["standard","fast","flex"]))),supportedResponseVerbosities:Q.Optional(Q.Array(Z(["low","medium","high"]))),communicationStyles:Q.Optional(Q.Array(G1,{maxItems:36})),input:Q.Optional(Q.Array(Z(["text","image"]))),overrides:Q.Optional(Q.Object({baseUrl:Q.Optional(Q.String()),temperature:Q.Optional(Q.Number()),maxOutputTokens:Q.Optional(Q.Number()),timeout:Q.Optional(Q.Number()),streamIdleTimeout:Q.Optional(Q.Number({minimum:1000}))}))})),OQ=X(Z(["vs-dark","vs-light","hc-black"])),w1=X(Z(["light","dark","system"])),M1=X(Q.Object({language:Q.String(),codeTheme:Q.String(),uiTheme:w1,autoSaveSessions:Q.Boolean(),notifyBuild:Q.Boolean(),notifyErrors:Q.Boolean(),notifySounds:Q.Boolean(),privacyTelemetry:Q.Boolean(),privacyCrash:Q.Boolean(),agentTeamsEnabled:Q.Boolean(),communicationStyle:Q.Optional(G)})),VQ=X(Q.Partial(M1));var s=a("Service"),A1=1;function _1(){return t.join(i(),"schedules.json")}class L{filePath;static instance;static getInstance(){if(!L.instance)L.instance=new L;return L.instance}writeChain=Promise.resolve();constructor($=_1()){this.filePath=$}async readFile(){try{let $=await I1(this.filePath,"utf-8"),J=JSON.parse($);if(!J||!Array.isArray(J.schedules))return[];let K=[],B=0;for(let W of J.schedules){let Y=f.safeParse(W);if(Y.success)K.push(Y.data);else B+=1}if(B>0)s.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return K}catch($){let J=$;if(J.code!=="ENOENT")s.warn("[ScheduleStore] Failed to read schedules; treating as empty:",J);return[]}}async writeFile($){await P1(t.dirname(this.filePath),{recursive:!0,mode:493});let J={version:A1,schedules:$};await D1(this.filePath,JSON.stringify(J,null,2),{mode:384})}serializeWrite($){let J=this.writeChain.then($,$);return this.writeChain=J.then(()=>{return},()=>{return}),J}async list(){return this.readFile()}async get($){return(await this.readFile()).find((K)=>K.id===$)}async create($){return this.serializeWrite(async()=>{let J=$.trigger.kind==="cron"&&!$.trigger.timezone?{...$.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:$.trigger,K=z(J);if(K)throw Error(K);let B=new Date;if(J.kind==="once"&&new Date(J.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let W=B.toISOString(),Y=F(J,B),O={id:L1(10),title:$.title,prompt:$.prompt,projectPath:$.projectPath,trigger:J,dispatch:{modelId:$.modelId,reasoningEffort:$.reasoningEffort,serviceTier:$.serviceTier,responseVerbosity:$.responseVerbosity,communicationStyle:$.communicationStyle,isolation:$.isolation??"worktree",permissionMode:$.permissionMode??"default"},enabled:$.enabled??!0,createdAt:W,updatedAt:W,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(O),await this.writeFile(V),O})}async update($,J){return this.serializeWrite(async()=>{let K=await this.readFile(),B=K.findIndex((H)=>H.id===$);if(B===-1)return;let W=K[B];if(J.trigger){let H=J.trigger.kind==="cron"&&!J.trigger.timezone?{...J.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:J.trigger,k=z(H);if(k)throw Error(k);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");J={...J,trigger:H}}let Y={...W,...J,dispatch:J.dispatch?{...W.dispatch,...J.dispatch}:W.dispatch,updatedAt:new Date().toISOString()},O=!W.enabled,V=Y.enabled,j=J.trigger!==void 0;if((j||O&&V)&&J.nextRunAt===void 0){let H=new Date,k=F(Y.trigger,H);if(Y.nextRunAt=k?k.toISOString():null,j)Y.expiresAt=null}return K[B]=Y,await this.writeFile(K),Y})}async remove($){return this.serializeWrite(async()=>{let J=await this.readFile(),K=J.filter((B)=>B.id!==$);if(K.length===J.length)return!1;return await this.writeFile(K),!0})}async setEnabled($,J){return this.update($,{enabled:J})}}var NQ=L.getInstance();
2
+ export{l as Ia,v1 as Ja,F1 as Ka,F as La,z as Ma,z1 as Na,S1 as Oa,_ as Pa,n1 as Qa,o1 as Ra,T1 as Sa,y1 as Ta,p1 as Ua,e1 as Va,f as Wa,QQ as Xa,$Q as Ya,JQ as Za,XQ as _a,ZQ as $a,KQ as ab,YQ as bb,L as cb,NQ as db};
@@ -1 +1 @@
1
- import{h as o}from"./chunk-5vg1dwh1.js";import"./chunk-5j0b62sr.js";import"./chunk-nh45xp7r.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
1
+ import{h as o}from"./chunk-630jj776.js";import"./chunk-v2bvrk83.js";import"./chunk-g2yaghbk.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};