blade-code 0.10.177 → 0.10.178

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 (42) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-fkm1k8xy.js → chunk-2p9j16ed.js} +1 -1
  3. package/dist/{chunk-4xqhmp61.js → chunk-4jfs3qsd.js} +1 -1
  4. package/dist/{chunk-pwj9zz8z.js → chunk-4vn0dr8c.js} +1 -1
  5. package/dist/{chunk-qjhsps46.js → chunk-5f3jvt7q.js} +1 -1
  6. package/dist/{chunk-f3dbn3bh.js → chunk-5hs5pv2z.js} +1 -1
  7. package/dist/{chunk-bw5x4ywa.js → chunk-600xa10z.js} +1 -1
  8. package/dist/{chunk-5esk0stg.js → chunk-6ayrcbda.js} +1 -1
  9. package/dist/{chunk-dd6rtthc.js → chunk-8gdw286x.js} +1 -1
  10. package/dist/{chunk-htd9p2fd.js → chunk-8wnhsgvw.js} +1 -1
  11. package/dist/{chunk-dpjy7s53.js → chunk-96jpzf75.js} +1 -1
  12. package/dist/{chunk-gnnht0bk.js → chunk-awxfg8y0.js} +1 -1
  13. package/dist/{chunk-qwjz3z9f.js → chunk-aznbr6ay.js} +1 -1
  14. package/dist/{chunk-ycafgg7y.js → chunk-b8rkgzjs.js} +1 -1
  15. package/dist/{chunk-ta34g0p4.js → chunk-c8mhvnyf.js} +1 -1
  16. package/dist/chunk-dma247n9.js +1 -0
  17. package/dist/{chunk-gcmw83t0.js → chunk-dqb5fm8x.js} +1 -1
  18. package/dist/{chunk-020t9es1.js → chunk-fb773kdb.js} +1 -1
  19. package/dist/{chunk-nxxnm4qc.js → chunk-fk3qhnsn.js} +1 -1
  20. package/dist/{chunk-3cf79p63.js → chunk-hv1z8nxq.js} +1 -1
  21. package/dist/{chunk-abpf6meb.js → chunk-knyn38rp.js} +1 -1
  22. package/dist/{chunk-1h6mg4zp.js → chunk-mdepy489.js} +1 -1
  23. package/dist/{chunk-b1rwsq1x.js → chunk-mjw0evjt.js} +1 -1
  24. package/dist/{chunk-xg7fft50.js → chunk-mn8e305h.js} +2 -2
  25. package/dist/{chunk-mt7tn0gn.js → chunk-nan8mv2n.js} +1 -1
  26. package/dist/{chunk-rf4h1sf4.js → chunk-nr4axed3.js} +1 -1
  27. package/dist/{chunk-2srv8n3m.js → chunk-nxmcc4rw.js} +1 -1
  28. package/dist/{chunk-j4wxy839.js → chunk-pq1cyhc1.js} +1 -1
  29. package/dist/{chunk-tacbdem4.js → chunk-qtnykwv9.js} +1 -1
  30. package/dist/{chunk-d2nz3pfs.js → chunk-r0ragech.js} +4 -4
  31. package/dist/{chunk-ysf775dm.js → chunk-sdn7af9d.js} +1 -1
  32. package/dist/{chunk-sbj9wyn4.js → chunk-vpwar5x8.js} +1 -1
  33. package/dist/{chunk-vas2gskt.js → chunk-vw4f9sx9.js} +1 -1
  34. package/dist/chunk-w41f5j91.js +1 -0
  35. package/dist/{chunk-xaaege0t.js → chunk-x1vjav7g.js} +1 -1
  36. package/dist/{chunk-bhtn8jz2.js → chunk-y94nrgaf.js} +1 -1
  37. package/dist/{chunk-95b7eanh.js → chunk-yc8ejwev.js} +1 -1
  38. package/dist/{chunk-we29e656.js → chunk-z8drxtsd.js} +1 -1
  39. package/dist/{chunk-4gns7fxm.js → chunk-zvf33r3d.js} +1 -1
  40. package/package.json +1 -1
  41. package/dist/chunk-fkah1s04.js +0 -1
  42. package/dist/chunk-hgg2etq8.js +0 -1
@@ -1,4 +1,4 @@
1
- import{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-pwj9zz8z.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-4gns7fxm.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{wf as v}from"./chunk-nheny8xp.js";import{Pf as e}from"./chunk-4vn0dr8c.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-zvf33r3d.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(`
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. 配置文件权限是否正确
@@ -1 +1 @@
1
- import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-020t9es1.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{$j as f,Wj as a,Xj as b,Yj as c,Zj as d,_j as e}from"./chunk-fb773kdb.js";import"./chunk-eg3ms291.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{a,b as i,c as l,d as m}from"./chunk-abpf6meb.js";import"./chunk-95b7eanh.js";import"./chunk-zj1g4nbq.js";import"./chunk-nxxnm4qc.js";import"./chunk-ysf775dm.js";import"./chunk-1h6mg4zp.js";import"./chunk-d2nz3pfs.js";import"./chunk-g01mth5d.js";import"./chunk-qjhsps46.js";import"./chunk-30x3mcsb.js";import"./chunk-bw5x4ywa.js";import"./chunk-zzvs471p.js";import"./chunk-ycafgg7y.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-5esk0stg.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-pwj9zz8z.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-we29e656.js";import"./chunk-fkm1k8xy.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-dpjy7s53.js";import"./chunk-3y2x6fb6.js";import"./chunk-4gns7fxm.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-020t9es1.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
1
+ import{a,b as i,c as l,d as m}from"./chunk-knyn38rp.js";import"./chunk-yc8ejwev.js";import"./chunk-zj1g4nbq.js";import"./chunk-fk3qhnsn.js";import"./chunk-sdn7af9d.js";import"./chunk-mdepy489.js";import"./chunk-r0ragech.js";import"./chunk-g01mth5d.js";import"./chunk-5f3jvt7q.js";import"./chunk-30x3mcsb.js";import"./chunk-600xa10z.js";import"./chunk-zzvs471p.js";import"./chunk-b8rkgzjs.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as n}from"./chunk-6ayrcbda.js";import"./chunk-jj4ggb04.js";import{Uf as s}from"./chunk-4vn0dr8c.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-z8drxtsd.js";import"./chunk-2p9j16ed.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-96jpzf75.js";import"./chunk-3y2x6fb6.js";import"./chunk-zvf33r3d.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-fb773kdb.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1,4 +1,4 @@
1
- import{Ga as W3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as HW,Qa as fY,Ra as e0}from"./chunk-qjhsps46.js";import{$a as BX,Sa as Y5,Va as pZ,Za as tZ,_a as zX,bb as nW,db as aW,eb as A9,wb as sW}from"./chunk-30x3mcsb.js";import{Ab as p7,Bb as D2,Cb as GY,Db as x1,Eb as s7,Fb as DY,Gb as ZY,Hb as qY,Ib as wY,Jb as UQ,Lb as YX,Nb as V0,Pb as F2,Sb as p4,Ub as FZ,Vb as l4,Wb as i4,Yb as MJ,Zb as R$,dc as sX,ec as G8,fc as oX,gc as JX,ic as u1,jc as kX,oc as rY,rc as nY,xb as s5,yb as g7,zb as J1}from"./chunk-bw5x4ywa.js";import{$c as r8,$d as iY,Ac as k3,Bc as T1,Cc as ZJ,Dc as F0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as YY,Lc as QY,Mc as TX,Nc as X3,Nd as V8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as YW,Yc as d2,Yd as HX,Zc as z3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as PX,fd as d6,fe as SX,gd as J2,hd as m6,he as o,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as CX,zc as r3}from"./chunk-ycafgg7y.js";import{ie as i,je as GQ,ke as KQ,le as hJ,ne as _2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as RX,Le as fX,Ue as $V,ff as ZV,pe as tW,se as eW}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as pY,cg as B2}from"./chunk-pwj9zz8z.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as lY,ng as mY,og as cX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as eX}from"./chunk-50vwafn5.js";import{Ag as jX,xg as OX,yg as NX,zg as bX}from"./chunk-we29e656.js";import{$g as MX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as F1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as V2,Og as z8,Pg as l1,Qg as i1,Rg as AX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as vX}from"./chunk-fkm1k8xy.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as W2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as LW,th as EX,uh as W8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-dpjy7s53.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as SY,Di as kY,Ei as vY,Fh as XJ,Fi as yY,Gi as AZ,Hi as xY,Ii as B1,Ji as IY,Kh as WJ,Ki as hY,Li as gY,Mh as D9,Ni as t3,Pi as xX,Qi as LX,Rh as UW,Ri as B0,Vh as VJ,Xh as wX,Zh as zY,_h as BY,pi as h1,si as $Y}from"./chunk-4gns7fxm.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as $X,Yi as ZX}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as _X,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as NW,Tj as _W}from"./chunk-4cdk4mds.js";import{Xj as AW}from"./chunk-020t9es1.js";import{bk as yX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as e7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as LV}from"node:crypto";var DV=String.raw`
1
+ import{Ga as W3}from"./chunk-g01mth5d.js";import{Ja as T,Ka as $$,Pa as HW,Qa as fY,Ra as e0}from"./chunk-5f3jvt7q.js";import{$a as BX,Sa as Y5,Va as pZ,Za as tZ,_a as zX,bb as nW,db as aW,eb as A9,wb as sW}from"./chunk-30x3mcsb.js";import{Ab as p7,Bb as D2,Cb as GY,Db as x1,Eb as s7,Fb as DY,Gb as ZY,Hb as qY,Ib as wY,Jb as UQ,Lb as YX,Nb as V0,Pb as F2,Sb as p4,Ub as FZ,Vb as l4,Wb as i4,Yb as MJ,Zb as R$,dc as sX,ec as G8,fc as oX,gc as JX,ic as u1,jc as kX,oc as rY,rc as nY,xb as s5,yb as g7,zb as J1}from"./chunk-600xa10z.js";import{$c as r8,$d as iY,Ac as k3,Bc as T1,Cc as ZJ,Dc as F0,Ec as S2,Fc as N1,Gc as S6,Hc as f9,Ic as m4,Jc as c4,Kc as YY,Lc as QY,Mc as TX,Nc as X3,Nd as V8,Oc as A1,Pc as Y3,Pd as f0,Qc as i8,Qd as b$,Rc as $1,Sc as Z1,Tc as l2,Uc as p2,Vc as i2,Wc as g6,Xc as u6,Xd as YW,Yc as d2,Yd as HX,Zc as z3,_c as m2,ad as M1,bd as e1,cd as c2,dd as $2,ed as Z2,ee as PX,fd as d6,fe as SX,gd as J2,hd as m6,he as o,id as c6,jd as k$,kd as p6,ld as O3,md as r2,nd as l6,od as i6,pd as r6,qd as n6,rd as N3,sd as b3,ud as j3,xc as v$,yc as CX,zc as r3}from"./chunk-b8rkgzjs.js";import{ie as i,je as GQ,ke as KQ,le as hJ,ne as _2}from"./chunk-53fc0yrq.js";import{Ge as P9,He as J$,Ie as q2,Je as $9,Ke as RX,Le as fX,Ue as $V,ff as ZV,pe as tW,se as eW}from"./chunk-y5wngtz0.js";import{Bf as NJ,Cf as LJ}from"./chunk-jj4ggb04.js";import{Of as r4,Pf as q0,Qf as d,Tf as j0,Uf as P4,Vf as L2,Wf as G1,Xf as CZ,Yf as R1,Zf as pY,cg as B2}from"./chunk-4vn0dr8c.js";import{dg as d1}from"./chunk-t0gm0pn1.js";import{hg as jZ,ig as lY,ng as mY,og as cX,pg as S4}from"./chunk-1yq72zb7.js";import{qg as nZ}from"./chunk-kqvzmnja.js";import{tg as m0,ug as O1}from"./chunk-0mr8nexh.js";import{vg as eX}from"./chunk-50vwafn5.js";import{Ag as jX,xg as OX,yg as NX,zg as bX}from"./chunk-z8drxtsd.js";import{$g as MX,Bg as I4,Cg as h4,Dg as g4,Fg as u4,Gg as d4,Hg as F1,Ig as FQ,Jg as I$,Kg as j$,Lg as G$,Mg as $5,Ng as V2,Og as z8,Pg as l1,Qg as i1,Rg as AX,Vg as J9,Xg as c0,Yg as f$,_g as k4,ah as vX}from"./chunk-2p9j16ed.js";import{ch as D1,eh as T$,fh as O4}from"./chunk-3kszepm6.js";import{gh as d3,hh as W2,ih as m3,jh as s2,kh as c3,lh as p3,mh as Z4,nh as $4,oh as l3,ph as i3,qh as e6}from"./chunk-wcps5gjm.js";import{rh as LW,th as EX,uh as W8,vh as bJ}from"./chunk-vbjgcn49.js";import{xh as L9,zh as x0}from"./chunk-96jpzf75.js";import{Ah as E6,Bh as R9,Ch as A6,Dh as r1}from"./chunk-3y2x6fb6.js";import{Ci as SY,Di as kY,Ei as vY,Fh as XJ,Fi as yY,Gi as AZ,Hi as xY,Ii as B1,Ji as IY,Kh as WJ,Ki as hY,Li as gY,Mh as D9,Ni as t3,Pi as xX,Qi as LX,Rh as UW,Ri as B0,Vh as VJ,Xh as wX,Zh as zY,_h as BY,pi as h1,si as $Y}from"./chunk-zvf33r3d.js";import{Ui as L$}from"./chunk-kv458q06.js";import{Wi as $X,Yi as ZX}from"./chunk-5v0jcyea.js";import{$i as X4,bj as C}from"./chunk-2f8d0km4.js";import{Dj as e,Fj as a6,Gj as X2,Hj as K,Ij as R3,Jj as P,Kj as u}from"./chunk-2mk914vk.js";import{Oj as _X,Pj as FX}from"./chunk-j8hbddjp.js";import{Qj as NW,Tj as _W}from"./chunk-4cdk4mds.js";import{Xj as AW}from"./chunk-fb773kdb.js";import{bk as yX,ck as a0}from"./chunk-rvs364rz.js";import{Bk as E$,Gk as u3,fk as t,gk as N$,hk as D$,ik as t1,jk as o9,kk as u2,lk as X$,mk as e7,pk as I6,yk as P6}from"./chunk-4wx5sya5.js";import{Mk as Y$}from"./chunk-eg3ms291.js";import{randomUUID as M8}from"crypto";import{randomUUID as LV}from"node:crypto";var DV=String.raw`
2
2
  const { spawn } = require('node:child_process');
3
3
  const [ownerPidValue, command, ...args] = process.argv.slice(1);
4
4
  const ownerPid = Number(ownerPidValue);
@@ -118,7 +118,7 @@ process.stdin.once('data', (chunk) => {
118
118
  `,{encoding:"utf8",mode:384,fsync:!0}),Q}remove($){l0.rmSync(this.filePath($),{force:!0})}async reapOrphans(){let $=0,Z=0,J=0,Y=0;for(let Q of this.readAll()){if(R6(Q.ownerPid)&&S6(Q.ownerPid,Q.ownerIdentity)){J++;continue}if(!R6(Q.rootPid)){if(process.platform!=="win32"&&E6(Q.rootPid)){let V=await A6(Q.rootPid,{validatePidOwnership:()=>!R6(Q.rootPid)});if(R6(Q.rootPid)){Y++;continue}if(!V.success)throw Error(`Failed to reap leaderless ${this.options.label} ${Q.processId}`);$++}else Z++;this.remove(Q.processId);continue}let X=()=>f9(Q.rootPid,Q.identity);if(!X()){Y++;continue}if(!(await R9(Q.rootPid,{validatePidOwnership:X})).success)throw Error(`Failed to reap ${this.options.label} ${Q.processId}`);$++,this.remove(Q.processId)}return{reaped:$,stale:Z,active:J,protected:Y}}readAll(){let $;try{$=l0.readdirSync(this.directory)}catch(J){if(J.code==="ENOENT")return[];throw Error(`Unable to read durable ${this.options.label} leases`)}let Z=[];for(let J of $){if(!J.endsWith(".json"))continue;try{let Y=f6.join(this.directory,J);if(l0.statSync(Y).size>FV)throw Error("lease exceeds size limit");let Q=JSON.parse(l0.readFileSync(Y,"utf8")),X=this.normalizeLease(Q);if(!X)throw Error("lease schema is invalid");Z.push(X)}catch{throw Error(`Invalid durable ${this.options.label} lease: ${J}`)}}return Z}normalizeLease($){if(!$||typeof $!=="object")return;let Z=$,J=new Set(["version",this.options.idField,"sessionId","ownerPid","ownerIdentity","rootPid","identity","startedAt"]),Y=Z[this.options.idField];if(Object.keys(Z).some((Q)=>!J.has(Q))||Z.version!==N8||Z.sessionId!==this.sessionId||typeof Y!=="string"||!Y.startsWith(this.options.idPrefix)||Y.length>128||!Number.isSafeInteger(Z.ownerPid)||Number(Z.ownerPid)<=1||!S2(Z.ownerIdentity)||!Number.isSafeInteger(Z.rootPid)||Number(Z.rootPid)<=1||!S2(Z.identity)||typeof Z.startedAt!=="string"||!Number.isFinite(Date.parse(Z.startedAt)))return;return{version:N8,processId:Y,sessionId:this.sessionId,ownerPid:Number(Z.ownerPid),ownerIdentity:Z.ownerIdentity,rootPid:Number(Z.rootPid),identity:Z.identity,startedAt:Z.startedAt}}filePath($){return f6.join(this.directory,`${T9($)}.json`)}}class b1{store;constructor($,Z){this.store=new k2($,Z,{directoryName:".foreground-processes",idField:"processId",idPrefix:"foreground_",label:"foreground process"})}register($,Z){this.store.register($,Z)}remove($){this.store.remove($)}reapOrphans(){return this.store.reapOrphans()}}class n1 extends Error{constructor($,Z){super($,Z);this.name="ForegroundProcessAdmissionError"}}async function a1($,Z,J,Y){let Q=`foreground_${LV()}`,{child:X,processTree:W}=M6($,Z,J);if(!X.pid)throw await W.terminate(),new n1("Foreground command gate did not expose a PID");let V=Y?new b1(Y.projectPath,Y.sessionId):void 0;try{V?.register(Q,X.pid)}catch(B){throw await W.terminate(),new n1("Failed to register durable foreground command lease",{cause:B})}let U,H,z=!1;return{child:X,processTree:W,processId:Q,release(){return U??=C6(X).catch((B)=>{throw W.terminate(),Error("Failed to release durable foreground command gate",{cause:B})}),U},handoff(B,G){if(z)return;if(H)throw Error("Cannot hand off a finalized foreground command");B(X.pid);try{V?.remove(Q),z=!0}catch(D){throw G(),D}},finalize(){return H??=(async()=>{if(!(await T6(X,W)).success)throw Error("Failed to finalize foreground command process group");if(!z)V?.remove(Q)})(),H}}}class v2{store;constructor($,Z){this.store=new k2($,Z,{directoryName:".background-shells",idField:"shellId",idPrefix:"bash_",label:"background shell"})}register($,Z){let J=this.store.register($,Z);return{version:J.version,shellId:$,sessionId:J.sessionId,ownerPid:J.ownerPid,ownerIdentity:J.ownerIdentity,rootPid:J.rootPid,identity:J.identity,startedAt:J.startedAt}}remove($){this.store.remove($)}reapOrphans(){return this.store.reapOrphans()}}import{StringDecoder as OV}from"node:string_decoder";class b8{buffer;decoder=new OV("utf8");totalChars=0;accountingComplete=!0;finished=!1;constructor($){this.buffer=new J$($)}append($){if(this.finished)return;let Z=typeof $==="string"?Buffer.from($):$;this.buffer.append(Z),this.totalChars+=this.decoder.write(Z).length}markAccountingIncomplete(){this.accountingComplete=!1}finish(){if(this.finished)return;this.totalChars+=this.decoder.end().length,this.finished=!0}snapshot(){let $=this.buffer.peek();return{content:$.content,totalBytes:$.totalBytes,retainedBytes:$.retainedBytes,omittedBytes:$.omittedBytes,totalChars:this.totalChars,accountingComplete:this.accountingComplete}}}class K${terminalOutputMerged;stdout;stderr;constructor($=P9,Z=!1){this.terminalOutputMerged=Z;this.stdout=new b8($),this.stderr=new b8($)}append($,Z){this.streamFor($).append(Z)}markAccountingIncomplete(){this.stdout.markAccountingIncomplete(),this.stderr.markAccountingIncomplete()}finish(){this.stdout.finish(),this.stderr.finish()}snapshot(){return{stdout:this.stdout.snapshot(),stderr:this.stderr.snapshot(),terminalOutputMerged:this.terminalOutputMerged}}streamFor($){return $==="stdout"?this.stdout:this.stderr}}import{constants as NV}from"node:fs";import{access as bV,mkdir as k6,realpath as x2}from"node:fs/promises";import jV from"node:os";import i0 from"node:path";import{Mutex as EV}from"async-mutex";var S9=new EV,l$,j8;function AV(){return import("@anthropic-ai/sandbox-runtime")}async function y2(){if(l$)return l$;if(!j8)j8=AV();return l$=await j8,l$}var MV={isSupportedPlatform:async()=>(await y2()).SandboxManager.isSupportedPlatform(),checkDependencies:async()=>(await y2()).SandboxManager.checkDependencies(),getDefaultWritePaths:async()=>(await y2()).getDefaultWritePaths(),initialize:async($)=>(await y2()).SandboxManager.initialize($),updateConfig:($)=>{if(!l$)throw Error("Sandbox runtime is not initialized");l$.SandboxManager.updateConfig($)},wrapWithSandboxArgv:async($,Z,J,Y,Q)=>(await y2()).SandboxManager.wrapWithSandboxArgv($,Z,J,Y,Q),cleanupAfterCommand:()=>l$?.SandboxManager.cleanupAfterCommand(),reset:async()=>{await l$?.SandboxManager.reset()}};function E8($){return{network:{allowedDomains:$,deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:[],allowRead:[],allowWrite:[],denyWrite:[]},enableWeakerNestedSandbox:!0}}class i$ extends Error{constructor($){super($);this.name="WorkspaceSandboxUnavailableError"}}class s1 extends Error{constructor($){super($);this.name="WorkspaceSandboxBoundaryError"}}class k9{backend;constructor($){this.backend=$}async prepare($){let Z=i0.resolve($.workspaceRoot),J=i0.resolve($.cwd);if(!F0.isWithinWorkspace(J,Z))throw new s1(`Bash cwd is outside the workspace sandbox: ${$.cwd}`);let Y,Q;try{[Y,Q]=await Promise.all([x2(Z),x2(J)])}catch(X){throw new s1(`Workspace sandbox path cannot be resolved: ${X instanceof Error?X.message:String(X)}`)}if(!F0.isWithinWorkspace(Q,Y))throw new s1(`Bash cwd resolves outside the workspace sandbox: ${$.cwd}`);return this.backend.prepare({...$,cwd:Q,workspaceRoot:Y})}}class v9{runtime;tempRoot;defaultWritePaths;initialization;constructor($={}){this.runtime=$.runtime??MV,this.tempRoot=$.tempRoot??i0.join(t(),"sandbox-tmp"),this.defaultWritePaths=$.defaultWritePaths}async prepare($){await this.ensureInitialized();let Z=await this.prepareTempRoot(),J=i0.join(Z,"tmp"),Y=i0.join(Z,"cache"),Q=i0.join(Y,"npm"),X=i0.join(Y,"bun");await Promise.all([k6(J,{recursive:!0}),k6(Q,{recursive:!0}),k6(X,{recursive:!0})]);let V=(this.defaultWritePaths??await this.runtime.getDefaultWritePaths()).filter((_)=>!_.startsWith("/dev/")),U=$.access==="workspace-read-only",H=U?await x2(process.execPath).catch(()=>i0.resolve(process.execPath)):void 0,z=U?await CV("node",$.trustedPath):void 0,B=U?[jV.homedir(),t(),process.env.BLADE_REAL_API_CREDENTIALS_FILE].filter((_)=>typeof _==="string"&&_.trim().length>0).map((_)=>i0.resolve(_)).filter((_,O,b)=>b.indexOf(_)===O):[],G=process.platform==="win32"?"bash":"/bin/bash",D,w,q=()=>{if(!w)return;let _=w;w=void 0;try{this.runtime.updateConfig(E8(["*"]))}finally{_()}},F=async()=>{let _=process.env.CLAUDE_CODE_TMPDIR;process.env.CLAUDE_CODE_TMPDIR=J;try{return await this.runtime.wrapWithSandboxArgv($.command,G,{network:U?{allowedDomains:[],deniedDomains:[],strictAllowlist:!0}:{allowedDomains:["*"],deniedDomains:[],strictAllowlist:!0},filesystem:{denyRead:B,allowRead:U&&H?[$.workspaceRoot,H,...z?[z]:[],Z]:[],allowWrite:U?[Z]:[$.workspaceRoot,Z],denyWrite:U?[$.workspaceRoot,...V]:V},git:{safeDirectories:[$.workspaceRoot]}},$.signal,$.cwd)}finally{if(_===void 0)delete process.env.CLAUDE_CODE_TMPDIR;else process.env.CLAUDE_CODE_TMPDIR=_}};try{if(U)w=await S9.acquire(),this.runtime.updateConfig(E8([])),D=await F();else D=await S9.runExclusive(F)}catch(_){if(q(),_ instanceof Error&&_.name==="AbortError")throw _;throw new i$(`Workspace sandbox failed to prepare the command: ${_ instanceof Error?_.message:String(_)}`)}let L=!1;return{executable:D.argv[0]??G,args:D.argv.slice(1),env:{...D.env,TMPDIR:J,TMP:J,TEMP:J,XDG_CACHE_HOME:Y,npm_config_cache:Q,BUN_INSTALL_CACHE_DIR:X},sandboxed:!0,inheritProcessEnv:!U,cleanup:()=>{if(L)return;L=!0;try{this.runtime.cleanupAfterCommand()}finally{q()}}}}async dispose(){this.initialization=void 0,await this.runtime.reset()}async ensureInitialized(){if(!this.initialization)this.initialization=this.initializeRuntime().catch(($)=>{throw this.initialization=void 0,$});return this.initialization}async initializeRuntime(){if(!await this.runtime.isSupportedPlatform())throw new i$(`Workspace sandbox is unsupported on ${process.platform}`);let $=await this.runtime.checkDependencies();if($.errors.length>0)throw new i$(`Workspace sandbox dependencies are unavailable: ${$.errors.join("; ")}`);try{await this.runtime.initialize(E8(["*"]))}catch(Z){throw new i$(`Workspace sandbox failed to initialize: ${Z instanceof Error?Z.message:String(Z)}`)}}async prepareTempRoot(){return await k6(this.tempRoot,{recursive:!0}),x2(this.tempRoot)}}async function CV($,Z){if(!Z)return;let J=process.platform==="win32"?[`${$}.exe`,`${$}.cmd`,$]:[$];for(let Y of Z.split(i0.delimiter)){if(!i0.isAbsolute(Y))continue;for(let Q of J){let X=i0.join(Y,Q);try{return await bV(X,NV.X_OK),await x2(X)}catch{}}}return}function I2($,Z){let J=Z.toLowerCase();return $===71&&J.includes("sandbox-exec")||J.includes("sandbox_apply: operation not permitted")||J.includes("bwrap: creating new namespace failed")||J.includes("failed to create new user namespace")||J.includes("srt-win sandbox failed")}var TV=new v9,RV={prepare:($)=>TV.prepare($)},A8=new k9(RV);var fV=16,PV=4;class r$ extends Error{scope;limit;constructor($,Z){super(`Background Shell ${$} capacity is full (max ${Z})`);this.scope=$;this.limit=Z;this.name="BackgroundShellCapacityError"}}class Y0{static instance=null;processes=new Map;activeGlobal=0;activeBySession=new Map;globalMaxActive;sessionMaxActive;constructor($={}){if(this.globalMaxActive=this.positiveLimit($.globalMaxActive??fV,"globalMaxActive"),this.sessionMaxActive=this.positiveLimit($.sessionMaxActive??PV,"sessionMaxActive"),this.sessionMaxActive>this.globalMaxActive)throw Error("sessionMaxActive must not exceed globalMaxActive")}static getInstance(){if(!Y0.instance)Y0.instance=new Y0;return Y0.instance}async startBackgroundProcess($){let Z;try{Z=this.reserve($.sessionId)}catch(G){throw $.sandboxedCommand?.cleanup(),G}let J=`bash_${M8()}`,Y={};for(let[G,D]of Object.entries({...process.env,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"}))if(D!==void 0)Y[G]=D;let Q=$.sandboxedCommand?.executable??"bash",X=$.sandboxedCommand?.args??["-c",$.command],W,V;try{({child:W,processTree:V}=M6(Q,X,{cwd:$.cwd||C(),env:Y,stdio:["pipe","pipe","pipe"]}))}catch(G){throw Z(),$.sandboxedCommand?.cleanup(),G}if(!W.pid)throw V.terminate(),Z(),$.sandboxedCommand?.cleanup(),Error("Background process did not expose a PID");let U=new v2($.projectPath??$.cwd??C(),$.sessionId);try{U.register(J,W.pid)}catch(G){let D=!0;try{process.kill(W.pid,0)}catch(w){D=w instanceof Error&&"code"in w&&w.code==="EPERM"}if(D)throw W.kill("SIGKILL"),V.terminate(),Z(),$.sandboxedCommand?.cleanup(),G}let H=this.createCompletion(),z={id:J,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:W,processTree:V,pid:W.pid,status:"running",startTime:Date.now(),pendingStdout:new J$,pendingStderr:new J$,sandboxed:Boolean($.sandboxedCommand),transport:"local",visible:!0,autoBackgrounded:!1,backgroundReason:"explicit",completion:H.promise,resolveCompletion:H.resolve,releaseAdmission:this.releaseOnce(Z),terminalSettled:!1,leaseStore:U};W.stdout?.on("data",(G)=>{z.pendingStdout.append(G)}),W.stderr?.on("data",(G)=>{z.pendingStderr.append(G)});let B=()=>{return z.finalizationPromise??=T6(W,V).then((G)=>{if(G.success)return z.leaseStore?.remove(z.id),!0;return!1}).catch(()=>!1),z.finalizationPromise};W.on("close",(G,D)=>{(async()=>{let w=await B();if(!w)z.finalizationFailed=!0;if(z.terminalSettled)return;z.terminalSettled=!0,$.sandboxedCommand?.cleanup();let q=z.sandboxed&&I2(G,z.pendingStderr.peek().content);if(z.status=z.status==="killed"?"killed":q||!w?"error":"exited",z.exitCode=G,z.signal=D,q)z.errorMessage="Workspace sandbox failed to start; command was not executed";else if(!w)z.errorMessage="Background command process group could not be finalized";z.endTime=Date.now(),z.process=void 0,z.releaseAdmission(),z.resolveCompletion()})()}),W.on("error",(G)=>{(async()=>{let D=await B();if(!D)z.finalizationFailed=!0;if(z.terminalSettled)return;z.terminalSettled=!0,$.sandboxedCommand?.cleanup(),z.status="error",z.errorMessage=D?G.message:"Background command process group could not be finalized",z.endTime=Date.now(),z.process=void 0,z.pendingStderr.append(`
119
119
  [error] ${G.message}`),z.releaseAdmission(),z.resolveCompletion()})()}),this.processes.set(J,z);try{await C6(W)}catch(G){throw z.status="killed",z.endTime=Date.now(),await V.terminate(),z.leaseStore?.remove(z.id),this.processes.delete(J),z.releaseAdmission(),z.resolveCompletion(),$.sandboxedCommand?.cleanup(),Error("Failed to release durable background command gate",{cause:G})}return z}async startForegroundCandidate($){let Z=this.reserve($.sessionId),J=`bash_${M8()}`,Y=$.sandboxedCommand?.executable??"bash",Q=$.sandboxedCommand?.args??["-c",$.command],X=$.sandboxedCommand?.inheritProcessEnv===!1?{}:process.env,W;try{W=await a1(Y,Q,{cwd:$.cwd||C(),env:{...X,...$.env,...$.sandboxedCommand?.env,BLADE_CLI:"1"},stdio:["pipe","pipe","pipe"]},$.ownership)}catch(G){throw Z(),$.sandboxedCommand?.cleanup(),G}let{child:V,processTree:U}=W,H=this.createCompletion(),z={id:J,command:$.command,sessionId:$.sessionId,cwd:$.cwd,env:$.env,process:V,processTree:U,pid:V.pid,status:"running",startTime:Date.now(),pendingStdout:new J$,pendingStderr:new J$,sandboxed:Boolean($.sandboxedCommand),transport:"local",visible:!1,autoBackgrounded:!1,completion:H.promise,resolveCompletion:H.resolve,releaseAdmission:this.releaseOnce(Z),foreground:W,foregroundCapture:new K$,terminalSettled:!1};V.stdout?.on("data",(G)=>{z.pendingStdout.append(G),z.foregroundCapture?.append("stdout",G)}),V.stderr?.on("data",(G)=>{z.pendingStderr.append(G),z.foregroundCapture?.append("stderr",G)});let B=()=>{return z.finalizationPromise??=W.finalize().then(()=>{return z.leaseStore?.remove(z.id),!0}).catch(()=>!1),z.finalizationPromise};V.on("close",(G,D)=>{(async()=>{let w=await B();if(!w)z.finalizationFailed=!0;if(z.terminalSettled)return;z.terminalSettled=!0,$.sandboxedCommand?.cleanup();let q=z.sandboxed&&I2(G,z.pendingStderr.peek().content);if(z.status=z.status!=="running"?z.status:q||!w?"error":"exited",z.exitCode=G,z.signal=D,q)z.errorMessage="Workspace sandbox failed to start; command was not executed";else if(!w)z.errorMessage="Background command process group could not be finalized";z.endTime=Date.now(),z.process=void 0,z.releaseAdmission(),z.resolveCompletion()})()}),V.on("error",(G)=>{(async()=>{let D=await B();if(!D)z.finalizationFailed=!0;if(z.terminalSettled)return;z.terminalSettled=!0,$.sandboxedCommand?.cleanup(),z.status="error",z.errorMessage=D?G.message:"Background command process group could not be finalized",z.endTime=Date.now(),z.process=void 0,z.pendingStderr.append(`
120
120
  [error] ${G.message}`),z.foregroundCapture?.append("stderr",`
121
- [error] ${G.message}`),z.releaseAdmission(),z.resolveCompletion()})()}),this.processes.set(J,z);try{await W.release()}catch(G){throw z.status="aborted",z.endTime=Date.now(),await U.terminate(),this.processes.delete(J),z.releaseAdmission(),z.resolveCompletion(),$.sandboxedCommand?.cleanup(),G}return z}startExternalForegroundCandidate($){let Z=this.reserve($.sessionId),J=`bash_${M8()}`,Y=this.createCompletion(),Q={id:J,command:$.command,sessionId:$.sessionId,cwd:$.cwd,status:"running",startTime:Date.now(),pendingStdout:new J$,pendingStderr:new J$,sandboxed:$.sandboxed??!1,transport:"acp",visible:!1,autoBackgrounded:!1,completion:Y.promise,resolveCompletion:Y.resolve,releaseAdmission:this.releaseOnce(Z),terminateExternal:$.terminate,terminalSettled:!1};return this.processes.set(J,Q),Q}promoteExternalForegroundCandidate($,Z,J){let Y=this.getOwnedProcess($,Z);if(!Y||Y.visible||Y.status!=="running"||Y.transport!=="acp")return;return Y.visible=!0,Y.autoBackgrounded=!0,Y.backgroundReason="foreground_budget",Y.foregroundBudgetMs=J,Y.foregroundCapture=void 0,Y}appendExternalOutput($,Z,J,Y){let Q=this.getOwnedProcess($,Z);if(!Q||Q.transport!=="acp")return;if(J==="stdout")Q.pendingStdout.append(Y);else Q.pendingStderr.append(Y)}replaceExternalOutput($,Z,J,Y){let Q=this.getOwnedProcess($,Z);if(!Q||Q.transport!=="acp")return;Q.pendingStdout=new J$,Q.pendingStderr=new J$,Q.pendingStdout.append(J),Q.pendingStderr.append(Y)}completeExternalProcess($,Z,J){let Y=this.getOwnedProcess($,Z);if(!Y||Y.transport!=="acp"||Y.terminalSettled)return;if(Y.terminalSettled=!0,Y.status=J.status,Y.exitCode=J.exitCode,Y.signal=J.signal,Y.errorMessage=J.errorMessage,J.finalizationFailed)Y.finalizationFailed=!0;Y.endTime=Date.now(),Y.releaseAdmission(),Y.resolveCompletion()}promoteForegroundCandidate($,Z,J,Y){let Q=this.getOwnedProcess($,Z);if(!Q||Q.visible||Q.status!=="running"||!Q.foreground)return;let X=new v2(J,Z);return Q.foreground.handoff((W)=>X.register($,W),()=>X.remove($)),Q.leaseStore=X,Q.visible=!0,Q.autoBackgrounded=!0,Q.backgroundReason="foreground_budget",Q.foregroundBudgetMs=Y,Q}waitForCompletion($,Z){return this.getOwnedProcess($,Z)?.completion}consumeCandidateOutput($,Z){let J=this.getOwnedProcess($,Z);if(!J)return;let Y=this.snapshot(J,!0);if(J.foregroundCapture)J.foregroundCapture.finish(),Y.capture=J.foregroundCapture.snapshot(),J.foregroundCapture=void 0;return Y}removeCandidate($,Z){let J=this.getOwnedProcess($,Z);if(!J||J.visible||J.status==="running")return;this.processes.delete($)}terminateForegroundCandidate($,Z,J){let Y=this.getOwnedProcess($,Z);if(!Y||Y.visible)return;return this.terminateProcess(Y,J)}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;return this.snapshot(J,!0)}getProcess($,Z){let J=this.getOwnedProcess($,Z);return J?.visible?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$&&Z.visible)}async writeInput($,Z,J,Y=!1){let Q=this.getProcess($,Z);if(!Q)return;if(Q.transport==="acp")return{success:!1,status:Q.status,bytesWritten:0,stdinClosed:!1,errorMessage:"ACP background terminals do not support stdin writes"};let X=Q.process?.stdin;if(Q.status!=="running"||!X||X.destroyed||X.writableEnded)return{success:!1,status:Q.status,bytesWritten:0,stdinClosed:!X||X.destroyed||X.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((W,V)=>{let U=(z)=>{X.off("error",U),V(z)},H=(z)=>{if(X.off("error",U),z)V(z);else W()};if(X.once("error",U),Y)X.end(J,H);else X.write(J,H)}),{success:!0,status:Q.status,bytesWritten:Buffer.byteLength(J),stdinClosed:Y}}catch(W){return{success:!1,status:Q.status,bytesWritten:0,stdinClosed:X.destroyed||X.writableEnded,errorMessage:W instanceof Error?W.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getOwnedProcess($,Z);if(!J?.visible)return;return this.terminateProcess(J)}async killSession($){let Z=Array.from(this.processes.values()).filter((J)=>J.sessionId===$);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}reapOrphanedSession($,Z){return new v2(Z,$).reapOrphans()}async terminateProcess($,Z="killed"){if($.externalTerminationPromise)return $.externalTerminationPromise;if($.status!=="running")return{success:!1,alreadyExited:!0,status:$.status,...$.finalizationFailed?{finalizationFailed:!0}:{},pid:$.pid,exitCode:$.exitCode,signal:$.signal};if($.terminateExternal){let Y=$.terminateExternal;return $.externalTerminationPromise=Promise.resolve().then(async()=>{try{await Y(Z)}catch{this.completeExternalProcess($.id,$.sessionId,{status:"error",finalizationFailed:!0,errorMessage:"ACP terminal finalization failed"})}return $.releaseAdmission(),{success:$.status!=="error",alreadyExited:!1,status:$.status,...$.finalizationFailed?{finalizationFailed:!0}:{},pid:$.pid,exitCode:$.exitCode,signal:$.signal}}).finally(()=>{$.externalTerminationPromise=void 0}),$.externalTerminationPromise}if($.status=Z==="timeout"?"timed_out":Z==="aborted"?"aborted":"killed",$.endTime=Date.now(),!$.process)return $.releaseAdmission(),{success:!1,alreadyExited:!0,status:$.status,...$.finalizationFailed?{finalizationFailed:!0}:{},pid:$.pid,exitCode:$.exitCode,signal:$.signal};let J=await $.processTree?.terminate();if(!J?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:J?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return $.leaseStore?.remove($.id),$.releaseAdmission(),{success:!0,alreadyExited:J.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}getAdmissionStats(){return{active:this.activeGlobal,maxActive:this.globalMaxActive,sessions:Object.fromEntries([...this.activeBySession].map(([$,Z])=>[$,{active:Z,maxActive:this.sessionMaxActive}]))}}getOwnedProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}snapshot($,Z){let J=Z?$.pendingStdout.consume():$.pendingStdout.peek(),Y=Z?$.pendingStderr.consume():$.pendingStderr.peek();return{id:$.id,command:$.command,status:$.status,stdout:J.content,stderr:Y.content,stdoutOmittedBytes:J.omittedBytes,stderrOmittedBytes:Y.omittedBytes,stdoutTotalBytes:J.totalBytes,stderrTotalBytes:Y.totalBytes,exitCode:$.exitCode,signal:$.signal,pid:$.pid,startedAt:$.startTime,endedAt:$.endTime,errorMessage:$.errorMessage,...$.finalizationFailed?{finalizationFailed:!0}:{},sandboxed:$.sandboxed,transport:$.transport,autoBackgrounded:$.autoBackgrounded,backgroundReason:$.backgroundReason,foregroundBudgetMs:$.foregroundBudgetMs}}reserve($){let Z=this.activeBySession.get($)??0;if(Z>=this.sessionMaxActive)throw new r$("session",this.sessionMaxActive);if(this.activeGlobal>=this.globalMaxActive)throw new r$("global",this.globalMaxActive);return this.activeGlobal++,this.activeBySession.set($,Z+1),this.releaseOnce(()=>{this.activeGlobal=Math.max(0,this.activeGlobal-1);let J=Math.max(0,(this.activeBySession.get($)??0)-1);if(J===0)this.activeBySession.delete($);else this.activeBySession.set($,J)})}releaseOnce($){let Z=!1;return()=>{if(Z)return;Z=!0,$()}}createCompletion(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}positiveLimit($,Z){if(!Number.isSafeInteger($)||$<=0)throw Error(`${Z} must be a positive safe integer`);return $}}import{stat as GX}from"node:fs/promises";import{Mutex as KX}from"async-mutex";import{nanoid as cD}from"nanoid";import*as _0 from"path";import*as Q$ from"fs/promises";class h2{async readTextFile($){return Q$.readFile($,"utf-8")}async writeTextFile($,Z){await Q$.writeFile($,Z,"utf-8")}async exists($){try{return await Q$.access($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async readBinaryFile($){return Q$.readFile($)}async stat($){try{let Z=await Q$.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async mkdir($,Z){await Q$.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var SV=new h2;function n$(){return SV}import{createHash as t9}from"node:crypto";import*as I8 from"@agentclientprotocol/sdk";import{createHash as kV}from"node:crypto";var g0=30000,v6=5000,C8=120000,T8=60000;var R8=31,f8=1024,vV={aborted:"ACP remote file request was aborted",timeout:"ACP remote file request timed out",busy:"ACP remote file path is busy",capacity:"ACP remote file request capacity is full",closed:"ACP remote filesystem connection is closed","stale-reconciliation":"ACP remote file reconciliation is stale"};class g extends Error{reason;operation;dispatched;requestPending;name="AcpRemoteFileBoundaryError";constructor($,Z,J,Y){super(vV[$]);this.reason=$;this.operation=Z;this.dispatched=J;this.requestPending=Y}}function N0($){return D$($),`acp-remote-connection-path:${kV("sha256").update($.collisionIdentity).digest("hex")}`}var P8=new WeakMap,S8=new WeakMap;function y9(){return{normalTokens:new Set,recoveryToken:void 0,mutationStates:new Map,readTokens:new Map,recoveryPermits:new Map,closed:!1}}function yV($,Z){let J,Y,Q=new Promise((X,W)=>{J=X,Y=W});return Q.catch(()=>{return}),{kind:Z,operation:$.operation,purpose:$.purpose,sessionId:$.sessionId,pathIdentity:$.pathIdentity,exactPathIdentity:$.exactPathIdentity,controller:new AbortController,localPromise:Q,resolve:J,reject:Y,timer:void 0,parentAbortHandler:void 0,deadlineAbortHandler:void 0,settled:!1,dispatched:!1,requestPending:!1,timedOut:!1,aborted:!1,boundaryError:void 0}}function k8($){if(!$)return;return P8.get($)}function x9($,Z){let J=Z.userReadPermit?.lane==="recovery"||Z.purpose==="rollback"?"recovery":"normal";if(J==="normal"&&$.normalTokens.size>=R8)throw new g("capacity",Z.operation,!1,!1);if(J==="recovery"&&$.recoveryToken!==void 0)throw new g("capacity",Z.operation,!1,!1);let Y=yV(Z,J),Q=k8(Z.lease);if(Z.operation==="write"&&Q)if(Q.kind==="active"){let X=Q.exactPathIdentities.get(Z.pathIdentity);if(X===void 0)throw new g("busy",Z.operation,!1,!1);Y.writeLeaseSnapshot={generation:Q.generations.get(Z.pathIdentity)??0,leaseId:Q.leaseId,leaseKind:Q.kind,exactPathIdentity:X}}else Y.writeLeaseSnapshot={generation:Q.generation,leaseId:Q.leaseId,leaseKind:Q.kind,exactPathIdentity:Q.exactPathIdentity};if(Z.operation==="read"){let X=Z.userReadPermit?S8.get(Z.userReadPermit):void 0;if(Y.readToken={pathIdentity:Z.pathIdentity,exactPathIdentity:Z.exactPathIdentity,generation:Z.userReadPermit?.generation,permitId:X?.permitId,detached:!1,settled:!1},$.readTokens.set(Z.pathIdentity,Y.readToken),Z.userReadPermit?.lane==="recovery"){let W=$.mutationStates.get(Z.pathIdentity),V=$.recoveryPermits.get(Z.pathIdentity);if(W?.sessionId===Z.sessionId&&W.exactPathIdentity===Z.exactPathIdentity&&W.generation===Z.userReadPermit.generation&&V!==void 0&&X!==void 0&&V.permitId===X.permitId)W.kind="reconciling",W.reconciliationPermitId=V.permitId;if(V?.sessionId===Z.sessionId&&V.exactPathIdentity===Z.exactPathIdentity&&V.generation===Z.userReadPermit.generation)V.active=!0}}if(J==="normal")$.normalTokens.add(Y);else $.recoveryToken=Y;return Y}function v8($,Z){if(Z.kind==="normal")$.normalTokens.delete(Z);else if($.recoveryToken===Z)$.recoveryToken=void 0;if(Z.readToken?.settled&&$.readTokens.get(Z.pathIdentity)===Z.readToken)$.readTokens.delete(Z.pathIdentity)}function I9($){if($.timer)clearTimeout($.timer),$.timer=void 0;if($.parentAbortHandler&&$.parentSignal)$.parentSignal.removeEventListener("abort",$.parentAbortHandler),$.parentAbortHandler=void 0,$.parentSignal=void 0}function h9($){if($.settled)return;$.settled=!0;let Z=new g("closed",$.operation,$.dispatched,$.requestPending);return $.reject(Z),Z}function g9($,Z,J,Y){if(Z.settled)return;let Q=Z.operation==="write"&&Z.dispatched&&Y&&Z.writeLeaseSnapshot!==void 0;if(Z.boundaryError=j1(new g(J,Z.operation,Z.dispatched,Y&&Z.dispatched),Q),Z.operation==="read"&&Z.readToken){if(Z.readToken.detached=Z.boundaryError.requestPending,!Z.boundaryError.requestPending)$.readTokens.delete(Z.pathIdentity)}if(Z.operation==="write"&&Z.dispatched){let X=$.mutationStates.get(Z.pathIdentity),W=Z.writeLeaseSnapshot;if(X&&W&&X.sessionId===Z.sessionId&&X.exactPathIdentity===Z.exactPathIdentity&&X.exactPathIdentity===W.exactPathIdentity&&X.generation===W.generation&&X.leaseId===W.leaseId&&X.leaseKind===W.leaseKind)X.kind="pending-write",X.forwardVerified=!1}return Z.settled=!0,Z.reject(Z.boundaryError),Z.boundaryError}function u9($){let Z=0,J=0,Y=0,Q=0;for(let W of $.mutationStates.values()){if(W.kind==="active-mutation")Z+=1;if(W.kind==="pending-write")J+=1;if(W.kind==="needs-read")Y+=1;if(W.kind==="reconciling")Q+=1}let X=0;for(let W of $.readTokens.values())if(!W.detached)X+=1;return{pendingNormal:$.normalTokens.size,pendingRecovery:$.recoveryToken?1:0,activeNormalReads:X,mutationPaths:$.mutationStates.size,activeMutations:Z,pendingWrites:J,needsRead:Y,reconciling:Q,closed:$.closed}}function d9($,Z){if(Z.length===0)throw new g("busy","write",!1,!1);let J=$.mutationStates.size;for(let Y of Z){let Q=$.mutationStates.get(Y);if(Q)throw j1(new g("busy","write",!1,!1),Q.kind==="pending-write"||Q.kind==="needs-read")}if(J+Z.length>f8)throw new g("capacity","write",!1,!1)}function y6($){let Z=new Map;for(let J of $){let Y=N0(J);if(!Z.has(Y))Z.set(Y,J)}return[...Z.entries()].sort(([J],[Y])=>J.localeCompare(Y)).map(([,J])=>J)}function m9($,Z,J){let Y=y6(Z).map((Q)=>({pathIdentity:N0(Q),exactPathIdentity:Q.exactIdentity}));return xV($,Y,J)}function xV($,Z,J){let Y=Z.map(({pathIdentity:B})=>B),Q=Symbol("acp-mutation-lease"),X={kind:"active",sessionId:J,leaseId:Q,generations:new Map,exactPathIdentities:new Map,released:!1},W=new Map;for(let{pathIdentity:B,exactPathIdentity:G}of Z){let w=($.mutationStates.get(B)?.generation??0)+1;W.set(B,w),X.generations.set(B,w),X.exactPathIdentities.set(B,G)}for(let{pathIdentity:B,exactPathIdentity:G}of Z){let D=$.mutationStates.get(B),w=new Set(D?.retiredGenerations??[]);if(D)w.add(D.generation);$.mutationStates.set(B,{pathIdentity:B,exactPathIdentity:G,sessionId:J,generation:W.get(B)??1,kind:"active-mutation",leaseKind:"active",leaseId:Q,forwardVerified:!1,retiredGenerations:w})}let V=!1,U=!1,H=(B,G)=>{let D=W.get(B),w=$.mutationStates.get(B);if(D===void 0||!w||w.sessionId!==J||w.generation!==D||w.exactPathIdentity!==G||w.leaseKind!=="active"||w.leaseId!==Q)return;return w},z={sessionId:J,pathIdentities:Y,generationFor(B){let G=N0(B);return H(G,B.exactIdentity)?.generation??0},isCurrent(B){let G=N0(B);return!V&&H(G,B.exactIdentity)!==void 0},markForwardVerified(B){if(V)return;let G=N0(B),D=H(G,B.exactIdentity);if(D)D.kind="active-mutation",D.forwardVerified=!0},markDefinite(B){if(V)return;let G=N0(B);if(H(G,B.exactIdentity))$.mutationStates.delete(G)},markUncertain(B){if(V)return;let G=N0(B),D=H(G,B.exactIdentity);if(D)D.kind="needs-read",D.forwardVerified=!1},beginRecovery(B){if(V)throw new g("stale-reconciliation","read",!1,!1);let G=N0(B),D=B.exactIdentity,w=H(G,D);if(!w||w.kind==="pending-write")throw new g("stale-reconciliation","read",!1,!1);let q=w.generation,F=q+1,L=Symbol("acp-recovery-lease");W.set(G,F),X.generations.set(G,F);let _=new Set(w.retiredGenerations??[]);_.add(q),w.generation=F,w.kind="active-mutation",w.leaseKind="recovery",w.leaseId=L,w.forwardVerified=!1,w.reconciliationPermitId=void 0,w.retiredGenerations=_;let O={generation:F,pathIdentity:G,exactPathIdentity:D,finish(N){if(b.finished)return;let A=$.mutationStates.get(G);if(!A||A.sessionId!==J||A.generation!==F||A.exactPathIdentity!==D||A.leaseKind!=="recovery"||A.leaseId!==L)return;if(b.finished=!0,A.kind==="pending-write")return;if(N==="restored")$.mutationStates.delete(G);else A.kind="needs-read",A.forwardVerified=!1,A.reconciliationPermitId=void 0}},b={kind:"recovery",sessionId:J,leaseId:L,pathIdentity:G,exactPathIdentity:D,generation:F,finished:!1};return P8.set(O,b),O},commitVerified(){U=!0},release(){if(V)return;for(let{pathIdentity:B,exactPathIdentity:G}of Z){let D=H(B,G);if(!D)continue;if(D.kind==="active-mutation"){if(!D.forwardVerified){$.mutationStates.delete(B);continue}if(U){$.mutationStates.delete(B);continue}D.kind="needs-read",D.forwardVerified=!1,D.reconciliationPermitId=void 0;continue}if(D.kind==="pending-write")continue;if(D.kind==="needs-read"){D.forwardVerified=!1;continue}if(U)$.mutationStates.delete(B)}V=!0,X.released=!0}};return P8.set(z,X),z}function c9($,Z,J){let Y=N0(Z),Q=$.mutationStates.get(Y);if(!Q)return Object.freeze({sessionId:J,pathIdentity:Y,exactPathIdentity:Z.exactIdentity,generation:void 0,lane:"normal",complete:(X,W)=>{W()},fail:()=>{}});if(Q.kind==="pending-write")throw j1(new g("busy","read",!1,!1),!0);if(Q.kind==="needs-read"&&Q.sessionId===J&&Q.exactPathIdentity===Z.exactIdentity&&!$.recoveryToken&&!$.recoveryPermits.has(Y)){let X=Symbol("acp-recovery-permit"),W={sessionId:J,pathIdentity:Y,exactPathIdentity:Z.exactIdentity,generation:Q.generation,permitId:X,active:!1};$.recoveryPermits.set(Y,W);let V={sessionId:J,pathIdentity:Y,exactPathIdentity:Z.exactIdentity,generation:Q.generation,lane:"recovery",complete:(H,z)=>{let B=$.mutationStates.get(Y);if($.recoveryPermits.get(Y)!==W||!W.active||!B||B.sessionId!==J||B.generation!==W.generation||B.exactPathIdentity!==W.exactPathIdentity||B.reconciliationPermitId!==W.permitId||B.kind!=="needs-read")throw new g("stale-reconciliation","read",!1,!1);if(z(),$.recoveryPermits.delete(Y),W.active=!1,H==="content"||H==="not-found")$.mutationStates.delete(Y)},fail:()=>{if($.recoveryPermits.get(Y)===W){$.recoveryPermits.delete(Y);let H=$.mutationStates.get(Y);if(H?.kind==="needs-read"&&H.reconciliationPermitId===X)H.reconciliationPermitId=void 0}W.active=!1}},U=Object.freeze(V);return S8.set(U,{permitId:X}),U}throw new g("busy","read",!1,!1)}function p9($,Z){if(Z.userReadPermit?.lane==="recovery"){let Q=$.mutationStates.get(Z.pathIdentity);if(Q?.kind==="pending-write")throw j1(new g("busy","read",!1,!1),!0);if(!Q||Q.kind!=="needs-read")throw new g("stale-reconciliation","read",!1,!1);let X=$.recoveryPermits.get(Z.pathIdentity),W=S8.get(Z.userReadPermit);if(!X||!W||X.permitId!==W.permitId||Z.userReadPermit.pathIdentity!==Z.pathIdentity||Z.userReadPermit.exactPathIdentity!==Z.exactPathIdentity||Z.userReadPermit.sessionId!==Z.sessionId||Q.sessionId!==Z.sessionId||Q.exactPathIdentity!==Z.exactPathIdentity||Q.generation!==Z.userReadPermit.generation||X.sessionId!==Z.userReadPermit.sessionId||X.exactPathIdentity!==Z.userReadPermit.exactPathIdentity||X.generation!==Z.userReadPermit.generation)throw new g("stale-reconciliation","read",!1,!1);let V=$.readTokens.get(Z.pathIdentity);if(V&&!V.detached)throw new g("busy","read",!1,!1);if(Q.retiredGenerations?.has(Z.userReadPermit.generation))throw new g("stale-reconciliation","read",!1,!1);if(Q.exactPathIdentity!==Z.exactPathIdentity)throw new g("busy","read",!1,!1);return}if($.readTokens.get(Z.pathIdentity))throw new g("busy","read",!1,!1);let Y=$.mutationStates.get(Z.pathIdentity);if(!Y)return;if(Y.kind!=="active-mutation")throw j1(new g("busy","read",!1,!1),Y.kind==="pending-write"||Y.kind==="needs-read");if(!IV(Z,Y))throw new g("busy","read",!1,!1)}function l9($,Z){let J=$.mutationStates.get(Z.pathIdentity),Y=k8(Z.lease);if(!J||!Y||Y.sessionId!==Z.sessionId)throw j1(new g("busy","write",!1,!1),J?.kind==="pending-write"||J?.kind==="needs-read");if(J.kind!=="active-mutation")throw j1(new g("busy","write",!1,!1),J.kind==="pending-write"||J.kind==="needs-read");if(Y.kind==="active"){if(Y.released||!Y.generations.has(Z.pathIdentity)||Y.exactPathIdentities.get(Z.pathIdentity)!==Z.exactPathIdentity||Y.generations.get(Z.pathIdentity)!==J.generation||J.exactPathIdentity!==Z.exactPathIdentity||J.leaseKind!==Y.kind||J.leaseId!==Y.leaseId)throw new g("busy","write",!1,!1);return}if(Y.finished||Y.pathIdentity!==Z.pathIdentity||Y.exactPathIdentity!==Z.exactPathIdentity||Y.generation!==J.generation||J.exactPathIdentity!==Z.exactPathIdentity||J.leaseKind!==Y.kind||J.leaseId!==Y.leaseId)throw new g("busy","write",!1,!1)}function IV($,Z){let J=k8($.lease);if(!J||J.sessionId!==$.sessionId||Z.sessionId!==$.sessionId||Z.exactPathIdentity!==$.exactPathIdentity)return!1;if(J.kind==="active")return!J.released&&J.generations.get($.pathIdentity)===Z.generation&&J.exactPathIdentities.get($.pathIdentity)===$.exactPathIdentity&&Z.leaseKind==="active"&&Z.leaseId===J.leaseId;return!J.finished&&J.pathIdentity===$.pathIdentity&&J.exactPathIdentity===$.exactPathIdentity&&J.generation===Z.generation&&Z.leaseKind==="recovery"&&Z.leaseId===J.leaseId}function j1($,Z){if(!Z)return $;return Object.defineProperty($,"requiresRead",{value:!0,enumerable:!0,configurable:!0}),$}function i9($,Z){if(Z.requestPending=!1,Z.operation==="read"){if(Z.kind==="recovery"){let Q=$.mutationStates.get(Z.pathIdentity);if(Q&&Q.kind==="reconciling"&&Q.sessionId===Z.sessionId&&Q.exactPathIdentity===Z.exactPathIdentity&&Q.generation===Z.readToken?.generation&&Q.reconciliationPermitId===Z.readToken?.permitId){if(Q.kind="needs-read",Z.boundaryError)Q.reconciliationPermitId=void 0}}if(Z.readToken)Z.readToken.settled=!0;return}let J=$.mutationStates.get(Z.pathIdentity),Y=Z.writeLeaseSnapshot;if(J&&Y&&J.sessionId===Z.sessionId&&J.exactPathIdentity===Z.exactPathIdentity&&J.exactPathIdentity===Y.exactPathIdentity&&Z.boundaryError?.dispatched&&J.generation===Y.generation&&J.leaseId===Y.leaseId&&J.leaseKind===Y.leaseKind)J.kind="needs-read",J.forwardVerified=!1,J.reconciliationPermitId=void 0}function r9($,Z){if(Z.operation==="read"&&Z.readToken){if(Z.kind==="recovery"){let J=$.mutationStates.get(Z.pathIdentity);if(J?.kind==="reconciling"&&J.sessionId===Z.sessionId&&J.exactPathIdentity===Z.exactPathIdentity&&J.generation===Z.readToken.generation&&J.reconciliationPermitId===Z.readToken.permitId)J.kind="needs-read",J.reconciliationPermitId=void 0;let Y=$.recoveryPermits.get(Z.pathIdentity);if(Y?.sessionId===Z.sessionId&&Y.exactPathIdentity===Z.exactPathIdentity&&Y.generation===Z.readToken.generation&&Y.permitId===Z.readToken.permitId)$.recoveryPermits.delete(Z.pathIdentity)}Z.readToken.settled=!0}if(Z.readToken&&$.readTokens.get(Z.pathIdentity)===Z.readToken)$.readTokens.delete(Z.pathIdentity);v8($,Z)}var g2=new WeakMap;function o1($){if($.signal.aborted){let Y=g2.get($);if(Y)return Y;let Q=new y8($);return g2.set($,Q),Q}let Z=g2.get($);if(Z)return Z;let J=new y8($);return g2.set($,J),J}class y8{connection;state;closeHandler;constructor($){this.connection=$;if(this.state=y9(),this.state.closed=$.signal.aborted,this.closeHandler=()=>{this.handleConnectionClosed()},!this.state.closed)$.signal.addEventListener("abort",this.closeHandler,{once:!0})}runRequest($){let Z;try{this.assertOpen($.operation),this.assertBeforeBoundary($.signal,$.operation),this.assertPathAvailability($),Z=this.reserveRequestToken($)}catch(U){return Promise.reject(U)}let J=Z.controller,Y=()=>{this.boundaryReject(Z,this.buildBoundaryReason($.signal,$.deadlineAt),!0),J.abort()};Z.parentSignal=$.signal,Z.parentAbortHandler=Y,$.signal?.addEventListener("abort",Y,{once:!0});let Q=()=>{this.closeRejectToken(Z),J.abort()};Z.deadlineAbortHandler=Q,this.connection.signal.addEventListener("abort",Q,{once:!0});let X=Date.now();if($.deadlineAt<=X)return this.boundaryReject(Z,"timeout",!1),this.cleanupReservedButUndispatchedToken(Z),J.abort(),Z.localPromise;let W=$.deadlineAt-X;Z.timer=setTimeout(()=>{this.boundaryReject(Z,"timeout",!0),J.abort()},W),Z.timer.unref?.();let V;try{V=$.dispatch(J.signal),Z.dispatched=!0,Z.requestPending=!0,this.observeUnderlyingSettlement(Z,V)}catch(U){return this.clearLocalBoundaryResources(Z),this.cleanupReservedButUndispatchedToken(Z),Z.reject(U),Z.localPromise}if($.signal?.aborted)this.boundaryReject(Z,"aborted",!0),J.abort();return Z.localPromise}precheckMutationPaths($,Z){this.assertOpen("write");let J=y6($).map(N0);this.assertMutationPathsAvailable(J)}tryAcquireMutationLease($,Z){this.assertOpen("write");let J=y6($),Y=J.map(N0);return this.assertMutationPathsAvailable(Y),m9(this.state,J,Z)}beginUserRead($,Z){return this.assertOpen("read"),c9(this.state,$,Z)}getStatsForTests(){return u9(this.state)}assertOpen($){if(this.state.closed||this.connection.signal.aborted)throw this.state.closed=!0,new g("closed",$,!1,!1)}assertBeforeBoundary($,Z){if($?.aborted)throw new g("aborted",Z,!1,!1)}assertPathAvailability($){if($.operation==="read"){p9(this.state,$);return}l9(this.state,$)}reserveRequestToken($){return x9(this.state,$)}observeUnderlyingSettlement($,Z){Z.then((J)=>{this.handleSettlement($,{status:"fulfilled",value:J})},(J)=>{this.handleSettlement($,{status:"rejected",reason:J})})}handleSettlement($,Z){if(this.state.closed){this.clearLocalBoundaryResources($),this.cleanupToken($);return}if(i9(this.state,$),$.boundaryError){this.clearLocalBoundaryResources($),this.cleanupToken($);return}if(this.clearLocalBoundaryResources($),this.cleanupToken($),Z.status==="fulfilled"){$.resolve(Z.value);return}$.reject(Z.reason)}boundaryReject($,Z,J){g9(this.state,$,Z,J),this.clearLocalBoundaryResources($)}closeRejectToken($){if(!h9($))return;this.clearLocalBoundaryResources($),$.controller.abort()}cleanupToken($){v8(this.state,$)}cleanupReservedButUndispatchedToken($){r9(this.state,$)}clearLocalBoundaryResources($){if($.deadlineAbortHandler)this.connection.signal.removeEventListener("abort",$.deadlineAbortHandler),$.deadlineAbortHandler=void 0;I9($)}buildBoundaryReason($,Z){if($?.aborted)return"aborted";if(Z<=Date.now())return"timeout";return"aborted"}assertMutationPathsAvailable($){d9(this.state,$)}handleConnectionClosed(){if(this.state.closed)return;this.state.closed=!0,g2.set(this.connection,this);for(let $ of this.state.normalTokens)this.closeRejectToken($);if(this.state.recoveryToken)this.closeRejectToken(this.state.recoveryToken),this.state.recoveryToken=void 0;this.state.normalTokens.clear(),this.state.readTokens.clear(),this.state.recoveryPermits.clear(),this.state.mutationStates.clear()}}var n9=e("Agent"),hV=1024;class M0 extends Error{operation;name="AcpFileSystemCapabilityError";constructor($){super(`ACP remote filesystem does not support ${$}`);this.operation=$}}function q$($){if(gV($,-32002))return!0;if(!($ instanceof Error))return!1;let Z=$.message.toLowerCase();return["not found","no such file","enoent","does not exist","file not found","path not found"].some((J)=>Z.includes(J))}class v0{connection;sessionId;capabilities;remoteAccessLedger=new Map;remoteAccessCollisionIndex=new Map;disposeController=new AbortController;pathProfile;constructor($,Z,J,Y){this.connection=$;this.sessionId=Z;t1(Y),this.capabilities={readTextFile:J.readTextFile===!0,writeTextFile:J.writeTextFile===!0},this.pathProfile=o9(Y)}async readTextFile($,Z){let J=this.parsePath($);return this.readTextFileForParsedPath(J,{signal:Z?.signal,deadlineAt:Z?.deadlineAt,purpose:Z?.purpose??"preflight",lease:Z?.lease})}async readTextFileForParsedPath($,Z){return this.assertParsedPathStyle($),this.runBoundedTextReadPath($,Z)}async readTextFileForUser($,Z){let J=this.parsePath($);return this.readTextFileForUserForParsedPath(J,Z)}async readTextFileForUserForParsedPath($,Z){this.assertParsedPathStyle($);let Y=o1(this.connection).beginUserRead($,this.sessionId);try{let Q=await this.readTextFileForParsedPath($,{signal:Z?.signal,deadlineAt:Z?.deadlineAt,purpose:"user-read",userReadPermit:Y});return Y.complete("content",()=>{this.recordRemoteAccessForPath($,Q,"read")}),Q}catch(Q){if(q$(Q))throw Y.complete("not-found",()=>{this.deleteRemoteAccessCollisionClass($)}),Q;throw Y.fail(),Q}}async writeTextFile($,Z,J){let Y=this.parsePath($);return this.writeTextFileForParsedPath(Y,Z,J)}async writeTextFileForParsedPath($,Z,J){if(this.assertParsedPathStyle($),!this.capabilities.writeTextFile)throw new M0("writeTextFile");let Y=J?.lease===void 0?this.tryAcquireMutationLeaseForParsedPaths([$]):void 0,Q=J?.lease??Y,X=s9(this.disposeController.signal,J?.signal),W=J?.deadlineAt??Date.now()+g0,V=o1(this.connection);try{if(await V.runRequest({operation:"write",purpose:J?.purpose??"mutation",sessionId:this.sessionId,pathIdentity:N0($),exactPathIdentity:$.exactIdentity,deadlineAt:W,signal:X.signal,lease:Q,dispatch:(U)=>this.connection.request(I8.CLIENT_METHODS.fs_write_text_file,{path:$.wirePath,content:Z,sessionId:this.sessionId},{cancellationSignal:U})}),Y)Y.markDefinite($)}catch(U){if(n9.warn("[AcpFileSystem] writeTextFile ACP request failed"),Y&&uV(U))Y.markUncertain($);throw U}finally{if(Y)Y.release();X.cleanup()}}async exists($){if(!this.capabilities.readTextFile)throw new M0("readTextFile");try{let Z=this.parsePath($);return await this.readTextFileForParsedPath(Z,{purpose:"preflight"}),!0}catch(Z){if(q$(Z))return!1;throw Z}}async readBinaryFile($){throw new M0("readBinaryFile")}async stat($){throw new M0("stat")}async mkdir($,Z){throw new M0("mkdir")}getCapabilities(){return{...this.capabilities}}getPathProfile(){return this.pathProfile}parsePath($){return X$($,this.pathProfile.style)}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}assertTextMutationCapabilities(){if(!this.canReadTextFile())throw new M0("readTextFile");if(!this.canWriteTextFile())throw new M0("writeTextFile")}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}createOpaqueLockKey($){let Z=this.parsePath($);return this.createOpaqueLockKeyForParsedPath(Z)}createOpaqueLockKeyForParsedPath($){return this.assertParsedPathStyle($),`acp-remote:${t9("sha256").update(this.sessionId).update("\x00").update($.collisionIdentity).digest("hex")}`}async readTextFileIfExists($,Z){let J=this.parsePath($);return this.readTextFileIfExistsForParsedPath(J,Z)}async readTextFileIfExistsForParsedPath($,Z){this.assertParsedPathStyle($);try{return{exists:!0,content:await this.readTextFileForParsedPath($,{signal:Z?.signal,deadlineAt:Z?.deadlineAt,purpose:Z?.purpose??"preflight",userReadPermit:Z?.userReadPermit,lease:Z?.lease})}}catch(J){if(q$(J))return{exists:!1};throw J}}recordRemoteAccess($,Z,J){let Y=this.parsePath($);this.recordRemoteAccessForPath(Y,Z,J)}recordRemoteAccessForParsedPath($,Z,J){this.assertParsedPathStyle($),this.recordRemoteAccessForPath($,Z,J)}recordRemoteAccessForPath($,Z,J){let Y={filePath:$.wirePath,accessTime:Date.now(),contentSha256:a9(Z),sessionId:this.sessionId,lastOperation:J,source:"remote"},Q=this.remoteAccessCollisionIndex.get($.collisionIdentity);if(Q)this.deleteRemoteAccessEntry(Q);this.remoteAccessLedger.set($.exactIdentity,{collisionIdentity:$.collisionIdentity,record:Y}),this.remoteAccessCollisionIndex.set($.collisionIdentity,$.exactIdentity);while(this.remoteAccessLedger.size>hV){let X=this.remoteAccessLedger.keys().next().value;if(X===void 0)break;this.deleteRemoteAccessEntry(X)}}checkRemoteAccess($,Z){let J=this.parsePath($);return this.checkRemoteAccessForParsedPath(J,Z)}checkRemoteAccessForParsedPath($,Z){this.assertParsedPathStyle($);let J=this.remoteAccessLedger.get($.exactIdentity);if(!J)return"missing";return this.remoteAccessLedger.delete($.exactIdentity),this.remoteAccessLedger.set($.exactIdentity,J),J.record.contentSha256===a9(Z)?"current":"modified"}getRemoteAccessRecord($){let Z=this.parsePath($),J=this.remoteAccessLedger.get(Z.exactIdentity);if(!J)return;return{...J.record}}precheckMutationPaths($){let Z=$.map((J)=>this.parsePath(J));this.precheckMutationPathsForParsedPaths(Z)}precheckMutationPathsForParsedPaths($){for(let J of $)this.assertParsedPathStyle(J);o1(this.connection).precheckMutationPaths($,this.sessionId)}tryAcquireMutationLease($){let Z=$.map((J)=>this.parsePath(J));return this.tryAcquireMutationLeaseForParsedPaths(Z)}tryAcquireMutationLeaseForParsedPaths($){for(let J of $)this.assertParsedPathStyle(J);return o1(this.connection).tryAcquireMutationLease($,this.sessionId)}dispose(){this.disposeController.abort(),this.remoteAccessLedger.clear(),this.remoteAccessCollisionIndex.clear()}async runBoundedTextReadPath($,Z){if(!this.capabilities.readTextFile)throw new M0("readTextFile");let J=s9(this.disposeController.signal,Z.signal),Y=o1(this.connection),Q=Z.deadlineAt??Date.now()+g0;try{return(await Y.runRequest({operation:"read",purpose:Z.purpose,sessionId:this.sessionId,pathIdentity:N0($),exactPathIdentity:$.exactIdentity,deadlineAt:Q,signal:J.signal,lease:Z.lease,userReadPermit:Z.userReadPermit,dispatch:(W)=>this.connection.request(I8.CLIENT_METHODS.fs_read_text_file,{path:$.wirePath,sessionId:this.sessionId},{cancellationSignal:W})})).content}catch(X){if(q$(X))this.deleteRemoteAccessCollisionClass($);throw n9.warn("[AcpFileSystem] readTextFile ACP request failed"),X}finally{J.cleanup()}}deleteRemoteAccessCollisionClass($){let Z=this.remoteAccessCollisionIndex.get($.collisionIdentity);if(!Z)return;this.deleteRemoteAccessEntry(Z)}deleteRemoteAccessEntry($){let Z=this.remoteAccessLedger.get($);if(!Z)return;if(this.remoteAccessLedger.delete($),this.remoteAccessCollisionIndex.get(Z.collisionIdentity)===$)this.remoteAccessCollisionIndex.delete(Z.collisionIdentity)}assertParsedPathStyle($){if(D$($),$.style!==this.pathProfile.style)this.parsePath($.wirePath)}}function gV($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function a9($){return t9("sha256").update($).digest("hex")}function uV($){if(!($ instanceof g))return!0;if(!$.dispatched)return!1;return!$.requestPending}function s9(...$){let Z=$.filter((W)=>W!==void 0);if(Z.length===0)return{signal:new AbortController().signal,cleanup:x8};if(Z.length===1)return{signal:Z[0],cleanup:x8};let J=Z.find((W)=>W.aborted);if(J){let W=new AbortController;return W.abort(J.reason),{signal:W.signal,cleanup:x8}}let Y=new AbortController,Q=new Map,X=(W)=>{if(!Y.signal.aborted)Y.abort(W.reason)};for(let W of Z){let V=()=>{X(W)};Q.set(W,V),W.addEventListener("abort",V,{once:!0})}return{signal:Y.signal,cleanup:()=>{for(let[W,V]of Q)W.removeEventListener("abort",V)}}}function x8(){}var a$=e("Agent"),dV=5000;class x6{defaultCwd;constructor($){this.defaultCwd=$}async execute($,Z){let J=process.platform==="win32"?"cmd.exe":"/bin/bash",Y=process.platform==="win32"?["/c",$]:["-c",$],Q;try{Q=await a1(J,Y,{cwd:Z?.cwd??this.defaultCwd??C(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]},Z?.durableOwnership)}catch(X){return{success:!1,stdout:"",stderr:"",exitCode:null,error:X instanceof Error?X.message:"Foreground command admission failed",failureKind:"admission",transport:"local"}}return new Promise((X)=>{let{child:W,processTree:V}=Q,U,H=()=>{return U??=V.terminate(),U},z=new K$,B,G=!1,D=!1,w=!1,q=!1,F,L,_=Z?.timeout?setTimeout(()=>{if(q)return;if(!B)B="timeout";H()},Z.timeout):null,O=null,b=()=>{if(_)clearTimeout(_);if(O&&Z?.signal)Z.signal.removeEventListener("abort",O),O=null},N=(E)=>{if(w)return;w=!0,b(),X(E)};if(Z?.signal){if(O=()=>{if(q)return;if(!B)B="aborted";H()},Z.signal.addEventListener("abort",O),Z.signal.aborted)O()}W.stdout?.on("data",(E)=>{z.append("stdout",E);let j=E.toString();Z?.onOutput?.(j)}),W.stderr?.on("data",(E)=>{z.append("stderr",E);let j=E.toString();Z?.onOutput?.(j)});let A=(E,j)=>{q=!0,b(),F??=(async()=>{if(await L,B||G)await H();try{await Q.finalize()}catch{D=!0}z.finish();let M=z.snapshot(),k=D?"finalization":B==="timeout"?"timeout":B==="aborted"?"aborted":G?"admission":j?"spawn":void 0;N({success:E===0&&!k,stdout:M.stdout.content,stderr:M.stderr.content,exitCode:E,error:k==="timeout"||k==="aborted"?"Command was terminated":k==="admission"?"Foreground command admission failed":k==="finalization"?"Foreground command finalization failed":j?.message,failureKind:k,...D&&(B==="timeout"||B==="aborted")?{terminationReason:B}:{},transport:"local",capture:M})})()};if(W.once("close",(E)=>A(E)),W.once("error",(E)=>A(null,E)),Z?.signal?.aborted)B="aborted",L=Promise.resolve(),H();else L=Q.release().catch(async()=>{if(G=!0,!B)B="admission";await H()})})}isAvailable(){return!0}}class h8{async execute(){return{success:!1,stdout:"",stderr:"",exitCode:null,error:"ACP terminal capability is unavailable",failureKind:"unavailable",transport:"acp"}}isAvailable(){return!1}}class E1 extends Error{code="acp_session_unavailable";constructor(){super("ACP session filesystem is unavailable");this.name="AcpFileSystemUnavailableError"}}class $3{async readTextFile(){throw new E1}async writeTextFile(){throw new E1}async exists(){throw new E1}async readBinaryFile(){throw new E1}async stat(){throw new E1}async mkdir(){throw new E1}}class Z3{connection;sessionId;remoteFileSystem;fallback;constructor($,Z,J=!1,Y){this.connection=$;this.sessionId=Z;this.remoteFileSystem=J;this.fallback=Y}async execute($,Z){let J;try{a$.debug(`[AcpTerminal] Executing command via ACP: ${$}`),J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([E,j])=>({name:E,value:j})):void 0});let Y=J,Q=Y0.getInstance(),X,W=!1,V=new K$(void 0,!0),U=0,H=0,z=!1,B=!1,G,D,w=async()=>{return},q=async()=>{let E,j=Y.currentOutput().then((k)=>({type:"output",response:k})).catch(()=>({type:"error"})),M=new Promise((k)=>{E=setTimeout(()=>k({type:"timeout"}),dV)});return await Promise.race([j,M]).finally(()=>{if(E)clearTimeout(E)})},F=(E)=>{let j=E.length;if(j>=H){let M=E.slice(H);if(M)Z?.onOutput?.(M);H=j}},L=(E)=>{let j=E.output.length;if(!E.truncated&&j>=U){let M=E.output.slice(U);if(M){if(V.append("stdout",M),X)Q.appendExternalOutput(X,this.sessionId,"stdout",M)}F(E.output),U=j;return}if(V=new K$(void 0,!0),V.append("stdout",E.output),V.markAccountingIncomplete(),X)Q.replaceExternalOutput(X,this.sessionId,E.output,"");H=j,U=j},_=(async()=>{while(!z){let E=await q();if(E.type==="output")L(E.response);else if(V.markAccountingIncomplete(),E.type==="timeout"){B=!0,z=!0;break}if(z)break;await new Promise((j)=>{let M=setTimeout(j,100);G=()=>{clearTimeout(M),j()}}),G=void 0}})(),O=async()=>{z=!0,G?.(),await _},b=Y.waitForExit().then((E)=>({type:"completed",exitCode:E.exitCode??null})).catch((E)=>({type:"failed",error:E})),N=(E)=>{return D??=(async()=>{let j=!1;if(E.type!=="completed")await Y.kill().catch(()=>{j=!0});await O();let M=B?{type:"timeout"}:await q();if(M.type==="output"){let p=M.response;if(p.output.length>=H)F(p.output);if(V=new K$(void 0,!0),V.append("stdout",p.output),p.truncated)V.markAccountingIncomplete()}else V.markAccountingIncomplete();await Y.release().catch(()=>{j=!0}),V.finish();let k=V.snapshot();if(X){Q.replaceExternalOutput(X,this.sessionId,k.stdout.content,k.stderr.content);let p=j?"error":E.type==="completed"?"exited":E.type==="timeout"?"timed_out":E.type==="aborted"?"aborted":E.type==="killed"?"killed":"error";if(Q.completeExternalProcess(X,this.sessionId,{status:p,exitCode:E.type==="completed"?E.exitCode:null,...j?{finalizationFailed:!0}:{},errorMessage:j?"ACP terminal finalization failed":E.type==="failed"?E.error instanceof Error?E.error.message:"ACP terminal unavailable":void 0}),!W)Q.removeCandidate(X,this.sessionId)}return{success:!j&&E.type==="completed"&&E.exitCode===0,stdout:k.stdout.content,stderr:k.stderr.content,exitCode:E.type==="completed"?E.exitCode:null,error:j?"ACP terminal finalization failed":E.type==="timeout"?"Command timed out":E.type==="aborted"||E.type==="killed"?"Command was aborted":E.type==="failed"?E.error instanceof Error?`ACP terminal unavailable: ${E.error.message}`:"ACP terminal unavailable":void 0,failureKind:j?"finalization":E.type==="timeout"?"timeout":E.type==="aborted"||E.type==="killed"?"aborted":E.type==="failed"?"unavailable":void 0,...j&&(E.type==="timeout"||E.type==="aborted"||E.type==="killed")?{terminationReason:E.type==="timeout"?"timeout":"aborted"}:{},transport:"acp",capture:k}})(),D};if(!this.remoteFileSystem&&Z?.foregroundHandoffMs&&Z.foregroundHandoffMs>0&&Z.durableOwnership)try{X=Q.startExternalForegroundCandidate({command:$,sessionId:this.sessionId,cwd:Z.cwd,terminate:async(j)=>{await w(j)}}).id,w=async(j)=>{await N({type:j})}}catch(E){if(!(E instanceof r$))throw E}let A=await new Promise((E)=>{let j=!1,M=(h)=>{if(j)return;if(j=!0,k)clearTimeout(k);if(p)clearTimeout(p);Z?.signal?.removeEventListener("abort",R),E(h)},k=Z?.timeout?setTimeout(()=>M({type:"timeout"}),Z.timeout):void 0,p=X&&Z?.foregroundHandoffMs?setTimeout(()=>M({type:"handoff"}),Z.foregroundHandoffMs):void 0,R=()=>M({type:"aborted"});if(Z?.signal?.aborted)R();else Z?.signal?.addEventListener("abort",R,{once:!0});b.then(M)});if(A.type==="handoff"&&X&&Z?.foregroundHandoffMs){let E=Q.promoteExternalForegroundCandidate(X,this.sessionId,Z.foregroundHandoffMs);if(E)return W=!0,b.then(N),{success:!0,stdout:"",stderr:"",exitCode:null,transport:"acp",capture:V.snapshot(),background:{shellId:E.id,autoBackgrounded:!0,foregroundBudgetMs:Z.foregroundHandoffMs}}}return await N(A.type==="handoff"?await b:A)}catch(Y){if(J)await J.release().catch(()=>{return});if(this.remoteFileSystem||Z?.allowLocalFallback!==!0)return{success:!1,stdout:"",stderr:"",exitCode:null,error:Y instanceof Error?`ACP terminal unavailable: ${Y.message}`:"ACP terminal unavailable",failureKind:"unavailable",transport:"acp"};return a$.warn("[AcpTerminal] ACP terminal failed, using fallback:",Y),{...await(this.fallback??new x6(Z?.cwd)).execute($,Z),transport:"local_fallback"}}}isAvailable(){return!0}}function e9($,Z){return JSON.stringify([$,Z])}class y{static sessions=new Map;static remoteSurfaceOwners=new Map;static remoteSurfaceOwnerKeysBySessionId=new Map;static sessionRegistrationGeneration=0n;static currentSessionId=null;constructor(){}static getInstance(){return new y}static initializeSession($,Z,J,Y,Q,X){if(y.sessions.get(Z)){y.currentSessionId=Z,a$.debug(`[AcpServiceContext:${Z}] initializeSession ignored because the session already exists`);return}let V=J?.fs?.readTextFile===!0||J?.fs?.writeTextFile===!0,U;if(V){let G=X??u2(Y);U=new v0($,Z,J?.fs??{},G)}else U=new h2;if(V)a$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let H=J?.terminal?new Z3($,Z,V):V?new h8:new x6(Y);a$.debug(`[AcpServiceContext:${Z}] Using ${J?.terminal?"ACP":"local"} terminal service`),y.sessionRegistrationGeneration+=1n;let z=Object.freeze({generation:`acp-owner-generation:${y.sessionRegistrationGeneration.toString(36)}`,sessionId:Z}),B={fileSystemService:U,terminalService:H,connection:$,registration:z,sendUpdate:Q,clientCapabilities:J||null,executionRoot:Y,remoteFileSystem:V};if(y.sessions.set(Z,B),V){let G=X??u2(Y),D=e9(Z,G.workspace.exactIdentity);y.remoteSurfaceOwners.set(D,{exactIdentity:G.workspace.exactIdentity,generation:z.generation,readText:J?.fs?.readTextFile===!0,services:B,writeText:J?.fs?.writeTextFile===!0,terminal:J?.terminal===!0}),y.remoteSurfaceOwnerKeysBySessionId.set(Z,D)}return y.currentSessionId=Z,a$.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile}),z}static destroySession($){let Z=y.remoteSurfaceOwnerKeysBySessionId.get($);if(Z)y.remoteSurfaceOwners.delete(Z),y.remoteSurfaceOwnerKeysBySessionId.delete($);let J=y.sessions.get($);if(J?.fileSystemService instanceof v0)J.fileSystemService.dispose();if(y.sessions.delete($),y.currentSessionId===$){let Y=Array.from(y.sessions.keys());y.currentSessionId=Y[0]||null}a$.debug(`[AcpServiceContext:${$}] Session destroyed`)}static destroyRegisteredSession($){if(!$)return;if(y.sessions.get($.sessionId)?.registration!==$)return;y.destroySession($.sessionId)}static getSessionServices($){return y.sessions.get($)||null}static setCurrentSession($){if(y.sessions.has($))y.currentSessionId=$}static getCurrentSessionId(){return y.currentSessionId}static isRemoteFileSystem($){return y.sessions.get($)?.remoteFileSystem??!1}static getRemoteSurfaceOwnerSnapshot($,Z){let J;try{J=I6(Z)}catch{return{connection:"offline"}}let Y=y.remoteSurfaceOwners.get(e9($,J.exactIdentity));if(!Y||Y.exactIdentity!==J.exactIdentity||y.sessions.get($)!==Y.services||Y.services.connection.signal.aborted)return{connection:"offline"};return{connection:"online",generation:Y.generation,readText:Y.readText,writeText:Y.writeText,terminal:Y.terminal}}initialize($,Z,J,Y){y.initializeSession($,Z,J,Y||C())}reset(){if(y.currentSessionId)y.destroySession(y.currentSessionId)}isAcpMode(){return y.currentSessionId!==null}getFileSystemService($){if($!==void 0)return y.sessions.get($)?.fileSystemService??new $3;let Z=$??y.currentSessionId;if(Z){let J=y.sessions.get(Z);if(J)return J.fileSystemService}return new h2}getTerminalService($){let Z=$??y.currentSessionId;if(Z){let J=y.sessions.get(Z);if(J)return J.terminalService;if($)return new h8}return new x6}getConnection(){if(y.currentSessionId){let $=y.sessions.get(y.currentSessionId);if($)return $.connection}return null}getSessionId(){return y.currentSessionId}getClientCapabilities(){if(y.currentSessionId){let $=y.sessions.get(y.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,Y,Q){let X=y.currentSessionId;if(!X)return;let W=y.sessions.get(X);if(!W)return;if(!W.sendUpdate)return;try{await W.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:Y||[],kind:Q||"other"})}catch(V){a$.warn("[AcpServiceContext] Failed to send tool update:",V)}}}function w$($){return y.getInstance().getFileSystemService($)}function J3($){return y.getInstance().getTerminalService($)}function H0($){return $?y.getSessionServices($)!==null:y.getInstance().isAcpMode()}function _$($){let Z=$??y.getCurrentSessionId();return Z?y.isRemoteFileSystem(Z):!1}function s$($,Z,J){if(J==="local")return!1;if(J==="acp-remote"||Z==="acp-remote"){let Y=$??y.getCurrentSessionId();return Y===null||!y.isRemoteFileSystem(Y)}return $!==void 0&&y.getSessionServices($)===null}import{createHash as YU,randomUUID as QU}from"node:crypto";var mV=["BrowserNavigate","BrowserSnapshot","BrowserInteract","BrowserWait","BrowserInspect","BrowserPage"];function g8($){return mV.includes($)}class f extends Error{code;details;constructor($,Z,J={}){super(Z);this.code=$;this.details=J;this.name="BrowserRuntimeError"}}class u8{maxPending;queue=[];closeController=new AbortController;idleWaiters=new Set;active=!1;closed=!1;constructor($=Y3){this.maxPending=$;if(!Number.isSafeInteger($)||$<=0)throw Error("Browser operation pending limit must be a positive integer")}run($,Z){if(this.closed)return Promise.reject(new f("browser_disposed","Browser Session Runtime is closed"));if(Z?.aborted)return Promise.reject(Z.reason??Error("Browser operation aborted"));if(this.queue.length>=this.maxPending)return Promise.reject(new f("browser_busy","Browser operation queue is full",{retryable:!0}));return new Promise((J,Y)=>{let Q={run:$,resolve:J,reject:Y,signal:Z};if(Z)Q.abortListener=()=>{let X=this.queue.indexOf(Q);if(X<0)return;this.queue.splice(X,1),Y(Z.reason??Error("Browser operation aborted"))},Z.addEventListener("abort",Q.abortListener,{once:!0});this.queue.push(Q),this.drain()})}close(){if(!this.closed){this.closed=!0,this.closeController.abort(new f("browser_disposed","Browser Session Runtime is closed"));for(let $ of this.queue.splice(0)){if($.signal&&$.abortListener)$.signal.removeEventListener("abort",$.abortListener);$.reject(new f("browser_disposed","Browser Session Runtime is closed"))}}if(!this.active)return Promise.resolve();return new Promise(($)=>this.idleWaiters.add($))}stats(){return{active:this.active,pending:this.queue.length,closed:this.closed}}drain(){if(this.active||this.closed)return;let $=this.queue.shift();if(!$)return;if($.signal&&$.abortListener)$.signal.removeEventListener("abort",$.abortListener);this.active=!0;let Z=$.signal?AbortSignal.any([$.signal,this.closeController.signal]):this.closeController.signal;Promise.resolve().then(()=>$.run(Z)).then($.resolve,$.reject).finally(()=>{if(this.active=!1,this.closed){for(let J of this.idleWaiters)J();this.idleWaiters.clear()}this.drain()})}}import{randomUUID as cV}from"node:crypto";import{Mutex as pV}from"async-mutex";var lV={viewport:{width:1440,height:900},deviceScaleFactor:1,locale:"en-US",timezoneId:"UTC",acceptDownloads:!1};async function iV(){let{chromium:$}=await import("playwright");return{launch:(Z)=>$.launch(Z)}}class V3{mutex=new pV;leases=new Map;maxContexts;contextOptions;environment;adapter;browser;launchPromise;generation=0;disposed=!1;disconnectListener;constructor($={}){if(this.adapter=$.adapter,this.contextOptions=$.contextOptions??lV,this.environment=$.environment??process.env,this.maxContexts=$.maxContexts??X3,!Number.isSafeInteger(this.maxContexts)||this.maxContexts<=0)throw Error("Browser context limit must be a positive integer")}async acquire($){return this.mutex.runExclusive(async()=>{if(this.disposed)throw new f("browser_disposed","Browser process pool is closed");if(this.leases.size>=this.maxContexts)throw new f("browser_capacity",`Browser context capacity is full (max ${this.maxContexts})`,{retryable:!0});let Z=await this.ensureBrowser(),J=this.generation,Y;try{Y=await Z.newContext(this.contextOptions)}catch(W){if(!Z.isConnected()||Z!==this.browser)throw new f("browser_disconnected","Chromium disconnected while creating a Session context",{retryable:!0});if(this.leases.size===0&&Z===this.browser)this.detachDisconnectListener(Z),this.browser=void 0,this.launchPromise=void 0,await Z.close().catch(()=>{return});throw W}if(this.disposed||Z!==this.browser||J!==this.generation)throw await Y.close().catch(()=>{return}),new f(this.disposed?"browser_disposed":"browser_disconnected",this.disposed?"Browser process pool is closed":"Chromium disconnected while creating a Session context",{retryable:!this.disposed});let Q=cV();this.leases.set(Q,{context:Y,generation:J,onDisconnected:$});let X=!1;return{context:Y,generation:J,release:async()=>{if(X)return;X=!0,await this.release(Q)}}})}stats(){return{generation:this.generation,contexts:this.leases.size,launching:this.launchPromise!==void 0&&this.browser===void 0,running:this.browser?.isConnected()===!0,disposed:this.disposed}}async dispose(){let $=await this.mutex.runExclusive(async()=>{if(this.disposed)return;this.disposed=!0;let Z=this.browser,J=[...this.leases.values()].map((Y)=>Y.context);return this.leases.clear(),this.detachDisconnectListener(Z),this.browser=void 0,this.launchPromise=void 0,this.generation++,{browser:Z,contexts:J}});if(!$)return;await Promise.allSettled($.contexts.map((Z)=>Z.close())),await $.browser?.close().catch(()=>{return})}async ensureBrowser(){if(this.browser?.isConnected())return this.browser;if(!this.launchPromise)this.launchPromise=this.launch();try{return await this.launchPromise}finally{this.launchPromise=void 0}}async launch(){let $=this.adapter??await iV();this.adapter=$;let Z;try{Z=await $.launch({headless:!0,chromiumSandbox:!0,env:W3(this.environment)})}catch{throw new f("browser_not_installed",`Chromium is unavailable or failed to launch.
121
+ [error] ${G.message}`),z.releaseAdmission(),z.resolveCompletion()})()}),this.processes.set(J,z);try{await W.release()}catch(G){throw z.status="aborted",z.endTime=Date.now(),await U.terminate(),this.processes.delete(J),z.releaseAdmission(),z.resolveCompletion(),$.sandboxedCommand?.cleanup(),G}return z}startExternalForegroundCandidate($){let Z=this.reserve($.sessionId),J=`bash_${M8()}`,Y=this.createCompletion(),Q={id:J,command:$.command,sessionId:$.sessionId,cwd:$.cwd,status:"running",startTime:Date.now(),pendingStdout:new J$,pendingStderr:new J$,sandboxed:$.sandboxed??!1,transport:"acp",visible:!1,autoBackgrounded:!1,completion:Y.promise,resolveCompletion:Y.resolve,releaseAdmission:this.releaseOnce(Z),terminateExternal:$.terminate,terminalSettled:!1};return this.processes.set(J,Q),Q}promoteExternalForegroundCandidate($,Z,J){let Y=this.getOwnedProcess($,Z);if(!Y||Y.visible||Y.status!=="running"||Y.transport!=="acp")return;return Y.visible=!0,Y.autoBackgrounded=!0,Y.backgroundReason="foreground_budget",Y.foregroundBudgetMs=J,Y.foregroundCapture=void 0,Y}appendExternalOutput($,Z,J,Y){let Q=this.getOwnedProcess($,Z);if(!Q||Q.transport!=="acp")return;if(J==="stdout")Q.pendingStdout.append(Y);else Q.pendingStderr.append(Y)}replaceExternalOutput($,Z,J,Y){let Q=this.getOwnedProcess($,Z);if(!Q||Q.transport!=="acp")return;Q.pendingStdout=new J$,Q.pendingStderr=new J$,Q.pendingStdout.append(J),Q.pendingStderr.append(Y)}completeExternalProcess($,Z,J){let Y=this.getOwnedProcess($,Z);if(!Y||Y.transport!=="acp"||Y.terminalSettled)return;if(Y.terminalSettled=!0,Y.status=J.status,Y.exitCode=J.exitCode,Y.signal=J.signal,Y.errorMessage=J.errorMessage,J.finalizationFailed)Y.finalizationFailed=!0;Y.endTime=Date.now(),Y.releaseAdmission(),Y.resolveCompletion()}promoteForegroundCandidate($,Z,J,Y){let Q=this.getOwnedProcess($,Z);if(!Q||Q.visible||Q.status!=="running"||!Q.foreground)return;let X=new v2(J,Z);return Q.foreground.handoff((W)=>X.register($,W),()=>X.remove($)),Q.leaseStore=X,Q.visible=!0,Q.autoBackgrounded=!0,Q.backgroundReason="foreground_budget",Q.foregroundBudgetMs=Y,Q}waitForCompletion($,Z){return this.getOwnedProcess($,Z)?.completion}consumeCandidateOutput($,Z){let J=this.getOwnedProcess($,Z);if(!J)return;let Y=this.snapshot(J,!0);if(J.foregroundCapture)J.foregroundCapture.finish(),Y.capture=J.foregroundCapture.snapshot(),J.foregroundCapture=void 0;return Y}removeCandidate($,Z){let J=this.getOwnedProcess($,Z);if(!J||J.visible||J.status==="running")return;this.processes.delete($)}terminateForegroundCandidate($,Z,J){let Y=this.getOwnedProcess($,Z);if(!Y||Y.visible)return;return this.terminateProcess(Y,J)}consumeOutput($,Z){let J=this.getProcess($,Z);if(!J)return;return this.snapshot(J,!0)}getProcess($,Z){let J=this.getOwnedProcess($,Z);return J?.visible?J:void 0}listForSession($){return Array.from(this.processes.values()).filter((Z)=>Z.sessionId===$&&Z.visible)}async writeInput($,Z,J,Y=!1){let Q=this.getProcess($,Z);if(!Q)return;if(Q.transport==="acp")return{success:!1,status:Q.status,bytesWritten:0,stdinClosed:!1,errorMessage:"ACP background terminals do not support stdin writes"};let X=Q.process?.stdin;if(Q.status!=="running"||!X||X.destroyed||X.writableEnded)return{success:!1,status:Q.status,bytesWritten:0,stdinClosed:!X||X.destroyed||X.writableEnded,errorMessage:"Shell stdin is not writable"};try{return await new Promise((W,V)=>{let U=(z)=>{X.off("error",U),V(z)},H=(z)=>{if(X.off("error",U),z)V(z);else W()};if(X.once("error",U),Y)X.end(J,H);else X.write(J,H)}),{success:!0,status:Q.status,bytesWritten:Buffer.byteLength(J),stdinClosed:Y}}catch(W){return{success:!1,status:Q.status,bytesWritten:0,stdinClosed:X.destroyed||X.writableEnded,errorMessage:W instanceof Error?W.message:"Failed to write stdin"}}}async kill($,Z){let J=this.getOwnedProcess($,Z);if(!J?.visible)return;return this.terminateProcess(J)}async killSession($){let Z=Array.from(this.processes.values()).filter((J)=>J.sessionId===$);await Promise.all(Z.map((J)=>this.terminateProcess(J)));for(let J of Z)this.processes.delete(J.id)}reapOrphanedSession($,Z){return new v2(Z,$).reapOrphans()}async terminateProcess($,Z="killed"){if($.externalTerminationPromise)return $.externalTerminationPromise;if($.status!=="running")return{success:!1,alreadyExited:!0,status:$.status,...$.finalizationFailed?{finalizationFailed:!0}:{},pid:$.pid,exitCode:$.exitCode,signal:$.signal};if($.terminateExternal){let Y=$.terminateExternal;return $.externalTerminationPromise=Promise.resolve().then(async()=>{try{await Y(Z)}catch{this.completeExternalProcess($.id,$.sessionId,{status:"error",finalizationFailed:!0,errorMessage:"ACP terminal finalization failed"})}return $.releaseAdmission(),{success:$.status!=="error",alreadyExited:!1,status:$.status,...$.finalizationFailed?{finalizationFailed:!0}:{},pid:$.pid,exitCode:$.exitCode,signal:$.signal}}).finally(()=>{$.externalTerminationPromise=void 0}),$.externalTerminationPromise}if($.status=Z==="timeout"?"timed_out":Z==="aborted"?"aborted":"killed",$.endTime=Date.now(),!$.process)return $.releaseAdmission(),{success:!1,alreadyExited:!0,status:$.status,...$.finalizationFailed?{finalizationFailed:!0}:{},pid:$.pid,exitCode:$.exitCode,signal:$.signal};let J=await $.processTree?.terminate();if(!J?.success)return $.status="error",$.errorMessage="Failed to terminate owned process tree",{success:!1,alreadyExited:J?.alreadyExited??!1,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal};return $.leaseStore?.remove($.id),$.releaseAdmission(),{success:!0,alreadyExited:J.alreadyExited,status:$.status,pid:$.pid,exitCode:$.exitCode,signal:$.signal}}async killAll(){await Promise.all(Array.from(this.processes.values()).map(($)=>this.terminateProcess($))),this.processes.clear()}getAdmissionStats(){return{active:this.activeGlobal,maxActive:this.globalMaxActive,sessions:Object.fromEntries([...this.activeBySession].map(([$,Z])=>[$,{active:Z,maxActive:this.sessionMaxActive}]))}}getOwnedProcess($,Z){let J=this.processes.get($);return J?.sessionId===Z?J:void 0}snapshot($,Z){let J=Z?$.pendingStdout.consume():$.pendingStdout.peek(),Y=Z?$.pendingStderr.consume():$.pendingStderr.peek();return{id:$.id,command:$.command,status:$.status,stdout:J.content,stderr:Y.content,stdoutOmittedBytes:J.omittedBytes,stderrOmittedBytes:Y.omittedBytes,stdoutTotalBytes:J.totalBytes,stderrTotalBytes:Y.totalBytes,exitCode:$.exitCode,signal:$.signal,pid:$.pid,startedAt:$.startTime,endedAt:$.endTime,errorMessage:$.errorMessage,...$.finalizationFailed?{finalizationFailed:!0}:{},sandboxed:$.sandboxed,transport:$.transport,autoBackgrounded:$.autoBackgrounded,backgroundReason:$.backgroundReason,foregroundBudgetMs:$.foregroundBudgetMs}}reserve($){let Z=this.activeBySession.get($)??0;if(Z>=this.sessionMaxActive)throw new r$("session",this.sessionMaxActive);if(this.activeGlobal>=this.globalMaxActive)throw new r$("global",this.globalMaxActive);return this.activeGlobal++,this.activeBySession.set($,Z+1),this.releaseOnce(()=>{this.activeGlobal=Math.max(0,this.activeGlobal-1);let J=Math.max(0,(this.activeBySession.get($)??0)-1);if(J===0)this.activeBySession.delete($);else this.activeBySession.set($,J)})}releaseOnce($){let Z=!1;return()=>{if(Z)return;Z=!0,$()}}createCompletion(){let $;return{promise:new Promise((J)=>{$=J}),resolve:$}}positiveLimit($,Z){if(!Number.isSafeInteger($)||$<=0)throw Error(`${Z} must be a positive safe integer`);return $}}import{stat as GX}from"node:fs/promises";import{Mutex as KX}from"async-mutex";import{nanoid as cD}from"nanoid";import*as _0 from"path";import*as Q$ from"fs/promises";class h2{async readTextFile($){return Q$.readFile($,"utf-8")}async writeTextFile($,Z){await Q$.writeFile($,Z,"utf-8")}async exists($){try{return await Q$.access($),!0}catch(Z){if(Z.code==="ENOENT")return!1;throw Z}}async readBinaryFile($){return Q$.readFile($)}async stat($){try{let Z=await Q$.stat($);return{size:Z.size,isDirectory:Z.isDirectory(),isFile:Z.isFile(),mtime:Z.mtime}}catch(Z){if(Z.code==="ENOENT")return null;throw Z}}async mkdir($,Z){await Q$.mkdir($,{recursive:Z?.recursive??!1,mode:Z?.mode??493})}}var SV=new h2;function n$(){return SV}import{createHash as t9}from"node:crypto";import*as I8 from"@agentclientprotocol/sdk";import{createHash as kV}from"node:crypto";var g0=30000,v6=5000,C8=120000,T8=60000;var R8=31,f8=1024,vV={aborted:"ACP remote file request was aborted",timeout:"ACP remote file request timed out",busy:"ACP remote file path is busy",capacity:"ACP remote file request capacity is full",closed:"ACP remote filesystem connection is closed","stale-reconciliation":"ACP remote file reconciliation is stale"};class g extends Error{reason;operation;dispatched;requestPending;name="AcpRemoteFileBoundaryError";constructor($,Z,J,Y){super(vV[$]);this.reason=$;this.operation=Z;this.dispatched=J;this.requestPending=Y}}function N0($){return D$($),`acp-remote-connection-path:${kV("sha256").update($.collisionIdentity).digest("hex")}`}var P8=new WeakMap,S8=new WeakMap;function y9(){return{normalTokens:new Set,recoveryToken:void 0,mutationStates:new Map,readTokens:new Map,recoveryPermits:new Map,closed:!1}}function yV($,Z){let J,Y,Q=new Promise((X,W)=>{J=X,Y=W});return Q.catch(()=>{return}),{kind:Z,operation:$.operation,purpose:$.purpose,sessionId:$.sessionId,pathIdentity:$.pathIdentity,exactPathIdentity:$.exactPathIdentity,controller:new AbortController,localPromise:Q,resolve:J,reject:Y,timer:void 0,parentAbortHandler:void 0,deadlineAbortHandler:void 0,settled:!1,dispatched:!1,requestPending:!1,timedOut:!1,aborted:!1,boundaryError:void 0}}function k8($){if(!$)return;return P8.get($)}function x9($,Z){let J=Z.userReadPermit?.lane==="recovery"||Z.purpose==="rollback"?"recovery":"normal";if(J==="normal"&&$.normalTokens.size>=R8)throw new g("capacity",Z.operation,!1,!1);if(J==="recovery"&&$.recoveryToken!==void 0)throw new g("capacity",Z.operation,!1,!1);let Y=yV(Z,J),Q=k8(Z.lease);if(Z.operation==="write"&&Q)if(Q.kind==="active"){let X=Q.exactPathIdentities.get(Z.pathIdentity);if(X===void 0)throw new g("busy",Z.operation,!1,!1);Y.writeLeaseSnapshot={generation:Q.generations.get(Z.pathIdentity)??0,leaseId:Q.leaseId,leaseKind:Q.kind,exactPathIdentity:X}}else Y.writeLeaseSnapshot={generation:Q.generation,leaseId:Q.leaseId,leaseKind:Q.kind,exactPathIdentity:Q.exactPathIdentity};if(Z.operation==="read"){let X=Z.userReadPermit?S8.get(Z.userReadPermit):void 0;if(Y.readToken={pathIdentity:Z.pathIdentity,exactPathIdentity:Z.exactPathIdentity,generation:Z.userReadPermit?.generation,permitId:X?.permitId,detached:!1,settled:!1},$.readTokens.set(Z.pathIdentity,Y.readToken),Z.userReadPermit?.lane==="recovery"){let W=$.mutationStates.get(Z.pathIdentity),V=$.recoveryPermits.get(Z.pathIdentity);if(W?.sessionId===Z.sessionId&&W.exactPathIdentity===Z.exactPathIdentity&&W.generation===Z.userReadPermit.generation&&V!==void 0&&X!==void 0&&V.permitId===X.permitId)W.kind="reconciling",W.reconciliationPermitId=V.permitId;if(V?.sessionId===Z.sessionId&&V.exactPathIdentity===Z.exactPathIdentity&&V.generation===Z.userReadPermit.generation)V.active=!0}}if(J==="normal")$.normalTokens.add(Y);else $.recoveryToken=Y;return Y}function v8($,Z){if(Z.kind==="normal")$.normalTokens.delete(Z);else if($.recoveryToken===Z)$.recoveryToken=void 0;if(Z.readToken?.settled&&$.readTokens.get(Z.pathIdentity)===Z.readToken)$.readTokens.delete(Z.pathIdentity)}function I9($){if($.timer)clearTimeout($.timer),$.timer=void 0;if($.parentAbortHandler&&$.parentSignal)$.parentSignal.removeEventListener("abort",$.parentAbortHandler),$.parentAbortHandler=void 0,$.parentSignal=void 0}function h9($){if($.settled)return;$.settled=!0;let Z=new g("closed",$.operation,$.dispatched,$.requestPending);return $.reject(Z),Z}function g9($,Z,J,Y){if(Z.settled)return;let Q=Z.operation==="write"&&Z.dispatched&&Y&&Z.writeLeaseSnapshot!==void 0;if(Z.boundaryError=j1(new g(J,Z.operation,Z.dispatched,Y&&Z.dispatched),Q),Z.operation==="read"&&Z.readToken){if(Z.readToken.detached=Z.boundaryError.requestPending,!Z.boundaryError.requestPending)$.readTokens.delete(Z.pathIdentity)}if(Z.operation==="write"&&Z.dispatched){let X=$.mutationStates.get(Z.pathIdentity),W=Z.writeLeaseSnapshot;if(X&&W&&X.sessionId===Z.sessionId&&X.exactPathIdentity===Z.exactPathIdentity&&X.exactPathIdentity===W.exactPathIdentity&&X.generation===W.generation&&X.leaseId===W.leaseId&&X.leaseKind===W.leaseKind)X.kind="pending-write",X.forwardVerified=!1}return Z.settled=!0,Z.reject(Z.boundaryError),Z.boundaryError}function u9($){let Z=0,J=0,Y=0,Q=0;for(let W of $.mutationStates.values()){if(W.kind==="active-mutation")Z+=1;if(W.kind==="pending-write")J+=1;if(W.kind==="needs-read")Y+=1;if(W.kind==="reconciling")Q+=1}let X=0;for(let W of $.readTokens.values())if(!W.detached)X+=1;return{pendingNormal:$.normalTokens.size,pendingRecovery:$.recoveryToken?1:0,activeNormalReads:X,mutationPaths:$.mutationStates.size,activeMutations:Z,pendingWrites:J,needsRead:Y,reconciling:Q,closed:$.closed}}function d9($,Z){if(Z.length===0)throw new g("busy","write",!1,!1);let J=$.mutationStates.size;for(let Y of Z){let Q=$.mutationStates.get(Y);if(Q)throw j1(new g("busy","write",!1,!1),Q.kind==="pending-write"||Q.kind==="needs-read")}if(J+Z.length>f8)throw new g("capacity","write",!1,!1)}function y6($){let Z=new Map;for(let J of $){let Y=N0(J);if(!Z.has(Y))Z.set(Y,J)}return[...Z.entries()].sort(([J],[Y])=>J.localeCompare(Y)).map(([,J])=>J)}function m9($,Z,J){let Y=y6(Z).map((Q)=>({pathIdentity:N0(Q),exactPathIdentity:Q.exactIdentity}));return xV($,Y,J)}function xV($,Z,J){let Y=Z.map(({pathIdentity:B})=>B),Q=Symbol("acp-mutation-lease"),X={kind:"active",sessionId:J,leaseId:Q,generations:new Map,exactPathIdentities:new Map,released:!1},W=new Map;for(let{pathIdentity:B,exactPathIdentity:G}of Z){let w=($.mutationStates.get(B)?.generation??0)+1;W.set(B,w),X.generations.set(B,w),X.exactPathIdentities.set(B,G)}for(let{pathIdentity:B,exactPathIdentity:G}of Z){let D=$.mutationStates.get(B),w=new Set(D?.retiredGenerations??[]);if(D)w.add(D.generation);$.mutationStates.set(B,{pathIdentity:B,exactPathIdentity:G,sessionId:J,generation:W.get(B)??1,kind:"active-mutation",leaseKind:"active",leaseId:Q,forwardVerified:!1,retiredGenerations:w})}let V=!1,U=!1,H=(B,G)=>{let D=W.get(B),w=$.mutationStates.get(B);if(D===void 0||!w||w.sessionId!==J||w.generation!==D||w.exactPathIdentity!==G||w.leaseKind!=="active"||w.leaseId!==Q)return;return w},z={sessionId:J,pathIdentities:Y,generationFor(B){let G=N0(B);return H(G,B.exactIdentity)?.generation??0},isCurrent(B){let G=N0(B);return!V&&H(G,B.exactIdentity)!==void 0},markForwardVerified(B){if(V)return;let G=N0(B),D=H(G,B.exactIdentity);if(D)D.kind="active-mutation",D.forwardVerified=!0},markDefinite(B){if(V)return;let G=N0(B);if(H(G,B.exactIdentity))$.mutationStates.delete(G)},markUncertain(B){if(V)return;let G=N0(B),D=H(G,B.exactIdentity);if(D)D.kind="needs-read",D.forwardVerified=!1},beginRecovery(B){if(V)throw new g("stale-reconciliation","read",!1,!1);let G=N0(B),D=B.exactIdentity,w=H(G,D);if(!w||w.kind==="pending-write")throw new g("stale-reconciliation","read",!1,!1);let q=w.generation,F=q+1,L=Symbol("acp-recovery-lease");W.set(G,F),X.generations.set(G,F);let _=new Set(w.retiredGenerations??[]);_.add(q),w.generation=F,w.kind="active-mutation",w.leaseKind="recovery",w.leaseId=L,w.forwardVerified=!1,w.reconciliationPermitId=void 0,w.retiredGenerations=_;let O={generation:F,pathIdentity:G,exactPathIdentity:D,finish(N){if(b.finished)return;let A=$.mutationStates.get(G);if(!A||A.sessionId!==J||A.generation!==F||A.exactPathIdentity!==D||A.leaseKind!=="recovery"||A.leaseId!==L)return;if(b.finished=!0,A.kind==="pending-write")return;if(N==="restored")$.mutationStates.delete(G);else A.kind="needs-read",A.forwardVerified=!1,A.reconciliationPermitId=void 0}},b={kind:"recovery",sessionId:J,leaseId:L,pathIdentity:G,exactPathIdentity:D,generation:F,finished:!1};return P8.set(O,b),O},commitVerified(){U=!0},release(){if(V)return;for(let{pathIdentity:B,exactPathIdentity:G}of Z){let D=H(B,G);if(!D)continue;if(D.kind==="active-mutation"){if(!D.forwardVerified){$.mutationStates.delete(B);continue}if(U){$.mutationStates.delete(B);continue}D.kind="needs-read",D.forwardVerified=!1,D.reconciliationPermitId=void 0;continue}if(D.kind==="pending-write")continue;if(D.kind==="needs-read"){D.forwardVerified=!1;continue}if(U)$.mutationStates.delete(B)}V=!0,X.released=!0}};return P8.set(z,X),z}function c9($,Z,J){let Y=N0(Z),Q=$.mutationStates.get(Y);if(!Q)return Object.freeze({sessionId:J,pathIdentity:Y,exactPathIdentity:Z.exactIdentity,generation:void 0,lane:"normal",complete:(X,W)=>{W()},fail:()=>{}});if(Q.kind==="pending-write")throw j1(new g("busy","read",!1,!1),!0);if(Q.kind==="needs-read"&&Q.sessionId===J&&Q.exactPathIdentity===Z.exactIdentity&&!$.recoveryToken&&!$.recoveryPermits.has(Y)){let X=Symbol("acp-recovery-permit"),W={sessionId:J,pathIdentity:Y,exactPathIdentity:Z.exactIdentity,generation:Q.generation,permitId:X,active:!1};$.recoveryPermits.set(Y,W);let V={sessionId:J,pathIdentity:Y,exactPathIdentity:Z.exactIdentity,generation:Q.generation,lane:"recovery",complete:(H,z)=>{let B=$.mutationStates.get(Y);if($.recoveryPermits.get(Y)!==W||!W.active||!B||B.sessionId!==J||B.generation!==W.generation||B.exactPathIdentity!==W.exactPathIdentity||B.reconciliationPermitId!==W.permitId||B.kind!=="needs-read")throw new g("stale-reconciliation","read",!1,!1);if(z(),$.recoveryPermits.delete(Y),W.active=!1,H==="content"||H==="not-found")$.mutationStates.delete(Y)},fail:()=>{if($.recoveryPermits.get(Y)===W){$.recoveryPermits.delete(Y);let H=$.mutationStates.get(Y);if(H?.kind==="needs-read"&&H.reconciliationPermitId===X)H.reconciliationPermitId=void 0}W.active=!1}},U=Object.freeze(V);return S8.set(U,{permitId:X}),U}throw new g("busy","read",!1,!1)}function p9($,Z){if(Z.userReadPermit?.lane==="recovery"){let Q=$.mutationStates.get(Z.pathIdentity);if(Q?.kind==="pending-write")throw j1(new g("busy","read",!1,!1),!0);if(!Q||Q.kind!=="needs-read")throw new g("stale-reconciliation","read",!1,!1);let X=$.recoveryPermits.get(Z.pathIdentity),W=S8.get(Z.userReadPermit);if(!X||!W||X.permitId!==W.permitId||Z.userReadPermit.pathIdentity!==Z.pathIdentity||Z.userReadPermit.exactPathIdentity!==Z.exactPathIdentity||Z.userReadPermit.sessionId!==Z.sessionId||Q.sessionId!==Z.sessionId||Q.exactPathIdentity!==Z.exactPathIdentity||Q.generation!==Z.userReadPermit.generation||X.sessionId!==Z.userReadPermit.sessionId||X.exactPathIdentity!==Z.userReadPermit.exactPathIdentity||X.generation!==Z.userReadPermit.generation)throw new g("stale-reconciliation","read",!1,!1);let V=$.readTokens.get(Z.pathIdentity);if(V&&!V.detached)throw new g("busy","read",!1,!1);if(Q.retiredGenerations?.has(Z.userReadPermit.generation))throw new g("stale-reconciliation","read",!1,!1);if(Q.exactPathIdentity!==Z.exactPathIdentity)throw new g("busy","read",!1,!1);return}if($.readTokens.get(Z.pathIdentity))throw new g("busy","read",!1,!1);let Y=$.mutationStates.get(Z.pathIdentity);if(!Y)return;if(Y.kind!=="active-mutation")throw j1(new g("busy","read",!1,!1),Y.kind==="pending-write"||Y.kind==="needs-read");if(!IV(Z,Y))throw new g("busy","read",!1,!1)}function l9($,Z){let J=$.mutationStates.get(Z.pathIdentity),Y=k8(Z.lease);if(!J||!Y||Y.sessionId!==Z.sessionId)throw j1(new g("busy","write",!1,!1),J?.kind==="pending-write"||J?.kind==="needs-read");if(J.kind!=="active-mutation")throw j1(new g("busy","write",!1,!1),J.kind==="pending-write"||J.kind==="needs-read");if(Y.kind==="active"){if(Y.released||!Y.generations.has(Z.pathIdentity)||Y.exactPathIdentities.get(Z.pathIdentity)!==Z.exactPathIdentity||Y.generations.get(Z.pathIdentity)!==J.generation||J.exactPathIdentity!==Z.exactPathIdentity||J.leaseKind!==Y.kind||J.leaseId!==Y.leaseId)throw new g("busy","write",!1,!1);return}if(Y.finished||Y.pathIdentity!==Z.pathIdentity||Y.exactPathIdentity!==Z.exactPathIdentity||Y.generation!==J.generation||J.exactPathIdentity!==Z.exactPathIdentity||J.leaseKind!==Y.kind||J.leaseId!==Y.leaseId)throw new g("busy","write",!1,!1)}function IV($,Z){let J=k8($.lease);if(!J||J.sessionId!==$.sessionId||Z.sessionId!==$.sessionId||Z.exactPathIdentity!==$.exactPathIdentity)return!1;if(J.kind==="active")return!J.released&&J.generations.get($.pathIdentity)===Z.generation&&J.exactPathIdentities.get($.pathIdentity)===$.exactPathIdentity&&Z.leaseKind==="active"&&Z.leaseId===J.leaseId;return!J.finished&&J.pathIdentity===$.pathIdentity&&J.exactPathIdentity===$.exactPathIdentity&&J.generation===Z.generation&&Z.leaseKind==="recovery"&&Z.leaseId===J.leaseId}function j1($,Z){if(!Z)return $;return Object.defineProperty($,"requiresRead",{value:!0,enumerable:!0,configurable:!0}),$}function i9($,Z){if(Z.requestPending=!1,Z.operation==="read"){if(Z.kind==="recovery"){let Q=$.mutationStates.get(Z.pathIdentity);if(Q&&Q.kind==="reconciling"&&Q.sessionId===Z.sessionId&&Q.exactPathIdentity===Z.exactPathIdentity&&Q.generation===Z.readToken?.generation&&Q.reconciliationPermitId===Z.readToken?.permitId){if(Q.kind="needs-read",Z.boundaryError)Q.reconciliationPermitId=void 0}}if(Z.readToken)Z.readToken.settled=!0;return}let J=$.mutationStates.get(Z.pathIdentity),Y=Z.writeLeaseSnapshot;if(J&&Y&&J.sessionId===Z.sessionId&&J.exactPathIdentity===Z.exactPathIdentity&&J.exactPathIdentity===Y.exactPathIdentity&&Z.boundaryError?.dispatched&&J.generation===Y.generation&&J.leaseId===Y.leaseId&&J.leaseKind===Y.leaseKind)J.kind="needs-read",J.forwardVerified=!1,J.reconciliationPermitId=void 0}function r9($,Z){if(Z.operation==="read"&&Z.readToken){if(Z.kind==="recovery"){let J=$.mutationStates.get(Z.pathIdentity);if(J?.kind==="reconciling"&&J.sessionId===Z.sessionId&&J.exactPathIdentity===Z.exactPathIdentity&&J.generation===Z.readToken.generation&&J.reconciliationPermitId===Z.readToken.permitId)J.kind="needs-read",J.reconciliationPermitId=void 0;let Y=$.recoveryPermits.get(Z.pathIdentity);if(Y?.sessionId===Z.sessionId&&Y.exactPathIdentity===Z.exactPathIdentity&&Y.generation===Z.readToken.generation&&Y.permitId===Z.readToken.permitId)$.recoveryPermits.delete(Z.pathIdentity)}Z.readToken.settled=!0}if(Z.readToken&&$.readTokens.get(Z.pathIdentity)===Z.readToken)$.readTokens.delete(Z.pathIdentity);v8($,Z)}var g2=new WeakMap;function o1($){if($.signal.aborted){let Y=g2.get($);if(Y)return Y;let Q=new y8($);return g2.set($,Q),Q}let Z=g2.get($);if(Z)return Z;let J=new y8($);return g2.set($,J),J}class y8{connection;state;closeHandler;constructor($){this.connection=$;if(this.state=y9(),this.state.closed=$.signal.aborted,this.closeHandler=()=>{this.handleConnectionClosed()},!this.state.closed)$.signal.addEventListener("abort",this.closeHandler,{once:!0})}runRequest($){let Z;try{this.assertOpen($.operation),this.assertBeforeBoundary($.signal,$.operation),this.assertPathAvailability($),Z=this.reserveRequestToken($)}catch(U){return Promise.reject(U)}let J=Z.controller,Y=()=>{this.boundaryReject(Z,this.buildBoundaryReason($.signal,$.deadlineAt),!0),J.abort()};Z.parentSignal=$.signal,Z.parentAbortHandler=Y,$.signal?.addEventListener("abort",Y,{once:!0});let Q=()=>{this.closeRejectToken(Z),J.abort()};Z.deadlineAbortHandler=Q,this.connection.signal.addEventListener("abort",Q,{once:!0});let X=Date.now();if($.deadlineAt<=X)return this.boundaryReject(Z,"timeout",!1),this.cleanupReservedButUndispatchedToken(Z),J.abort(),Z.localPromise;let W=$.deadlineAt-X;Z.timer=setTimeout(()=>{this.boundaryReject(Z,"timeout",!0),J.abort()},W),Z.timer.unref?.();let V;try{V=$.dispatch(J.signal),Z.dispatched=!0,Z.requestPending=!0,this.observeUnderlyingSettlement(Z,V)}catch(U){return this.clearLocalBoundaryResources(Z),this.cleanupReservedButUndispatchedToken(Z),Z.reject(U),Z.localPromise}if($.signal?.aborted)this.boundaryReject(Z,"aborted",!0),J.abort();return Z.localPromise}precheckMutationPaths($,Z){this.assertOpen("write");let J=y6($).map(N0);this.assertMutationPathsAvailable(J)}tryAcquireMutationLease($,Z){this.assertOpen("write");let J=y6($),Y=J.map(N0);return this.assertMutationPathsAvailable(Y),m9(this.state,J,Z)}beginUserRead($,Z){return this.assertOpen("read"),c9(this.state,$,Z)}getStatsForTests(){return u9(this.state)}assertOpen($){if(this.state.closed||this.connection.signal.aborted)throw this.state.closed=!0,new g("closed",$,!1,!1)}assertBeforeBoundary($,Z){if($?.aborted)throw new g("aborted",Z,!1,!1)}assertPathAvailability($){if($.operation==="read"){p9(this.state,$);return}l9(this.state,$)}reserveRequestToken($){return x9(this.state,$)}observeUnderlyingSettlement($,Z){Z.then((J)=>{this.handleSettlement($,{status:"fulfilled",value:J})},(J)=>{this.handleSettlement($,{status:"rejected",reason:J})})}handleSettlement($,Z){if(this.state.closed){this.clearLocalBoundaryResources($),this.cleanupToken($);return}if(i9(this.state,$),$.boundaryError){this.clearLocalBoundaryResources($),this.cleanupToken($);return}if(this.clearLocalBoundaryResources($),this.cleanupToken($),Z.status==="fulfilled"){$.resolve(Z.value);return}$.reject(Z.reason)}boundaryReject($,Z,J){g9(this.state,$,Z,J),this.clearLocalBoundaryResources($)}closeRejectToken($){if(!h9($))return;this.clearLocalBoundaryResources($),$.controller.abort()}cleanupToken($){v8(this.state,$)}cleanupReservedButUndispatchedToken($){r9(this.state,$)}clearLocalBoundaryResources($){if($.deadlineAbortHandler)this.connection.signal.removeEventListener("abort",$.deadlineAbortHandler),$.deadlineAbortHandler=void 0;I9($)}buildBoundaryReason($,Z){if($?.aborted)return"aborted";if(Z<=Date.now())return"timeout";return"aborted"}assertMutationPathsAvailable($){d9(this.state,$)}handleConnectionClosed(){if(this.state.closed)return;this.state.closed=!0,g2.set(this.connection,this);for(let $ of this.state.normalTokens)this.closeRejectToken($);if(this.state.recoveryToken)this.closeRejectToken(this.state.recoveryToken),this.state.recoveryToken=void 0;this.state.normalTokens.clear(),this.state.readTokens.clear(),this.state.recoveryPermits.clear(),this.state.mutationStates.clear()}}var n9=e("Agent"),hV=1024;class M0 extends Error{operation;name="AcpFileSystemCapabilityError";constructor($){super(`ACP remote filesystem does not support ${$}`);this.operation=$}}function q$($){if(gV($,-32002))return!0;if(!($ instanceof Error))return!1;let Z=$.message.toLowerCase();return["not found","no such file","enoent","does not exist","file not found","path not found"].some((J)=>Z.includes(J))}class v0{connection;sessionId;capabilities;remoteAccessLedger=new Map;remoteAccessCollisionIndex=new Map;disposeController=new AbortController;pathProfile;constructor($,Z,J,Y){this.connection=$;this.sessionId=Z;t1(Y),this.capabilities={readTextFile:J.readTextFile===!0,writeTextFile:J.writeTextFile===!0},this.pathProfile=o9(Y)}async readTextFile($,Z){let J=this.parsePath($);return this.readTextFileForParsedPath(J,{signal:Z?.signal,deadlineAt:Z?.deadlineAt,purpose:Z?.purpose??"preflight",lease:Z?.lease})}async readTextFileForParsedPath($,Z){return this.assertParsedPathStyle($),this.runBoundedTextReadPath($,Z)}async readTextFileForUser($,Z){let J=this.parsePath($);return this.readTextFileForUserForParsedPath(J,Z)}async readTextFileForUserForParsedPath($,Z){this.assertParsedPathStyle($);let Y=o1(this.connection).beginUserRead($,this.sessionId);try{let Q=await this.readTextFileForParsedPath($,{signal:Z?.signal,deadlineAt:Z?.deadlineAt,purpose:"user-read",userReadPermit:Y});return Y.complete("content",()=>{this.recordRemoteAccessForPath($,Q,"read")}),Q}catch(Q){if(q$(Q))throw Y.complete("not-found",()=>{this.deleteRemoteAccessCollisionClass($)}),Q;throw Y.fail(),Q}}async writeTextFile($,Z,J){let Y=this.parsePath($);return this.writeTextFileForParsedPath(Y,Z,J)}async writeTextFileForParsedPath($,Z,J){if(this.assertParsedPathStyle($),!this.capabilities.writeTextFile)throw new M0("writeTextFile");let Y=J?.lease===void 0?this.tryAcquireMutationLeaseForParsedPaths([$]):void 0,Q=J?.lease??Y,X=s9(this.disposeController.signal,J?.signal),W=J?.deadlineAt??Date.now()+g0,V=o1(this.connection);try{if(await V.runRequest({operation:"write",purpose:J?.purpose??"mutation",sessionId:this.sessionId,pathIdentity:N0($),exactPathIdentity:$.exactIdentity,deadlineAt:W,signal:X.signal,lease:Q,dispatch:(U)=>this.connection.request(I8.CLIENT_METHODS.fs_write_text_file,{path:$.wirePath,content:Z,sessionId:this.sessionId},{cancellationSignal:U})}),Y)Y.markDefinite($)}catch(U){if(n9.warn("[AcpFileSystem] writeTextFile ACP request failed"),Y&&uV(U))Y.markUncertain($);throw U}finally{if(Y)Y.release();X.cleanup()}}async exists($){if(!this.capabilities.readTextFile)throw new M0("readTextFile");try{let Z=this.parsePath($);return await this.readTextFileForParsedPath(Z,{purpose:"preflight"}),!0}catch(Z){if(q$(Z))return!1;throw Z}}async readBinaryFile($){throw new M0("readBinaryFile")}async stat($){throw new M0("stat")}async mkdir($,Z){throw new M0("mkdir")}getCapabilities(){return{...this.capabilities}}getPathProfile(){return this.pathProfile}parsePath($){return X$($,this.pathProfile.style)}canReadTextFile(){return this.capabilities.readTextFile??!1}canWriteTextFile(){return this.capabilities.writeTextFile??!1}assertTextMutationCapabilities(){if(!this.canReadTextFile())throw new M0("readTextFile");if(!this.canWriteTextFile())throw new M0("writeTextFile")}usesRemoteFiles(){return this.canReadTextFile()||this.canWriteTextFile()}createOpaqueLockKey($){let Z=this.parsePath($);return this.createOpaqueLockKeyForParsedPath(Z)}createOpaqueLockKeyForParsedPath($){return this.assertParsedPathStyle($),`acp-remote:${t9("sha256").update(this.sessionId).update("\x00").update($.collisionIdentity).digest("hex")}`}async readTextFileIfExists($,Z){let J=this.parsePath($);return this.readTextFileIfExistsForParsedPath(J,Z)}async readTextFileIfExistsForParsedPath($,Z){this.assertParsedPathStyle($);try{return{exists:!0,content:await this.readTextFileForParsedPath($,{signal:Z?.signal,deadlineAt:Z?.deadlineAt,purpose:Z?.purpose??"preflight",userReadPermit:Z?.userReadPermit,lease:Z?.lease})}}catch(J){if(q$(J))return{exists:!1};throw J}}recordRemoteAccess($,Z,J){let Y=this.parsePath($);this.recordRemoteAccessForPath(Y,Z,J)}recordRemoteAccessForParsedPath($,Z,J){this.assertParsedPathStyle($),this.recordRemoteAccessForPath($,Z,J)}recordRemoteAccessForPath($,Z,J){let Y={filePath:$.wirePath,accessTime:Date.now(),contentSha256:a9(Z),sessionId:this.sessionId,lastOperation:J,source:"remote"},Q=this.remoteAccessCollisionIndex.get($.collisionIdentity);if(Q)this.deleteRemoteAccessEntry(Q);this.remoteAccessLedger.set($.exactIdentity,{collisionIdentity:$.collisionIdentity,record:Y}),this.remoteAccessCollisionIndex.set($.collisionIdentity,$.exactIdentity);while(this.remoteAccessLedger.size>hV){let X=this.remoteAccessLedger.keys().next().value;if(X===void 0)break;this.deleteRemoteAccessEntry(X)}}checkRemoteAccess($,Z){let J=this.parsePath($);return this.checkRemoteAccessForParsedPath(J,Z)}checkRemoteAccessForParsedPath($,Z){this.assertParsedPathStyle($);let J=this.remoteAccessLedger.get($.exactIdentity);if(!J)return"missing";return this.remoteAccessLedger.delete($.exactIdentity),this.remoteAccessLedger.set($.exactIdentity,J),J.record.contentSha256===a9(Z)?"current":"modified"}getRemoteAccessRecord($){let Z=this.parsePath($),J=this.remoteAccessLedger.get(Z.exactIdentity);if(!J)return;return{...J.record}}precheckMutationPaths($){let Z=$.map((J)=>this.parsePath(J));this.precheckMutationPathsForParsedPaths(Z)}precheckMutationPathsForParsedPaths($){for(let J of $)this.assertParsedPathStyle(J);o1(this.connection).precheckMutationPaths($,this.sessionId)}tryAcquireMutationLease($){let Z=$.map((J)=>this.parsePath(J));return this.tryAcquireMutationLeaseForParsedPaths(Z)}tryAcquireMutationLeaseForParsedPaths($){for(let J of $)this.assertParsedPathStyle(J);return o1(this.connection).tryAcquireMutationLease($,this.sessionId)}dispose(){this.disposeController.abort(),this.remoteAccessLedger.clear(),this.remoteAccessCollisionIndex.clear()}async runBoundedTextReadPath($,Z){if(!this.capabilities.readTextFile)throw new M0("readTextFile");let J=s9(this.disposeController.signal,Z.signal),Y=o1(this.connection),Q=Z.deadlineAt??Date.now()+g0;try{return(await Y.runRequest({operation:"read",purpose:Z.purpose,sessionId:this.sessionId,pathIdentity:N0($),exactPathIdentity:$.exactIdentity,deadlineAt:Q,signal:J.signal,lease:Z.lease,userReadPermit:Z.userReadPermit,dispatch:(W)=>this.connection.request(I8.CLIENT_METHODS.fs_read_text_file,{path:$.wirePath,sessionId:this.sessionId},{cancellationSignal:W})})).content}catch(X){if(q$(X))this.deleteRemoteAccessCollisionClass($);throw n9.warn("[AcpFileSystem] readTextFile ACP request failed"),X}finally{J.cleanup()}}deleteRemoteAccessCollisionClass($){let Z=this.remoteAccessCollisionIndex.get($.collisionIdentity);if(!Z)return;this.deleteRemoteAccessEntry(Z)}deleteRemoteAccessEntry($){let Z=this.remoteAccessLedger.get($);if(!Z)return;if(this.remoteAccessLedger.delete($),this.remoteAccessCollisionIndex.get(Z.collisionIdentity)===$)this.remoteAccessCollisionIndex.delete(Z.collisionIdentity)}assertParsedPathStyle($){if(D$($),$.style!==this.pathProfile.style)this.parsePath($.wirePath)}}function gV($,Z){return $ instanceof Error&&"code"in $&&$.code===Z}function a9($){return t9("sha256").update($).digest("hex")}function uV($){if(!($ instanceof g))return!0;if(!$.dispatched)return!1;return!$.requestPending}function s9(...$){let Z=$.filter((W)=>W!==void 0);if(Z.length===0)return{signal:new AbortController().signal,cleanup:x8};if(Z.length===1)return{signal:Z[0],cleanup:x8};let J=Z.find((W)=>W.aborted);if(J){let W=new AbortController;return W.abort(J.reason),{signal:W.signal,cleanup:x8}}let Y=new AbortController,Q=new Map,X=(W)=>{if(!Y.signal.aborted)Y.abort(W.reason)};for(let W of Z){let V=()=>{X(W)};Q.set(W,V),W.addEventListener("abort",V,{once:!0})}return{signal:Y.signal,cleanup:()=>{for(let[W,V]of Q)W.removeEventListener("abort",V)}}}function x8(){}var a$=e("Agent"),dV=5000;class x6{defaultCwd;constructor($){this.defaultCwd=$}async execute($,Z){let J=process.platform==="win32"?"cmd.exe":"/bin/bash",Y=process.platform==="win32"?["/c",$]:["-c",$],Q;try{Q=await a1(J,Y,{cwd:Z?.cwd??this.defaultCwd??C(),env:{...process.env,...Z?.env},stdio:["pipe","pipe","pipe"]},Z?.durableOwnership)}catch(X){return{success:!1,stdout:"",stderr:"",exitCode:null,error:X instanceof Error?X.message:"Foreground command admission failed",failureKind:"admission",transport:"local"}}return new Promise((X)=>{let{child:W,processTree:V}=Q,U,H=()=>{return U??=V.terminate(),U},z=new K$,B,G=!1,D=!1,w=!1,q=!1,F,L,_=Z?.timeout?setTimeout(()=>{if(q)return;if(!B)B="timeout";H()},Z.timeout):null,O=null,b=()=>{if(_)clearTimeout(_);if(O&&Z?.signal)Z.signal.removeEventListener("abort",O),O=null},N=(E)=>{if(w)return;w=!0,b(),X(E)};if(Z?.signal){if(O=()=>{if(q)return;if(!B)B="aborted";H()},Z.signal.addEventListener("abort",O),Z.signal.aborted)O()}W.stdout?.on("data",(E)=>{z.append("stdout",E);let j=E.toString();Z?.onOutput?.(j)}),W.stderr?.on("data",(E)=>{z.append("stderr",E);let j=E.toString();Z?.onOutput?.(j)});let A=(E,j)=>{q=!0,b(),F??=(async()=>{if(await L,B||G)await H();try{await Q.finalize()}catch{D=!0}z.finish();let M=z.snapshot(),k=D?"finalization":B==="timeout"?"timeout":B==="aborted"?"aborted":G?"admission":j?"spawn":void 0;N({success:E===0&&!k,stdout:M.stdout.content,stderr:M.stderr.content,exitCode:E,error:k==="timeout"||k==="aborted"?"Command was terminated":k==="admission"?"Foreground command admission failed":k==="finalization"?"Foreground command finalization failed":j?.message,failureKind:k,...D&&(B==="timeout"||B==="aborted")?{terminationReason:B}:{},transport:"local",capture:M})})()};if(W.once("close",(E)=>A(E)),W.once("error",(E)=>A(null,E)),Z?.signal?.aborted)B="aborted",L=Promise.resolve(),H();else L=Q.release().catch(async()=>{if(G=!0,!B)B="admission";await H()})})}isAvailable(){return!0}}class h8{async execute(){return{success:!1,stdout:"",stderr:"",exitCode:null,error:"ACP terminal capability is unavailable",failureKind:"unavailable",transport:"acp"}}isAvailable(){return!1}}class E1 extends Error{code="acp_session_unavailable";constructor(){super("ACP session filesystem is unavailable");this.name="AcpFileSystemUnavailableError"}}class $3{async readTextFile(){throw new E1}async writeTextFile(){throw new E1}async exists(){throw new E1}async readBinaryFile(){throw new E1}async stat(){throw new E1}async mkdir(){throw new E1}}class Z3{connection;sessionId;remoteFileSystem;fallback;constructor($,Z,J=!1,Y){this.connection=$;this.sessionId=Z;this.remoteFileSystem=J;this.fallback=Y}async execute($,Z){if(Z?.signal?.aborted)return{success:!1,stdout:"",stderr:"",exitCode:null,error:"Command was aborted",failureKind:"aborted",transport:"acp"};let J;try{a$.debug(`[AcpTerminal] Executing command via ACP: ${$}`),J=await this.connection.createTerminal({sessionId:this.sessionId,command:$,cwd:Z?.cwd,env:Z?.env?Object.entries(Z.env).map(([E,j])=>({name:E,value:j})):void 0});let Y=J,Q=Y0.getInstance(),X,W=!1,V=new K$(void 0,!0),U=0,H=0,z=!1,B=!1,G,D,w=async()=>{return},q=async()=>{let E,j=Y.currentOutput().then((k)=>({type:"output",response:k})).catch(()=>({type:"error"})),M=new Promise((k)=>{E=setTimeout(()=>k({type:"timeout"}),dV)});return await Promise.race([j,M]).finally(()=>{if(E)clearTimeout(E)})},F=(E)=>{let j=E.length;if(j>=H){let M=E.slice(H);if(M)Z?.onOutput?.(M);H=j}},L=(E)=>{let j=E.output.length;if(!E.truncated&&j>=U){let M=E.output.slice(U);if(M){if(V.append("stdout",M),X)Q.appendExternalOutput(X,this.sessionId,"stdout",M)}F(E.output),U=j;return}if(V=new K$(void 0,!0),V.append("stdout",E.output),V.markAccountingIncomplete(),X)Q.replaceExternalOutput(X,this.sessionId,E.output,"");H=j,U=j},_=(async()=>{while(!z){let E=await q();if(E.type==="output")L(E.response);else if(V.markAccountingIncomplete(),E.type==="timeout"){B=!0,z=!0;break}if(z)break;await new Promise((j)=>{let M=setTimeout(j,100);G=()=>{clearTimeout(M),j()}}),G=void 0}})(),O=async()=>{z=!0,G?.(),await _},b=Y.waitForExit().then((E)=>({type:"completed",exitCode:E.exitCode??null})).catch((E)=>({type:"failed",error:E})),N=(E)=>{return D??=(async()=>{let j=!1;if(E.type!=="completed")await Y.kill().catch(()=>{j=!0});await O();let M=B?{type:"timeout"}:await q();if(M.type==="output"){let p=M.response;if(p.output.length>=H)F(p.output);if(V=new K$(void 0,!0),V.append("stdout",p.output),p.truncated)V.markAccountingIncomplete()}else V.markAccountingIncomplete();await Y.release().catch(()=>{j=!0}),V.finish();let k=V.snapshot();if(X){Q.replaceExternalOutput(X,this.sessionId,k.stdout.content,k.stderr.content);let p=j?"error":E.type==="completed"?"exited":E.type==="timeout"?"timed_out":E.type==="aborted"?"aborted":E.type==="killed"?"killed":"error";if(Q.completeExternalProcess(X,this.sessionId,{status:p,exitCode:E.type==="completed"?E.exitCode:null,...j?{finalizationFailed:!0}:{},errorMessage:j?"ACP terminal finalization failed":E.type==="failed"?E.error instanceof Error?E.error.message:"ACP terminal unavailable":void 0}),!W)Q.removeCandidate(X,this.sessionId)}return{success:!j&&E.type==="completed"&&E.exitCode===0,stdout:k.stdout.content,stderr:k.stderr.content,exitCode:E.type==="completed"?E.exitCode:null,error:j?"ACP terminal finalization failed":E.type==="timeout"?"Command timed out":E.type==="aborted"||E.type==="killed"?"Command was aborted":E.type==="failed"?E.error instanceof Error?`ACP terminal unavailable: ${E.error.message}`:"ACP terminal unavailable":void 0,failureKind:j?"finalization":E.type==="timeout"?"timeout":E.type==="aborted"||E.type==="killed"?"aborted":E.type==="failed"?"unavailable":void 0,...j&&(E.type==="timeout"||E.type==="aborted"||E.type==="killed")?{terminationReason:E.type==="timeout"?"timeout":"aborted"}:{},transport:"acp",capture:k}})(),D};if(!this.remoteFileSystem&&Z?.foregroundHandoffMs&&Z.foregroundHandoffMs>0&&Z.durableOwnership)try{X=Q.startExternalForegroundCandidate({command:$,sessionId:this.sessionId,cwd:Z.cwd,terminate:async(j)=>{await w(j)}}).id,w=async(j)=>{await N({type:j})}}catch(E){if(!(E instanceof r$))throw E}let A=await new Promise((E)=>{let j=!1,M=(h)=>{if(j)return;if(j=!0,k)clearTimeout(k);if(p)clearTimeout(p);Z?.signal?.removeEventListener("abort",R),E(h)},k=Z?.timeout?setTimeout(()=>M({type:"timeout"}),Z.timeout):void 0,p=X&&Z?.foregroundHandoffMs?setTimeout(()=>M({type:"handoff"}),Z.foregroundHandoffMs):void 0,R=()=>M({type:"aborted"});if(Z?.signal?.aborted)R();else Z?.signal?.addEventListener("abort",R,{once:!0});b.then(M)});if(A.type==="handoff"&&X&&Z?.foregroundHandoffMs){let E=Q.promoteExternalForegroundCandidate(X,this.sessionId,Z.foregroundHandoffMs);if(E)return W=!0,b.then(N),{success:!0,stdout:"",stderr:"",exitCode:null,transport:"acp",capture:V.snapshot(),background:{shellId:E.id,autoBackgrounded:!0,foregroundBudgetMs:Z.foregroundHandoffMs}}}return await N(A.type==="handoff"?await b:A)}catch(Y){if(J)await J.release().catch(()=>{return});if(!J&&Z?.signal?.aborted)return{success:!1,stdout:"",stderr:"",exitCode:null,error:"Command was aborted",failureKind:"aborted",transport:"acp"};if(this.remoteFileSystem||Z?.allowLocalFallback!==!0)return{success:!1,stdout:"",stderr:"",exitCode:null,error:Y instanceof Error?`ACP terminal unavailable: ${Y.message}`:"ACP terminal unavailable",failureKind:"unavailable",transport:"acp"};return a$.warn("[AcpTerminal] ACP terminal failed, using fallback:",Y),{...await(this.fallback??new x6(Z?.cwd)).execute($,Z),transport:"local_fallback"}}}isAvailable(){return!0}}function e9($,Z){return JSON.stringify([$,Z])}class y{static sessions=new Map;static remoteSurfaceOwners=new Map;static remoteSurfaceOwnerKeysBySessionId=new Map;static sessionRegistrationGeneration=0n;static currentSessionId=null;constructor(){}static getInstance(){return new y}static initializeSession($,Z,J,Y,Q,X){if(y.sessions.get(Z)){y.currentSessionId=Z,a$.debug(`[AcpServiceContext:${Z}] initializeSession ignored because the session already exists`);return}let V=J?.fs?.readTextFile===!0||J?.fs?.writeTextFile===!0,U;if(V){let G=X??u2(Y);U=new v0($,Z,J?.fs??{},G)}else U=new h2;if(V)a$.debug(`[AcpServiceContext:${Z}] Using ACP file system service`);let H=J?.terminal?new Z3($,Z,V):V?new h8:new x6(Y);a$.debug(`[AcpServiceContext:${Z}] Using ${J?.terminal?"ACP":"local"} terminal service`),y.sessionRegistrationGeneration+=1n;let z=Object.freeze({generation:`acp-owner-generation:${y.sessionRegistrationGeneration.toString(36)}`,sessionId:Z}),B={fileSystemService:U,terminalService:H,connection:$,registration:z,sendUpdate:Q,clientCapabilities:J||null,executionRoot:Y,remoteFileSystem:V};if(y.sessions.set(Z,B),V){let G=X??u2(Y),D=e9(Z,G.workspace.exactIdentity);y.remoteSurfaceOwners.set(D,{exactIdentity:G.workspace.exactIdentity,generation:z.generation,readText:J?.fs?.readTextFile===!0,services:B,writeText:J?.fs?.writeTextFile===!0,terminal:J?.terminal===!0}),y.remoteSurfaceOwnerKeysBySessionId.set(Z,D)}return y.currentSessionId=Z,a$.debug(`[AcpServiceContext:${Z}] Initialized with capabilities:`,{fs:!!J?.fs,readTextFile:J?.fs?.readTextFile,writeTextFile:J?.fs?.writeTextFile}),z}static destroySession($){let Z=y.remoteSurfaceOwnerKeysBySessionId.get($);if(Z)y.remoteSurfaceOwners.delete(Z),y.remoteSurfaceOwnerKeysBySessionId.delete($);let J=y.sessions.get($);if(J?.fileSystemService instanceof v0)J.fileSystemService.dispose();if(y.sessions.delete($),y.currentSessionId===$){let Y=Array.from(y.sessions.keys());y.currentSessionId=Y[0]||null}a$.debug(`[AcpServiceContext:${$}] Session destroyed`)}static destroyRegisteredSession($){if(!$)return;if(y.sessions.get($.sessionId)?.registration!==$)return;y.destroySession($.sessionId)}static getSessionServices($){return y.sessions.get($)||null}static setCurrentSession($){if(y.sessions.has($))y.currentSessionId=$}static getCurrentSessionId(){return y.currentSessionId}static isRemoteFileSystem($){return y.sessions.get($)?.remoteFileSystem??!1}static getRemoteSurfaceOwnerSnapshot($,Z){let J;try{J=I6(Z)}catch{return{connection:"offline"}}let Y=y.remoteSurfaceOwners.get(e9($,J.exactIdentity));if(!Y||Y.exactIdentity!==J.exactIdentity||y.sessions.get($)!==Y.services||Y.services.connection.signal.aborted)return{connection:"offline"};return{connection:"online",generation:Y.generation,readText:Y.readText,writeText:Y.writeText,terminal:Y.terminal}}initialize($,Z,J,Y){y.initializeSession($,Z,J,Y||C())}reset(){if(y.currentSessionId)y.destroySession(y.currentSessionId)}isAcpMode(){return y.currentSessionId!==null}getFileSystemService($){if($!==void 0)return y.sessions.get($)?.fileSystemService??new $3;let Z=$??y.currentSessionId;if(Z){let J=y.sessions.get(Z);if(J)return J.fileSystemService}return new h2}getTerminalService($){let Z=$??y.currentSessionId;if(Z){let J=y.sessions.get(Z);if(J)return J.terminalService;if($)return new h8}return new x6}getConnection(){if(y.currentSessionId){let $=y.sessions.get(y.currentSessionId);if($)return $.connection}return null}getSessionId(){return y.currentSessionId}getClientCapabilities(){if(y.currentSessionId){let $=y.sessions.get(y.currentSessionId);if($)return $.clientCapabilities}return null}async sendToolUpdate($,Z,J,Y,Q){let X=y.currentSessionId;if(!X)return;let W=y.sessions.get(X);if(!W)return;if(!W.sendUpdate)return;try{await W.sendUpdate({sessionUpdate:"tool_call",toolCallId:$,status:Z,title:J,content:Y||[],kind:Q||"other"})}catch(V){a$.warn("[AcpServiceContext] Failed to send tool update:",V)}}}function w$($){return y.getInstance().getFileSystemService($)}function J3($){return y.getInstance().getTerminalService($)}function H0($){return $?y.getSessionServices($)!==null:y.getInstance().isAcpMode()}function _$($){let Z=$??y.getCurrentSessionId();return Z?y.isRemoteFileSystem(Z):!1}function s$($,Z,J){if(J==="local")return!1;if(J==="acp-remote"||Z==="acp-remote"){let Y=$??y.getCurrentSessionId();return Y===null||!y.isRemoteFileSystem(Y)}return $!==void 0&&y.getSessionServices($)===null}import{createHash as YU,randomUUID as QU}from"node:crypto";var mV=["BrowserNavigate","BrowserSnapshot","BrowserInteract","BrowserWait","BrowserInspect","BrowserPage"];function g8($){return mV.includes($)}class f extends Error{code;details;constructor($,Z,J={}){super(Z);this.code=$;this.details=J;this.name="BrowserRuntimeError"}}class u8{maxPending;queue=[];closeController=new AbortController;idleWaiters=new Set;active=!1;closed=!1;constructor($=Y3){this.maxPending=$;if(!Number.isSafeInteger($)||$<=0)throw Error("Browser operation pending limit must be a positive integer")}run($,Z){if(this.closed)return Promise.reject(new f("browser_disposed","Browser Session Runtime is closed"));if(Z?.aborted)return Promise.reject(Z.reason??Error("Browser operation aborted"));if(this.queue.length>=this.maxPending)return Promise.reject(new f("browser_busy","Browser operation queue is full",{retryable:!0}));return new Promise((J,Y)=>{let Q={run:$,resolve:J,reject:Y,signal:Z};if(Z)Q.abortListener=()=>{let X=this.queue.indexOf(Q);if(X<0)return;this.queue.splice(X,1),Y(Z.reason??Error("Browser operation aborted"))},Z.addEventListener("abort",Q.abortListener,{once:!0});this.queue.push(Q),this.drain()})}close(){if(!this.closed){this.closed=!0,this.closeController.abort(new f("browser_disposed","Browser Session Runtime is closed"));for(let $ of this.queue.splice(0)){if($.signal&&$.abortListener)$.signal.removeEventListener("abort",$.abortListener);$.reject(new f("browser_disposed","Browser Session Runtime is closed"))}}if(!this.active)return Promise.resolve();return new Promise(($)=>this.idleWaiters.add($))}stats(){return{active:this.active,pending:this.queue.length,closed:this.closed}}drain(){if(this.active||this.closed)return;let $=this.queue.shift();if(!$)return;if($.signal&&$.abortListener)$.signal.removeEventListener("abort",$.abortListener);this.active=!0;let Z=$.signal?AbortSignal.any([$.signal,this.closeController.signal]):this.closeController.signal;Promise.resolve().then(()=>$.run(Z)).then($.resolve,$.reject).finally(()=>{if(this.active=!1,this.closed){for(let J of this.idleWaiters)J();this.idleWaiters.clear()}this.drain()})}}import{randomUUID as cV}from"node:crypto";import{Mutex as pV}from"async-mutex";var lV={viewport:{width:1440,height:900},deviceScaleFactor:1,locale:"en-US",timezoneId:"UTC",acceptDownloads:!1};async function iV(){let{chromium:$}=await import("playwright");return{launch:(Z)=>$.launch(Z)}}class V3{mutex=new pV;leases=new Map;maxContexts;contextOptions;environment;adapter;browser;launchPromise;generation=0;disposed=!1;disconnectListener;constructor($={}){if(this.adapter=$.adapter,this.contextOptions=$.contextOptions??lV,this.environment=$.environment??process.env,this.maxContexts=$.maxContexts??X3,!Number.isSafeInteger(this.maxContexts)||this.maxContexts<=0)throw Error("Browser context limit must be a positive integer")}async acquire($){return this.mutex.runExclusive(async()=>{if(this.disposed)throw new f("browser_disposed","Browser process pool is closed");if(this.leases.size>=this.maxContexts)throw new f("browser_capacity",`Browser context capacity is full (max ${this.maxContexts})`,{retryable:!0});let Z=await this.ensureBrowser(),J=this.generation,Y;try{Y=await Z.newContext(this.contextOptions)}catch(W){if(!Z.isConnected()||Z!==this.browser)throw new f("browser_disconnected","Chromium disconnected while creating a Session context",{retryable:!0});if(this.leases.size===0&&Z===this.browser)this.detachDisconnectListener(Z),this.browser=void 0,this.launchPromise=void 0,await Z.close().catch(()=>{return});throw W}if(this.disposed||Z!==this.browser||J!==this.generation)throw await Y.close().catch(()=>{return}),new f(this.disposed?"browser_disposed":"browser_disconnected",this.disposed?"Browser process pool is closed":"Chromium disconnected while creating a Session context",{retryable:!this.disposed});let Q=cV();this.leases.set(Q,{context:Y,generation:J,onDisconnected:$});let X=!1;return{context:Y,generation:J,release:async()=>{if(X)return;X=!0,await this.release(Q)}}})}stats(){return{generation:this.generation,contexts:this.leases.size,launching:this.launchPromise!==void 0&&this.browser===void 0,running:this.browser?.isConnected()===!0,disposed:this.disposed}}async dispose(){let $=await this.mutex.runExclusive(async()=>{if(this.disposed)return;this.disposed=!0;let Z=this.browser,J=[...this.leases.values()].map((Y)=>Y.context);return this.leases.clear(),this.detachDisconnectListener(Z),this.browser=void 0,this.launchPromise=void 0,this.generation++,{browser:Z,contexts:J}});if(!$)return;await Promise.allSettled($.contexts.map((Z)=>Z.close())),await $.browser?.close().catch(()=>{return})}async ensureBrowser(){if(this.browser?.isConnected())return this.browser;if(!this.launchPromise)this.launchPromise=this.launch();try{return await this.launchPromise}finally{this.launchPromise=void 0}}async launch(){let $=this.adapter??await iV();this.adapter=$;let Z;try{Z=await $.launch({headless:!0,chromiumSandbox:!0,env:W3(this.environment)})}catch{throw new f("browser_not_installed",`Chromium is unavailable or failed to launch.
122
122
  Install with: blade browser install`)}if(this.disposed)throw await Z.close().catch(()=>{return}),new f("browser_disposed","Browser process pool is closed");this.generation++,this.browser=Z;let J=this.generation,Y=()=>this.handleDisconnected(Z,J);return this.disconnectListener=Y,Z.on("disconnected",Y),Z}handleDisconnected($,Z){if($!==this.browser||Z!==this.generation)return;this.detachDisconnectListener($),this.browser=void 0,this.launchPromise=void 0,this.generation++;let J=[...this.leases.values()];this.leases.clear();for(let Y of J)queueMicrotask(Y.onDisconnected)}async release($){let Z=await this.mutex.runExclusive(async()=>{let J=this.leases.get($);if(!J)return;this.leases.delete($);let Y=this.browser,Q=this.leases.size===0&&Y!==void 0;if(Q)this.detachDisconnectListener(Y),this.browser=void 0,this.launchPromise=void 0;return{context:J.context,browser:Q?Y:void 0}});if(!Z)return;await Z.context.close().catch(()=>{return}),await Z.browser?.close().catch(()=>{return})}detachDisconnectListener($){if($&&this.disconnectListener)$.off("disconnected",this.disconnectListener);this.disconnectListener=void 0}}var Q3;function U3(){return Q3??=new V3,Q3}import{isIP as B3}from"node:net";var rV={"http:":"80","https:":"443"},nV=/password|passwd|passcode|one[-_ ]?time|otp|api[-_ ]?key|secret|token|credential|cvv|cvc/i,aV=new Set(["current-password","new-password","one-time-code","cc-number","cc-csc"]);function C0($){return Buffer.byteLength($,"utf8")}function G3($,Z,J,Y={}){if(!Y.allowEmpty&&$.length===0||C0($)>Z)throw new f("browser_unsupported",`${J} is empty or exceeds the supported size`)}function o$($,Z){let J=Buffer.from($);if(J.length<=Z)return $;let Y=J.subarray(0,Z).toString("utf8");while(Buffer.byteLength(Y)>Z)Y=Y.slice(0,-1);return Y.replace(/\uFFFD$/,"")}function T0($,Z){let J=[...$].filter((Y)=>{let Q=Y.codePointAt(0)??0;return(Q===9||Q===10||Q===13||Q>=32)&&Q!==127}).join("");return o$(J,Z)}function sV($){let Z=$.toLowerCase();return Z.includes(":")&&!Z.startsWith("[")?`[${Z}]`:Z}function d8($){if($.protocol!=="http:"&&$.protocol!=="https:")return"null";let Z=$.port||rV[$.protocol],J=`${$.protocol}//${sV($.hostname)}:${Z}`;if(C0(J)>m2)throw new f("browser_unsupported","Browser origin exceeds the supported size");return J}function K3($){if(B3($)!==4)return;return $.split(".").map(Number)}function H3($){let[Z=0,J=0]=$;return Z===0||Z===10||Z===127||Z===100&&J>=64&&J<=127||Z===169&&J===254||Z===172&&J>=16&&J<=31||Z===192&&J===168}function oV($){return $.replace(/^\[|\]$/g,"").toLowerCase()}function tV($){let Z=/^(?:::ffff:|0:0:0:0:0:ffff:)(.+)$/u.exec($);if(!Z?.[1])return;let J=K3(Z[1]);if(J)return J;let Y=Z[1].split(":");if(Y.length!==2||Y.some((W)=>!/^[0-9a-f]{1,4}$/u.test(W)))return;let Q=Number.parseInt(Y[0],16),X=Number.parseInt(Y[1],16);return[Q>>>8,Q&255,X>>>8,X&255]}function h6($){let Z=$.replace(/\.$/,"").toLowerCase();if(Z==="localhost"||Z.endsWith(".localhost"))return"loopback";let J=K3(Z);if(J){if(J[0]===127)return"loopback";return H3(J)?"private-network":"public"}let Y=oV(Z);if(B3(Y)===6){let Q=tV(Y);if(Q){if(Q[0]===127)return"loopback";return H3(Q)?"private-network":"public"}if(Y==="::1")return"loopback";if(Y.startsWith("fc")||Y.startsWith("fd")||/^fe[89ab]/.test(Y))return"private-network"}return"public"}function r0($){G3($,d2,"Browser URL");let Z;try{Z=new URL($)}catch{throw new f("browser_unsupported","Browser URL is invalid")}if(Z.protocol!=="http:"&&Z.protocol!=="https:")throw new f("browser_unsupported","Browser navigation only supports HTTP(S) URLs");if(Z.username||Z.password)throw new f("browser_unsupported","Browser URLs cannot contain credentials");return Z.hash="",{url:Z,href:Z.href,origin:d8(Z),classification:h6(Z.hostname)}}function W$($){G3($,m2,"Browser origin");let Z;try{Z=new URL($)}catch{throw new f("browser_unsupported","Browser origin is invalid")}if(Z.protocol!=="http:"&&Z.protocol!=="https:"||Z.username||Z.password||Z.pathname!=="/"||Z.search||Z.hash)throw new f("browser_unsupported","Browser origin is invalid");let J=d8(Z);if(J!==$.toLowerCase())throw new f("browser_unsupported",`Browser origin must use canonical form: ${J}`);return J}function t$($){if($==="about:blank")return $;try{let Z=new URL($);Z.hash="";for(let J of new Set(Z.searchParams.keys())){let Y=Z.searchParams.getAll(J).length;Z.searchParams.delete(J);for(let Q=0;Q<Y;Q++)Z.searchParams.append(J,"[redacted]")}return o$(Z.href,z3)}catch{return"[invalid-url]"}}function n0($){if($==="about:blank")return null;try{let Z=new URL($);return Z.protocol==="http:"||Z.protocol==="https:"?d8(Z):null}catch{return null}}function eV($){return $.normalize("NFKC").replace(/\s+/gu," ").trim().toLowerCase()}function D3($){if($.type?.toLowerCase()==="password")return!0;if($.accessibleNameExceededLimit||$.referencedAccessibleNameUnavailable)return!0;if(($.autocomplete?.toLowerCase().trim().split(/\s+/).filter(Boolean)??[]).some((J)=>aV.has(J)))return!0;for(let J of[$.name,$.id,$.ariaLabel,$.accessibleName]){if(!J)continue;if(C0(J)>c2)return!0;if(nV.test(eV(J)))return!0}return!1}import{randomUUID as _3}from"node:crypto";var q3=/\[ref=([a-z][a-z0-9]*)\]/g,$U=/\s+\[box=[^\]]*\]/g,m8=`
123
123
  ... (browser snapshot truncated)`;function ZU($,Z){let J=$.replace(`[ref=${Z}]`,"").replace($U,"").trim().replace(/\s+/g," ");return{value:T0(J,c2),exceededLimit:Buffer.byteLength(J)>c2}}function w3($){let Z=new Map;for(let J of $.split(`
124
124
  `)){q3.lastIndex=0;for(let Y of J.matchAll(q3)){let Q=Y[1];if(Z.has(Q))throw new f("browser_snapshot_stale",`Browser snapshot contains duplicate ref ${Q}`);Z.set(Q,ZU(J,Q))}}return Z}function JU($,Z=p2){let J=T0($,Number.MAX_SAFE_INTEGER),Y=Math.min(p2,Math.max(0,Z));if(Buffer.byteLength(J)<=Y)return{snapshot:J,truncated:!1};let Q=Buffer.byteLength(m8);if(Y<=Q)return{snapshot:o$(m8,Y),truncated:!0};let X=Y-Q,W=[],V=0;for(let H of J.split(`
@@ -861,7 +861,7 @@ ${A0}
861
861
  </approved-plan>
862
862
 
863
863
  IMPORTANT: Execute according to the approved plan above. Follow the steps exactly as specified.`;if(typeof O==="string")S$=O+j6;else S$=[...O,{type:"text",text:j6}]}S=yield*this.runLoop(S$,b,{...x,inputMessageId:void 0})}if(!this.sessionRuntime||!I)return S;let l=await this.sessionRuntime.recordGoalProgress({tokens:S.metadata?.tokensUsed??0,elapsedMs:S.metadata?.duration??0,...v?{goalId:v.goalId,objective:v.objective,turnId:I.id}:{},executionHostFailureCategory:S.metadata?.executionHostFailureCategory,prematureStopPattern:S.success?HY(S.finalMessage):void 0});if(l)yield{kind:"goal_updated",goal:l};if(!S.success||b.signal?.aborted){if(l=await this.sessionRuntime.pauseActiveGoal(b.signal?.aborted?"goal paused after user cancellation":S.error?.message??"goal paused after turn failure"),l)yield{kind:"goal_updated",goal:l}}if(S.success&&!b.signal?.aborted&&h<20)await this.sessionRuntime.waitForBackgroundSubagentFollowUp(I,b.signal);let a=S.success&&!b.signal?.aborted&&h<20,p0=WG(S)||!S.success&&S.error?.type==="max_turns_exceeded";if(R=await this.sessionRuntime.finishTurn(I,{continuePending:a,...p0?{acknowledgeInput:!0}:{},outcome:S.success&&!b.signal?.aborted?{status:"completed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}:{status:"aborted",cause:b.signal?.aborted?"cancelled":"failed",turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,durationMs:S.metadata?.duration??0}}),R){h++,N=!0,A=!1,j=null,O="",p=void 0,M="",k=void 0,E=Z0(),yield{kind:"follow_up_started",queued:this.sessionRuntime.getPendingSteeringCount(),recovered:this.sessionRuntime.getRecoveredSteeringCount(),messages:$0(),queue:await this.sessionRuntime.getFollowUpQueueSnapshot()};continue}if(yield{kind:"follow_up_queue_changed",queue:await this.sessionRuntime.getFollowUpQueueSnapshot()},!S.success||b.signal?.aborted)return S;if(l=await this.sessionRuntime.getGoal(),!l||l.status!=="active"&&l.status!=="verifying")return S;let J0=await this.sessionRuntime.prepareGoalContinuation(l);if(!J0.ok){if(J0.goal)yield{kind:"goal_updated",goal:J0.goal};return{success:!1,error:{type:"goal_frontier_unavailable",message:J0.error.message},metadata:{turnsCount:S.metadata?.turnsCount??0,toolCallsCount:S.metadata?.toolCallsCount??0,duration:S.metadata?.duration??0}}}let h0=await this.sessionRuntime.beginGoalTurn(J0.goal);if(!h0)return S;j=h0.goal,q={...J0,goal:h0.goal},R=h0.handle,N=!1,A=!0,O=S5(j),p=void 0,E=void 0,yield{kind:"goal_frontier_updated",goal:j,frontier:J0.frontier,tasks:J0.tasks},yield{kind:"goal_continuation_started",goal:j,continuation:j.continuationCount,...j.prematureStop?{prematureStopPattern:j.prematureStop.pattern,prematureStopCount:j.prematureStop.consecutiveCount}:{}},yield{kind:"goal_updated",goal:j}}}finally{if(this.sessionRuntime&&R)await this.sessionRuntime.finishTurn(R)}}let F=typeof z==="string"?z:z.filter((O)=>O.type==="text").map((O)=>O.text).join(`
864
- `),L={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-htd9p2fd.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){s.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){s.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return nY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=rY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,s.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){s.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){s.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${Z} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${XG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)s.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
864
+ `),L={id:this.generateTaskId(),type:"simple",prompt:F};return{success:!0,finalMessage:(await this.executeTask(L)).content,metadata:{turnsCount:1,toolCallsCount:0,duration:0}}}async chat($,Z,J){let{drainLoop:Y}=await import("./chunk-8wnhsgvw.js");return Y(this.chatStream($,Z,J))}async*runPlanLoop($,Z,J){s.debug("Processing Plan mode message...");let{prompt:Y}=await Y1({...Z.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:Z.workspaceRoot||C()},mode:"plan",includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:Z.executionRoot??Z.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...Z.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}}),Q;if(typeof $==="string")Q=t2($);else{let X=$.filter((W)=>W.type==="text");if(X.length>0){let W=X[0];Q=$.map((V)=>V===W?{type:"text",text:t2(W.text)}:V)}else Q=[{type:"text",text:t2("")},...$]}return yield*this.executeLoop(Q,Z,J,Y)}async*runLoop($,Z,J){s.debug("Processing enhanced chat message...");let Y=Z.systemPrompt??await this.buildSystemPromptOnDemand(Z);return yield*this.executeLoop($,Z,J,Y)}async buildSystemPromptOnDemand($){let Z=this.runtimeOptions.systemPrompt,J=this.runtimeOptions.appendSystemPrompt;return(await Y1({...$.workspaceKind==="acp-remote"?{workspaceAccess:"none"}:{projectPath:$.workspaceRoot||C()},replaceDefault:Z,append:J,includeEnvironment:!0,environmentOptions:{...u1,workingDirectory:$.executionRoot??$.workspaceRoot??C()},language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...$.workspaceKind==="acp-remote"?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot}})).prompt}executeLoop($,Z,J,Y){if(!this.isInitialized)throw Error("Agent未初始化");let Q=this.buildLoopDependencies();return nY(Q,$,Z,J,Y)}takeStartupAdoptedToolResultEvents(){return(this.sessionRuntime?.takeStartupAdoptedToolResults()??[]).flatMap(({call:Z,result:J})=>{let Y={id:Z.toolCallId,type:"function",function:{name:Z.toolName,arguments:JSON.stringify(Z.input)}},Q=J.metadata&&typeof J.metadata==="object"&&!Array.isArray(J.metadata)?J.metadata:void 0,X=J.error===void 0,W=J.output,V={success:X,llmContent:typeof W==="string"||W!==null&&typeof W==="object"?W:W===null?J.error?`Subagent execution failed: ${J.error}.`:"":String(W),...J.error?{error:{type:"execution_error",message:J.error}}:{},...Q?{metadata:Q}:{}},U=[{kind:"tool_result",toolCall:Y,result:V}],H=rY(Y,V);if(H)U.push(H);return U})}takeStartupRecoveryEvents(){let $=this.sessionRuntime?.getTurnRecoveryAssessment(),Z=$?.state==="requires_attention"?$:this.sessionRuntime?.takeStartupTurnRecoveryAssessment(),J=Z&&Z.state!=="none"?[{kind:"turn_recovery",assessment:Z}]:[];return J.push(...this.takeStartupAdoptedToolResultEvents()),J}buildLoopDependencies(){return{chatService:this.chatService,toolExecutor:this.toolExecutor,executionEngine:this.executionEngine,config:this.config,runtimeOptions:this.runtimeOptions,currentModelMaxContextTokens:this.currentModelMaxContextTokens,activeSkillContext:this.activeSkillContext,onSkillActivated:($)=>{this.activeSkillContext=$,s.debug(`Skill "${$.skillName}" activated`+($.allowedTools?` with allowed tools: ${$.allowedTools.join(", ")}`:""))},onModelSwitch:($)=>this.switchModelIfNeeded($),applySkillToolRestrictions:($)=>this.applySkillToolRestrictions($),staticProjectRules:this.sessionRuntime?.getStaticProjectRules(),hydrateProjectRules:this.sessionRuntime?($)=>this.sessionRuntime.hydrateProjectRules($):void 0,resolveContextualProjectRules:this.sessionRuntime?($,Z,J,Y)=>this.sessionRuntime.resolveContextualProjectRules($,Z,J,Y):void 0}}async chatWithSystem($,Z){if(!this.isInitialized)throw Error("Agent未初始化");let J=[{role:"system",content:$},{role:"user",content:Z}];return(await this.chatService.chat(J)).content}getActiveTask(){return this.activeTask}getChatService(){return this.chatService}getContextManager(){return this.executionEngine?.getContextManager()}getStats(){return{initialized:this.isInitialized,activeTask:this.activeTask?.id,components:{chatService:this.chatService?"ready":"not_loaded",executionEngine:this.executionEngine?"ready":"not_loaded"}}}getAvailableTools(){return this.toolExecutor?this.toolExecutor.getRegistry().getAll():[]}getToolRegistry(){return this.toolExecutor.getRegistry()}applyToolWhitelist($){let Z=this.toolExecutor.getRegistry(),Y=Z.getAll().filter((Q)=>!$.includes(Q.name));for(let Q of Y)Z.unregister(Q.name);s.debug(`Applied tool whitelist: ${$.join(", ")} (removed ${Y.length} tools)`)}applyToolBlacklist($){let Z=this.toolExecutor.getRegistry(),J=new Set($);for(let Y of Z.getAll())if(J.has(Y.name))Z.unregister(Y.name);s.debug(`Applied tool blacklist: ${$.join(", ")}`)}getToolStats(){let $=this.getAvailableTools(),Z=new Map;return $.forEach((J)=>{let Y=Z.get(J.kind)||0;Z.set(J.kind,Y+1)}),{totalTools:$.length,toolsByKind:Object.fromEntries(Z),toolNames:$.map((J)=>J.name)}}async destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=(async()=>{this.log("销毁Agent..."),await this.activeOperations.shutdown("agent-destroy");try{await this.legacyMcpRegistry?.disconnectAll(),this.legacyMcpRegistry=void 0,this.log("Agent已销毁")}catch($){throw this.error("Agent销毁失败",$),$}finally{this.toolExecutor.dispose(),this.isInitialized=!1}})(),this.destroyPromise}syncRuntimeState(){if(!this.sessionRuntime)return;this.chatService=this.sessionRuntime.getChatService(),this.executionEngine=this.sessionRuntime.getExecutionEngine(),this.attachmentCollector=this.sessionRuntime.getAttachmentCollector(),this.currentModelId=this.sessionRuntime.getCurrentModelId(),this.currentModelMaxContextTokens=this.sessionRuntime.getCurrentModelMaxContextTokens()}generateTaskId(){return`task_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}log($,Z){s.debug(`[MainAgent] ${$}`,Z||"")}error($,Z){s.error(`[MainAgent] ${$}`,Z||"")}async initializeSystemPrompt(){try{let $=this.runtimeOptions.systemPrompt,Z=this.runtimeOptions.appendSystemPrompt,J=await Y1({...this.sessionRuntime?.isRemoteWorkspace()?{workspaceAccess:"none"}:{projectPath:this.sessionRuntime?.workspaceRoot??C()},replaceDefault:$,append:Z,includeEnvironment:!1,language:this.config.language,availableSkills:this.agentResources?.skills.generateAvailableSkillsList(),communicationStyle:this.sessionRuntime?.getCommunicationStyleConfiguration().selection,communicationStyleCatalog:this.sessionRuntime?.getCommunicationStyleCatalog(),projectRuleCatalog:this.sessionRuntime?.getProjectRuleCatalog(),...this.sessionRuntime?.isRemoteWorkspace()?{}:{projectInstructionSourcePath:this.sessionRuntime?.projectRoot},...this.sessionRuntime?{environmentOptions:{...u1,workingDirectory:this.sessionRuntime.executionRoot}}:{}});if(J.prompt)this.log("系统提示配置验证成功"),s.debug(`[SystemPrompt] 可用来源: ${J.sources.filter((Y)=>Y.loaded).map((Y)=>Y.name).join(", ")}`)}catch($){this.error("系统提示配置验证失败",$)}}async registerBuiltinTools(){try{let $=await v4({sessionId:"default",configDir:t(),workspaceRoot:C(),resourceRoot:C(),agentResources:this.agentResources});s.debug(`Registering ${$.length} builtin tools...`),this.toolExecutor.getRegistry().registerAll($);let Z=this.toolExecutor.getRegistry().getAll().length;s.debug(`Builtin tools registered: ${Z} tools`),s.debug(`[Tools] ${this.toolExecutor.getRegistry().getAll().map((J)=>J.name).join(", ")}`),await this.registerMcpTools()}catch($){throw s.error("Failed to register builtin tools:",$),$}}async registerMcpTools(){try{let $=await W4({workspaceRoot:C(),storeServers:this.config.mcpServers??{},cliConfigs:this.runtimeOptions.mcpConfig,strictCliConfig:this.runtimeOptions.strictMcpConfig});if(Object.keys($).length===0){s.debug("No MCP servers configured");return}let Z=e0.createIsolated({artifactWriter:new o2(`legacy-${XG()}`)});this.legacyMcpRegistry=Z;for(let[X,W]of Object.entries($))try{s.debug(`Connecting to MCP server: ${X}`),await Z.registerServer(X,W),s.debug(`MCP server "${X}" connected`)}catch(V){s.warn(`Warning: MCP server "${X}" connection failed:`,V)}let J=this.toolExecutor.getRegistry();J.setMcpCatalogBarrier(()=>Z.waitForCatalogIdle());let Y=Z.getCatalogSnapshot();J.replaceMcpTools(Y.tools),J.registerAll(Y6(Z));let Q=Z.getInstructionsSnapshot();if(J.queueMcpInstructionsChange({revision:Q.revision,reason:"snapshot",replace:!0,instructions:Q.instructions,removed:[]}),Z.on("catalogChanged",(X)=>{J.replaceMcpTools(X.tools,X)}),Z.on("contentCatalogChanged",(X)=>{J.queueMcpContentChange(X)}),Z.on("resourceUpdated",(X)=>{J.queueMcpResourceUpdated(X)}),Z.on("connectionLifecycleChanged",(X)=>{J.queueMcpConnectionChange(X)}),Z.on("log",(X)=>{J.queueMcpLog(X)}),Z.on("instructionsChanged",(X)=>{J.queueMcpInstructionsChange({revision:X.revision,reason:X.reason,replace:!1,instructions:X.action==="added"&&X.instruction?[{serverName:X.serverName,...X.instruction}]:[],removed:X.action==="removed"?[X.serverName]:[]})}),Y.tools.length>0)s.debug(`Registered ${Y.tools.length} MCP tools`),s.debug(`[MCP Tools] ${Y.tools.map((X)=>X.name).join(", ")}`)}catch($){s.warn("Failed to register MCP tools:",$)}}async loadSubagents(){let $=await c0(C());if(this.agentResources=k4($),this.subagentRegistry=this.agentResources.subagents,this.runtimeOptions.agents?.length)this.subagentRegistry.applyOverrides(this.runtimeOptions.agents);let Z=this.subagentRegistry.getAllNames().length;if(Z>0)s.debug(`Loaded ${Z} subagents: ${this.subagentRegistry.getAllNames().join(", ")}`);else s.debug("No subagents configured")}applySkillToolRestrictions($){if(!this.activeSkillContext?.allowedTools)return $;let Z=this.activeSkillContext.allowedTools;s.debug(`Applying Skill tool restrictions: ${Z.join(", ")}`);let J=$.filter((Y)=>{if(Y.name==="ReadPromptArtifact")return!0;return Z.some((Q)=>{if(Q===Y.name)return!0;let X=Q.match(/^(\w+)\(.*\)$/);if(X&&X[1]===Y.name)return!0;return!1})});return s.debug(`Filtered tools: ${J.map((Y)=>Y.name).join(", ")} (${J.length}/${$.length})`),J}clearSkillContext(){if(this.activeSkillContext)s.debug(`Skill "${this.activeSkillContext.skillName}" deactivated`),this.activeSkillContext=void 0}async processAtMentionsForContent($){if(!this.attachmentCollector)return $;if(typeof $==="string")return this.processAtMentions($);let Z=[];for(let Y of $)if(Y.type==="text")Z.push(Y.text);if(Z.length===0)return $;let J=Z.join(`
865
865
  `);try{let Y=await this.attachmentCollector.collect(J);if(Y.length===0)return $;s.debug(`Processed ${Y.length} @ file mentions in multimodal message`);let Q=this.buildAttachmentText(Y);if(!Q)return $;return[...$,{type:"text",text:Q}]}catch(Y){return s.error("Failed to process @ mentions in multimodal message:",Y),$}}buildAttachmentText($){let Z=[],J=[];for(let Q of $)if(Q.type==="file"){let X=Q.metadata?.lineRange?` (lines ${Q.metadata.lineRange.start}${Q.metadata.lineRange.end?`-${Q.metadata.lineRange.end}`:""})`:"";Z.push(`<file path="${Q.path}"${X?` range="${X}"`:""}>`,Q.content,"</file>")}else if(Q.type==="directory")Z.push(`<directory path="${Q.path}">`,Q.content,"</directory>");else if(Q.type==="error")J.push(`- @${Q.path}: ${Q.error}`);let Y="";if(Z.length>0)Y+=`
866
866
 
867
867
  <system-reminder>
@@ -1677,7 +1677,7 @@ ${J}
1677
1677
  `)),{success:!0,message:"Schedules listed",content:U.join(`
1678
1678
  `)}}case"create":{let V=sw(X);if("error"in V)return Y.sendMessage(`创建失败:${V.error}`),{success:!1,error:V.error};let U={prompt:V.prompt,projectPath:W,trigger:V.trigger,isolation:"worktree",permissionMode:"default",enabled:!0};try{let H=await $.create(U),z=H.nextRunAt?new Date(H.nextRunAt).toLocaleString():"(无)";return Y.sendMessage(`[OK] 已创建定时任务 \`${H.id}\`
1679
1679
  ${A9(H.trigger)} · 下次运行: ${z}`),{success:!0,message:`Schedule ${H.id} created`}}catch(H){let z=H instanceof Error?H.message:String(H);return Y.sendMessage(`创建失败:${z}`),{success:!1,error:z}}}case"remove":case"rm":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule remove <id>"),{success:!1,error:"Missing schedule id"};let U=await $.remove(V);return Y.sendMessage(U?`[OK] 已删除 \`${V}\``:`未找到 \`${V}\``),{success:U,message:U?"Removed":"Not found"}}case"enable":case"disable":{let V=X[0];if(!V)return Y.sendMessage(`用法:/schedule ${Q} <id>`),{success:!1,error:"Missing schedule id"};let U=await $.setEnabled(V,Q==="enable");return Y.sendMessage(U?`[OK] 已${Q==="enable"?"启用":"停用"} \`${V}\``:`未找到 \`${V}\``),{success:Boolean(U),message:U?"Updated":"Not found"}}case"run":{let V=X[0];if(!V)return Y.sendMessage("用法:/schedule run <id>"),{success:!1,error:"Missing schedule id"};try{return await ow(V),Y.sendMessage(`[OK] 已触发 \`${V}\``),{success:!0,message:"Schedule triggered"}}catch(U){let H=U instanceof Error?U.message:String(U);return Y.sendMessage(`运行失败:${H}`),{success:!1,error:H}}}default:return Y.sendMessage(`未知子命令: ${Q}
1680
- 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var oW=tw();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function JV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let G=await ew($,Q??C(),J,Y);if(G)return G}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),z=[],B=Y?$:$.toLowerCase();for(let G of H){if(z.length>=J)break;let D=P2.basename(G,".jsonl"),w=await $_(G,B,Y,D);if(z.push(...w),z.length>=J){z.length=J;break}}return z}async function ew($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await $V();if(!X)return null;let{SessionService:W}=await import("./chunk-sbj9wyn4.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),U=ZV(X,$,V,J*4),H=Y?$:$.toLowerCase(),z=[];for(let B of U){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,H,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)z.push(G);if(z.length>=J)break}return z}catch{return null}}async function $_($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
1680
+ 使用 /schedule 查看帮助`),{success:!1,error:`Unknown subcommand: ${Q}`}}}}}var oW=tw();import*as f2 from"node:fs/promises";import*as P2 from"node:path";async function JV($,Z={}){let{maxResults:J=20,caseSensitive:Y=!1,projectPath:Q,storagePath:X}=Z,W=X??P6(Q??C());if(!X){let G=await ew($,Q??C(),J,Y);if(G)return G}let V;try{V=(await f2.readdir(W)).filter((D)=>D.endsWith(".jsonl")&&!D.startsWith("agent_")).map((D)=>P2.join(W,D))}catch{return[]}let H=(await Promise.all(V.map(async(G)=>{try{let D=await f2.stat(G);return{path:G,mtime:D.mtimeMs}}catch{return null}}))).filter((G)=>G!==null).sort((G,D)=>D.mtime-G.mtime).map((G)=>G.path),z=[],B=Y?$:$.toLowerCase();for(let G of H){if(z.length>=J)break;let D=P2.basename(G,".jsonl"),w=await $_(G,B,Y,D);if(z.push(...w),z.length>=J){z.length=J;break}}return z}async function ew($,Z,J,Y){try{let{syncAll:Q}=await import("./chunk-d420fs8m.js"),X=await $V();if(!X)return null;let{SessionService:W}=await import("./chunk-vpwar5x8.js");await Q(X,W.projectionDeriverForSearch());let V=P2.resolve(Z),U=ZV(X,$,V,J*4),H=Y?$:$.toLowerCase(),z=[];for(let B of U){if(B.role!=="user"&&B.role!=="assistant")continue;let G=M9(B.text,H,Y,B.session_id,B.role,B.timestamp??void 0,0);if(G)z.push(G);if(z.length>=J)break}return z}catch{return null}}async function $_($,Z,J,Y){try{let Q=await f2.readFile($,"utf8"),W=Q.split(`
1681
1681
  `).flatMap((B,G)=>{if(!B.trim())return[];try{return[{event:JSON.parse(B),index:G}]}catch{return[]}});if(!W.some(({event:B})=>B.type==="session_created"))return Z_(W,Z,J,Y);let U=new Map(W.flatMap(({event:B,index:G})=>typeof B.id==="string"?[[B.id,G+1]]:[])),H=tW(eW(Q,$)),z=new Map;for(let B of H){if(B.type==="message_created"&&(B.data.role==="user"||B.data.role==="assistant"))z.set(B.data.messageId,{role:B.data.role,content:[],timestamp:B.timestamp,lineNumber:U.get(B.id)??0});if(B.type==="part_created"&&B.data.partType==="text"){let G=z.get(B.data.messageId),D=B.data.payload.text;if(G&&typeof D==="string")G.content.push(D)}}return[...z.values()].flatMap((B)=>{let G=M9(B.content.join(" "),Z,J,Y,B.role,B.timestamp,B.lineNumber);return G?[G]:[]})}catch{return[]}}function Z_($,Z,J,Y){return $.flatMap(({event:Q,index:X})=>{if(Q.type!=="message")return[];let W=Q.message;if(W?.role!=="user"&&W?.role!=="assistant"||!W.content)return[];let V=typeof W.content==="string"?W.content:Array.isArray(W.content)?W.content.filter((H)=>typeof H==="object"&&H!==null&&H.type==="text"&&typeof H.text==="string").map((H)=>H.text).join(" "):"",U=M9(V,Z,J,Y,W.role,typeof Q.timestamp==="string"?Q.timestamp:void 0,X+1);return U?[U]:[]})}function M9($,Z,J,Y,Q,X,W){if(!$)return;let V=J?$:$.toLowerCase();if(!V.includes(Z))return;let U=V.indexOf(Z),H=Math.max(0,U-80),z=Math.min($.length,U+Z.length+80);return{sessionId:Y,role:Q,content:(H>0?"...":"")+$.slice(H,z).replace(/\n/g," ")+(z<$.length?"...":""),timestamp:X,lineNumber:W}}function YV($){if($.length===0)return"没有找到匹配的历史记录";let Z=[`**找到 ${$.length} 条匹配:**
1682
1682
  `];for(let J of $){let Y=J.timestamp?new Date(J.timestamp).toLocaleString("zh-CN",{timeZone:"Asia/Shanghai"}):"?",Q=J.role==="user"?"\uD83D\uDC64":"\uD83E\uDD16";Z.push(`${Q} \`${J.sessionId.slice(0,8)}\` (${Y})`),Z.push(` ${J.content}`),Z.push("")}return Z.join(`
1683
1683
  `)}var J_={name:"search",description:"Search past session transcripts",fullDescription:"搜索历史会话记录,查找过去的对话内容",usage:"/search <keyword>",aliases:["find","history"],category:"Session",examples:['/search 断路器 - 搜索包含"断路器"的历史对话',"/search edit tool - 搜索 edit tool 相关讨论"],async handler($,Z){let J=c(Z);if($.length===0)return J.sendMessage("**用法:** `/search <关键词>`\n\n在历史会话中搜索包含指定关键词的对话"),{success:!0,message:"显示帮助"};let Y=$.join(" ");J.sendMessage(`正在搜索: "${Y}" ...`);try{let Q=await JV(Y,{maxResults:15,projectPath:Z.cwd}),X=YV(Q);return J.sendMessage(X),{success:!0,message:`found ${Q.length} results`,data:{matches:Q.length}}}catch(Q){let X=Q instanceof Error?Q.message:"未知错误";return J.sendMessage(`搜索失败: ${X}`),{success:!1,error:X}}}},QV=J_;var Y_={name:"skills",description:"查看所有可用的 Skills",fullDescription:"显示所有已发现的 Skills 及其详细信息,包括名称、描述、来源和允许的工具。",usage:"/skills",category:"system",examples:["/skills"],handler:async($,Z)=>{try{let J=Z.workspaceRoot??Z.cwd;return await f$(J,async(Y)=>{await Y.skills.refresh(),i1(J),await l1(J)}),{success:!0,message:"show_skills_manager",data:{action:"show_skills_manager"}}}catch(J){let Y=`获取 Skills 失败: ${J instanceof Error?J.message:"未知错误"}`;return d().addAssistantMessage(Y),{success:!1,error:Y}}}},XV=Y_;import Q_ from"node:path";function O8($){if($<1000)return`${$}ms`;let Z=Math.floor($/1000);if(Z<60)return`${Z}s`;let J=Math.floor(Z/60);if(J<60)return`${J}m ${Z%60}s`;return`${Math.floor(J/60)}h ${J%60}m`}function WV($){switch($){case"running":return"[RUNNING]";case"completed":case"exited":return"[OK]";case"failed":case"error":return"[FAIL]";case"killed":case"cancelled":return"[STOPPED]";default:return"[?]"}}function VV($,Z){if($.length<=Z)return $;return $.slice(0,Z-3)+"..."}async function X_($,Z){let J=c(Z),Y=$[0],Q=Y0.getInstance(),X=D0.getInstance(),W=Z.sessionId??"",V=Z.sessionId?{sessionId:Z.sessionId,projectPath:Q_.resolve(Z.workspaceRoot??Z.cwd)}:void 0;if(Y==="resume"){let D=$[1],w=$.slice(2).join(" ").trim();if(!D||!w)return{success:!1,error:"Usage: /tasks resume <agentId> <prompt>"};if(!Z.subagents)return{success:!1,error:"This surface does not own a subagent runtime"};let q=await Z.subagents.resume(D,w),F=`Resumed \`${D}\` as \`${q.session.id}\` (depth ${q.session.resumeDepth}).`;return J.sendMessage(F),{success:!0,message:F,data:{action:"subagent_resumed",sourceAgentId:D,subagent:q.session}}}if(Y==="clean"){let D=X.cleanupExpiredSessionsForParent(V??W,0);return J.sendMessage(`已清理 ${D} 个已完成的 Agent 会话`),{success:!0,message:`Cleaned ${D} agent sessions`}}let U=[`**后台任务列表**
@@ -1,4 +1,4 @@
1
- import{ea as p}from"./chunk-d2nz3pfs.js";import{Pb as _}from"./chunk-bw5x4ywa.js";import{Ad as U,Bd as I,Cd as A,Dd as z,Od as q,he as O,zd as N}from"./chunk-ycafgg7y.js";import{te as o}from"./chunk-y5wngtz0.js";import{dg as P}from"./chunk-t0gm0pn1.js";import{Eg as e}from"./chunk-fkm1k8xy.js";import{Ck as j}from"./chunk-4wx5sya5.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
1
+ import{ea as p}from"./chunk-r0ragech.js";import{Pb as _}from"./chunk-600xa10z.js";import{Ad as U,Bd as I,Cd as A,Dd as z,Od as q,he as O,zd as N}from"./chunk-b8rkgzjs.js";import{te as o}from"./chunk-y5wngtz0.js";import{dg as P}from"./chunk-t0gm0pn1.js";import{Eg as e}from"./chunk-2p9j16ed.js";import{Ck as j}from"./chunk-4wx5sya5.js";import{createHash as ff}from"node:crypto";var af=4,cf=1000,E=4000,wf=120000,M=0.2;function $f(a){try{return q(a)&&a.retryable}catch{return!1}}function gf(a,c){let f=Number.isSafeInteger(c)&&c>0?c:1,w=f-1,h=Math.min(cf*2**w,E),$=ff("sha256").update(`${a}\x00${f}`).digest().readUInt32BE(0)/4294967295,k=1-M+2*M*$;return Math.min(E,Math.max(0,Math.round(h*k)))}function Tf(a){let c=gf(a.sessionIdentity,a.failedAttempt),f=a.evidence,w=a.workStillPending===!0&&f!==void 0&&$f(f.taskFailure)&&f.outputStarted===!1&&f.toolExecutionStarted===!1&&Number.isInteger(f.toolCallsCount)&&f.toolCallsCount===0,h=Number.isSafeInteger(a.failedAttempt)&&a.failedAttempt>0&&a.failedAttempt<af,g=a.now??Date.now(),$=g-a.recoveryStartedAt,k=Number.isFinite(g)&&Number.isFinite(a.recoveryStartedAt)&&Number.isFinite($)&&$>=0&&$+c<=wf;return{phase:w?h&&k?"retry_scheduled":"exhausted":"failed",delayMs:c,retryable:w,withinAttemptBudget:h,withinTimeBudget:k}}import R from"node:path";import{nanoid as Lf}from"nanoid";import{execFile as hf}from"node:child_process";import{createHash as xf}from"node:crypto";import{lstat as bf,readFile as mf,realpath as i}from"node:fs/promises";import n from"node:path";import{promisify as kf}from"node:util";var lf=kf(hf),T=8388608,s=500,u=200;async function C(a,c){try{return(await lf("git",["-c","core.pager=cat",...c],{cwd:a,encoding:"utf8",timeout:30000,maxBuffer:T+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let w=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${T} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${w}`)}}function d(a,c){let f=a?.trim();if(!f||f.length>u||f.includes("\x00")||f.includes(`
2
2
  `)||f.includes("\r"))throw Error(`${c} must contain 1-${u} characters`);return f}function Q(a){return a.split("\x00").filter(Boolean)}async function X(a,c){return(await C(a,["rev-parse","--verify",`${c}^{commit}`])).trim()}async function Ff(a,c,f,w,h){let g=h,$=await i(a);for(let k of c){let l=n.resolve($,k),x=n.relative($,l);if(!x||x.startsWith("..")||n.isAbsolute(x))throw Error(`Untracked review path escapes the workspace: ${k}`);let b=await bf(l);if(!b.isFile()||b.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${k}`);if(g+=b.size,g>T)throw Error(`Review target exceeds ${T} bytes`);f.update("\x00untracked\x00"),f.update(x.replaceAll(n.sep,"/")),f.update("\x00");let F=await mf(l);f.update(F);let m=Math.max(1,F.toString("utf8").split(`
3
3
  `).length);w.set(x.replaceAll(n.sep,"/"),[{start:1,end:m}])}}function Y(a,c){let f=new Map,w,h,g,$,k=!1,l=(x,b)=>{let F=f.get(x)??[],m=F.at(-1);if(m&&b<=m.end+1)m.end=Math.max(m.end,b);else F.push({start:b,end:b});f.set(x,F)};for(let x of a.split(`
4
4
  `)){if(x.startsWith("--- ")){let b=x.slice(4).split("\t")[0]?.trim();w=b&&b!=="/dev/null"?b.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(x.startsWith("+++ ")){let b=x.slice(4).split("\t")[0]?.trim();k=b==="/dev/null",h=k?w:b?b.replace(/^b\//,"").replaceAll("\\","/"):void 0,g=void 0,$=void 0;continue}if(x.startsWith("@@ ")){let b=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(x);g=b?Math.max(1,Number(b[1])):void 0,$=b?Math.max(1,Number(b[2])):void 0;continue}if(!h||g===void 0||$===void 0)continue;if(x.startsWith("+")&&!x.startsWith("+++"))l(h,$),$++;else if(x.startsWith("-")&&!x.startsWith("---"))l(h,k?g:$),g++;else if(!x.startsWith("\\"))g++,$++}for(let x of c)if(!f.has(x))f.set(x,[{start:1,end:1}]);return f}function D(a){if(a.length>s)throw Error(`Review target exceeds the ${s} file limit`)}class K{static async resolve(a,c){let f=await i(a);await C(f,["rev-parse","--is-inside-work-tree"]);let w=await X(f,"HEAD"),h=xf("sha256");h.update(`kind\x00${c.kind}\x00head\x00${w}\x00`);let g="",$=[],k,l,x,b,F=new Map;switch(c.kind){case"uncommitted":{g=await C(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=Q(await C(f,["diff","--name-only","-z","--relative","HEAD","--","."])),L=Q(await C(f,["ls-files","--others","--exclude-standard","-z","--","."]));if($=[...new Set([...m,...L])].sort(),D($),$.length===0)throw Error("No uncommitted changes to review");h.update(g),F=Y(g,m),await Ff(f,L,h,F,Buffer.byteLength(g)),x="uncommitted changes",b=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=d(c.ref,"Base ref");k=await X(f,m);let L=(await C(f,["merge-base",k,w])).trim();if(g=await C(f,["diff","--binary","--no-ext-diff","--relative",`${L}..${w}`,"--","."]),$=Q(await C(f,["diff","--name-only","-z","--relative",`${L}..${w}`,"--","."])),D($),$.length===0)throw Error(`No changes between ${m} and HEAD`);h.update(g),h.update(`\x00merge-base\x00${L}`),F=Y(g,$),x=`changes against ${m}`,b=`Review changes introduced by ${L}..${w}.`;break}case"commit":{let m=d(c.ref,"Commit ref");if(l=await X(f,m),g=await C(f,["show","--format=","--binary","--no-ext-diff","--relative",l,"--","."]),$=Q(await C(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",l,"--","."])),D($),$.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);h.update(g),h.update(`\x00commit\x00${l}`),F=Y(g,$),x=`commit ${m}`,b=`Review only the changes introduced by commit ${l}.`;break}}if(Buffer.byteLength(g)>T)throw Error(`Review diff exceeds ${T} bytes`);return{info:{kind:c.kind,label:x,headSha:w,...k?{baseSha:k}:{},...l?{commitSha:l}:{},digest:h.digest("hex"),fileCount:$.length},instruction:b,changedLines:F}}}var Wf=131072,t=50,Z=new Set;function v(a,c){return`${R.resolve(a)}\x00${c}`}function S(a){return`/review ${a.kind}${a.kind==="uncommitted"?"":` ${a.ref?.trim()??""}`}`}function V(a,c,f,w=!1){if(typeof a!=="string")throw Error(`${c} must be a string`);let h=a.trim();if(!w&&!h||h.length>f)throw Error(`${c} exceeds its allowed length`);return h}function Hf(a,c,f){if(!a||typeof a!=="object"||Array.isArray(a))throw Error("Review finding must be an object");let w=a,h=typeof w.line==="number"&&Number.isInteger(w.line)?w.line:void 0,g=w.code_location??(typeof w.file==="string"&&h!==void 0?{path:w.file,line_start:h,line_end:h}:void 0);if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Review finding has no code_location");let $=g,k=V($.path,"Finding path",1000),l=R.posix.normalize(k.replaceAll("\\","/"));if(R.posix.isAbsolute(l)||l===".."||l.startsWith("../"))throw Error("Review finding path must be workspace-relative");let x=R.resolve(c,l),b=R.relative(R.resolve(c),x);if(b.startsWith("..")||R.isAbsolute(b))throw Error("Review finding path escapes the workspace");let F=typeof w.severity==="string"?w.severity.toLowerCase():"",m=F==="critical"?0:F==="high"?1:F==="medium"?2:F==="low"?3:void 0,L=w.priority??m;if(L!==0&&L!==1&&L!==2&&L!==3)throw Error("Review finding priority must be 0-3");let W=w.confidence_score??w.confidence??0.8;if(typeof W!=="number"||!Number.isFinite(W)||W<0||W>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:H,line_end:r}=$;if(!Number.isInteger(H)||!Number.isInteger(r)||H<1||r<H||r-H>=10)throw Error("Review finding line range is invalid");let G=f.changedLines.get(l);if(!G)throw Error("Review finding path is outside the review target");if(!G.some((y)=>H<=y.end&&r>=y.start))throw Error("Review finding line range does not overlap the changed lines");let B=V(w.title??`[P${L}] ${String(w.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(y)=>y.toUpperCase())}`,"Finding title",120);if(!B.startsWith(`[P${L}] `))throw Error("Review finding title priority does not match priority");return{title:B,body:V(w.body??w.description,"Finding body",4000),priority:L,confidenceScore:W,codeLocation:{path:l,lineStart:H,lineEnd:r}}}function Rf(a,c,f){if(Buffer.byteLength(a)>Wf)throw Error("Review output exceeds the 128 KiB limit");let w=a.indexOf("{"),h=a.lastIndexOf("}");if(w<0||h<=w)throw Error("Reviewer did not return a JSON object");let g;try{g=JSON.parse(a.slice(w,h+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!g||typeof g!=="object"||Array.isArray(g))throw Error("Reviewer output must be an object");let $=g;if(!Array.isArray($.findings))throw Error("Reviewer output must contain findings");if($.findings.length>t)throw Error(`Reviewer returned more than ${t} findings`);return{overallExplanation:V($.overall_explanation??$.summary,"Review explanation",1e4,!0),findings:$.findings.map((k)=>Hf(k,c,f))}}async function J(a,c){return new o(j(a,c)).readAll()}class rf{static async start(a){let{sessionId:c,projectPath:f,runtime:w,request:h,onEvent:g}=a;if(w.sessionId!==c||R.resolve(w.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(w.hasTurnOwner())throw Error("Cannot start a review during an active turn");await O.assertSessionWritable(c,f);let $=v(f,c);if(Z.has($))throw Error("Session already has an active review");let k=await J(f,c);if(U(k))throw Error("Session has an interrupted review that must be recovered");let l=h.instructions?.trim();if(l&&l.length>4000)throw Error("Review instructions exceed 4,000 characters");let x=await K.resolve(f,h),b=Lf(16),F=P("review"),m=new Date().toISOString(),L={reviewId:b,reviewerSessionId:F,target:x.info,startedAt:m},W=new _(f);await W.saveReviewStart(c,L),await W.saveMessage(c,"user",S(h),null,{codeReview:{reviewId:b,phase:"started",targetKind:x.info.kind,targetDigest:x.info.digest}}),await O.updateSessionMetadata(c,f,{taskStatus:"running",taskStatusReason:`Reviewing ${x.info.label}`,taskPromptSummary:S(h),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),Z.add($);let H=this.execute({...a,target:x,reviewId:b,reviewerSessionId:F,instructions:l,store:W,onEvent:g}).finally(()=>{Z.delete($)});return{reviewId:b,completion:H}}static async execute(a){let{sessionId:c,projectPath:f,runtime:w,request:h,signal:g,onEvent:$,target:k,reviewId:l,reviewerSessionId:x,instructions:b,store:F}=a,m;try{let W=[k.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${k.info.digest}`,`Changed file count: ${k.info.fileCount}`,b?`Additional review instructions:
@@ -1 +1 @@
1
- import{be as a,ce as b,de as c,ee as d,fe as e,ge as f,he as g}from"./chunk-ycafgg7y.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-50vwafn5.js";import"./chunk-vbjgcn49.js";import"./chunk-3y2x6fb6.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4cdk4mds.js";import"./chunk-020t9es1.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
1
+ import{be as a,ce as b,de as c,ee as d,fe as e,ge as f,he as g}from"./chunk-b8rkgzjs.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-50vwafn5.js";import"./chunk-vbjgcn49.js";import"./chunk-3y2x6fb6.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4cdk4mds.js";import"./chunk-fb773kdb.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
@@ -1 +1 @@
1
- import{$f as n,Of as a,Pf as b,Qf as c,Rf as d,Sf as e,Tf as f,Uf as g,Vf as h,Wf as i,Xf as j,Yf as k,Zf as l,_f as m,ag as o,bg as p,cg as q}from"./chunk-pwj9zz8z.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-4gns7fxm.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-020t9es1.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{$f as n,Of as a,Pf as b,Qf as c,Rf as d,Sf as e,Tf as f,Uf as g,Vf as h,Wf as i,Xf as j,Yf as k,Zf as l,_f as m,ag as o,bg as p,cg as q}from"./chunk-4vn0dr8c.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-zvf33r3d.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-fb773kdb.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -0,0 +1 @@
1
+ import{rf as a,sf as b}from"./chunk-4jfs3qsd.js";import"./chunk-fb773kdb.js";import"./chunk-eg3ms291.js";export{a as globalOptions,b as cliConfig};
@@ -1 +1 @@
1
- import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-fkm1k8xy.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-dpjy7s53.js";import"./chunk-3y2x6fb6.js";import"./chunk-4gns7fxm.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-020t9es1.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
1
+ import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-2p9j16ed.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-96jpzf75.js";import"./chunk-3y2x6fb6.js";import"./chunk-zvf33r3d.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-fb773kdb.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};