blade-code 0.10.192 → 0.10.193

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-4cdk4mds.js → chunk-0eajnhrj.js} +1 -1
  3. package/dist/{chunk-8xdmwdw2.js → chunk-0h97pwtv.js} +2 -2
  4. package/dist/{chunk-89s3c1tg.js → chunk-0w1w2555.js} +1 -1
  5. package/dist/{chunk-xmymx75h.js → chunk-0xf70s5c.js} +1 -1
  6. package/dist/{chunk-vbjgcn49.js → chunk-1cy4ab77.js} +1 -1
  7. package/dist/chunk-1gwae1gr.js +1 -0
  8. package/dist/{chunk-rftaax5b.js → chunk-2qjsbxq5.js} +1 -1
  9. package/dist/{chunk-d420fs8m.js → chunk-2xpjy0ef.js} +1 -1
  10. package/dist/{chunk-0mr8nexh.js → chunk-3cas6rv5.js} +2 -2
  11. package/dist/chunk-42vt2eqq.js +1 -0
  12. package/dist/chunk-4bd6fe6g.js +1 -0
  13. package/dist/{chunk-kqvzmnja.js → chunk-4fbpydtn.js} +2 -2
  14. package/dist/{chunk-naz4esc9.js → chunk-4g3qg8j7.js} +1 -1
  15. package/dist/{chunk-7g2r6fy1.js → chunk-4vcea99r.js} +247 -247
  16. package/dist/{chunk-t0gm0pn1.js → chunk-5yyp6njq.js} +1 -1
  17. package/dist/chunk-6ax5dpd3.js +1 -0
  18. package/dist/{chunk-tb4998x1.js → chunk-6q0n03nz.js} +2 -2
  19. package/dist/chunk-6vaq3jf6.js +1 -0
  20. package/dist/{chunk-m0g2m5ex.js → chunk-6wmjxmdg.js} +2 -2
  21. package/dist/{chunk-06hkf59s.js → chunk-7ajvrtb3.js} +1 -1
  22. package/dist/chunk-8sggrqep.js +1 -0
  23. package/dist/chunk-8sqpz0sz.js +1 -0
  24. package/dist/{chunk-wpjxm6b0.js → chunk-97rqk0ek.js} +1 -1
  25. package/dist/{chunk-7bv1wb40.js → chunk-9c7hesmj.js} +1 -1
  26. package/dist/{chunk-30x3mcsb.js → chunk-9fyjyk2f.js} +1 -1
  27. package/dist/chunk-ae0fafmv.js +1 -0
  28. package/dist/{chunk-chksejtw.js → chunk-azd57pvw.js} +1 -1
  29. package/dist/{chunk-eg3ms291.js → chunk-cjfb4kjp.js} +1 -1
  30. package/dist/{chunk-g5e8b4ad.js → chunk-cycsbwm3.js} +2 -2
  31. package/dist/{chunk-92n0zamq.js → chunk-czrktgmy.js} +2 -2
  32. package/dist/{chunk-kh6c85x0.js → chunk-dkhn7mqt.js} +2 -2
  33. package/dist/{chunk-53fc0yrq.js → chunk-egss0m1x.js} +1 -1
  34. package/dist/chunk-ety33ry2.js +10 -0
  35. package/dist/{chunk-zzvs471p.js → chunk-fdr4fcrf.js} +1 -1
  36. package/dist/{chunk-pms1zh39.js → chunk-fnfay5y6.js} +2 -2
  37. package/dist/{chunk-a6wkam4s.js → chunk-g383afnv.js} +1 -1
  38. package/dist/{chunk-y57vfqkz.js → chunk-gerzcz6q.js} +1 -1
  39. package/dist/{chunk-rvs364rz.js → chunk-ggdgk3gy.js} +2 -2
  40. package/dist/{chunk-j4pehxf9.js → chunk-ghvfd7bx.js} +2 -2
  41. package/dist/{chunk-9pwnevy1.js → chunk-gr9603ca.js} +1 -1
  42. package/dist/{chunk-zj1g4nbq.js → chunk-hnvvve5d.js} +1 -1
  43. package/dist/{chunk-j8hbddjp.js → chunk-j89qk7bp.js} +2 -2
  44. package/dist/{chunk-nheny8xp.js → chunk-je908ygr.js} +2 -2
  45. package/dist/chunk-jg7agxyv.js +1 -0
  46. package/dist/{chunk-3kszepm6.js → chunk-kehgewqh.js} +1 -1
  47. package/dist/{chunk-wcps5gjm.js → chunk-kkzznz4w.js} +1 -1
  48. package/dist/{chunk-82fmsk3q.js → chunk-ks48r1c6.js} +3 -3
  49. package/dist/{chunk-vw9paban.js → chunk-ky592ay9.js} +1 -1
  50. package/dist/{chunk-psecx3yk.js → chunk-m31pg7t5.js} +1 -1
  51. package/dist/{chunk-68tdn3y5.js → chunk-m6bx0jv1.js} +2 -2
  52. package/dist/{chunk-qx6gb5k6.js → chunk-myvt7yjm.js} +2 -2
  53. package/dist/{chunk-4wx5sya5.js → chunk-n52n2w5v.js} +1 -1
  54. package/dist/{chunk-cs3z7w8b.js → chunk-nh9d0m2m.js} +2 -2
  55. package/dist/chunk-ntdw1nq1.js +1 -0
  56. package/dist/{chunk-jj4ggb04.js → chunk-p0wyhp5a.js} +2 -2
  57. package/dist/{chunk-w33zjw8m.js → chunk-p6586ftx.js} +2 -2
  58. package/dist/{chunk-nkzq66vk.js → chunk-pk3ftt16.js} +1 -1
  59. package/dist/{chunk-2f8d0km4.js → chunk-qdbbke8f.js} +1 -1
  60. package/dist/{chunk-kv458q06.js → chunk-qpmvp4q2.js} +1 -1
  61. package/dist/{chunk-wvxrtmws.js → chunk-qr80p5m0.js} +3 -3
  62. package/dist/{chunk-2mk914vk.js → chunk-rmfzym94.js} +2 -2
  63. package/dist/chunk-rmvfnmzv.js +1 -0
  64. package/dist/chunk-tm3789m3.js +2 -0
  65. package/dist/chunk-vsxv2sc6.js +1 -0
  66. package/dist/{chunk-g01mth5d.js → chunk-vzdsext4.js} +1 -1
  67. package/dist/{chunk-ddvdc2p0.js → chunk-wezr6wfq.js} +1 -1
  68. package/dist/{chunk-kvp523gt.js → chunk-wk869s65.js} +1 -1
  69. package/dist/chunk-wpg023nf.js +1 -0
  70. package/dist/{chunk-0tzecdv3.js → chunk-x49bw41v.js} +1 -1
  71. package/dist/{chunk-abdssgwg.js → chunk-xs15f82r.js} +1 -1
  72. package/dist/{chunk-fqf4xb61.js → chunk-xvqbvpks.js} +1 -1
  73. package/dist/{chunk-3y2x6fb6.js → chunk-ys8gysg8.js} +1 -1
  74. package/dist/{chunk-hxanwm8c.js → chunk-z4cz1rce.js} +2 -2
  75. package/dist/{chunk-50vwafn5.js → chunk-zfxcef0z.js} +1 -1
  76. package/dist/{chunk-n6x5wpv9.js → chunk-zjjwxnmd.js} +1 -1
  77. package/dist/{chunk-y5wngtz0.js → chunk-ztreczac.js} +2 -2
  78. package/package.json +1 -1
  79. package/dist/chunk-4k0a4pk5.js +0 -1
  80. package/dist/chunk-4vg1kj17.js +0 -1
  81. package/dist/chunk-5v0jcyea.js +0 -2
  82. package/dist/chunk-66wk3exc.js +0 -1
  83. package/dist/chunk-6n9vnesr.js +0 -10
  84. package/dist/chunk-8q2cnd79.js +0 -1
  85. package/dist/chunk-9rkp8g7g.js +0 -1
  86. package/dist/chunk-b7rp2bt3.js +0 -1
  87. package/dist/chunk-fc55qj8t.js +0 -1
  88. package/dist/chunk-pzqy0x7r.js +0 -1
  89. package/dist/chunk-se2k6ntw.js +0 -1
  90. package/dist/chunk-stgsvg57.js +0 -1
  91. package/dist/chunk-whqveat6.js +0 -1
  92. package/dist/chunk-yp13ezhf.js +0 -1
  93. package/dist/chunk-z2jwe9q4.js +0 -1
@@ -1,3 +1,3 @@
1
- import{Jk as $,fk as F}from"./chunk-4wx5sya5.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{Kk as $,gk as F}from"./chunk-n52n2w5v.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as j};
@@ -1,3 +1,3 @@
1
- import{Rj as N,Uj as M}from"./chunk-4cdk4mds.js";import{fk as H}from"./chunk-4wx5sya5.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{Sj as N,Vj as M}from"./chunk-0eajnhrj.js";import{gk as H}from"./chunk-n52n2w5v.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 Lj,X as Mj,J as Nj,L as Oj,hu as Pj};
3
+ export{K as Mj,X as Nj,J as Oj,L as Pj,hu as Qj};
@@ -1,2 +1,2 @@
1
- import{wh as Q}from"./chunk-06hkf59s.js";import{Fj as F,Hj as k,Kj as G}from"./chunk-2mk914vk.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
- export{Z as wf};
1
+ import{xh as Q}from"./chunk-7ajvrtb3.js";import{Gj as F,Ij as k,Lj as G}from"./chunk-rmfzym94.js";var V=k.String({minLength:1,maxLength:128,pattern:"^[A-Za-z0-9][A-Za-z0-9_-]*$"}),K=k.Array(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"}),{maxItems:128}),W=k.Object({description:k.String({minLength:1,maxLength:4096,pattern:".*\\S.*"}),prompt:k.String({minLength:1,maxLength:1e5,pattern:".*\\S.*"}),tools:k.Optional(K),disallowedTools:k.Optional(K),model:k.Optional(k.String({minLength:1,maxLength:200,pattern:".*\\S.*"})),permissionMode:k.Optional(G(["default","acceptEdits","dontAsk","bypassPermissions","plan","ignore"])),maxTurns:k.Optional(k.Integer({minimum:1})),isolation:k.Optional(G(["none","worktree"]))},{additionalProperties:!1});function Z(R){let w;try{w=JSON.parse(R)}catch{throw Error("Invalid JSON provided to --agents")}if(w===null||Array.isArray(w)||typeof w!=="object")throw Error("--agents must be a JSON object");let H=Object.entries(w);if(H.length>64)throw Error("--agents supports at most 64 definitions");return H.map(([z,U])=>{if(!F(V,z).success)throw Error(`Invalid --agents name "${z}": use letters, numbers, hyphens, or underscores`);let I=F(W,U);if(!I.success)throw Error(`Invalid --agents definition for "${z}"`);let q=I.data;return{name:z,description:q.description.trim(),systemPrompt:q.prompt.trim(),tools:q.tools?[...new Set(q.tools.map((B)=>B.trim()))]:void 0,disallowedTools:q.disallowedTools?[...new Set(q.disallowedTools.map((B)=>B.trim()))]:void 0,model:q.model?.trim(),permissionMode:q.permissionMode===void 0?void 0:Q(q.permissionMode),maxTurns:q.maxTurns,isolation:q.isolation,source:"flag"}})}
2
+ export{Z as xf};
@@ -0,0 +1 @@
1
+ import{k as a,l as b,m as c,n as d,o as e}from"./chunk-xvqbvpks.js";import"./chunk-cycsbwm3.js";import"./chunk-cjfb4kjp.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
@@ -1,2 +1,2 @@
1
1
  var i="verification",E="goal-verification",e="review";function t(n){return n==="verification"||n==="goal-verification"}function o(n){return t(n)||n==="review"}
2
- export{i as bh,E as ch,e as dh,t as eh,o as fh};
2
+ export{i as ch,E as dh,e as eh,t as fh,o as gh};
@@ -1,2 +1,2 @@
1
1
  var t=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],e=128,o=["pending","pass","fail","partial"],n=4000,r=3,a=["unable_to_proceed","stopping_here","internal_wait","self_deferral","handoff"],i=3,s=3,l=["timeout","admission","spawn","finalization","sandbox_start","terminal"],u=["waiting_dependency","same_task_no_effect","repeated_deferral"],c=3;
2
- export{t as gh,e as hh,o as ih,n as jh,r as kh,a as lh,i as mh,s as nh,l as oh,u as ph,c as qh};
2
+ export{t as hh,e as ih,o as jh,n as kh,r as lh,a as mh,i as nh,s as oh,l as ph,u as qh,c as rh};
@@ -1,4 +1,4 @@
1
- import{wc as G8}from"./chunk-zzvs471p.js";import{$d as t1,Ac as A2,Bc as a1,Dc as j$,Ed as E2,Fd as L8,Gd as F8,Hd as V6,Id as JZ,Jd as O8,Kd as P8,Ld as r1,Pd as rJ,Yd as u0,_d as R6,ae as M6,he as X1,td as b2,vd as y2,wd as f2,xc as q$,xd as w6,yd as U6,zc as U$}from"./chunk-92n0zamq.js";import{me as q8}from"./chunk-53fc0yrq.js";import{Ee as f0,pe as q0,se as j2,te as u$}from"./chunk-y5wngtz0.js";import{dg as p2}from"./chunk-t0gm0pn1.js";import{eg as w8,fg as C0,gg as H8,hg as dJ,jg as i1,kg as T6,lg as cJ,mg as lJ,pg as iJ}from"./chunk-qx6gb5k6.js";import{bh as K$,ch as n0,fh as U8}from"./chunk-3kszepm6.js";import{kh as a2,oh as Y2}from"./chunk-wcps5gjm.js";import{zh as R$}from"./chunk-wvxrtmws.js";import{Ui as x$}from"./chunk-kv458q06.js";import{bj as j0}from"./chunk-2f8d0km4.js";import{Dj as S0}from"./chunk-2mk914vk.js";import{Xj as _2}from"./chunk-g5e8b4ad.js";import{Bk as FJ,Ck as ZZ,Ek as O2,Jk as P2,Kk as N2,fk as F2,uk as w2,vk as U2,yk as H1}from"./chunk-4wx5sya5.js";import{Mk as lZ}from"./chunk-eg3ms291.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!S$(W)&&!E$(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(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...f0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function e6($){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 $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=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"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^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 xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function J1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function WJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function V$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function m8($){let Z=V$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\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],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function CZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\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}(?:测试|单测|集成测试|检查|构建)/],HJ={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},s8={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},t8="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.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&T$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\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|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\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|子代理)/],W9=[/\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 Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="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.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\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 wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="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.",B9="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.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function L9($){let Z=$;for(let H of q9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<turn_aborted>
1
+ import{xc as G8}from"./chunk-fdr4fcrf.js";import{$d as R6,Ac as U$,Bc as A2,Cc as a1,Ec as j$,Fd as E2,Gd as L8,Hd as F8,Id as V6,Jd as JZ,Kd as O8,Ld as P8,Md as r1,Qd as rJ,Zd as u0,ae as t1,be as M6,ie as X1,ud as b2,wd as y2,xd as f2,yc as q$,yd as w6,zd as U6}from"./chunk-czrktgmy.js";import{ne as q8}from"./chunk-egss0m1x.js";import{Fe as f0,qe as q0,te as j2,ue as u$}from"./chunk-ztreczac.js";import{eg as p2}from"./chunk-5yyp6njq.js";import{fg as w8,gg as C0,hg as H8,ig as dJ,kg as i1,lg as T6,mg as cJ,ng as lJ,qg as iJ}from"./chunk-myvt7yjm.js";import{ch as K$,dh as n0,gh as U8}from"./chunk-kehgewqh.js";import{lh as a2,ph as Y2}from"./chunk-kkzznz4w.js";import{Ah as R$}from"./chunk-qr80p5m0.js";import{Vi as x$}from"./chunk-qpmvp4q2.js";import{cj as j0}from"./chunk-qdbbke8f.js";import{Ej as S0}from"./chunk-rmfzym94.js";import{Yj as _2}from"./chunk-cycsbwm3.js";import{Ck as FJ,Dk as ZZ,Fk as O2,Kk as P2,Lk as N2,gk as F2,vk as w2,wk as U2,zk as H1}from"./chunk-n52n2w5v.js";import{Nk as lZ}from"./chunk-cjfb4kjp.js";function S$($){return $.role==="system"&&Array.isArray($.content)}function E$($){if($.role!=="system"||!$.metadata||Array.isArray($.metadata))return!1;return typeof $.metadata==="object"&&$.metadata.contextualProjectRules===!0}class C1{systemMessages;_contextualSystemMessages;_history;_pending=[];_contextRevision=0;context;constructor($,Z){this.context=$;let J=$.messages.find(S$);if(this._contextualSystemMessages=$.messages.filter(E$),J)this.systemMessages=[J,...this._contextualSystemMessages];else if(Z)this.systemMessages=[{role:"system",content:[{type:"text",text:Z,providerOptions:{anthropic:{cacheControl:{type:"ephemeral"}}}}]},...this._contextualSystemMessages];else this.systemMessages=[...this._contextualSystemMessages];this._history=$.messages.filter((W)=>!S$(W)&&!E$(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(!E$($))throw Error("Contextual project instructions require safe metadata");this._contextualSystemMessages.push($),this.systemMessages.push($)}syncContextualSystemMessages(){let $=this.systemMessages.filter(S$);this.systemMessages.splice(0,this.systemMessages.length,...$,...this._contextualSystemMessages)}appendControl($,Z){if($==="system")throw Error("Cannot append system control message via appendControl. Use constructor for root system prompt.");this._pending.push({...Z,metadata:{...Z.metadata&&typeof Z.metadata==="object"&&!Array.isArray(Z.metadata)?Z.metadata:{},...f0}})}appendDurableControl($){if(!$.id||$.role!=="user")throw Error("Durable control messages require a user role and identity");if(this._history.some((Z)=>Z.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((Z)=>!S$(Z)&&!E$(Z)),this._contextRevision++}restoreDurableHistory($){this._contextualSystemMessages=$.filter(E$),this._history=$.filter((Z)=>!S$(Z)&&!E$(Z)),this._pending=[],this.syncContextualSystemMessages(),this._contextRevision++}removeMessages($){let Z=[this._history.length,this._pending.length,this._contextualSystemMessages.length];if(this._history=this._history.filter((J)=>!$(J)),this._pending=this._pending.filter((J)=>!$(J)),this._contextualSystemMessages=this._contextualSystemMessages.filter((J)=>!$(J)),this.syncContextualSystemMessages(),this._history.length!==Z[0]||this._pending.length!==Z[1]||this._contextualSystemMessages.length!==Z[2])this._contextRevision++}writeback(){this.commitPending(),this.context.messages=[...this._contextualSystemMessages,...this._history]}get hasSystemPrompt(){return this.systemMessages.length>0}}function e6($){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 $J($){return{budget:$.budget,usage:0,consecutiveContinuations:0,lastOutputDelta:0,isSubagent:$.isSubagent??!1}}function ZJ($,Z,J){return{...$,usage:$.usage+Z,lastOutputDelta:Z,consecutiveContinuations:J?$.consecutiveContinuations+1:0}}import z$ from"node:path";var k8=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"]),x8=/^(LD_.+|DYLD_.+|PATH)$/,JJ=/^([A-Za-z_][A-Za-z0-9_]*)=([\w./:@-]*)$/;function Z1($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(!k8.has(X))break;Z=Y}return Z}function r5($){let Z=$;while(!0){let J=Z.match(/^(\S+)[ \t]+([\s\S]*)$/);if(!J)break;let W=J[1],Y=J[2],K=W.match(JJ);if(!K)break;let X=K[1];if(x8.test(X))break;Z=Y}return Z}var I8=[/^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 xZ($){let Z=$,J=!0;while(J){J=!1;for(let W of I8){let Y=Z.match(W);if(Y){Z=Z.slice(Y[0].length),J=!0;break}}if(Z.startsWith("-- "))Z=Z.slice(3),J=!0}return Z}function J1($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){J+=Q,K=!0;continue}if(Q==="'"&&!Y){W=!W,J+=Q;continue}if(Q==='"'&&!W){Y=!Y,J+=Q;continue}if(W||Y){J+=Q;continue}if(Q==="|"){if(X+1<$.length&&$[X+1]==="|"){if(J.trim())Z.push(J.trim());J="",X++;continue}return null}if(Q===">"||Q==="<")return null;if(Q==="&"&&X+1<$.length&&$[X+1]==="&"){if(J.trim())Z.push(J.trim());J="",X++;continue}if(Q==="&")return null;if(Q===";"){if(J.trim())Z.push(J.trim());J="";continue}J+=Q}if(J.trim())Z.push(J.trim());return Z.length>0?Z:null}function WJ($){let Z=!1,J=!1,W=!1;for(let Y=0;Y<$.length;Y++){let K=$[Y];if(W){W=!1;continue}if(K==="\\"&&!Z){W=!0;continue}if(K==="'"&&!J){Z=!Z;continue}if(K==='"'&&!Z){J=!J;continue}if(Z)continue;if(K==="$"){let X=$[Y+1];if(X&&/[A-Za-z_@*#?!$0-9({]/.test(X))return!0}if(K==="`")return!0;if(J)continue;if(K==="|")return!0;if(K===">"||K==="<")return!0;if(K==="{"){let X=$.slice(Y);if(/^\{[^}]*,[^}]*\}/.test(X)||/^\{[^}]*\.\.[^}]*\}/.test(X))return!0}}return!1}function V$($){let Z=[],J="",W=!1,Y=!1,K=!1;for(let X=0;X<$.length;X++){let Q=$[X];if(K){J+=Q,K=!1;continue}if(Q==="\\"&&!W){if(K=!0,Y){let H=$[X+1];if(H&&'$`"\\'.includes(H))continue;J+=Q,K=!1}continue}if(Q==="'"&&!Y){W=!W;continue}if(Q==='"'&&!W){Y=!Y;continue}if(!W&&!Y&&/[ \t]/.test(Q)){if(J)Z.push(J),J="";continue}J+=Q}if(J)Z.push(J);return Z}var h8=new Set(["npm","pnpm","yarn","bun"]),YJ=new Set(["biome","eslint","jest","mypy","pyright","pytest","ruff","tsc","vitest"]),v8=new Set(["-u","--fix","--update","--update-snapshot","--updateSnapshot","--watch","--watchAll","--write"]),C8=/[ \t]*;[ \t]*echo[ \t]+"[A-Za-z0-9 _:=.-]*(?:\$\{PIPESTATUS\[0\]\}|\$\?)[A-Za-z0-9 _:=.-]*"[ \t]*$/;function g8($){return $!==void 0&&/^(?:test|lint|build|type-?check)(?::[\w.-]+)*$/i.test($)}function KJ($){return $.replace(/\s+2>&1\s*$/,"").trim()}function p8($,Z,J){if(!J||Z.length!==2)return;let W=/^(.+?)[ \t]+&&[ \t]+([\s\S]+)$/.exec($);if(!W)return;let Y=V$(W[1]??"");if(Y.length!==2||Y[0]!=="cd")return;let K=Y[1];if(!K||K==="-")return;let X=z$.isAbsolute(K)?z$.resolve(K):z$.resolve(J,K);if(!j$.isWithinWorkspace(X,J))return;return W[2]?.trim()||void 0}function u8($){let Z=[],J=!1,W=!1,Y=!1;for(let K=0;K<$.length;K++){let X=$[K];if(Y){Y=!1;continue}if(X==="\\"&&!J){Y=!0;continue}if(X==="'"&&!W){J=!J;continue}if(X==='"'&&!J){W=!W;continue}if(X!=="|"||J||W)continue;if($[K+1]==="|")return;Z.push(K)}return Z}function m8($){let Z=V$($),[J,W,Y]=Z;if(J!=="head"&&J!=="tail")return!1;if(Z.length===1)return!0;let K=(X)=>X!==void 0&&/^[1-9]\d{0,4}$/.test(X);if(Z.length===2)return W?.startsWith("--lines=")&&K(W.slice(8))||W?.startsWith("-")&&K(W.slice(1));return Z.length===3&&(W==="-n"||W==="--lines")&&K(Y)}function d8($){let Z=KJ($.replace(C8,"").trim()),J=u8(Z);if(!J)return;if(J.length===0)return XJ(Z);if(J.length!==1)return;let W=J[0];if(W===void 0)return;let Y=KJ(Z.slice(0,W).trim()),K=Z.slice(W+1).trim();if(!Y||!m8(K))return;return XJ(Y)}function XJ($){let J=J1($)?.at(-1);if(!J)return $;let W=V$(J),[Y,K]=W;if(!(Y==="vitest"||(Y==="npx"||Y==="bunx")&&K==="vitest")||W.some((Q)=>Q==="--configLoader"||Q.startsWith("--configLoader=")))return $;return`${$} --configLoader runner`}function T$($,Z){let J=d8($);if(!J)return!1;let W=Z1(J),Y=J1(W);if(!Y||WJ(W)||/[\r\n]/.test(W))return!1;let K=Y.length===1?Y[0]:p8(W,Y,Z);if(!K)return!1;let X=V$(K);if(X.length===0||X.some((z)=>[...v8].some((w)=>z===w||z.startsWith(`${w}=`))))return!1;let[Q,H,V]=X;if(h8.has(Q??""))return g8(H==="run"?V:H)||H==="--test";if((Q==="npx"||Q==="bunx")&&YJ.has(H??""))return!0;if(YJ.has(Q??""))return!0;if(Q==="node"&&H==="--test")return!0;if(Q==="go"&&["build","test","vet"].includes(H??""))return!0;return Q==="cargo"&&["build","check","clippy","test"].includes(H??"")}function t5($,Z){if($===void 0)return!0;if(typeof $!=="string"||$.split(/[\\/]/).includes(".."))return!1;if(!Z)return!z$.isAbsolute($);let J=z$.isAbsolute($)?z$.resolve($):z$.resolve(Z,$);return j$.isWithinWorkspace(J,Z)}var IZ=S0("Agent"),c8=3;function hZ($,Z,J){if($!=="length")return{action:"none"};if(Z>=c8)return{action:"truncated"};if(e6(J)==="stop")return IZ.info("[Loop] Token budget: diminishing returns detected, skipping recovery"),{action:"budget_stop"};return{action:"recover"}}var l8=[/:\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],i8=/```[\s\S]{50,}```/,QJ="请执行你提到的操作,不要只是描述。使用 Edit/Write/ApplyPatch/Bash 工具来实际修改文件。",r8=2;function vZ($,Z,J=!0){if(!$||Z>=r8)return{action:"none"};if(!J&&i8.test($))return{action:"retry",prompt:QJ};let W=$.slice(-200),Y=W.match(/```/g);if(Y&&Y.length%2!==0)return{action:"none"};if(l8.some((X)=>X.test(W)))return{action:"retry",prompt:QJ};return{action:"none"}}var g1=2,n8="The model returned tool-call JSON as text instead of completing the requested tool workflow.",o8="The previous response contained tool-call JSON as ordinary text. It did not execute a tool. If the requested operation is still needed, use the native tool-call interface with an available tool. If it already succeeded, use the recorded result to answer instead of repeating the operation. Do not return another tool-call JSON envelope as your final answer.";function CZ($,Z,J,W){if(!$||$.length>65536||J.length===0)return{action:"none"};let Y=Z.replace(/```[\s\S]*?(?:```|$)/g,"").replace(/^\s*>.*$/gm,"");if(/\b(?:example|schema|serialize|serialization|quote|print|illustrate|verbatim)\b|示例|样例|序列化|引用原文/i.test(Y)||/\b(?:explain|show|return|output)\b[^.!?\n]{0,80}\b(?:json|tool.calls?)\b|(?:解释|展示|输出|返回)[^。!?\n]{0,40}(?:JSON|工具调用格式)/i.test(Y)||/\b(?:do not|don't|never)\s+(?:use|call|invoke|execute)\s+(?:any\s+)?tools?\b|不要(?:使用|调用|执行)(?:任何)?工具/i.test(Y))return{action:"none"};let K;try{K=JSON.parse($)}catch{return{action:"none"}}if(!K||typeof K!=="object"||Array.isArray(K)||Object.keys(K).length!==1||!("tool_calls"in K)||!Array.isArray(K.tool_calls)||K.tool_calls.length===0||K.tool_calls.length>32)return{action:"none"};let X=new Set;for(let Q of K.tool_calls){if(!Q||typeof Q!=="object"||Array.isArray(Q))return{action:"none"};let H="function"in Q;if(Object.keys(Q).some((G)=>!["id","type",...H?["function"]:["name","arguments"]].includes(G)))return{action:"none"};if("type"in Q&&Q.type!=="function")return{action:"none"};let V=H?Q.function:Q;if(!V||typeof V!=="object"||Array.isArray(V)||!("name"in V)||typeof V.name!=="string"||!("arguments"in V))return{action:"none"};if(H&&Object.keys(V).some((G)=>G!=="name"&&G!=="arguments"))return{action:"none"};if(!J.includes(V.name))return{action:"none"};let z=V.arguments;if(typeof z!=="string"&&(!z||typeof z!=="object"||Array.isArray(z)))return{action:"none"};let w=V.name.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),B=new RegExp(`(?:^|[.!?。!?;;\\n])\\s*(?:please\\s+)?(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:^|[。!?;\\n])\\s*(?:请)?(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i"),j=new RegExp(`(?:do not|don't|never)\\s+(?:call|invoke|execute|run|use)\\s+(?:the\\s+)?(?:tool\\s+)?[\`"']?${w}(?![\\w:-])|(?:不要|禁止)(?:调用|使用|执行)\\s*(?:工具\\s*)?[\`"']?${w}(?![\\w:-])`,"i");if(!B.test(Y)||j.test(Y))return{action:"none"};X.add(V.name)}return W<g1?{action:"retry",prompt:o8,...X.size===1?{toolName:[...X][0]}:{}}:{action:"fail",message:n8}}var a8=[/\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}(?:测试|单测|集成测试|检查|构建)/],HJ={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},s8={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},t8="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.",e8="Required verification did not run successfully before the retry limit.",$9=3;function zJ($,Z,J,W){if(!J.success)return;if(["Edit","Write","ApplyPatch","NotebookEdit"].includes(Z)){$.clear();return}if(Z==="Bash"&&typeof J.metadata?.command==="string"&&J.metadata.exit_code===0&&T$(J.metadata.command,W)){$.add(J.metadata.command);return}if(!["Task","TaskOutput"].includes(Z))return;let Y=J.metadata?.verificationCommands;if(!Array.isArray(Y))return;for(let K of Y)if(typeof K==="string"&&T$(K,W))$.add(K)}function gZ($,Z,J){if(!$||!a8.some((H)=>H.test($)))return{action:"none"};let W=Object.keys(HJ).filter((H)=>HJ[H].test($)),Y=[...Z],K=W.filter((H)=>!Y.some((V)=>s8[H].test(V)));if(W.length>0?K.length===0:Y.some((H)=>T$(H)))return{action:"none"};if(J>=$9)return{action:"fail",message:e8};let Q=W.length>1&&K.length>0?` Missing successful verification categories: ${K.join(", ")}.`:"";return{action:"retry",prompt:`${t8}${Q}`}}var Z9=[/\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|子代理|子智能体)/],jJ=[/\b(?:do not|don't|never)\s+(?:delegate|call|use|invoke)\b/i,/(?:不要|禁止|无需)(?:委派|调用|使用).{0,20}(?:Task|子代理|子智能体)?/];function BJ($){return typeof $==="string"&&jJ.some((Z)=>Z.test($))}var J9=[/\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|子代理)/],W9=[/\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 Y9($){if(typeof $!=="string")return;if(W9.some((Z)=>Z.test($)))return"multiple-allowed";return J9.some((Z)=>Z.test($))?"required":void 0}function Y1($){for(let Z of $){let J=Y9(Z);if(J!==void 0)return J==="required"}return!1}var K9="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.",X9="Required delegation did not complete before the retry limit.",Q9=3;function DJ($,Z,J){let W=(typeof $==="string"?[$]:$??[]).map((X)=>X.trim()).filter(Boolean),Y=Y1(W),K=!1;if(!Y)for(let X of W){if(jJ.some((Q)=>Q.test(X)))break;if(Z9.some((Q)=>Q.test(X))){K=!0;break}}if(W.length===0||!Y&&!K||Z.has("Task"))return{action:"none"};if(J>=Q9)return{action:"fail",message:X9};return{action:"retry",prompt:K9}}var H9=[/\b(?:use|create|enter|start|work\s+(?:in|inside))\b.{0,60}\bworktree\b/i,/(?:使用|创建|进入).{0,30}(?:worktree|工作树)/i],V9=[/\b(?:exit|leave)\b.{0,40}\bworktree\b/i,/\bworktree\b.{0,60}\b(?:action\s+)?(?:keep|remove)\b/i,/(?:退出|离开).{0,30}(?:worktree|工作树)/i],z9=[/\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 wJ($){return z9.reduce((Z,J)=>Z.replace(J," "),$)}function p1($){if(typeof $!=="string")return!1;let Z=wJ($);return H9.some((J)=>J.test(Z))}var j9="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.",B9="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.",D9="Required worktree lifecycle did not complete before the retry limit.",w9=3;function UJ($,Z,J){if(!$)return{action:"none"};let W=wJ($);if(!p1(W))return{action:"none"};let Y=V9.some((X)=>X.test(W));if(Z.has("TaskWorktree"))return{action:"none"};let K=!Z.has("EnterWorktree")?"EnterWorktree":Y&&!Z.has("ExitWorktree")?"ExitWorktree":void 0;if(!K)return{action:"none"};if(J>=w9)return{action:"fail",message:D9};return{action:"retry",tool:K,prompt:K==="EnterWorktree"?j9:B9}}var VJ=30000;async function pZ($){try{let J=R$.getInstance().executeStopHooks({projectDir:$.workspaceRoot??j0(),sessionId:$.sessionId,permissionMode:$.permissionMode,reason:$.reason,abortSignal:$.abortSignal}),W,Y=new Promise((K)=>{W=setTimeout(()=>K("timeout"),VJ)});try{let K=await Promise.race([J,Y]);if(K==="timeout")return IZ.warn(`[Loop] Stop hook 超时 (${VJ}ms),按 shouldStop: true 处理`),{action:"stop"};let X=K;if(!X.shouldStop)return{action:"continue",reason:X.continueReason};return{action:"stop"}}finally{clearTimeout(W)}}catch(Z){return IZ.warn("[Loop] Stop hook execution failed:",Z),{action:"stop"}}}async function U9($,Z){let J;while(!(J=await $.next()).done)if(Z)await Z(J.value);return J.value}var q9=[/<system-reminder>[\s\S]*?<\/system-reminder>/gi,/<file[^>]*>[\s\S]*?<\/file>/gi,/<hooks_context>[\s\S]*?<\/hooks_context>/gi,/<[^>]+>/g];function G9($){if(typeof $==="string")return $;if(Array.isArray($))return $.map((Z)=>{if(typeof Z==="string")return Z;if(Z&&typeof Z==="object"&&"text"in Z){let J=Z.text;return typeof J==="string"?J:""}return""}).join(" ");return""}function L9($){let Z=$;for(let H of q9)Z=Z.replace(H," ");Z=Z.replace(/^\s*\/[a-zA-Z][\w-]*\s+/,"");let J=Z.replace(/\s+/g," ").trim();if(!J)return"";let W=J.match(/^(.+?)(?:[.!?]\s|[。!?](?=\S|$)|$)/),Y=W&&W[1].length>=6?W[1]:J;if(Y=Y.trim().replace(/[\s.。!!??,,;;::-]+$/,""),Y.length<=60)return Y;let K=Y.slice(0,60),X=K.lastIndexOf(" ");return`${(X>36?K.slice(0,X):K).trimEnd()}…`}function qJ($){return L9(G9($))}import{EventEmitter as F9}from"events";import GJ from"node:path";function uZ($){if(FJ($.sessionId),!GJ.isAbsolute($.projectPath))throw Error("projectPath must be absolute");return{sessionId:$.sessionId,projectPath:GJ.resolve($.projectPath)}}function LJ($){let Z=uZ($);return JSON.stringify([Z.projectPath,Z.sessionId])}function j3($,Z){return LJ($)===LJ(Z)}class M$ extends F9{static instance;constructor(){super();this.setMaxListeners(100)}static getInstance(){if(!M$.instance)M$.instance=new M$;return M$.instance}publish($,Z,J,W){let Y=uZ($);this.emit("event",{sessionId:Y.sessionId,projectPath:Y.projectPath,type:Z,...W!==void 0?{seq:W}:{},properties:J})}subscribe($){return this.on("event",$),()=>this.off("event",$)}}var K1=M$.getInstance();var $$=S0("Agent"),u1=new Set;async function O9($,Z){let J=$.sessionId;if(!J||$.subagentInfo)return;if(u1.has(J))return;if(u1.size>=5000)u1.clear();u1.add(J);try{let W=$.workspaceRoot,Y=await X1.findSessionMetadata(J,W);if(!Y)return;if(Y.title&&Y.title.trim())return;let K=qJ(Z);if(!K)return;await X1.updateSessionMetadata(J,Y.projectPath,{title:K}),K1.publish({sessionId:J,projectPath:Y.projectPath},"session.updated",{title:K})}catch(W){$$.debug?.("[Loop] 自动生成会话标题失败:",W)}}var mZ=`<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>`,B$="Tool execution was blocked because its durable call record could not be committed. No tool side effect was started.",OJ="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 k$ extends Error{phase;constructor($,Z){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.",Z);this.phase=$;this.name="DurableConversationPersistenceError"}}function D$($){return $.executionEngine?.getContextManager()}async function r0($,Z,J,W=null,Y,K={}){let X=K.required??$.executionEngine!==void 0;try{let Q=D$($),H=typeof J==="string"?J.trim()!=="":J.some((V)=>V.type==="text"?V.text.trim()!=="":!0);if(Q&&Z.sessionId&&H){let V=await Q.saveMessage(Z.sessionId,"user",J,W,Y,Z.subagentInfo);if(X&&!V)throw Error("Durable user-message commit returned no identity");if(Y?.clientVisible!==!1)O9(Z,J);return V}if(X&&Z.sessionId&&H)throw Error("Durable user-message storage is unavailable")}catch(Q){if($$.warn("[Loop] 保存用户消息失败:",Q),X)throw new k$("user_message",{cause:Q})}return null}async function v0($,Z,J,W,Y,K,X={}){let Q=X.required??$.executionEngine!==void 0;try{let H=D$($),V=Boolean(J.trim()||Y?.trim());if(H&&Z.sessionId&&V){let z=await H.saveMessage(Z.sessionId,"assistant",J,W,K,Z.subagentInfo,Y);if(Q&&!z)throw Error("Durable assistant-message commit returned no identity");return z}if(Q&&Z.sessionId&&V)throw Error("Durable assistant-message storage is unavailable")}catch(H){if($$.warn("[Loop] 保存助手消息失败:",H),Q)throw new k$("assistant_message",{cause:H})}return null}async function PJ($,Z,J){try{let W=D$($);if(W&&Z.sessionId)return await W.saveMessage(Z.sessionId,"system",mZ,J,void 0,Z.subagentInfo)}catch(W){$$.warn("[Loop] 保存中断边界失败:",W)}return null}async function NJ($,Z,J,W,Y){try{let K=D$($);if(!K||!Z.sessionId||J.length===0)return null;return await K.saveMessage(Z.sessionId,"system",`<contextual-project-instructions-ref count="${J.length}" />`,Y,{contextualProjectRules:!0,ruleReferences:JSON.parse(JSON.stringify(J.map((X)=>({...X})))),triggerPaths:[...W]},Z.subagentInfo)}catch(K){$$.warn("[Loop] 保存 contextual project rules provenance 失败:",K)}return null}async function dZ($,Z,J,W,Y,K={}){try{let X=D$($);if(X&&Z.sessionId){let Q=await X.saveToolUse(Z.sessionId,J,W,Y,Z.subagentInfo,K.providerToolCallId);if(K.required&&!Q)throw Error("Durable tool-use commit returned no identity");return Q}if(K.required&&Z.sessionId)throw Error("Durable tool-use storage is unavailable")}catch(X){if($$.warn("[Loop] 保存工具调用失败:",X),K.required)throw X}return null}async function m1($,Z,J,W,Y,K,X,Q,H,V={}){try{let z=D$($);if(z&&Z.sessionId){let w=await z.saveToolResult(Z.sessionId,J,W,Y,K,X,Z.subagentInfo,Q,H);if(V.required&&!w)throw Error("Durable tool-result commit returned no identity");return w}if(V.required&&Z.sessionId)throw Error("Durable tool-result storage is unavailable")}catch(z){if($$.warn("[Loop] 保存工具结果失败:",z),V.required)throw z}return null}async function Q1($,Z,J,W,Y={}){try{let K=D$($);if(K&&Z.sessionId){let X=await K.saveCompaction(Z.sessionId,J,W,null);if(Y.required&&!X)throw Error("Compaction checkpoint commit returned no identity");return X||null}if(Y.required&&Z.sessionId)throw Error("Compaction checkpoint storage is unavailable")}catch(K){if($$.warn("[Loop] 保存压缩数据失败:",K),Y.required)throw K}return null}async function V0($){let{deps:Z,context:J,state:W,assistantContent:Y,assistantReasoningContent:K,lastMessageUuid:X,controlPrompt:Q}=$;W.appendAssistant({role:"assistant",content:Y,reasoningContent:K});let H=X,V=await v0(Z,J,Y,H,K);if(V)H=V;if(Q!==void 0){let z={role:"user",content:Q,metadata:f0};W.appendControl("user",z);let w=await r0(Z,J,Q,H,f0);if(w)H=w}return H}import{createHash as k6}from"node:crypto";import{promises as n9}from"node:fs";import o9 from"node:path";import{nanoid as J$}from"nanoid";import*as $0 from"node:fs/promises";import*as Z$ from"node:path";import AJ from"write-file-atomic";var _J={enabled:!0,maxIndexLines:200};var P9="memory",cZ="MEMORY.md",iZ="<!-- blade:auto-memory-topics:start -->",d1="<!-- blade:auto-memory-topics:end -->",N9={realpath:!1,retries:{retries:5,factor:1.2,minTimeout:20,maxTimeout:100,randomize:!0}},_9=new x$,bJ;function fJ($){return $.trim().replace(/\s+/g," ")}function A9($){return fJ($.replace(/^- \[\d{4}-\d{2}-\d{2}\] /,""))}function b9($){return[iZ,"## Auto-consolidated topics",...$.map((Z)=>`- [${Z}](${Z}.md)`),d1].join(`
4
4
  `)}function y9($,Z){let J=b9(Z),W=$.indexOf(iZ),Y=$.indexOf(d1,Math.max(0,W));if(W>=0&&Y>=W)return $.slice(0,W)+J+$.slice(Y+d1.length);if(!$)return`${J}
@@ -93,7 +93,7 @@ Full output saved to: ${Q}`}catch{return`${Z}
93
93
  ${Y}`}}function K2(){return{successfulBash:!1}}function q4($){return typeof $==="string"&&Y2.some((Z)=>Z===$)}function N7($){switch($){case"timeout":case"admission":case"spawn":case"finalization":return $;case"unavailable":return"terminal";default:return}}function _7($){return["<goal-execution-host-failure>",`Category: ${$.category}`,`Consecutive turns: ${$.consecutiveCount}/3`,"</goal-execution-host-failure>","","The execution host has failed in consecutive Goal turns. Do not blindly","repeat the same command path. Validate shell, sandbox, and terminal","availability, then switch to a different executable strategy or call","UpdateGoal blocked with concrete evidence if external intervention is required."].join(`
94
94
  `)}function X2($,Z,J){if(Z!=="Bash")return;if(J.success){$.successfulBash=!0;return}let W=J.metadata?.execution_host_failure;if(q4(W))$.category=W}function Q2($){return $.successfulBash?void 0:$.category}import C4 from"node:path";import{nanoid as g4}from"nanoid";import{randomUUID as w1}from"node:crypto";import*as g0 from"node:fs/promises";import*as B2 from"node:path";import{Mutex as N4}from"async-mutex";import _4 from"write-file-atomic";var H2=120,K6=128;function D1($){if(!Array.isArray($)||$.length>120||!$.every((Z)=>typeof Z==="string"&&Z.length>0&&Z.length<=128))return;return[...new Set($)]}function G4($){if(!$||typeof $!=="object"||Array.isArray($))return[];if(!("recovery"in $)||!$.recovery)return[];let Z=$.recovery;if(typeof Z!=="object"||Array.isArray(Z))return[];if(!("version"in Z)||Z.version!==1&&Z.version!==2&&Z.version!==3||!("inputMessageIds"in Z)||!("hadSuccessfulToolResult"in Z)||typeof Z.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in Z)||typeof Z.emptyFinalCorrectionSpent!=="boolean"||!("acknowledgedInputMessageIds"in $))return[];if((Z.version===2||Z.version===3)&&(!("interruptedToolCallCount"in Z)||!Number.isSafeInteger(Z.interruptedToolCallCount)||Z.interruptedToolCallCount<0))return[];if(Z.version===3&&(!("allSuccessfulToolResultsSafeForResume"in Z)||typeof Z.allSuccessfulToolResultsSafeForResume!=="boolean"))return[];let J=D1(Z.inputMessageIds),W=D1($.acknowledgedInputMessageIds);if(!J||!W)return[];let Y=new Set(J);return W.filter((K)=>Y.has(K))}function o1($,Z){let J=$[Z];if(J?.type!=="turn_aborted")return[];let W=G4(J.data);if(W.length===0)return[];let Y=-1;for(let X=Z-1;X>=0;X--){let Q=$[X];if(Q.type==="turn_started"){if(Q.data.turnId!==J.data.turnId)return[];Y=X;break}if(Q.type==="turn_completed"||Q.type==="turn_aborted")return[]}if(Y<0)return[];let K=new Set;for(let X=Y+1;X<Z;X++){let Q=$[X];if(Q.type!=="message_created"||Q.data.role!=="user")continue;let H=Q.data.metadata,V=Q.data.inboxMessageId!==void 0?Q.data.inboxMessageId:H!==null&&typeof H==="object"&&!Array.isArray(H)?H.inboxMessageId:void 0;if(typeof V==="string"&&V.length>0&&V.length<=128)K.add(V)}return W.filter((X)=>K.has(X))}import*as s1 from"node:fs/promises";import*as z2 from"node:path";var L4={realpath:!1,retries:{retries:150,factor:1.2,minTimeout:10,maxTimeout:100,randomize:!0}},F4=new x$,V2;async function g$($,Z,J,W=P4){let Y=U$($,Z);return F4.runExclusive(Y,()=>a1($,Z,async(K)=>{let X=z2.dirname(K.inboxPath);await s1.mkdir(X,{recursive:!0,mode:448}),await s1.chmod(X,448);let Q,H=await W(K.inboxPath,{...L4,onCompromised:(V)=>{Q=V}});try{if(Q)throw Q;let V=await J(K);if(Q)throw Q;return V}finally{await H()}}))}async function O4(){return V2??=await import("proper-lockfile"),V2}async function P4($,Z){return(await O4()).lock($,Z)}var H6=2,p$=8388608;function X6($,Z,J){let W={version:H6,sessionId:$,generation:Z,messages:J.map(({recovered:Y,...K})=>K)};return`${JSON.stringify(W)}
95
95
  `}function Q6($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function A4($){if(typeof $==="string")return!0;if(!Array.isArray($))return!1;return $.every((Z)=>{if(!Z||typeof Z!=="object"||!("type"in Z))return!1;if(Z.type==="text")return"text"in Z&&typeof Z.text==="string";return Z.type==="image_url"&&"image_url"in Z&&typeof Z.image_url==="object"&&Z.image_url!==null&&"url"in Z.image_url&&typeof Z.image_url.url==="string"})}function b4($,Z,J){let W;try{W=JSON.parse($)}catch(K){throw Error(`Invalid steering inbox JSON: ${Z}`,{cause:K})}if(!W||typeof W!=="object"||!("version"in W)||W.version!==1&&W.version!==H6||!("sessionId"in W)||W.sessionId!==J||!("messages"in W)||!Array.isArray(W.messages))throw Error(`Invalid steering inbox record: ${Z}`);let Y=W.messages.map((K)=>{if(!K||typeof K!=="object"||!("id"in K)||typeof K.id!=="string"||!("content"in K)||!A4(K.content)||!("queuedAt"in K)||typeof K.queuedAt!=="number"||"persisted"in K&&typeof K.persisted!=="boolean"||"origin"in K&&K.origin!=="user"&&K.origin!=="background_subagent"&&K.origin!=="team_message"&&K.origin!=="interaction_recovery"&&K.origin!=="user_shell"||"metadata"in K&&(K.metadata===null||typeof K.metadata!=="object"||Array.isArray(K.metadata))||"outputSchema"in K&&K.outputSchema!==void 0&&(!K.outputSchema||typeof K.outputSchema!=="object"||Array.isArray(K.outputSchema)))throw Error(`Invalid steering inbox message: ${Z}`);let X="outputSchema"in K&&K.outputSchema!==void 0?t1(K.outputSchema).schema:void 0;return{id:K.id,content:K.content,queuedAt:K.queuedAt,..."persisted"in K&&K.persisted===!0?{persisted:!0}:{},..."origin"in K&&K.origin?{origin:K.origin}:{},..."metadata"in K&&K.metadata?{metadata:JSON.parse(JSON.stringify(K.metadata))}:{},...X?{outputSchema:X}:{}}});if(new Set(Y.map((K)=>K.id)).size!==Y.length)throw Error(`Duplicate steering inbox message: ${Z}`);if(W.version===1)return{version:1,sessionId:J,messages:Y};if(!("generation"in W)||typeof W.generation!=="string"||!/^[a-f0-9-]{36}$/.test(W.generation))throw Error(`Invalid steering inbox generation: ${Z}`);return{version:H6,sessionId:J,generation:W.generation,messages:Y}}function y4($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return o1($,J);return[]}))}function f4($){return new Set($.flatMap((Z)=>{if(Z.type!=="message_created"||Z.data.role!=="user")return[];let J=Z.data.metadata,W=Z.data.inboxMessageId!==void 0?Z.data.inboxMessageId:J!==null&&typeof J==="object"&&!Array.isArray(J)?J.inboxMessageId:void 0;return typeof W==="string"?[W]:[]}))}class e1{sessionId;stateStorage;writeFile;lockFile;mutex=new N4;generation=w1();messages=[];constructor($,Z,J,W){this.sessionId=$;this.stateStorage=Z;this.writeFile=J;this.lockFile=W}static async open($,Z,J=q$($),W={}){let Y=new e1(Z,J,W.writeFile??_4,W.lockFile);return await Y.loadAndReconcile(),Y}async enqueue($,Z){return this.mutex.runExclusive(async()=>{let J=await g$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.messages.some((H)=>H.id===$.id))return{accepted:!0,snapshot:Y};if(Z&&!Z(Y.messages))return{accepted:!1,snapshot:Y};let K=[...Y.messages,{...$,recovered:!1}],X=w1(),Q=X6(this.sessionId,X,K);if(Buffer.byteLength(Q)>p$)return{accepted:!1,snapshot:Y};return await this.persistAtPath(K,X,W,Q),{accepted:!0,snapshot:{generation:X,messages:K}}},this.lockFile);return this.install(J.snapshot),J.accepted})}async acknowledge($){if($.length===0)return;let Z=new Set($);await this.mutex.runExclusive(async()=>{let J=await g$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W),K=Y.messages.filter((Q)=>!Z.has(Q.id));if(K.length===Y.messages.length&&!Y.acknowledgedRemoved)return Y;let X=w1();return await this.persistAtPath(K,X,W),{generation:X,messages:K}},this.lockFile);this.install(J)})}snapshot(){return{generation:this.generation,messages:this.list()}}async refresh(){return this.mutex.runExclusive(async()=>{let $=await g$(this.stateStorage,this.sessionId,(Z)=>this.readAndReconcileAtPath(Z),this.lockFile);return this.install($),this.snapshot()})}async replace($,Z){return this.mutex.runExclusive(async()=>{let J=await g$(this.stateStorage,this.sessionId,async(W)=>{let Y=await this.readAndReconcileAtPath(W);if(Y.generation!==$)return{replaced:!1,snapshot:Y};let K=w1(),X=Z.map((H)=>({...H})),Q=X6(this.sessionId,K,X);if(Buffer.byteLength(Q)>p$)return{replaced:!1,snapshot:Y};return await this.persistAtPath(X,K,W,Q),{replaced:!0,snapshot:{generation:K,messages:X}}},this.lockFile);return this.install(J.snapshot),{replaced:J.replaced,snapshot:this.snapshot()}})}list(){return this.messages.map(($)=>({...$,content:typeof $.content==="string"?$.content:$.content.map((Z)=>Z.type==="text"?{...Z}:{...Z,image_url:{...Z.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 $=await g$(this.stateStorage,this.sessionId,async(Z)=>{let J=await this.readAndReconcileAtPath(Z);if(J.migrationRequired||J.acknowledgedRemoved){let W=w1();return await this.persistAtPath(J.messages,W,Z),{generation:W,messages:J.messages}}return J},this.lockFile);this.install($)})}install($){this.generation=$.generation,this.messages=$.messages}async readAndReconcileAtPath($){let Z;try{let X=await g0.open($.inboxPath,"r");try{if((await X.stat()).size>p$)throw Error(`Steering inbox exceeds ${p$} bytes: ${$.inboxPath}`);Z=b4(await X.readFile("utf8"),$.inboxPath,this.sessionId)}finally{await X.close()}await g0.chmod($.inboxPath,384)}catch(X){if(!Q6(X,"ENOENT"))throw X}let J=new Set,W=new Set;try{let X=j2(await g0.readFile($.transcriptPath,"utf8"),$.transcriptPath);J=y4(X),W=f4(X)}catch(X){if(!Q6(X,"ENOENT"))throw X}let Y=new Map(this.messages.map((X)=>[X.id,X.recovered])),K=(Z?.messages??[]).filter((X)=>!J.has(X.id)).map((X)=>({...X,recovered:Y.get(X.id)??!0,...X.persisted===!0||W.has(X.id)?{persisted:!0}:{}}));return{generation:Z?.version===2?Z.generation:this.generation,messages:K,...Z?.version===1&&K.length>0?{migrationRequired:!0}:{},...Z&&K.length!==Z.messages.length?{acknowledgedRemoved:!0}:{}}}async persistAtPath($,Z,J,W){if(await g0.mkdir(B2.dirname(J.inboxPath),{recursive:!0,mode:448}),$.length===0){await g0.unlink(J.inboxPath).catch((K)=>{if(!Q6(K,"ENOENT"))throw K});return}let Y=W??X6(this.sessionId,Z,$);if(Buffer.byteLength(Y)>p$)throw Error(`Steering inbox exceeds ${p$} bytes: ${J.inboxPath}`);await this.writeFile(J.inboxPath,Y,{encoding:"utf8",mode:384,fsync:!0})}}import*as p0 from"node:fs/promises";import*as S2 from"node:path";import{nanoid as B0}from"nanoid";var D2=256;class O0{sessionId;projectPath;storage;static instances=new Map;subscribers=new Set;highestSeq=0;constructor($,Z,J){this.sessionId=$;this.projectPath=Z;this.storage=J}static for($,Z,J=q$(Z)){let W=U$(J,$),Y=O0.instances.get(W);if(!Y)Y=new O0($,Z,J),O0.instances.set(W,Y),O0.pruneIdleInstances(W);else O0.instances.delete(W),O0.instances.set(W,Y);return Y}static release($,Z,J=q$(Z)){O0.instances.delete(U$(J,$))}static pruneIdleInstances($){if(O0.instances.size<=D2)return;for(let[Z,J]of O0.instances){if(Z===$||J.subscribers.size>0)continue;if(O0.instances.delete(Z),O0.instances.size<=D2)return}}get lastSeq(){return this.highestSeq}async readAll(){return this.withStore(async($,Z,J)=>{let W=Z?await $.readAllValidated(Z):await $.readAll();return J(W),W})}async commit($){let[Z]=await this.commitEntries([$]);return this.record(Z),Z}async commitBatch($){if($.length===0)return[];let Z=await this.commitEntries($);for(let J of Z)this.record(J);return Z}async commitValidated($){let Z=await this.withStore((J,W,Y)=>J.appendValidated((K)=>{return Y(K),$(K)},W));return this.record(Z),Z}async commitValidatedBatch($){let Z=await this.withStore((J,W,Y)=>J.appendValidatedBatch((K)=>{return Y(K),$(K)},W));for(let J of Z)this.record(J);return Z}emitDelta($){for(let Z of this.subscribers)Z.onDelta?.($);K1.publish({sessionId:this.sessionId,projectPath:this.projectPath},"delta",{delta:$})}subscribe($,Z){if(this.subscribers.add($),Z?.fromSeq!==void 0)this.replay($,Z.fromSeq);return()=>{this.subscribers.delete($),O0.pruneIdleInstances()}}async replay($,Z){let J=await this.withStore(async(W,Y,K)=>{let X=Y?await W.readAllValidated(Y):await W.readAll();return K(X),X.filter((Q)=>(Q.seq??0)>=Z)});for(let W of J){if(V6(W))continue;await $.onCommitted(W)}}record($){if(typeof $.seq==="number"&&$.seq>this.highestSeq)this.highestSeq=$.seq;if(V6($))return;for(let Z of this.subscribers){let J=Z.onCommitted($);if(J)Promise.resolve(J).catch(()=>{return})}K1.publish({sessionId:this.sessionId,projectPath:this.projectPath},`committed.${$.type}`,{event:$},$.seq)}commitEntries($){return this.withStore((Z,J,W)=>J?Z.appendValidatedBatch((Y)=>{return W(Y),$},J):Z.appendBatch($))}withStore($){return a1(this.storage,this.sessionId,async(Z)=>{let J=new u$(Z.transcriptPath);if(!Z.remoteScope)return $(J,void 0,()=>{return});let W=Z.remoteScope;return $(J,{noFollow:!0,validateHandle:async(X)=>{await w2(W,Z.transcriptPath,X)}},(X)=>{U2(X,this.sessionId,this.projectPath,this.storage.kind==="acp-remote"?this.storage.descriptor:void 0)})})}}function G$($){let Z=null,J=null;for(let W of $){if(W.type==="turn_started"){Z=W.data;continue}if(W.type==="turn_completed")J={type:"turn_completed",data:W.data};else if(W.type==="turn_aborted")J={type:"turn_aborted",data:W.data};else continue;if(Z?.turnId===J.data.turnId)Z=null}return{active:Z,lastTerminal:J}}class E0 extends Error{}var E4="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 z6($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return!1;return $.slice(J+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 q2($,Z){let J=$.findLastIndex((Y)=>Y.type==="turn_started"&&Y.data.turnId===Z);if(J<0)return[];let W=[];for(let Y of $.slice(J+1)){if(Y.type==="turn_started"&&Y.data.turnId!==Z||(Y.type==="turn_completed"||Y.type==="turn_aborted")&&Y.data.turnId===Z)break;if(Y.type!=="message_created"||Y.data.role!=="user")continue;let K=Y.data.metadata,X=Y.data.inboxMessageId!==void 0?Y.data.inboxMessageId:K!==null&&typeof K==="object"&&!Array.isArray(K)?K.inboxMessageId:void 0;if(typeof X==="string"&&X.length>0&&X.length<=K6)W.push(X)}return[...new Set(W)]}function T2($){if(!$||typeof $!=="object"||Array.isArray($))return;if(!("version"in $)||$.version!==1&&$.version!==2&&$.version!==3)return;let Z="inputMessageIds"in $?D1($.inputMessageIds):void 0;if(!Z||!("hadSuccessfulToolResult"in $)||typeof $.hadSuccessfulToolResult!=="boolean"||!("emptyFinalCorrectionSpent"in $)||typeof $.emptyFinalCorrectionSpent!=="boolean")return;let J=$.version===1?0:("interruptedToolCallCount"in $)&&Number.isSafeInteger($.interruptedToolCallCount)&&$.interruptedToolCallCount>=0?$.interruptedToolCallCount:void 0;if(J===void 0)return;let W=$.version===3&&"allSuccessfulToolResultsSafeForResume"in $&&typeof $.allSuccessfulToolResultsSafeForResume==="boolean"?$.allSuccessfulToolResultsSafeForResume:!1;return{version:$.version,inputMessageIds:Z,hadSuccessfulToolResult:$.hadSuccessfulToolResult,interruptedToolCallCount:J,...$.version===3?{allSuccessfulToolResultsSafeForResume:W}:{},emptyFinalCorrectionSpent:$.emptyFinalCorrectionSpent}}function S4($,Z){let J=$.findLastIndex((Q)=>Q.type==="turn_started"&&Q.data.turnId===Z);if(J<0)return 0;let W=$.findIndex((Q,H)=>H>J&&Q.type==="turn_started"&&Q.data.turnId!==Z),Y=$.slice(J+1,W<0?void 0:W),K=new Set(Y.flatMap((Q)=>{if(Q.type!=="part_created"||Q.data.partType!=="tool_call")return[];let H=Q.data.payload;return H&&typeof H==="object"&&!Array.isArray(H)?[typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId]:[Q.data.partId]})),X=new Set;for(let Q of Y){if(Q.type!=="part_created"||Q.data.partType!=="tool_result")continue;let H=Q.data.payload;if(!H||typeof H!=="object"||Array.isArray(H))continue;let V=typeof H.toolCallId==="string"?H.toolCallId:Q.data.partId,z=H.metadata;if(K.has(V)&&z&&typeof z==="object"&&!Array.isArray(z)&&z.processRestartRecovery===!0&&z.sideEffectsUncertain===!0)X.add(V)}return X.size}function R2($){return new Set($.flatMap((Z,J)=>{if(Z.type==="inbox_acknowledged")return Z.data.messageIds;if(Z.type==="turn_aborted")return o1($,J);return[]}))}function j6($,Z,J=[]){let W=T2(Z.data.recovery);if(!W)return;if($.some((Q)=>Q.type==="turn_recovery_acknowledged"&&Q.data.turnId===Z.data.turnId))return;let Y=R2($);for(let Q of J)Y.add(Q);let K=W.inputMessageIds.filter((Q)=>!Y.has(Q)),X=W.version===1?S4($,Z.data.turnId):W.interruptedToolCallCount;if(K.length===0&&!W.hadSuccessfulToolResult&&X===0)return;return{turnId:Z.data.turnId,outcome:"aborted",inputMessageIds:K,hadSuccessfulToolResult:W.hadSuccessfulToolResult,...X>0?{interruptedToolCallCount:X}:{},...W.version===3&&W.allSuccessfulToolResultsSafeForResume===!0?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:W.emptyFinalCorrectionSpent}}function U1($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J.type!=="turn_aborted")continue;let W=j6($,J);if(W)return W}return}function $Z($,Z){let J=$.input,W=Z?.metadata,Y=Z?.subagentRef;if($.toolName!=="Task"||Z?.toolCallId!==$.toolCallId||Z.toolName!=="Task"||J===null||typeof J!=="object"||Array.isArray(J)||W===null||typeof W!=="object"||Array.isArray(W)||!Y)return!1;let{subagent_session_id:K,subagent_type:X,description:Q}=J,H=Y.subagentStatus==="completed"&&Z.error===void 0&&typeof Z.output==="string"||Y.subagentStatus==="failed"&&typeof Z.error==="string"&&Z.error.length>0&&Z.output===null;return typeof K==="string"&&K===Y.subagentSessionId&&W.subagentSessionId===Y.subagentSessionId&&typeof Q==="string"&&Y.subagentDescription===Q&&W.description===Q&&(X===void 0||typeof X==="string"&&X===Y.subagentType)&&W.subagentType===Y.subagentType&&W.subagentStatus===Y.subagentStatus&&H&&W.processRestartRecovery===!0&&W.subagentResultAdopted===!0&&W.sideEffectsUncertain===!1}var T4=1e4,R4=1e5,M4=2592000000,G2=128,k4=1e6,x4=256;function I4($){if(!$||typeof $!=="object"||Array.isArray($))return;let Z=$;if(typeof Z.goalId!=="string"||Z.goalId.length===0||Z.goalId.length>G2||typeof Z.verificationAttempt!=="number"||!Number.isSafeInteger(Z.verificationAttempt)||Z.verificationAttempt<1||Z.verificationAttempt>k4||typeof Z.verifierSessionId!=="string"||Z.verifierSessionId.length===0||Z.verifierSessionId.length>G2||typeof Z.evidenceSha256!=="string"||!/^[a-f0-9]{64}$/.test(Z.evidenceSha256)||typeof Z.goalUpdatedAt!=="string"||!Number.isFinite(Date.parse(Z.goalUpdatedAt)))return;return{goalId:Z.goalId,verificationAttempt:Z.verificationAttempt,verifierSessionId:Z.verifierSessionId,evidenceSha256:Z.evidenceSha256,goalUpdatedAt:Z.goalUpdatedAt}}function M2($,Z){let J=$.data.metadata;if(!J||typeof J!=="object"||Array.isArray(J))return;let W=J.turnFinalization;if(!W||typeof W!=="object"||Array.isArray(W))return;let Y=W,K=Y.turnId,X=Y.inputMessageIds,Q=Y.turnsCount,H=Y.toolCallsCount,V=Y.durationMs,z=Array.isArray(X)?X.filter((B)=>typeof B==="string"&&B.length>0&&B.length<=K6):[];if(typeof K!=="string"||K.length===0||K.length>128||Z!==void 0&&K!==Z||!Array.isArray(X)||X.length>H2||z.length!==X.length||typeof Q!=="number"||!Number.isSafeInteger(Q)||Q<0||Q>T4||typeof H!=="number"||!Number.isSafeInteger(H)||H<0||H>R4||typeof V!=="number"||!Number.isSafeInteger(V)||V<0||V>M4)return;let w;if("goalFinalization"in Y){if(w=I4(Y.goalFinalization),!w)return}return{turnId:K,inputMessageIds:[...new Set(z)],turnsCount:Q,toolCallsCount:H,durationMs:V,...w?{goalFinalization:w}:{}}}function L2($,Z){let J=$.findLastIndex((W)=>W.type==="turn_started"&&W.data.turnId===Z);if(J<0)return;for(let W=$.length-1;W>J;W--){let Y=$[W];if(Y?.type!=="message_created")continue;let K=M2(Y,Z);if(K)return K}return}function h4($){for(let Z=$.length-1;Z>=0;Z--){let J=$[Z];if(J?.type!=="message_created")continue;let W=M2(J);if(!W?.goalFinalization)continue;if(!$.slice(0,Z).some((K)=>K.type==="turn_started"&&K.data.turnId===W.turnId))continue;return{turnId:W.turnId,finalization:W}}return}function m$($,Z){let J=Z?$.findLastIndex((H)=>H.type==="turn_started"&&H.data.turnId===Z):-1;if(Z&&J<0)return{all:[],orphaned:[],hadSuccessfulResult:!1};let W=new Map,Y=new Set,K=new Set,X=new Set;for(let H of $.slice(J+1)){if(H.type==="interaction_requested"){X.add(H.data.toolCallId);continue}if(H.type!=="part_created")continue;let V=H.data.payload&&typeof H.data.payload==="object"&&!Array.isArray(H.data.payload)?H.data.payload:{},z=typeof V.toolCallId==="string"?V.toolCallId:H.data.partId;if(H.data.partType==="tool_call")W.set(z,{toolCallId:z,messageId:H.data.messageId,toolName:typeof V.toolName==="string"?V.toolName:"unknown",input:V.input??null});else if(H.data.partType==="tool_result"){if(Y.add(z),Y.add(H.data.partId),Y.add(H.data.messageId),W.has(z)&&V.error===null)K.add(z)}}let Q=[...W.values()];return{all:Q,orphaned:Q.filter((H)=>!Y.has(H.toolCallId)&&!X.has(H.toolCallId)),hadSuccessfulResult:Q.some((H)=>K.has(H.toolCallId))}}class R0{static sessionInitializationRuns=new Map;projectPath;maxSessions;version;stateStorage;initializedSessions=new Set;constructor($=j0(),Z=100,J=_2(),W=q$($)){this.projectPath=$,this.maxSessions=Z,this.version=J,this.stateStorage=W}createEvent($,Z,J){return{id:B0(),sessionId:Z,projectPath:this.projectPath,timestamp:new Date().toISOString(),type:$,cwd:this.projectPath,...this.stateStorage.kind==="local"?{gitBranch:P2(this.projectPath)}:{},version:this.version,data:J}}log($){return O0.for($,this.projectPath,this.stateStorage)}async ensureSessionCreated($,Z){let J=U$(this.stateStorage,$);if(this.initializedSessions.delete($)){this.initializedSessions.add($);return}let W=R0.sessionInitializationRuns.get(J);if(!W)W=this.initializeSessionFile($,J,Z),R0.sessionInitializationRuns.set(J,W);try{await W,this.rememberInitializedSession($)}finally{if(R0.sessionInitializationRuns.get(J)===W)R0.sessionInitializationRuns.delete(J)}}rememberInitializedSession($){this.initializedSessions.delete($),this.initializedSessions.add($);while(this.initializedSessions.size>x4){let Z=this.initializedSessions.values().next().value;if(Z===void 0)return;this.initializedSessions.delete(Z)}}async initializeSessionFile($,Z,J){if((await this.log($).readAll()).length>0)return;if(this.stateStorage.kind==="acp-remote")throw Error("ACP remote session has no durable creation record");let Y=new Date().toISOString(),K={sessionId:$,rootId:J?.parentSessionId??$,parentId:J?.parentSessionId,relationType:J?"subagent":void 0,resumedFrom:J?.resumedFrom,rootAgentId:J?.rootAgentId,resumeDepth:J?.resumeDepth,title:void 0,status:"running",taskStatus:J?"running":"queued",taskFailure:null,agentType:J?.subagentType,model:void 0,permission:void 0,createdAt:Y,updatedAt:Y},X=this.createEvent("session_created",$,K);await this.log($).commit(X)}buildCompactionMetadata($){let Z={trigger:$.trigger,preTokens:$.preTokens};if($.reason)Z.reason=$.reason;if($.strategy)Z.strategy=$.strategy;if($.preTokenSource)Z.preTokenSource=$.preTokenSource;if($.estimatedPendingTokens!==void 0)Z.estimatedPendingTokens=$.estimatedPendingTokens;if($.postTokens!==void 0)Z.postTokens=$.postTokens;if($.sampleAttempts!==void 0)Z.sampleAttempts=$.sampleAttempts;if($.inputReductions!==void 0)Z.inputReductions=$.inputReductions;if($.messagesOmitted!==void 0)Z.messagesOmitted=$.messagesOmitted;if($.filesOmitted!==void 0)Z.filesOmitted=$.filesOmitted;if($.imagesOmitted!==void 0)Z.imagesOmitted=$.imagesOmitted;if($.fallbackTargetTokens!==void 0)Z.fallbackTargetTokens=$.fallbackTargetTokens;if($.fallbackMessagesOmitted!==void 0)Z.fallbackMessagesOmitted=$.fallbackMessagesOmitted;if($.fallbackMessagesTruncated!==void 0)Z.fallbackMessagesTruncated=$.fallbackMessagesTruncated;if($.failureReason)Z.failureReason=$.failureReason;if($.filesIncluded)Z.filesIncluded=$.filesIncluded;if($.replacementMessages)Z.checkpointVersion=y2;return Z}async initialize(){try{await A2(this.stateStorage,async($)=>{if(this.stateStorage.kind==="local")await p0.mkdir($,{recursive:!0,mode:493})})}catch($){console.warn("[PersistentStore] 无法创建持久化存储目录:",$)}}async saveMessage($,Z,J,W=null,Y,K,X){try{await this.ensureSessionCreated($,K);let Q=new Date().toISOString(),H=B0(),V={messageId:H,role:Z,parentMessageId:W??void 0,inboxMessageId:Y?.inboxMessageId,createdAt:Q,model:Y?.model,usage:Y?.usage,metadata:Y?JSON.parse(JSON.stringify(Y)):void 0},z=this.createEvent("message_created",$,V),w=Z==="assistant"&&X?.trim()?[this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:"reasoning",payload:{text:X},createdAt:Q})]:[],B=typeof J==="string"?[this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:"text",payload:{text:J},createdAt:Q})]:J.map((j)=>this.createEvent("part_created",$,{partId:B0(),messageId:H,partType:j.type==="text"?"text":"image",payload:j.type==="text"?{text:j.text}:{mimeType:v4(j.image_url.url)??"image/png",dataUrl:j.image_url.url},createdAt:Q}));return await this.log($).commitBatch([z,...w,...B]),H}catch(Q){throw console.error(`[PersistentStore] 保存消息失败 (session: ${$}):`,Q),Q}}async acknowledgeInboxMessages($,Z){if(Z.length===0)return;await this.ensureSessionCreated($);let J=new Date().toISOString();await this.log($).commit(this.createEvent("inbox_acknowledged",$,{messageIds:[...Z],acknowledgedAt:J}))}async acknowledgeTurnRecovery($,Z){await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=q0(J);if(W.some((K)=>K.type==="turn_recovery_acknowledged"&&K.data.turnId===Z))throw new E0;let Y=W.findLast((K)=>K.type==="turn_aborted"&&K.data.turnId===Z);if(!Y||!j6(W,Y))throw new E0;return this.createEvent("turn_recovery_acknowledged",$,{turnId:Z,acknowledgedAt:new Date().toISOString()})})}catch(J){if(!(J instanceof E0))throw J}}async persistBackgroundSubagentCompletion($,Z){if(Z.inboxMessageId!==`background-subagent-completion:${Z.childSessionId}`)return{eligible:!1,acknowledged:!1,persisted:!1};await this.ensureSessionCreated($);let J={eligible:!1,acknowledged:!1,persisted:!1};return await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=Y.some((B)=>B.type==="inbox_acknowledged"&&B.data.messageIds.includes(Z.inboxMessageId)),X=Y.find((B)=>B.type==="message_created"&&B.data.inboxMessageId===Z.inboxMessageId),Q=Y.findLast((B)=>{if(B.type!=="part_created"||B.data.partType!=="tool_call"||!B.data.payload||typeof B.data.payload!=="object"||Array.isArray(B.data.payload))return!1;let j=B.data.payload;if(j.toolName!=="Task"||!j.input||typeof j.input!=="object"||Array.isArray(j.input))return!1;let G=j.input,N=G.resume_from??G.resume;return G.run_in_background===!0&&G.subagent_session_id===Z.childSessionId&&G.description===Z.subagentRef.subagentDescription&&(G.subagent_type===void 0||G.subagent_type===Z.subagentRef.subagentType)&&(G.resume_from===void 0||G.resume===void 0||G.resume_from===G.resume)&&(N===void 0?Z.subagentRef.subagentResumedFrom===void 0:N===Z.subagentRef.subagentResumedFrom)});if(!Q)return J={eligible:!1,acknowledged:K,persisted:!1,...X?{messageId:X.data.messageId}:{}},[];if(K)return J={eligible:!0,acknowledged:!0,persisted:!1,...X?{messageId:X.data.messageId}:{}},[];let H=Y.find((B)=>B.type==="part_created"&&B.data.partType==="subtask_ref"&&B.data.payload!==null&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)&&B.data.payload.childSessionId===Z.childSessionId&&B.data.payload.status===Z.subagentRef.subagentStatus);if(X&&H)return J={eligible:!0,acknowledged:!1,persisted:!1,messageId:X.data.messageId},[];let V=new Date().toISOString(),z=X?.data.messageId??B0(),w=[];if(!X){let B={messageId:z,role:"user",inboxMessageId:Z.inboxMessageId,createdAt:V,metadata:JSON.parse(JSON.stringify(Z.metadata))};w.push(this.createEvent("message_created",$,B)),w.push(this.createEvent("part_created",$,{partId:B0(),messageId:z,partType:"text",payload:{text:Z.content},createdAt:V}))}if(!H){let B=Y.findLast((G)=>G.type==="part_created"&&G.data.partType==="subtask_ref"&&G.data.messageId===Q.data.messageId&&G.data.payload!==null&&typeof G.data.payload==="object"&&!Array.isArray(G.data.payload)&&G.data.payload.childSessionId===Z.childSessionId),j=B?.data.payload&&typeof B.data.payload==="object"&&!Array.isArray(B.data.payload)?B.data.payload:void 0;w.push(this.createEvent("part_created",$,{partId:B0(),messageId:Q.data.messageId,partType:"subtask_ref",payload:{childSessionId:Z.subagentRef.subagentSessionId,agentType:Z.subagentRef.subagentType,description:Z.subagentRef.subagentDescription??"",status:Z.subagentRef.subagentStatus,summary:Z.subagentRef.subagentSummary??"",resumedFrom:Z.subagentRef.subagentResumedFrom??null,rootAgentId:Z.subagentRef.subagentRootId??Z.subagentRef.subagentSessionId,resumeDepth:Z.subagentRef.subagentResumeDepth??0,verificationVerdict:Z.subagentRef.verificationVerdict??null,startedAt:typeof j?.startedAt==="string"?j.startedAt:V,finishedAt:V},createdAt:V}))}return J={eligible:!0,acknowledged:!1,persisted:w.length>0,messageId:z},w}),J}async saveTurnStart($,Z){if(Z.goalLineage&&Z.goalLineage.currentTurnId!==Z.turnId)throw Error("Goal lineage current turn must match turn start");await this.ensureSessionCreated($);try{await this.log($).commitValidated((J)=>{let W=q0(J);if(W.some((K)=>K.type==="turn_started"&&K.data.turnId===Z.turnId))throw new E0;let Y=G$(W).active;if(Y)throw Error(`Session already has an active turn: ${Y.turnId}`);return this.createEvent("turn_started",$,Z)})}catch(J){if(!(J instanceof E0))throw J}}async saveTurnCompletion($,Z,J=[]){await this.ensureSessionCreated($);try{await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=new Set(Y.flatMap((V)=>V.type==="inbox_acknowledged"?V.data.messageIds:[])),X=[...new Set(J)].filter((V)=>!K.has(V)),Q=Y.findLast((V)=>(V.type==="turn_completed"||V.type==="turn_aborted")&&V.data.turnId===Z.turnId);if(Q){if(Q.type==="turn_aborted"||X.length===0)throw new E0;return[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]}let H=G$(Y).active;if(!H||H.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);return[...X.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:X,acknowledgedAt:Z.completedAt})]:[],this.createEvent("turn_completed",$,Z)]})}catch(W){if(!(W instanceof E0))throw W}}async saveTurnAbort($,Z,J={}){let W=J.acknowledgeInputMessageIds??[],Y=D1(W);if(!Y)throw Error("Invalid turn abort acknowledgement input message IDs");let K=Y;await this.ensureSessionCreated($);let X,Q=[];try{await this.log($).commitValidatedBatch((H)=>{let V=q0(H),z=R2(V),w=V.findLast((h)=>(h.type==="turn_completed"||h.type==="turn_aborted")&&h.data.turnId===Z.turnId);if(w){if(w.type==="turn_completed")throw X=void 0,Q=[],new E0;let h=T2(w.data.recovery),D0=h?K.filter((c)=>h.inputMessageIds.includes(c)):[],_0=D0.filter((c)=>!z.has(c));if(Q=D0,X=j6(V,w,D0),_0.length===0)throw new E0;return[this.createEvent("inbox_acknowledged",$,{messageIds:_0,acknowledgedAt:Z.abortedAt})]}let B=G$(V).active;if(!B||B.turnId!==Z.turnId)throw Error(`Turn is not active: ${Z.turnId}`);let j=m$(V,B.turnId),G=q2(V,B.turnId),N=U1(V),A=new Set(Z.recovery?.inputMessageIds??[]),S=N?N.inputMessageIds.filter((h)=>A.has(h)):[],T=[...new Set([...G,...S])],p=j.hadSuccessfulResult||Z.recovery?.hadSuccessfulToolResult===!0,x={version:3,inputMessageIds:T,hadSuccessfulToolResult:p,interruptedToolCallCount:j.orphaned.length+(Z.recovery?.version===2||Z.recovery?.version===3?Z.recovery.interruptedToolCallCount:0),allSuccessfulToolResultsSafeForResume:p&&!j.hadSuccessfulResult&&Z.recovery?.version===3&&Z.recovery.hadSuccessfulToolResult&&Z.recovery.allSuccessfulToolResultsSafeForResume,emptyFinalCorrectionSpent:z6(V,B.turnId)||Z.recovery?.emptyFinalCorrectionSpent===!0};X={turnId:Z.turnId,outcome:"aborted",inputMessageIds:x.inputMessageIds,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent};let o=K.filter((h)=>T.includes(h)),s=o.filter((h)=>!z.has(h));Q=o;let M=new Set(z);for(let h of o)M.add(h);let d=x.inputMessageIds.filter((h)=>!M.has(h)),t=x.hadSuccessfulToolResult||x.interruptedToolCallCount>0;X=d.length>0||t?{turnId:Z.turnId,outcome:"aborted",inputMessageIds:d,hadSuccessfulToolResult:x.hadSuccessfulToolResult,...x.interruptedToolCallCount>0?{interruptedToolCallCount:x.interruptedToolCallCount}:{},...x.allSuccessfulToolResultsSafeForResume?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:x.emptyFinalCorrectionSpent}:void 0;let{acknowledgedInputMessageIds:L,...u}=Z;return[this.createEvent("turn_aborted",$,{...u,...o.length>0?{acknowledgedInputMessageIds:o}:{},recovery:x}),...s.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:s,acknowledgedAt:Z.abortedAt})]:[]]})}catch(H){if(!(H instanceof E0))throw H}return{...X?{recovery:X}:{},acknowledgedInputMessageIds:Q}}async loadInterruptedToolCalls($){let Z=await this.loadEvents($);if(!Z)return[];let J=q0(Z),W=G$(J).active;return W?m$(J,W.turnId).orphaned.map((Y)=>({...Y,input:structuredClone(Y.input)})):[]}async hasRecoverableTurn($){let Z=await this.loadEvents($);if(!Z)return!1;let J=q0(Z),W=G$(J).active;if(W){let Y=m$(J,W.turnId);if(Y.orphaned.length>0||Y.hadSuccessfulResult)return!0;if(L2(J,W.turnId))return!0}return U1(J)!==void 0}async loadBackgroundTaskChildIds($){let Z=await this.loadEvents($);if(!Z)return new Set;let J=q0(Z).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 K=Y.input;return K.run_in_background===!0&&typeof K.subagent_session_id==="string"?[K.subagent_session_id]:[]});return new Set(J)}async recoverInterruptedTurn($,Z={}){await this.ensureSessionCreated($);let J;try{await this.log($).commitValidatedBatch((W)=>{let Y=q0(W),K=G$(Y).active,X=m$(Y);if(!K&&X.orphaned.length===0){if(J=U1(Y),J)return[];throw new E0}let Q=K?L2(Y,K.turnId):void 0;if(K&&Q&&X.orphaned.length===0){let M=m$(Y,K.turnId);J={turnId:K.turnId,outcome:"completed",inputMessageIds:Q.inputMessageIds,hadSuccessfulToolResult:M.hadSuccessfulResult,emptyFinalCorrectionSpent:z6(Y,K.turnId),finalization:Q};let d=new Set(Y.flatMap((u)=>u.type==="inbox_acknowledged"?u.data.messageIds:[])),t=Q.inputMessageIds.filter((u)=>!d.has(u)),L=new Date().toISOString();return[...t.length>0?[this.createEvent("inbox_acknowledged",$,{messageIds:t,acknowledgedAt:L})]:[],this.createEvent("turn_completed",$,{turnId:K.turnId,completedAt:L,turnsCount:Q.turnsCount,toolCallsCount:Q.toolCallsCount,durationMs:Q.durationMs})]}let H=K?m$(Y,K.turnId):void 0,V=H?.orphaned.some((M)=>{let d=Z.adoptedToolResults?.get(M.toolCallId);return $Z(M,d)&&d?.error===void 0})??!1,z=H?.orphaned.filter((M)=>{let d=Z.adoptedToolResults?.get(M.toolCallId);return d?.toolCallId===M.toolCallId&&d.toolName===M.toolName&&d.error===void 0}).every((M)=>$Z(M,Z.adoptedToolResults?.get(M.toolCallId)))??!0,w=new Set(K?.inputMessageIds??[]),B=K?U1(Y):void 0,j=B?B.inputMessageIds.filter((M)=>w.has(M)):[],G=j.length>0,N=K?q2(Y,K.turnId):[],A=H?H.orphaned.filter((M)=>{let d=Z.adoptedToolResults?.get(M.toolCallId);return!$Z(M,d)}).length:0,S=G&&B?.hadSuccessfulToolResult===!0,T=(H?.hadSuccessfulResult??!1)||V||S;J=K?{turnId:K.turnId,outcome:"aborted",inputMessageIds:[...new Set([...N,...j])],hadSuccessfulToolResult:T,...(()=>{let M=A+(G?B?.interruptedToolCallCount??0:0);return M>0?{interruptedToolCallCount:M}:{}})(),...T&&!(H?.hadSuccessfulResult??!1)&&z&&(!S||B?.allSuccessfulToolResultsSafeForResume===!0)?{allSuccessfulToolResultsSafeForResume:!0}:{},emptyFinalCorrectionSpent:z6(Y,K.turnId)||G&&B?.emptyFinalCorrectionSpent===!0}:U1(Y);let p=K?H?.all.length??0:0,x=new Date().toISOString(),o=K?Date.parse(K.startedAt):Number.NaN,s=X.orphaned.flatMap((M)=>{let d=Z.adoptedToolResults?.get(M.toolCallId),t=$Z(M,d)?d:void 0,L=this.createEvent("part_created",$,{partId:M.toolCallId,messageId:t?M.messageId:M.toolCallId,partType:"tool_result",payload:t?{toolCallId:M.toolCallId,toolName:M.toolName,output:t.output,error:t.error??null,...t.metadata===void 0?{}:{metadata:t.metadata}}:{toolCallId:M.toolCallId,toolName:M.toolName,output:null,error:E4,metadata:{processRestartRecovery:!0,sideEffectsUncertain:!0}},createdAt:x});if(!t?.subagentRef)return[L];let u=t.subagentRef;return[L,this.createEvent("part_created",$,{partId:B0(),messageId:M.messageId,partType:"subtask_ref",payload:{childSessionId:u.subagentSessionId,agentType:u.subagentType,description:u.subagentDescription??"",status:u.subagentStatus,summary:u.subagentSummary??"",resumedFrom:u.subagentResumedFrom??null,rootAgentId:u.subagentRootId??u.subagentSessionId,resumeDepth:u.subagentResumeDepth??0,verificationVerdict:u.verificationVerdict??null,startedAt:x,finishedAt:x},createdAt:x})]});return K?[...s,this.createEvent("turn_aborted",$,{turnId:K.turnId,cause:"process_restart",abortedAt:x,turnsCount:0,toolCallsCount:p,durationMs:Number.isFinite(o)?Math.max(0,Date.now()-o):0,recovery:J?{version:3,inputMessageIds:J.inputMessageIds,hadSuccessfulToolResult:J.hadSuccessfulToolResult,interruptedToolCallCount:J.interruptedToolCallCount??0,allSuccessfulToolResultsSafeForResume:J.allSuccessfulToolResultsSafeForResume===!0,emptyFinalCorrectionSpent:J.emptyFinalCorrectionSpent}:void 0})]:s})}catch(W){if(!(W instanceof E0))throw W}return J}async loadLatestGoalFinalization($){let Z=await this.loadEvents($);return Z?h4(Z):void 0}async saveInteractionRequest($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((Y)=>Y.type==="interaction_requested"&&Y.data.requestId===Z.requestId))throw Error(`Interaction request already exists: ${Z.requestId}`);return this.createEvent("interaction_requested",$,Z)})}async saveInteractionResponse($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="interaction_requested"&&K.data.requestId===Z.requestId))throw Error(`Interaction request not found: ${Z.requestId}`);if(J.some((K)=>K.type==="interaction_responded"&&K.data.requestId===Z.requestId))throw Error(`Interaction already responded: ${Z.requestId}`);return this.createEvent("interaction_responded",$,Z)})}async saveInteractionRecovery($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="interaction_responded"&&K.data.requestId===Z.requestId))throw Error(`Interaction response not found: ${Z.requestId}`);if(J.some((K)=>K.type==="interaction_recovered"&&K.data.requestId===Z.requestId))throw Error(`Interaction already recovered: ${Z.requestId}`);return this.createEvent("interaction_recovered",$,Z)})}async saveReviewStart($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(J.some((K)=>K.type==="review_started"&&K.data.reviewId===Z.reviewId))throw Error(`Review already exists: ${Z.reviewId}`);if(J.some((K)=>K.type==="review_started"&&!J.some((X)=>X.type==="review_completed"&&X.data.reviewId===K.data.reviewId)))throw Error("Session already has an active review");return this.createEvent("review_started",$,Z)})}async saveReviewCompletion($,Z){await this.ensureSessionCreated($),await this.log($).commitValidated((J)=>{if(!J.some((K)=>K.type==="review_started"&&K.data.reviewId===Z.reviewId))throw Error(`Review not found: ${Z.reviewId}`);if(J.some((K)=>K.type==="review_completed"&&K.data.reviewId===Z.reviewId))throw Error(`Review already completed: ${Z.reviewId}`);return this.createEvent("review_completed",$,Z)})}async saveToolUse($,Z,J,W=null,Y,K){try{if(K!==void 0&&(K.length===0||K.length>512))throw Error("Provider tool call identity must contain 1-512 characters");await this.ensureSessionCreated($,Y);let X=new Date().toISOString(),Q=W??B0(),H=[];if(!W){let w={messageId:Q,role:"assistant",parentMessageId:void 0,createdAt:X};H.push(this.createEvent("message_created",$,w))}let V=K??B0(),z={partId:V,messageId:Q,partType:"tool_call",payload:{toolCallId:V,toolName:Z,input:J},createdAt:X};if(H.push(this.createEvent("part_created",$,z)),Z==="Task"&&J&&typeof J==="object"){let w=J,B=typeof w.subagent_session_id==="string"?w.subagent_session_id:void 0,j=typeof w.subagent_type==="string"?w.subagent_type:void 0;if(B&&j){let G={partId:B0(),messageId:Q,partType:"subtask_ref",payload:{childSessionId:B,agentType:j,status:"running",summary:typeof w.description==="string"?w.description:"",startedAt:X},createdAt:X};H.push(this.createEvent("part_created",$,G))}}return await this.log($).commitBatch(H),V}catch(X){throw console.error(`[PersistentStore] 保存工具调用失败 (session: ${$}):`,X),X}}async saveToolResult($,Z,J,W,Y=null,K,X,Q,H){try{await this.ensureSessionCreated($,X);let V=new Date().toISOString(),z=Y??B0();return await this.log($).commitValidatedBatch((w)=>{let B=Q?.subagentStatus==="running"?q0(w).findLast((T)=>T.type==="part_created"&&T.data.partType==="subtask_ref"&&T.data.payload!==null&&typeof T.data.payload==="object"&&!Array.isArray(T.data.payload)&&T.data.payload.childSessionId===Q.subagentSessionId&&(T.data.payload.status==="completed"||T.data.payload.status==="failed"||T.data.payload.status==="cancelled")):void 0,j=B?.data.payload,G=H&&typeof H==="object"&&!Array.isArray(H)?H:{},N=j?{...G,subagentSessionId:j.childSessionId,subagentType:j.agentType,description:j.description,subagentStatus:j.status,subagentSummary:j.summary,subagentResumedFrom:j.resumedFrom,subagentRootId:j.rootAgentId,subagentResumeDepth:j.resumeDepth,verificationVerdict:j.verificationVerdict}:H,A=[];if(!Y){let T={messageId:z,role:"assistant",parentMessageId:void 0,createdAt:V};A.push(this.createEvent("message_created",$,T))}let S={partId:Z,messageId:z,partType:"tool_result",payload:{toolCallId:Z,toolName:J,output:W,error:K??null,...N===void 0?{}:{metadata:N}},createdAt:V};if(A.push(this.createEvent("part_created",$,S)),Q&&!B){let T=Q.subagentStatus==="running"?null:V,p={partId:B0(),messageId:z,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:V,finishedAt:T},createdAt:V};A.push(this.createEvent("part_created",$,p))}return A}),Z}catch(V){throw console.error(`[PersistentStore] 保存工具结果失败 (session: ${$}):`,V),V}}async saveCompaction($,Z,J,W=null){try{await this.ensureSessionCreated($);let Y=new Date().toISOString(),K=B0(),X={messageId:K,role:"system",parentMessageId:W??void 0,createdAt:Y},Q=this.buildCompactionMetadata(J),H={partId:B0(),messageId:K,partType:"summary",payload:{text:Z,metadata:Q,...J.replacementMessages?{replacementMessages:f2(J.replacementMessages)}:{}},createdAt:Y},V=[this.createEvent("message_created",$,X),this.createEvent("part_created",$,H)];return await this.log($).commitBatch(V),K}catch(Y){throw console.error(`[PersistentStore] 保存压缩失败 (session: ${$}):`,Y),Y}}async recordTokenBudgetHandoff($,Z){await this.ensureSessionCreated($);let J=JZ([]),W=await this.log($).commitValidatedBatch((K)=>{if(J=JZ(q0(K)),J.kind!=="none")return[];let X=new Date().toISOString();return[this.createEvent("token_budget_handoff_recorded",$,{...Z,messageId:`${E2}${B0()}`,createdAt:X})]});if(J.kind==="valid")return{outcome:"existing",event:J.event};if(J.kind==="suppressed")return{outcome:"suppressed",recordId:J.recordId};if(W.length!==1)throw Error("Token budget handoff commit produced an impossible result");let Y=JZ(W);if(Y.kind!=="valid")throw Error("Token budget handoff commit produced an invalid event");return{outcome:"created",event:Y.event}}async initSession($,Z){await this.ensureSessionCreated($,Z)}async loadEvents($){try{let Z=await this.log($).readAll();return Z.length>0?q0(Z):null}catch{return null}}async loadSession($){try{let Z=q0(await this.log($).readAll());if(Z.length===0)return null;let J=Z.find((W)=>W.type==="session_created");return{sessionId:$,userId:void 0,preferences:{},configuration:{},startTime:new Date(J?.timestamp??Z[0].timestamp).getTime()}}catch{return null}}async loadConversation($){try{let Z=q0(await this.log($).readAll());if(Z.length===0)return null;let J=new Map;for(let X of Z){if(X.type==="message_created")J.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 Q=J.get(X.data.messageId);if(Q){let H=X.data.payload;Q.content=H.text??""}}if(X.type==="part_created"&&X.data.partType==="image"){let Q=J.get(X.data.messageId);if(Q)Q.content=Q.content?`${Q.content}
96
- [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],K=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:K}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=H1(this.projectPath);return(await p0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=ZZ(this.projectPath,$),J=new u$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let K=q0(Y),X=Y[Y.length-1],Q=K.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=ZZ(this.projectPath,$);await new u$(Z).delete(),await p0.unlink(O2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await b2(this.projectPath,$,F2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-d420fs8m.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");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,K)=>K.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(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=ZZ(this.projectPath,J),K=await new u$(W).getStats();Z+=K.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=H1(this.projectPath);await p0.mkdir($,{recursive:!0,mode:493});let Z=S2.join($,".health-check");return await p0.writeFile(Z,"test","utf-8"),await p0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return N2()}}function v4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var k2=131072,B6=new x$;function D6($,Z){return`${C4.resolve($)}\x00${Z}`}function q6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>k2)throw Error(`${Z} exceeds ${k2} bytes`);return JSON.parse(J)}function x2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function p4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function u4($,Z){if($.request.interactionType!=="elicitation")return q6(Z,"Interaction response");return q6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function I2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function m4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function d4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
96
+ [Image]`:"[Image]"}}let W=Array.from(J.values()),Y=Z[Z.length-1],K=new Date(Y.timestamp).getTime();return{messages:W,topics:[],lastActivity:K}}catch{return null}}async listSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session enumeration requires SessionService");try{let $=H1(this.projectPath);return(await p0.readdir($)).filter((J)=>J.endsWith(".jsonl")).map((J)=>J.replace(".jsonl","")).sort()}catch{return[]}}async getSessionSummary($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session summaries require SessionService");try{let Z=ZZ(this.projectPath,$),J=new u$(Z);if(!(await J.getStats()).exists)return null;let Y=await J.readAll();if(Y.length===0)return null;let K=q0(Y),X=Y[Y.length-1],Q=K.filter((H)=>H.type==="message_created"&&["user","assistant"].includes(H.data.role)).length;return{sessionId:$,lastActivity:new Date(X.timestamp).getTime(),messageCount:Q,topics:[]}}catch{return null}}async deleteSession($){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session deletion requires SessionService");this.initializedSessions.delete($);try{let Z=ZZ(this.projectPath,$);await new u$(Z).delete(),await p0.unlink(O2(this.projectPath,$)).catch((W)=>{if(W.code!=="ENOENT")throw W}),await b2(this.projectPath,$,F2());try{let{getProjectionDb:W,removeSessionFromProjection:Y}=await import("./chunk-2xpjy0ef.js"),K=await W();if(K)Y(K,$,this.projectPath)}catch{}}catch(Z){console.warn(`[PersistentStore] 删除会话失败 (session: ${$}):`,Z)}finally{this.initializedSessions.delete($)}}async cleanupOldSessions(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote session cleanup requires SessionService");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,K)=>K.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(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage statistics require SessionService");try{let $=await this.listSessions(),Z=0;for(let J of $){let W=ZZ(this.projectPath,J),K=await new u$(W).getStats();Z+=K.size}return{totalSessions:$.length,totalSize:Z,projectPath:this.projectPath}}catch{return{totalSessions:0,totalSize:0,projectPath:this.projectPath}}}async checkStorageHealth(){if(this.stateStorage.kind==="acp-remote")throw Error("Remote storage health checks require SessionService");try{let $=H1(this.projectPath);await p0.mkdir($,{recursive:!0,mode:493});let Z=S2.join($,".health-check");return await p0.writeFile(Z,"test","utf-8"),await p0.unlink(Z),{isAvailable:!0,canWrite:!0}}catch($){return{isAvailable:!1,canWrite:!1,error:$ instanceof Error?$.message:String($)}}}static async listAllProjects(){return N2()}}function v4($){return/^data:([^;,]+)[;,]/.exec($)?.[1]??null}var k2=131072,B6=new x$;function D6($,Z){return`${C4.resolve($)}\x00${Z}`}function q6($,Z){let J=JSON.stringify($);if(J===void 0)throw Error(`${Z} is not JSON serializable`);if(Buffer.byteLength(J,"utf8")>k2)throw Error(`${Z} exceeds ${k2} bytes`);return JSON.parse(J)}function x2($){if($.type==="askUserQuestion")return"question";if($.type==="mcpElicitation")return"elicitation";if($.type==="permission"||$.type==="mcpSampling")return"permission";return}function p4($,Z){return JSON.stringify($)===JSON.stringify(Z)}function u4($,Z){if($.request.interactionType!=="elicitation")return q6(Z,"Interaction response");return q6({approved:Z.approved,...Z.reason?{reason:Z.reason}:{},...Z.elicitation?{elicitation:{action:Z.elicitation.action}}:{},...Z.openExternalUrl?{openExternalUrl:!0}:{}},"Interaction response")}function I2($){let Z=$.request.details;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction details: ${$.request.requestId}`);return Z}function m4($){let Z=$.response?.response;if(!Z||typeof Z!=="object"||Array.isArray(Z))throw Error(`Invalid durable interaction response: ${$.request.requestId}`);return Z}function d4($){if(!$.answers||Object.keys($.answers).length===0)return"No structured answers were provided.";return Object.entries($.answers).map(([Z,J])=>{let W=Array.isArray(J)?J.join(", "):J;return`${Z}: ${W}`}).join(`
97
97
  `)}function c4($,Z){let{request:J}=$;if(J.interactionType==="question"){let X=d4(Z);return{toolOutput:`User answers:
98
98
  ${X}`,inbox:`The process restarted while waiting for a structured answer. The recovered user response is:
99
99
  ${X}
@@ -178,4 +178,4 @@ ${y}`}if(typeof k==="object"&&k!==null)k=JSON.stringify(k,null,2);if(typeof k===
178
178
 
179
179
  <system-reminder>
180
180
  ${g2(H$)}
181
- </system-reminder>`,metadata:f0};L.appendControl("user",U);let D=await r0($,J,U.content,z,f0);if(D)z=D}}if(W?.signal?.aborted)return B(H,V.length,W.signal)}}catch(F){if(F instanceof k$)try{let O=J.sessionId?await X1.loadSessionModelContext(J.sessionId,J.workspaceRoot):t;L.restoreDurableHistory(O)}catch(O){r.error("[Loop] Failed to reload durable context after message commit failure:",O),L.restoreDurableHistory(t)}throw F}finally{if(W?.transientInput==="goal_continuation")L.removeMessages((F)=>{let O=F.metadata;return O!==null&&typeof O==="object"&&!Array.isArray(O)&&O.transientGoalContinuation===!0});L.writeback()}}catch(j){if(C0(j))return B(H,V.length,W?.signal);if(j instanceof k$)return{success:!1,error:{type:"message_persistence_failed",message:j.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};let G=S5(j);return r.error(`API 调用失败: ${G}`),{success:!1,error:{type:"api_error",message:G,details:j},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}finally{if(w)J.messages.push({role:"system",content:mZ}),await PJ($,J,z)}}export{N7 as xb,_7 as yb,c1 as zb,EJ as Ab,Z1 as Bb,r5 as Cb,xZ as Db,J1 as Eb,KJ as Fb,d8 as Gb,T$ as Hb,t5 as Ib,G$ as Jb,uZ as Kb,LJ as Lb,j3 as Mb,K1 as Nb,O0 as Ob,R0 as Pb,hZ as Qb,vZ as Rb,zJ as Sb,pZ as Tb,Z8 as Ub,J8 as Vb,Y8 as Wb,S$ as Xb,C1 as Yb,U9 as Zb,r0 as _b,v0 as $b,dZ as ac,m1 as bc,Q1 as cc,RJ as dc,a as ec,h$ as fc,e1 as gc,G0 as hc,SW as ic,Q8 as jc,zZ as kc,V8 as lc,z8 as mc,j8 as nc,y5 as oc,E6 as pc,N8 as qc,m5 as rc};
181
+ </system-reminder>`,metadata:f0};L.appendControl("user",U);let D=await r0($,J,U.content,z,f0);if(D)z=D}}if(W?.signal?.aborted)return B(H,V.length,W.signal)}}catch(F){if(F instanceof k$)try{let O=J.sessionId?await X1.loadSessionModelContext(J.sessionId,J.workspaceRoot):t;L.restoreDurableHistory(O)}catch(O){r.error("[Loop] Failed to reload durable context after message commit failure:",O),L.restoreDurableHistory(t)}throw F}finally{if(W?.transientInput==="goal_continuation")L.removeMessages((F)=>{let O=F.metadata;return O!==null&&typeof O==="object"&&!Array.isArray(O)&&O.transientGoalContinuation===!0});L.writeback()}}catch(j){if(C0(j))return B(H,V.length,W?.signal);if(j instanceof k$)return{success:!1,error:{type:"message_persistence_failed",message:j.message},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}};let G=S5(j);return r.error(`API 调用失败: ${G}`),{success:!1,error:{type:"api_error",message:G,details:j},metadata:{turnsCount:H,toolCallsCount:V.length,duration:Date.now()-K,tokensUsed:X}}}finally{if(w)J.messages.push({role:"system",content:mZ}),await PJ($,J,z)}}export{N7 as xb,_7 as yb,c1 as zb,EJ as Ab,Z1 as Bb,r5 as Cb,xZ as Db,J1 as Eb,KJ as Fb,d8 as Gb,T$ as Hb,t5 as Ib,G$ as Jb,uZ as Kb,LJ as Lb,j3 as Mb,K1 as Nb,O0 as Ob,R0 as Pb,hZ as Qb,vZ as Rb,zJ as Sb,pZ as Tb,Z8 as Ub,J8 as Vb,Y8 as Wb,S$ as Xb,C1 as Yb,U9 as Zb,r0 as _b,v0 as $b,dZ as ac,m1 as bc,Q1 as cc,RJ as dc,a as ec,Y$ as fc,h$ as gc,e1 as hc,G0 as ic,SW as jc,Q8 as kc,zZ as lc,V8 as mc,z8 as nc,j8 as oc,y5 as pc,E6 as qc,N8 as rc,m5 as sc};
@@ -1,2 +1,2 @@
1
1
  import{promises as B}from"node:fs";import q from"node:path";import{LRUCache as H}from"lru-cache";var K=512,Z=new H({max:K});async function L(x){let b=x;while(!0){try{return await B.lstat(q.join(b,".git")),b}catch(V){if(V.code!=="ENOENT")return}let F=q.dirname(b);if(F===b)return;b=F}}async function M(x){let b=q.join(x,".git"),F=await B.lstat(b);if(F.isDirectory())return x;if(!F.isFile())return;let V=await B.readFile(b,"utf8"),J=/^gitdir:\s*(.+)\s*$/im.exec(V);if(!J)return;let Q=await B.realpath(q.isAbsolute(J[1])?J[1]:q.resolve(x,J[1])),Y=Q;try{let z=(await B.readFile(q.join(Q,"commondir"),"utf8")).trim();if(z)Y=await B.realpath(q.resolve(Q,z))}catch(z){if(z.code!=="ENOENT")throw z}return q.basename(Y)===".git"?B.realpath(q.dirname(Y)):void 0}async function N(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x),F=Z.get(b);if(F)return F;let V=b;try{let Q=await L(b);if(Q){let Y=await M(Q),z=q.relative(Q,b);if(Y&&(z===""||!z.startsWith(`..${q.sep}`)&&z!==".."&&!q.isAbsolute(z))){let $=q.resolve(Y,z);V=await B.realpath($).catch(()=>$)}}}catch{}let J={projectPath:b,trustRoot:V};return Z.set(b,J),J}async function S(x){if(!q.isAbsolute(x))throw Error("Workspace path must be absolute");let b=await B.realpath(x);Z.delete(b)}
2
- export{N as dk,S as ek};
2
+ export{N as ek,S as fk};
@@ -1,4 +1,4 @@
1
- import{Ra as H}from"./chunk-nkzq66vk.js";import"./chunk-zzvs471p.js";import"./chunk-53fc0yrq.js";import{Yf as $,cg as T}from"./chunk-tb4998x1.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-wvxrtmws.js";import"./chunk-3y2x6fb6.js";import"./chunk-j4pehxf9.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as k}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-g5e8b4ad.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{Ra as H}from"./chunk-pk3ftt16.js";import"./chunk-fdr4fcrf.js";import"./chunk-egss0m1x.js";import{Zf as $,dg as T}from"./chunk-6q0n03nz.js";import"./chunk-v508x7cg.js";import"./chunk-5yyp6njq.js";import"./chunk-qr80p5m0.js";import"./chunk-ys8gysg8.js";import"./chunk-ghvfd7bx.js";import"./chunk-qpmvp4q2.js";import"./chunk-tm3789m3.js";import{cj as k}from"./chunk-qdbbke8f.js";import"./chunk-wezr6wfq.js";import"./chunk-rmfzym94.js";import"./chunk-j89qk7bp.js";import"./chunk-0eajnhrj.js";import"./chunk-cycsbwm3.js";import"./chunk-ggdgk3gy.js";import"./chunk-ky592ay9.js";import"./chunk-n52n2w5v.js";import"./chunk-cjfb4kjp.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器
@@ -1,6 +1,6 @@
1
- import{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-tb4998x1.js";import{Ci as S,Di as m,Ei as c,Fi as p,Hi as u,Ii as d,Mi as l,Ri as i,Si as t,ei as y,gi as D,hi as h,ji as A,qi as P,ri as T,ti as E,vi as _,wi as f,yi as C}from"./chunk-j4pehxf9.js";import{Ti as Y}from"./chunk-kv458q06.js";import{$i as X}from"./chunk-2f8d0km4.js";import{dj as U,ej as L,kj as M,lj as O,nj as $,oj as I,pj as G,rj as N,sj as j,uj as F,vj as R}from"./chunk-ddvdc2p0.js";import{Dj as s,Fj as x,Hj as k,Kj as Z}from"./chunk-2mk914vk.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
1
+ import{xf as v}from"./chunk-je908ygr.js";import{Qf as e}from"./chunk-6q0n03nz.js";import{Di as S,Ei as m,Fi as c,Gi as p,Ii as u,Ji as d,Ni as l,Si as i,Ti as t,fi as y,hi as D,ii as h,ki as A,ri as P,si as T,ui as E,wi as _,xi as f,zi as C}from"./chunk-ghvfd7bx.js";import{Ui as Y}from"./chunk-qpmvp4q2.js";import{aj as X}from"./chunk-qdbbke8f.js";import{ej as U,fj as L,lj as M,mj as O,oj as $,pj as I,qj as G,sj as N,tj as j,vj as F,wj as R}from"./chunk-wezr6wfq.js";import{Ej as s,Gj as x,Ij as k,Lj as Z}from"./chunk-rmfzym94.js";import{promises as a}from"node:fs";import g from"node:path";var r=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],kk=new Set([...Object.keys(l),...r,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),qk=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:U,maximum:L})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:M,maximum:O})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:I})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:N,maximum:j})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:F,maximum:R})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:S,maximum:m})),maxQueuedTasks:k.Optional(k.Integer({minimum:c,maximum:p})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:u,maximum:d})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:E,maximum:_})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:f,maximum:C})),maxResidentSessionProjections:k.Optional(k.Integer({minimum:y,maximum:D})),sessionProjectionIdleMs:k.Optional(k.Integer({minimum:h,maximum:A})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),wk=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"],["maxResidentSessionProjections","maxResidentSessionProjections"],["sessionProjectionIdleMs","sessionProjectionIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!kk.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(qk,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function n(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=g.resolve(X(),B),J;try{J=await a.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function o(q,B){if(!B)return;let w=B;for(let[J,H]of wk){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=s("General"),Uk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},Lk=async(q)=>{let B=await n(typeof q.settings==="string"?q.settings:void 0);if(o(q,B),typeof q.agents==="string")v(q.agents);zk(q);try{let J=await i.getInstance().initialize(B),H=t(J,q);if(e().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
2
2
  [FAIL] 配置初始化失败
3
3
  `),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
4
4
  请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
5
5
  `),process.exit(1)}};function zk(q){if(q.continue&&q.resume)throw Error("Cannot use both --continue and --resume flags simultaneously");if(q.forkSession&&!q.continue&&!q.resume)throw Error("--fork-session requires --resume or --continue");if(q.sessionId&&(q.continue||q.resume)&&!q.forkSession)throw Error("--session-id can only be combined with --resume or --continue when --fork-session is set")}var Mk=(q)=>{if(q.jsonSchema&&q.outputSchema)throw Error("--json-schema cannot be combined with --output-schema");if((q.jsonSchema||q.outputSchema)&&!q.print&&!q.headless)throw Error("--json-schema and --output-schema can only be used with --print or --headless");if(q.outputFormat&&q.outputFormat!=="text"&&!q.print&&!q.headless)throw Error("--output-format can only be used with --print or --headless");if(q.headless&&q.outputFormat&&!["text","jsonl"].includes(q.outputFormat))throw Error(`--headless only supports --output-format text|jsonl, but got "${q.outputFormat}". Use --print for json|stream-json support.`);if(q.print&&q.outputFormat&&!["text","json","stream-json"].includes(q.outputFormat))throw Error(`--print only supports --output-format text|json|stream-json, but got "${q.outputFormat}". Use --headless for jsonl support.`);if(q.inputFormat==="stream-json"&&q.print)Q.warn("[WARN] Warning: stream-json input format may not work as expected with --print")};
6
- export{Uk as tf,Lk as uf,Mk as vf};
6
+ export{Uk as uf,Lk as vf,Mk as wf};