blade-code 0.10.8 → 0.10.10

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 (112) hide show
  1. package/dist/blade.js +3 -3
  2. package/dist/{chunk-nymm525r.js → chunk-095x2ykj.js} +1 -1
  3. package/dist/{chunk-wmnszjmv.js → chunk-2mzcxq6c.js} +2 -2
  4. package/dist/{chunk-66hb7kxm.js → chunk-363pgv1e.js} +2 -2
  5. package/dist/chunk-3aqdjrtm.js +2 -0
  6. package/dist/chunk-3n4m3pcy.js +1 -0
  7. package/dist/{chunk-d0g4t8fw.js → chunk-3v0ay0sf.js} +1 -1
  8. package/dist/{chunk-8gnfj89a.js → chunk-4dq9y7zn.js} +2 -2
  9. package/dist/chunk-4zs5r4n4.js +1 -0
  10. package/dist/{chunk-kagpk2x5.js → chunk-576pdgtm.js} +2 -2
  11. package/dist/{chunk-y4c3wwpa.js → chunk-5s123nbs.js} +1 -1
  12. package/dist/chunk-632rgzcf.js +2 -0
  13. package/dist/{chunk-a8h3fymk.js → chunk-6kwv8ph0.js} +2 -2
  14. package/dist/{chunk-m2xrx1je.js → chunk-732n8xj6.js} +2 -2
  15. package/dist/{chunk-8gcvpmwk.js → chunk-74shfpve.js} +1 -1
  16. package/dist/chunk-7hjjjkj0.js +1 -0
  17. package/dist/chunk-7mhkm3x7.js +6 -0
  18. package/dist/{chunk-cbpqcdga.js → chunk-7wjy6kgt.js} +1 -1
  19. package/dist/{chunk-eq2qj9ja.js → chunk-8j01ssaf.js} +1 -1
  20. package/dist/chunk-9cnm1hgp.js +1 -0
  21. package/dist/chunk-9e5z64ap.js +1 -0
  22. package/dist/chunk-9tnaads5.js +2 -0
  23. package/dist/{chunk-33ave20b.js → chunk-afkhzdfc.js} +1 -1
  24. package/dist/{chunk-b5szbtmp.js → chunk-ah97bmns.js} +2 -2
  25. package/dist/chunk-b6gknm33.js +1 -0
  26. package/dist/chunk-bxp1w7sh.js +200 -0
  27. package/dist/chunk-c7201g75.js +3 -0
  28. package/dist/{chunk-7zsyejr1.js → chunk-cfwnbrrd.js} +12 -12
  29. package/dist/{chunk-yfs9tq3y.js → chunk-d600wn06.js} +2 -2
  30. package/dist/{chunk-4h9ff923.js → chunk-dpt56hah.js} +1 -1
  31. package/dist/{chunk-fj8v7pep.js → chunk-dsj62dcg.js} +1 -1
  32. package/dist/{chunk-h421wzbm.js → chunk-egmwj6xg.js} +2 -2
  33. package/dist/{chunk-s9aj3p11.js → chunk-epek6vr2.js} +1 -1
  34. package/dist/chunk-f4z3gkbs.js +2 -0
  35. package/dist/chunk-fvrmjhz5.js +1 -0
  36. package/dist/chunk-fvy56ajf.js +1 -0
  37. package/dist/{chunk-954vmnrn.js → chunk-g11hq0e5.js} +1 -1
  38. package/dist/{chunk-8h0yxh6y.js → chunk-g1qpzyt3.js} +1 -1
  39. package/dist/{chunk-w0nscjd2.js → chunk-gav4hxcv.js} +2 -2
  40. package/dist/{chunk-van4ysq6.js → chunk-ggq4y248.js} +300 -279
  41. package/dist/{chunk-vgp8m9fg.js → chunk-gvc0qqk4.js} +2 -2
  42. package/dist/{chunk-vsg8f0e6.js → chunk-heqs3xan.js} +1 -1
  43. package/dist/chunk-hetayg68.js +10 -0
  44. package/dist/{chunk-cf8e7e92.js → chunk-hfv5gcqj.js} +54 -20
  45. package/dist/chunk-hveqdgt6.js +1 -0
  46. package/dist/chunk-hxp5qs1x.js +1 -0
  47. package/dist/{chunk-2thg3fq1.js → chunk-j42jswx0.js} +1 -1
  48. package/dist/chunk-jw8gb53m.js +1 -0
  49. package/dist/{chunk-xmcsn7y0.js → chunk-ktf3bpmw.js} +2 -2
  50. package/dist/chunk-kvx3sb3z.js +2 -0
  51. package/dist/{chunk-rxqft6td.js → chunk-mhne9y2k.js} +2 -2
  52. package/dist/{chunk-fxpq9nh6.js → chunk-mtk2tf9n.js} +1 -1
  53. package/dist/chunk-nmmj1x0c.js +1 -0
  54. package/dist/chunk-p4zt7ts9.js +2 -0
  55. package/dist/chunk-r76wc1cn.js +2 -0
  56. package/dist/chunk-rhw2zkq8.js +6 -0
  57. package/dist/{chunk-v8pq6qmv.js → chunk-s5666ta0.js} +2 -2
  58. package/dist/{chunk-zvk3g177.js → chunk-t9aggrv8.js} +1 -1
  59. package/dist/chunk-tkqrhxqr.js +1 -0
  60. package/dist/chunk-ttncpgr6.js +1 -0
  61. package/dist/{chunk-nhc49pan.js → chunk-vdj00rsv.js} +2 -2
  62. package/dist/{chunk-7hbw6q6d.js → chunk-vmq248m7.js} +1 -1
  63. package/dist/chunk-wnqybbry.js +2 -0
  64. package/dist/{chunk-r7tsa2zv.js → chunk-xx1d9kfd.js} +1 -1
  65. package/dist/{chunk-8gcg2z3y.js → chunk-y56s2qww.js} +2 -2
  66. package/dist/{chunk-h28ptrrt.js → chunk-ybvdac8k.js} +1 -1
  67. package/dist/chunk-z5zcwwfm.js +1 -0
  68. package/dist/{chunk-pv9sw79c.js → chunk-z8c5rhdh.js} +2 -2
  69. package/dist/{chunk-j4tttsaz.js → chunk-zepqp80m.js} +2 -2
  70. package/dist/{chunk-g00wj2we.js → chunk-zf183j2y.js} +1 -1
  71. package/dist/{chunk-xa05phpw.js → chunk-zyf1r2j3.js} +3 -3
  72. package/dist/web/assets/ChatView-DdX4BvAo.js +7 -0
  73. package/dist/web/assets/{CodeBlockHighlighter-EgdsVoMQ.js → CodeBlockHighlighter-DBw81YZa.js} +1 -1
  74. package/dist/web/assets/{FilePreview-xicd9-Sl.js → FilePreview-Di-mSDMs.js} +2 -2
  75. package/dist/web/assets/{MarkdownRenderer-DBSjC_z3.js → MarkdownRenderer-CxSfwebU.js} +3 -3
  76. package/dist/web/assets/SettingsModal-CoBMb8of.js +5 -0
  77. package/dist/web/assets/{TaskSwitcher-DXcj0iJ_.js → TaskSwitcher-BmS-DA4i.js} +1 -1
  78. package/dist/web/assets/{TerminalPanel-DWVY-Elm.js → TerminalPanel-BPruynbV.js} +1 -1
  79. package/dist/web/assets/index-BC7ygRH_.css +1 -0
  80. package/dist/web/assets/index-Bx7HzeXs.js +32 -0
  81. package/dist/web/assets/{vendor-icons-Cv18Q6rW.js → vendor-icons-ICv1v-tf.js} +71 -66
  82. package/dist/web/index.html +3 -3
  83. package/package.json +1 -1
  84. package/dist/chunk-1w6azndv.js +0 -1
  85. package/dist/chunk-2gwaqpge.js +0 -1
  86. package/dist/chunk-2pjd4cys.js +0 -1
  87. package/dist/chunk-2zn5en0w.js +0 -1
  88. package/dist/chunk-3w1z6fwm.js +0 -1
  89. package/dist/chunk-43x4qbvt.js +0 -1
  90. package/dist/chunk-52csdk21.js +0 -3
  91. package/dist/chunk-6j8wgp2s.js +0 -2
  92. package/dist/chunk-6vsszvgg.js +0 -2
  93. package/dist/chunk-7evtr0yr.js +0 -10
  94. package/dist/chunk-8sfycn3y.js +0 -194
  95. package/dist/chunk-bxm2hq0m.js +0 -1
  96. package/dist/chunk-c8da4b3d.js +0 -1
  97. package/dist/chunk-kvnwhwx3.js +0 -1
  98. package/dist/chunk-nz57y1ad.js +0 -6
  99. package/dist/chunk-p2m56new.js +0 -2
  100. package/dist/chunk-qgp08qmz.js +0 -6
  101. package/dist/chunk-rkvfsx8e.js +0 -2
  102. package/dist/chunk-senkwdh6.js +0 -2
  103. package/dist/chunk-v1c58sm6.js +0 -1
  104. package/dist/chunk-w26jhcj9.js +0 -1
  105. package/dist/chunk-x6wgh726.js +0 -1
  106. package/dist/chunk-ymzcxryf.js +0 -1
  107. package/dist/chunk-zknv3d6y.js +0 -2
  108. package/dist/chunk-zp4x2mwj.js +0 -1
  109. package/dist/web/assets/ChatView-Fqy97qw9.js +0 -7
  110. package/dist/web/assets/SettingsModal-Bkh5rMAJ.js +0 -5
  111. package/dist/web/assets/index-Bi5ijAQP.css +0 -1
  112. package/dist/web/assets/index-CxEh32hc.js +0 -32
@@ -1,5 +1,5 @@
1
- import{r as A}from"./chunk-d0g4t8fw.js";import{s as zJ}from"./chunk-8h0yxh6y.js";import{$ as r,F as v,I as p,J as m,L as d,Z as l,_ as i,aa as a,v as N}from"./chunk-van4ysq6.js";import{ka as $J}from"./chunk-s9aj3p11.js";import{Ba as u,Ea as g,Pa as c}from"./chunk-8sfycn3y.js";import{_a as I}from"./chunk-nymm525r.js";import{Ab as f,Eb as _,Hb as L,lb as S,qb as R,tb as C,zb as y}from"./chunk-a8h3fymk.js";import"./chunk-kagpk2x5.js";import"./chunk-xmcsn7y0.js";import"./chunk-8gcg2z3y.js";import"./chunk-7hbw6q6d.js";import{Nc as JJ}from"./chunk-h28ptrrt.js";import"./chunk-b5szbtmp.js";import"./chunk-wmnszjmv.js";import{Wc as QJ}from"./chunk-eq2qj9ja.js";import"./chunk-rxqft6td.js";import"./chunk-cf8e7e92.js";import"./chunk-senkwdh6.js";import{vd as ZJ}from"./chunk-vsg8f0e6.js";import"./chunk-4h9ff923.js";import"./chunk-xa05phpw.js";import"./chunk-cbpqcdga.js";import{Id as O}from"./chunk-8gnfj89a.js";import"./chunk-yfs9tq3y.js";import"./chunk-zknv3d6y.js";import{Ge as x,He as k,Ie as h}from"./chunk-6j8wgp2s.js";import{Me as t}from"./chunk-y4c3wwpa.js";import"./chunk-v8pq6qmv.js";import{Se as s,Ve as e}from"./chunk-fj8v7pep.js";import"./chunk-6vsszvgg.js";import"./chunk-w0nscjd2.js";import"./chunk-33ave20b.js";import"./chunk-66hb7kxm.js";import"./chunk-954vmnrn.js";import{Readable as LJ,Writable as BJ}from"node:stream";import*as E from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as DJ}from"@agentclientprotocol/sdk";import o from"node:path";import{RequestError as HJ}from"@agentclientprotocol/sdk";import{nanoid as b}from"nanoid";var D=O("Agent");function M(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function FJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:M(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:M("headers"in J?J.headers:void 0)};return null}function GJ(J){let Z={};for(let Q of J){let W=FJ(Q);if(W)Z[Q.name]=W}return Z}function n(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function XJ(J){let Z=f(J.metadata);return Z?[{type:"text",text:y(Z)}]:n(J.content)}function jJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
- `)}class P{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode;constructor(J,Z,Q,W,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=W;this.options=H;this.messages=[...H.initialMessages??[]],this.mode=this.mapPermissionModeToMode(H.permissionMode)}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return d.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(D.debug(`[AcpSession ${this.id}] Initializing...`),await L.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),N.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),D.debug(`[AcpSession ${this.id}] ACP service context initialized`),await c.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await L.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?GJ(this.options.mcpServers):void 0,Q=N.getInstance().getTerminalService(this.id);if(this.runtime=await v.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let G=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(F)=>$.onOutput?.("stdout",F)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.error==="Command timed out",aborted:G.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await A.recoverInterrupted(this.cwd,this.id,this.runtime))this.messages=await L.loadSession(this.id,this.cwd);this.agent=await this.createAgent(),await i(this.cwd),D.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=g.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of XJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);D.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{D.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await this.runtime.rewindSession($);return this.messages=[...G.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),G}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,j,Y=(B)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.id,status:B.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:B.result?.message||B.result?.error||`Subagent ${B.status}`}}]})},X=this.runtime.resumeSubagent({agentId:$,prompt:G,onCompleted:(B)=>{if(F)Y(B);else j=B}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.session.id,status:"in_progress",title:`Resuming ${X.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${X.source.id} at depth ${X.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,j)Y(j);return X}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,G,F)},complete:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,G,F)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,G)},getLogs:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,G)},setLoggingLevel:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,G)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await A.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:G,onEvent:(X)=>{if(X.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.toolCall.id,status:"in_progress",title:`Review: ${X.toolCall.function.name}`,content:[],kind:this.mapToolKind(X.toolKind)});else if(X.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.toolCall.id,status:X.result.success?"completed":"failed",content:[]})}}),j=await F.completion,Y=(await A.list(this.cwd,this.id)).find((X)=>X.start.reviewId===F.reviewId);if(!Y)throw Error(`Review not found: ${F.reviewId}`);return this.messages=await L.loadSession(this.id,this.cwd),{reviewId:F.reviewId,status:j.status,findings:j.findings.length,content:S(Y.start,j)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,G,F)=>{let j=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,Y=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:Y})},sendToolResult:($,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},W=await r(J,Q),H=W.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages];if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages)this.messages=[...W.data.compactedMessages];let z=W.content||W.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return{stopReason:W.success?"end_turn":"cancelled"}}catch(Q){return D.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=a(this.cwd),Z=["model","permissions","theme","config","exit","ide"],W=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});D.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),D.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(J){D.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(N.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),W=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((F)=>F.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=C(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let F=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!F.accepted)throw Error(F.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(D.debug(`[AcpSession ${this.id}] Queued steering for active turn (${F.queued})`),F.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let G=new AbortController;this.pendingPrompt=G;try{if(D.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),l(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,G.signal)}let F={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Y)=>{this.mode=this.mapPermissionModeToMode(Y),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}},j=await u(this.agent.chatStream(W,F,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(Y)=>{switch(Y.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let X=Y.toolCall,B=X.function.name;if(B===R)break;let U=this.mapToolKind(Y.toolKind),V=`Executing ${B}`;if(B==="Task"&&"function"in X)try{let q=JSON.parse(X.function.arguments),w=q.resume_from??q.resume;if(typeof w==="string")V=`Resuming ${String(q.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X.id,status:"in_progress",title:V,content:[],kind:U});break}case"tool_progress":{let X=Y.toolCall;if(X.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Y.update.message}}]});break}case"tool_result":{let X=Y.toolCall;if(X.function.name===R)break;let B=Y.result,U=[],V=B.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let w of V.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;U.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))U.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let w=X.function.name,WJ=m(p(w,B));U.push({type:"content",content:{type:"text",text:WJ}})}if(X.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))U.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let q=B.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X.id,status:q,content:U});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Y.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
1
+ import{r as R}from"./chunk-3v0ay0sf.js";import{s as WJ}from"./chunk-g1qpzyt3.js";import{$ as a,F as p,I as m,J as d,L as l,Z as i,_ as r,aa as n,v as P}from"./chunk-ggq4y248.js";import{ka as zJ}from"./chunk-epek6vr2.js";import"./chunk-p4zt7ts9.js";import{Va as g,Ya as c,hb as v}from"./chunk-bxp1w7sh.js";import{sb as y}from"./chunk-095x2ykj.js";import{$b as B,Fb as C,Kb as O,Nb as f,Tb as T,Ub as u,Yb as q}from"./chunk-6kwv8ph0.js";import"./chunk-576pdgtm.js";import"./chunk-ktf3bpmw.js";import"./chunk-y56s2qww.js";import"./chunk-vmq248m7.js";import{fd as QJ}from"./chunk-ybvdac8k.js";import"./chunk-ah97bmns.js";import"./chunk-2mzcxq6c.js";import{od as ZJ}from"./chunk-8j01ssaf.js";import"./chunk-mhne9y2k.js";import"./chunk-hfv5gcqj.js";import"./chunk-9tnaads5.js";import{Td as $J}from"./chunk-heqs3xan.js";import"./chunk-dpt56hah.js";import"./chunk-zyf1r2j3.js";import"./chunk-7wjy6kgt.js";import{ee as E}from"./chunk-4dq9y7zn.js";import"./chunk-d600wn06.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import{cf as h,df as S,ef as I}from"./chunk-f4z3gkbs.js";import{if as s}from"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import{of as e,rf as JJ}from"./chunk-dsj62dcg.js";import"./chunk-wnqybbry.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";import{Readable as BJ,Writable as VJ}from"node:stream";import*as b from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as LJ}from"@agentclientprotocol/sdk";import t from"node:path";import{RequestError as FJ}from"@agentclientprotocol/sdk";import{nanoid as x}from"nanoid";var j=E("Agent");function k(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function GJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:k(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:k("headers"in J?J.headers:void 0)};return null}function XJ(J){let Z={};for(let Q of J){let W=GJ(Q);if(W)Z[Q.name]=W}return Z}function o(J){if(typeof J==="string")return J?[{type:"text",text:J}]:[];return J.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let Q=Z.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function jJ(J){let Z=u(J.metadata);return Z?[{type:"text",text:T(Z)}]:o(J.content)}function DJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
2
+ `)}class A{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;mode;constructor(J,Z,Q,W,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=W;this.options=H;this.messages=[...H.initialMessages??[]],this.mode=this.mapPermissionModeToMode(H.permissionMode)}mapPermissionModeToMode(J){switch(J){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return l.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await B.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),P.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await v.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))this.messages=await B.loadSession(this.id,this.cwd);let Z=this.options.mcpServers?XJ(this.options.mcpServers):void 0,Q=P.getInstance().getTerminalService(this.id);if(this.runtime=await p.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(z,$)=>{let G=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(F)=>$.onOutput?.("stdout",F)});return{exitCode:G.exitCode,stdout:G.stdout,stderr:G.stderr,...G.error?{error:G.error}:{},timedOut:G.error==="Command timed out",aborted:G.error==="Command was aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await R.recoverInterrupted(this.cwd,this.id,this.runtime))this.messages=await B.loadSession(this.id,this.cwd);this.agent=await this.createAgent(),await r(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=c.subscribe((z)=>{if(z.sessionId!==this.id||z.projectPath!==this.cwd)return;if(z.type==="task.delivery"){if(!z.properties.taskDelivery||typeof z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":z.properties.taskDelivery,...z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof z.properties.updatedAt==="string"?z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":z.properties.taskStatus,...typeof z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":z.properties.taskStatusReason}:{},...z.properties.taskFailure&&typeof z.properties.taskFailure==="object"?{"blade/taskFailure":z.properties.taskFailure}:{},...typeof z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":z.properties.taskStartedAt}:{},...typeof z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":z.properties.taskCompletedAt}:{},...z.properties.taskDiffStat&&typeof z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":z.properties.taskDiffStat}:{},...typeof z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":z.properties.taskQueuePosition}:{},...typeof z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":z.properties.taskQueueDepth}:{},...typeof z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":z.properties.taskConcurrencyLimit}:{},...typeof z.properties.taskInFlight==="number"?{"blade/taskInFlight":z.properties.taskInFlight}:{}}})});let H=await this.runtime.getGoal();if(this.runtime.getPendingSteeringCount()>0||H?.status==="active")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Q of jJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Q}))return}}if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);j.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{j.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.messages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await this.runtime.rewindSession($);return this.messages=[...G.messages],await this.agent?.destroy(),this.agent=await this.createAgent(),G}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async($)=>{if(await this.setReasoningEffort($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async($)=>{if(await this.setServiceTier($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async($)=>{if(await this.setResponseVerbosity($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async($)=>{if(await this.setCommunicationStyle($),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,X,L=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},Y=this.runtime.resumeSubagent({agentId:$,prompt:G,onCompleted:(D)=>{if(F)L(D);else X=D}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.session.id,status:"in_progress",title:`Resuming ${Y.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${Y.source.id} at depth ${Y.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,X)L(X);return Y}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs($)},getPrompt:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,G,F)},complete:async($,G,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,G,F)},listTasks:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks($)},getTask:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask($)},cancelTask:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,G)},getLogs:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,G)},setLoggingLevel:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,G)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await R.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:G,onEvent:(Y)=>{if(Y.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Y.toolCall.id,status:"in_progress",title:`Review: ${Y.toolCall.function.name}`,content:[],kind:this.mapToolKind(Y.toolKind)});else if(Y.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y.toolCall.id,status:Y.result.success?"completed":"failed",content:[]})}}),X=await F.completion,L=(await R.list(this.cwd,this.id)).find((Y)=>Y.start.reviewId===F.reviewId);if(!L)throw Error(`Review not found: ${F.reviewId}`);return this.messages=await B.loadSession(this.id,this.cwd),{reviewId:F.reviewId,status:X.status,findings:X.findings.length,content:C(L.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,G,F)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,L=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(G,null,2)}}],kind:L})},sendToolResult:($,G)=>{if(G.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:G.summary}})}}},W=await a(J,Q),H=W.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages];if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages)this.messages=[...W.data.compactedMessages];let z=W.content||W.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return{stopReason:W.success?"end_turn":"cancelled"}}catch(Q){return j.error(`[AcpSession ${this.id}] Slash command error:`,Q),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Q instanceof Error?Q.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async sendAvailableCommands(){try{let J=n(this.cwd),Z=["model","permissions","theme","config","exit","ide"],W=J.filter((H)=>!Z.includes(H.name)).map((H)=>{let z;if(H.usage){let $=H.usage.replace(/^\/\w+\s*/,"").trim();if($)z=$}if(H.aliases?.length){let $=`Aliases: ${H.aliases.join(", ")}`;z=z?`${z} | ${$}`:$}return{name:H.name,description:H.description,input:z?{hint:z}:void 0}});j.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),j.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(P.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),W=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((F)=>F.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=f(z).schema;if(H.trimStart().startsWith("!")){if($)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(H)}if(this.pendingPrompt){if($)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(H.trim()))return this.handleSlashCommand(H,this.pendingPrompt.signal);let F=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!F.accepted)throw Error(F.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(j.debug(`[AcpSession ${this.id}] Queued steering for active turn (${F.queued})`),F.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let G=new AbortController;this.pendingPrompt=G;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),i(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,G.signal)}let F={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.messages],signal:G.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Y)=>{this.mode=this.mapPermissionModeToMode(Y),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Y)=>{return this.requestPermission(Y)}}},X=await g(this.agent.chatStream(W,F,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(Y)=>{switch(Y.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Y.delta}});break;case"tool_start":{let D=Y.toolCall,U=D.function.name;if(U===O)break;let _=this.mapToolKind(Y.toolKind),V=`Executing ${U}`;if(U==="Task"&&"function"in D)try{let N=JSON.parse(D.function.arguments),w=N.resume_from??N.resume;if(typeof w==="string")V=`Resuming ${String(N.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:V,content:[],kind:_});break}case"tool_progress":{let D=Y.toolCall;if(D.function.name===O)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Y.update.message}}]});break}case"tool_result":{let D=Y.toolCall;if(D.function.name===O)break;let U=Y.result,_=[],V=U.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let w of V.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;_.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))_.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let w=D.function.name,YJ=d(m(w,U));_.push({type:"content",content:{type:"text",text:YJ}})}if(D.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))_.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let N=U.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:N,content:_});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Y.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
3
3
  `}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Y.contentKind} r${Y.revision} (${Y.serverName}): +${Y.added.length} -${Y.removed.length} ~${Y.updated.length}
4
4
  `}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Y.revision} (${Y.serverName}): ${Y.uri}
5
5
  `}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Y.revision} (${Y.serverName}): ${Y.phase} ${Y.attempt}/${Y.maxAttempts}
@@ -7,16 +7,16 @@ import{r as A}from"./chunk-d0g4t8fw.js";import{s as zJ}from"./chunk-8h0yxh6y.js"
7
7
  `}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Y.revision} (${Y.serverName}): ${Y.action}${Y.detailsOmitted?" details-omitted":""}
8
8
  `}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Y.revision} ${Y.taskId} (${Y.serverName}/${Y.toolName}): ${Y.status}${Y.hasResult?" result-available":""}
9
9
  `}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Y.files.length}${Y.blockedWrite?" (write retry required)":""}
10
- `}});break;case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let X of Y.messages){if(!X.recovered||X.persisted)continue;for(let B of n(X.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:B})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
10
+ `}});break;case"task_update":this.sendPlanUpdate(Y.tasks);break;case"steering_applied":break;case"follow_up_started":for(let D of Y.messages){if(!D.recovered||D.persisted)continue;for(let U of o(D.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:U})}if(Y.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${Y.recovered} queued instruction${Y.recovered===1?"":"s"} recovered after restart]
11
11
  `}});break;case"goal_updated":if(Y.goal&&Y.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Y.goal.status}: ${Y.goal.objective}]
12
- `}});break;case"goal_continuation_started":break;default:break}});if(this.messages=[...F.messages],!j.success){let Y=j.error?.type??"unknown";throw HJ.internalError({failureType:Y},`Agent turn failed (${Y})`)}if(G.signal.aborted)return{stopReason:"cancelled"};return{stopReason:"end_turn",...j.metadata?.structuredOutput?{_meta:{structuredOutput:j.metadata.structuredOutput,outputSchemaDigest:j.metadata.structuredOutputSchemaDigest}}:{}}}catch(F){if(G.signal.aborted||F instanceof Error&&F.name==="AbortError")return{stopReason:"cancelled"};throw D.error(`[AcpSession ${this.id}] Prompt error:`,F),F}finally{if(this.pendingPrompt===G){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let W,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async($)=>{if(W=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){H+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let G=y($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?jJ($.record):G}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((W)=>{D.error(`[AcpSession ${this.id}] Failed to resume pending input:`,W)})}cancel(){D.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)D.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",W=this.mapModeIdToPermissionMode(Q);await L.setSessionPermissionMode(this.id,this.cwd,W),this.mode=Q,D.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(D.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await L.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((W)=>{D.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await L.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(W){if(!(W instanceof _)&&W.code!=="ENOENT")throw W;await L.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:Z.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,W=async(H)=>{try{await H()}catch(z){Q??=z}};if(await W(()=>this.cancel()),J)await W(()=>J.destroy());if(Z)await W(()=>Z.dispose());if(await W(()=>N.destroySession(this.id)),D.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],W=0,H=0,z=0,$=(F)=>{if(Q.length>0)Q.push({type:"text",text:`
13
- `}),z+=1;if(Q.push(F),F.type==="text")z+=F.text.length};for(let F of J)if(F.type==="text")Z.push(F.text),$({type:"text",text:F.text});else if(F.type==="image"){let j=`data:${F.mimeType};base64,${F.data}`;W+=1,H+=j.length,Z.push(`[Image: ${F.mimeType}]`),$({type:"image_url",image_url:{url:j}})}else if(F.type==="resource"){let j=F.resource;if("text"in j){let Y=`<file path="${j.uri}">
14
- ${j.text}
15
- </file>`;Z.push(Y),$({type:"text",text:Y})}}else if(F.type==="resource_link"){let j=`[Resource: ${F.uri}]`;Z.push(j),$({type:"text",text:j})}if(W>x)throw Error(`ACP prompt contains more than ${x} images`);if(H>k)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>h)throw Error(`ACP prompt text exceeds ${h} characters`);let G=Z.join(`
16
- `);return{content:W>0?Q:G,displayText:G}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{D.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));D.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return D.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return D.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=b(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
12
+ `}});break;case"goal_continuation_started":break;default:break}});if(this.messages=[...F.messages],!X.success){let Y=X.error?.type??"unknown";throw FJ.internalError({failureType:Y},`Agent turn failed (${Y})`)}if(G.signal.aborted)return{stopReason:"cancelled"};let L={...X.metadata?.structuredOutput?{structuredOutput:X.metadata.structuredOutput,outputSchemaDigest:X.metadata.structuredOutputSchemaDigest}:{},...X.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:X.metadata.goalVerificationVerdict,...X.metadata.goalVerifierSessionId?{verifierSessionId:X.metadata.goalVerifierSessionId}:{},...X.metadata.goalVerificationEvidenceSha256?{evidenceSha256:X.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(F){if(G.signal.aborted||F instanceof Error&&F.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,F),F}finally{if(this.pendingPrompt===G){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.schedulePendingResume()}}}async handleUserShellCommand(J){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let Z=J.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let Q=new AbortController;this.pendingUserShell=Q;let W,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async($)=>{if(W=$.executionId,$.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:$.executionId,status:"in_progress",title:`! ${$.command}`,content:[],kind:"execute"});return}if($.type==="output"){H+=$.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.chunk}}]});return}let G=T($.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$.executionId,status:$.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?DJ($.record):G}}]})}});if(this.messages.push({role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}}),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(W)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W,status:"failed",content:[{type:"content",content:{type:"text",text:z instanceof Error?z.message:String(z)}}]});if(Q.signal.aborted)return{stopReason:"cancelled"};throw z}finally{if(this.pendingUserShell===Q)this.pendingUserShell=null}}schedulePendingResume(){if(this.destroyed||this.connection.signal.aborted)return;this.pendingResumeRequested=!0,queueMicrotask(()=>{this.resumePendingIfIdle()})}async resumePendingIfIdle(){if(this.destroyed||this.connection.signal.aborted)return;if(this.pendingPrompt||this.pendingUserShell||!this.runtime||!this.agent)return;let J=this.runtime.getPendingSteeringCount()>0,Q=(J?null:await this.runtime.getGoal())?.status==="active";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((W)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,W)})}cancel(){j.info(`[AcpSession ${this.id}] Cancel requested`),this.pendingResumeRequested=!1;let J=!1;if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,J=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,J=!0;if(!J)j.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",W=this.mapModeIdToPermissionMode(Q);await B.setSessionPermissionMode(this.id,this.cwd,W),this.mode=Q,j.info(`[AcpSession ${this.id}] Mode set to: ${this.mode}`),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})}mapModeToPermissionMode(){return this.mapModeIdToPermissionMode(this.mode)}mapModeIdToPermissionMode(J){switch(J){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(J){switch(this.mode){case"yolo":return!0;case"auto-edit":return J==="readonly"||J==="write";case"plan":return J==="readonly";case"default":default:return!1}}async setModel(J){if(j.info(`[AcpSession ${this.id}] Model set to: ${J}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCurrentModelId();await this.agent.switchModel(J);try{try{await B.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((W)=>{j.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw Q}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(J){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid reasoning effort")}if(Z.selection===J)return;await this.runtime.refresh({reasoningEffort:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:J})}}catch(Q){throw await this.runtime.refresh({reasoningEffort:Z.selection}),Q}}async setServiceTier(J){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid service tier")}if(Z.selection===J)return;await this.runtime.refresh({serviceTier:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:J})}}catch(Q){throw await this.runtime.refresh({serviceTier:Z.selection}),Q}}async setResponseVerbosity(J){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(J)}catch(Q){throw Error(Q instanceof Error?Q.message:"Invalid response verbosity")}if(Z.selection===J)return;await this.runtime.refresh({responseVerbosity:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof q)&&Q.code!=="ENOENT")throw Q;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:J})}}catch(Q){throw await this.runtime.refresh({responseVerbosity:Z.selection}),Q}}async setCommunicationStyle(J){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let Z=this.runtime.getCommunicationStyleConfiguration(),Q=this.runtime.resolveCommunicationStyleConfiguration(J);if(Q.source!=="built-in"&&!Q.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===J)return;await this.runtime.refresh({communicationStyle:J});try{try{await B.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(W){if(!(W instanceof q)&&W.code!=="ENOENT")throw W;await B.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:Z.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let J=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??J.currentModelId,models:J.models.map((Z)=>structuredClone(Z)),modelProviders:structuredClone(J.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}async destroy(){if(this.destroyed)return;if(this.destroyed=!0,this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime;this.agent=null,this.runtime=null;let Q,W=async(H)=>{try{await H()}catch(z){Q??=z}};if(await W(()=>this.cancel()),J)await W(()=>J.destroy());if(Z)await W(()=>Z.dispose());if(await W(()=>P.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],W=0,H=0,z=0,$=(F)=>{if(Q.length>0)Q.push({type:"text",text:`
13
+ `}),z+=1;if(Q.push(F),F.type==="text")z+=F.text.length};for(let F of J)if(F.type==="text")Z.push(F.text),$({type:"text",text:F.text});else if(F.type==="image"){let X=`data:${F.mimeType};base64,${F.data}`;W+=1,H+=X.length,Z.push(`[Image: ${F.mimeType}]`),$({type:"image_url",image_url:{url:X}})}else if(F.type==="resource"){let X=F.resource;if("text"in X){let L=`<file path="${X.uri}">
14
+ ${X.text}
15
+ </file>`;Z.push(L),$({type:"text",text:L})}}else if(F.type==="resource_link"){let X=`[Resource: ${F.uri}]`;Z.push(X),$({type:"text",text:X})}if(W>h)throw Error(`ACP prompt contains more than ${h} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>I)throw Error(`ACP prompt text exceeds ${I} characters`);let G=Z.join(`
16
+ `);return{content:W>0?Q:G,displayText:G}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted}async sendUpdateAndWait(J){if(!this.canSendUpdates())return!1;return await this.connection.sessionUpdate({sessionId:this.id,update:J}),this.canSendUpdates()}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{j.warn(`[AcpSession ${this.id}] Failed to send update:`,Q)})}sendPlanUpdate(J){let Z=J.map((Q)=>({content:Q.subject,priority:Q.priority,status:Q.status}));j.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(J){let Z=this.pendingPrompt?.signal;if(J.type==="askUserQuestion")return this.requestUserQuestions(J,Z);if(J.type==="mcpElicitation")return this.requestMcpElicitation(J,Z);let Q=J.kind?.toLowerCase()||"execute";if(J.type!=="mcpSampling"&&this.shouldAutoApprove(Q))return j.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return j.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=x(),H=[];if(J.message)H.push({type:"content",content:{type:"text",text:J.message}});if(J.details)H.push({type:"content",content:{type:"text",text:J.details}});if(J.risks&&J.risks.length>0)H.push({type:"content",content:{type:"text",text:`Risks:
17
17
  - ${J.risks.join(`
18
- - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:W,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},G=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!G)return{approved:!1,reason:I};let F=G.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let j=F.optionId;if(j==="allow_always")return{approved:!0,scope:"project"};if(j==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let Y=j==="allow_once";return{approved:Y,scope:"once",reason:Y?void 0:"User denied the operation"}}catch(W){return D.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[H,z]of Q.entries()){let $=z.options.map((Y,X)=>`answer:${H}:${X}`),G=`answer:${H}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((Y,X)=>({optionId:$[X],name:Y.label,kind:"allow_once"})),{optionId:G,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:b(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((Y)=>`${Y.label}: ${Y.description}`)].join(`
19
- `)}}]}}),Z);if(!F)return{approved:!1,reason:I};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let j=$.indexOf(F.outcome.optionId);if(j<0)return{approved:!1,reason:"User cancelled the question prompt"};W[z.header]=z.options[j].label}return{approved:!0,answers:W}}catch(H){return D.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
- `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)W[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return D.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),W=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
18
+ - `)}`}});let z=this.mapToolKind(Q),$={sessionId:this.id,options:J.type==="mcpSampling"?[{optionId:"allow_once",name:"Allow this sampling request",kind:"allow_once"},{optionId:"reject_once",name:"Deny",kind:"reject_once"}]:[{optionId:"allow_once",name:"Allow once",kind:"allow_once"},{optionId:"allow_always",name:"Always allow",kind:"allow_always"},{optionId:"reject_once",name:"Deny once",kind:"reject_once"},{optionId:"reject_always",name:"Always deny",kind:"reject_always"}],toolCall:{toolCallId:W,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},G=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!G)return{approved:!1,reason:y};let F=G.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let X=F.optionId;if(X==="allow_always")return{approved:!0,scope:"project"};if(X==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let L=X==="allow_once";return{approved:L,scope:"once",reason:L?void 0:"User denied the operation"}}catch(W){return j.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(J,Z){let Q=J.questions??[];if(Q.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Q.some((H)=>H.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[H,z]of Q.entries()){let $=z.options.map((L,Y)=>`answer:${H}:${Y}`),G=`answer:${H}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((L,Y)=>({optionId:$[Y],name:L.label,kind:"allow_once"})),{optionId:G,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((L)=>`${L.label}: ${L.description}`)].join(`
19
+ `)}}]}}),Z);if(!F)return{approved:!1,reason:y};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let X=$.indexOf(F.outcome.optionId);if(X<0)return{approved:!1,reason:"User cancelled the question prompt"};W[z.header]=z.options[X].label}return{approved:!0,answers:W}}catch(H){return j.warn(`[AcpSession ${this.id}] Question request failed:`,H),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(J,Z){let Q=J.mcpElicitation;if(!Q)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Q.mode==="url"){let H=await this.requestElicitationChoice("MCP external authorization",[Q.message,`Server: ${Q.serverName}`,`Domain: ${Q.domain??"unknown"}`,`URL: ${Q.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
20
+ `),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],Z);if(H==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:H==="decline"?"User declined URL":"User cancelled",elicitation:{action:H==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let H of Q.fields??[]){let z=await this.collectAcpElicitationField(H,Z);if(z.cancelled)return{approved:!1,reason:z.reason,elicitation:{action:"cancel"}};if(z.value!==void 0)W[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return j.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(J,Z){if(J.type==="select"||J.type==="boolean"){let Q=J.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(J.options??[]).map((z,$)=>({id:`option:${$}`,label:z.label,value:z.value})),W=await this.requestElicitationChoice(J.title,[J.description,J.required?"Required":"Optional"].filter(Boolean).join(`
21
21
  `),[...Q.map((z)=>({id:z.id,label:z.label})),...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(W==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===W);if(!H)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:H.value}}if(J.defaultValue!==void 0){let Q=await this.requestElicitationChoice(J.title,[J.description,`ACP cannot collect ${J.type} input. Use the server default: ${String(J.defaultValue)}?`].filter(Boolean).join(`
22
- `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,W){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:b(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),W);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,W)=>{let H=!1,z=(G)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),G()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((G)=>z(()=>Q(G)),(G)=>z(()=>W(G)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var K=O("Agent");class T{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return K.info("[BladeAgent] Initializing ACP connection"),K.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:DJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=JJ("acp"),Q=J.cwd||t(),W=J._meta?.["blade/taskIsolation"],H=W==="local"||W==="worktree"?W:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await zJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,G=$?.metadata.projectPath??Q;K.info(`[BladeAgent] Creating new session: ${Z}`),K.debug(`[BladeAgent] Session cwd: ${G}`);let F=new P(Z,G,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await F.initialize(),this.assertNotDestroyed()}catch(j){throw await F.destroy().catch(()=>{return}),j}return this.sessions.set(Z,F),K.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),F.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,F.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!o.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await L.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!o.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await L.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new P(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(W){throw await Q.destroy().catch(()=>{return}),W}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),K.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),W=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,W);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===W)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await L.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,W]=await Promise.all([L.loadSession(J.sessionId,J.cwd),L.findSessionMetadata(J.sessionId,J.cwd)]);if(!W)throw Error(`Session not found: ${J.sessionId}`);let H=new P(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:W.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],W=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){K.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)K.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else K.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){K.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")K.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&QJ(J.value))K.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&e(J.value))K.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&s(J.value))K.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&ZJ(J.value))K.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await $J.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function tJ(){let J=BJ.toWeb(process.stdout),Z=LJ.toWeb(process.stdin),Q=E.ndJsonStream(J,Z);await new E.AgentSideConnection((H)=>new T(H),Q).closed}export{tJ as runAcpIntegration};
22
+ `),[{id:"default",label:"Use default"},...!J.required?[{id:"skip",label:"Skip"}]:[]],Z);if(Q==="default")return{cancelled:!1,value:J.defaultValue};if(Q==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!J.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${J.type} field "${J.name}"`}}async requestElicitationChoice(J,Z,Q,W){let H=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Q.map((z)=>({optionId:z.id,name:z.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:x(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),W);return H?.outcome.outcome==="selected"?H.outcome.optionId:void 0}async waitForClientInteraction(J,Z){if(!Z)return J;if(Z.aborted)return;return new Promise((Q,W)=>{let H=!1,z=(G)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),G()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((G)=>z(()=>Q(G)),(G)=>z(()=>W(G)))})}mapToolKind(J){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[J||""]||"other"}}var K=E("Agent");class M{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return K.info("[BladeAgent] Initializing ACP connection"),K.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:LJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(J){return}async newSession(J){this.assertNotDestroyed();let Z=QJ("acp"),Q=J.cwd||s(),W=J._meta?.["blade/taskIsolation"],H=W==="local"||W==="worktree"?W:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await WJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,G=$?.metadata.projectPath??Q;K.info(`[BladeAgent] Creating new session: ${Z}`),K.debug(`[BladeAgent] Session cwd: ${G}`);let F=new A(Z,G,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await F.initialize(),this.assertNotDestroyed()}catch(X){throw await F.destroy().catch(()=>{return}),X}return this.sessions.set(Z,F),K.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),F.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,F.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!t.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await B.listSessionPage({cwd:J.cwd??void 0,cursor:J.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Q)=>({sessionId:Q.sessionId,cwd:Q.projectPath,title:Q.title??null,updatedAt:Q.lastMessageTime,_meta:{"blade/taskStatus":Q.taskStatus,...Q.taskStatusReason?{"blade/taskStatusReason":Q.taskStatusReason}:{},...Q.taskFailure?{"blade/taskFailure":Q.taskFailure}:{},...Q.taskStartedAt?{"blade/taskStartedAt":Q.taskStartedAt}:{},...Q.taskCompletedAt?{"blade/taskCompletedAt":Q.taskCompletedAt}:{},...Q.taskModelId?{"blade/taskModelId":Q.taskModelId}:{},...Q.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Q.taskRetriedFrom?{"blade/taskRetriedFrom":Q.taskRetriedFrom}:{},...Q.taskDelivery?{"blade/taskDelivery":Q.taskDelivery}:{},...Q.taskIsolation?{"blade/taskIsolation":Q.taskIsolation}:{},...Q.taskSourceProjectPath?{"blade/taskSourceProjectPath":Q.taskSourceProjectPath}:{},...Q.taskWorktreeBranch?{"blade/taskWorktreeBranch":Q.taskWorktreeBranch}:{},...Q.taskBaseCommit?{"blade/taskBaseCommit":Q.taskBaseCommit}:{},...Q.taskDiffStat?{"blade/taskDiffStat":Q.taskDiffStat}:{},...Q.taskQueuePosition?{"blade/taskQueuePosition":Q.taskQueuePosition}:{},...Q.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Q.taskQueueDepth}:{},...Q.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Q.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(J){if(this.assertNotDestroyed(),!t.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await B.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new A(Z.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Z.messages,permissionMode:Z.metadata.permissionMode,mcpServers:J.mcpServers});try{await Q.initialize(),this.assertNotDestroyed()}catch(W){throw await Q.destroy().catch(()=>{return}),W}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),K.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),W=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,W);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===W)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await B.assertSessionWritable(J.sessionId,J.cwd);let Z=this.sessions.get(J.sessionId);if(Z)try{await Z.destroy()}finally{if(this.sessions.get(J.sessionId)===Z)this.sessions.delete(J.sessionId)}let[Q,W]=await Promise.all([B.loadSession(J.sessionId,J.cwd),B.findSessionMetadata(J.sessionId,J.cwd)]);if(!W)throw Error(`Session not found: ${J.sessionId}`);let H=new A(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:W.permissionMode,mcpServers:J.mcpServers});try{await H.initialize(),await H.replayHistory(),this.assertNotDestroyed()}catch(z){throw await H.destroy().catch(()=>{return}),z}return this.sessions.set(J.sessionId,H),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}buildChildSessionResponse(J,Z,Q){return{sessionId:J,...this.buildSessionSetup(Q,Z?.permissionMode==="autoEdit"?"auto-edit":Z?.permissionMode),...Z?{_meta:{"blade/taskIsolation":Z.taskIsolation,"blade/taskSourceProjectPath":Z.taskSourceProjectPath,"blade/taskProjectPath":Z.projectPath,...Z.taskModelId?{"blade/taskModelId":Z.taskModelId}:{},...Z.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Z.taskRetriedFrom?{"blade/taskRetriedFrom":Z.taskRetriedFrom}:{},...Z.taskDelivery?{"blade/taskDelivery":Z.taskDelivery}:{},...Z.taskWorktreeBranch?{"blade/taskWorktreeBranch":Z.taskWorktreeBranch}:{},...Z.taskBaseCommit?{"blade/taskBaseCommit":Z.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}buildSessionSetup(J,Z="default"){let Q=J?.models??[],W=(J?.currentModelId&&Q.some(($)=>$.id===J.currentModelId)?J.currentModelId:void 0)??Q[0]?.id,H=[{id:"default",name:"Default",description:"Ask for confirmation before all file edits and commands"},{id:"auto-edit",name:"Auto Edit",description:"Auto-approve file edits, ask for shell commands"},{id:"yolo",name:"Full Auto",description:"Auto-approve everything without confirmation"},{id:"plan",name:"Plan Only",description:"Read-only mode, no file changes or commands"}],z=[];if(Q.length>0)z.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:Q.map(($)=>({value:$.id,name:$.displayName??$.model,description:`${J?.modelProviders[$.provider]?.name??$.provider} · ${$.model}`}))});if(J?.reasoning)z.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:J.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${J.reasoning.effective})`},...J.reasoning.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="off"?"Disable model reasoning":`Use ${$} reasoning effort`}))]});if(J?.serviceTier)z.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:J.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...J.serviceTier.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:$==="fast"?"Use the provider priority tier":$==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(J?.responseVerbosity)z.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:J.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...J.responseVerbosity.supported.map(($)=>({value:$,name:$[0].toUpperCase()+$.slice(1),description:`Use ${$} response verbosity`}))]});if(J?.communicationStyle)z.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:J.communicationStyle.selection,options:J.communicationStyle.supported.map(($)=>({value:$.id,name:$.name,description:`${$.description} · ${$.source}`}))});return{modes:{availableModes:H,currentModeId:Z},configOptions:z.length>0?z:void 0}}async prompt(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);return Z.prompt(J)}async cancel(J){K.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)K.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else K.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){K.info(`[BladeAgent] Setting session mode: ${J.modeId}`);let Z=this.sessions.get(J.sessionId);if(Z)await Z.setMode(J.modeId);return{}}async setSessionConfigOption(J){let Z=this.sessions.get(J.sessionId);if(!Z)throw Error(`Session not found: ${J.sessionId}`);if(J.configId==="model"&&"value"in J&&typeof J.value==="string")K.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&ZJ(J.value))K.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&JJ(J.value))K.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&e(J.value))K.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&$J(J.value))K.info(`[BladeAgent] Setting communication style: ${J.value}`),await Z.setCommunicationStyle(J.value);else throw Error(`Invalid session config option: ${J.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}async destroy(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let J;for(let Z of this.sessions.values())try{await Z.destroy()}catch(Q){J??=Q}this.sessions.clear();try{await zJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function sJ(){let J=VJ.toWeb(process.stdout),Z=BJ.toWeb(process.stdin),Q=b.ndJsonStream(J,Z);await new b.AgentSideConnection((H)=>new M(H),Q).closed}export{sJ as runAcpIntegration};
@@ -1,4 +1,4 @@
1
- import{Ee as Zn,Fe as Jn,xe as rn,ye as D,ze as m}from"./chunk-zknv3d6y.js";import{Ge as pn,He as Nn}from"./chunk-6j8wgp2s.js";import{Me as b}from"./chunk-y4c3wwpa.js";import{Oe as Dn,Re as H}from"./chunk-v8pq6qmv.js";import{Ze as fn,_e as En}from"./chunk-6vsszvgg.js";import{cf as P}from"./chunk-w0nscjd2.js";import{mf as un}from"./chunk-66hb7kxm.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((_)=>_.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ot=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),_t=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(on,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(l(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
1
+ import{We as Zn,Xe as Jn}from"./chunk-3aqdjrtm.js";import{Ye as rn,Ze as D,_e as m}from"./chunk-kvx3sb3z.js";import{cf as pn,df as Nn}from"./chunk-f4z3gkbs.js";import{if as b}from"./chunk-5s123nbs.js";import{kf as Dn,nf as H}from"./chunk-s5666ta0.js";import{vf as fn,wf as En}from"./chunk-wnqybbry.js";import{Af as P}from"./chunk-gav4hxcv.js";import{Kf as un}from"./chunk-363pgv1e.js";var Qn=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Wn(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function I(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&Wn(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{I(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function q(n){let t=n.oauth;if(!t)return;let e=t;for(let _ of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[_]!==void 0)throw Error(`MCP OAuth "${_}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(I(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((_)=>_.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let u=t.clientId?.trim();if(u&&u.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let M=t.scopes?.map((_)=>_.trim());if(M){if(M.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(M.some((_)=>!_||_.length>128||!Qn.test(_)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(M).size!==M.length)throw Error("MCP OAuth scopes must not contain duplicates")}let o=t.callbackPort;if(o!==void 0&&(!Number.isInteger(o)||o<1024||o>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,...u?{clientId:u}:{},...M?.length?{scopes:M}:{},...o!==void 0?{callbackPort:o}:{}}}import{randomUUID as J}from"node:crypto";import st from"node:http";import{auth as _n}from"@modelcontextprotocol/sdk/client/auth.js";import St from"open";import{createHash as jn,randomUUID as Fn}from"node:crypto";import{constants as O,promises as A}from"node:fs";import Y from"node:path";import{Mutex as vn}from"async-mutex";import nt from"write-file-atomic";var Mn=1,tt=1048576,et=5000,ut=50,rt=/^[a-f0-9]{64}$/,Mt=m.Object({client_id:m.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ot=m.Object({access_token:m.String({minLength:1,maxLength:65536}),token_type:m.String({minLength:1,maxLength:64}),expires_in:m.Optional(m.Number({minimum:0})),refresh_token:m.Optional(m.String({minLength:1,maxLength:65536})),scope:m.Optional(m.String({maxLength:16384})),id_token:m.Optional(m.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),_t=m.Unsafe({type:"object",properties:{authorizationServerUrl:m.String({format:"uri"}),resourceMetadataUrl:m.Optional(m.String({format:"uri"})),resourceMetadata:m.Optional(m.Unknown()),authorizationServerMetadata:m.Optional(m.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),on=m.Object({serverUrl:m.String({format:"uri"}),clientId:m.Optional(m.String({minLength:1,maxLength:4096})),clientInformation:m.Optional(Mt),tokens:m.Optional(ot),tokenExpiresAt:m.Optional(m.Number({minimum:0})),discoveryState:m.Optional(_t),updatedAt:m.String({format:"date-time"})},{additionalProperties:!1}),tn=m.Object({version:m.Literal(Mn),credentials:m.Record(m.String(),on)},{additionalProperties:!1});function l(n,t){return n instanceof Error&&"code"in n&&n.code===t}function it(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return l(t,"EPERM")}}function V(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!rt.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function y(n){let t=new URL(n);return t.hash="",t.toString()}function Z(n,t,e=[]){return jn("sha256").update(JSON.stringify({serverUrl:y(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class x{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=un()){this.stateRoot=Y.join(n,"mcp"),this.tokenFilePath=Y.join(this.stateRoot,"oauth-credentials.json");let t=x.mutexes.get(this.tokenFilePath);if(!t)t=new vn,x.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let e=(await this.readStore()).credentials[n];return e?V(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let r=e.credentials[n],u=await t(r?V(r):null);if(u)e.credentials[n]=D(on,u);else delete e.credentials[n];return u?V(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return this.mutex.runExclusive(async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return this.mutex.runExclusive(async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),r=await n(e);return await this.writeStore(e),r}finally{await t()}})}async ensureStateRoot(){await A.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await A.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await A.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>tt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await A.readFile(this.tokenFilePath,"utf8")),e=rn(tn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return en(e.data),e.data}catch(n){if(l(n,"ENOENT"))return{version:Mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=D(tn,n);en(t),await nt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
2
2
  `,{mode:384,encoding:"utf8"}),await A.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=Y.join(this.stateRoot,".oauth-credentials.lock"),t=Fn(),e=Date.now()+et;while(Date.now()<e)try{let r=await A.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await r.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
3
3
  `,"utf8"),await r.close(),async()=>{try{if(JSON.parse(await A.readFile(n,"utf8")).token===t)await A.unlink(n)}catch(u){if(!l(u,"ENOENT"))throw u}}}catch(r){if(!l(r,"EEXIST"))throw r;await this.removeDeadLock(n),await new Promise((u)=>setTimeout(u,ut))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await A.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let e=JSON.parse(await A.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!it(e.pid))await A.unlink(n)}}var sn="127.0.0.1",Sn=7777,mn="/oauth/callback",mt=300000;class Q extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class cn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ft(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
4
4
  <html lang="en">
@@ -41,4 +41,4 @@ ${e.map((r)=>` - ${r}`).join(`
41
41
  ]
42
42
  }
43
43
  `)}}function Mu(n,t={}){let e={...n};if(t.debug!==void 0)e.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((u)=>u.id===t.model))throw Error(`模型配置未找到: ${t.model}`);e.currentModelId=t.model}if(t.yolo===!0)e.permissionMode="yolo";else if(t.permissionMode!==void 0)e.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)e.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)e.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)e.maxQueuedTasks=t.maxQueuedTasks;return e.systemPrompt=t.systemPrompt,e.appendSystemPrompt=t.appendSystemPrompt,e.model=t.model,e.resumeSessionId=t.sessionId,e.forkSession=t.forkSession,e.allowedTools=t.allowedTools,e.disallowedTools=t.disallowedTools,e.mcpConfigPaths=t.mcpConfig,e.strictMcpConfig=t.strictMcpConfig,e.addDirs=t.addDir,e.outputFormat=t.outputFormat,e.inputFormat=t.inputFormat,e.print=t.print,e.includePartialMessages=t.includePartialMessages,e.replayUserMessages=t.replayUserMessages,e.agentsConfig=t.agents,e.settingSources=t.settingSources,e}
44
- export{B as Kd,q as Ld,x as Md,Q as Nd,cn as Od,L as Pd,Tn as Qd,se as Rd,K as Sd,fe as Td,Ee as Ud,ce as Vd,wn as Wd,dt as Xd,ae as Yd,xt as Zd,Te as _d,Rn as $d,be as ae,Pe as be,de as ce,xe as de,Le as ee,ln as fe,he as ge,Ce as he,$e as ie,Ie as je,f as ke,w as le,N as me,G as ne,zn as oe,Gn as pe,Hn as qe,qn as re,On as se,Yn as te,C as ue,Mu as ve};
44
+ export{B as ge,q as he,x as ie,Q as je,cn as ke,L as le,Tn as me,se as ne,K as oe,fe as pe,Ee as qe,ce as re,wn as se,dt as te,ae as ue,xt as ve,Te as we,Rn as xe,be as ye,Pe as ze,de as Ae,xe as Be,Le as Ce,ln as De,he as Ee,Ce as Fe,$e as Ge,Ie as He,f as Ie,w as Je,N as Ke,G as Le,zn as Me,Gn as Ne,Hn as Oe,qn as Pe,On as Qe,Yn as Re,C as Se,Mu as Te};
@@ -1,2 +1,2 @@
1
1
  function v(b){switch(b){case"default":case"ignore":case void 0:return"default";case"acceptEdits":return"autoEdit";case"dontAsk":case"bypassPermissions":return"yolo";case"plan":return"plan";default:return"default"}}
2
- export{v as Ad};
2
+ export{v as Yd};
@@ -1,2 +1,2 @@
1
1
  var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
2
- export{f as Se,p as Te,u as Ue,S as Ve,c as We,l as Xe};
2
+ export{f as of,p as pf,u as qf,S as rf,c as sf,l as tf};
@@ -1,4 +1,4 @@
1
- import{wc as W}from"./chunk-8gcg2z3y.js";import{Dd as X}from"./chunk-xa05phpw.js";import{Gd as Q,Id as U}from"./chunk-8gnfj89a.js";import{Me as V}from"./chunk-y4c3wwpa.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
1
+ import{Qc as W}from"./chunk-y56s2qww.js";import{$d as X}from"./chunk-zyf1r2j3.js";import{ce as Q,ee as U}from"./chunk-4dq9y7zn.js";import{if as V}from"./chunk-5s123nbs.js";function _(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var A=U("Service");function $(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class F{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!F.instance)F.instance=new F;return F.instance}initialize(){if(this.initialized){A.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{A.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)A.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else A.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
2
2
  再按一次 Ctrl+C 退出
3
3
  `)}),this.initialized=!0,A.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),A.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),A.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){A.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0,A.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);try{await Q()}catch(z){}try{let z=X.getInstance(),J=W(),N=J.session?.sessionId||"unknown",O=J.session?.workspaceRoot||V();if(z.isEnabled(O,N)){let Z=J.config?.config?.permissionMode||"default";await z.executeSessionEndHooks($(b),{projectDir:O,sessionId:N,permissionMode:Z})}}catch(z){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",z)}let B=5000,Y=new Promise((z,J)=>{setTimeout(()=>{J(Error(`清理超时 (${B}ms)`))},B)});try{let z=this.runCleanupHandlers();await Promise.race([z,Y])}catch(z){console.error("[GracefulShutdown] 清理过程中发生错误:",z)}finally{_(),setTimeout(()=>{process.exit(q)},100)}}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let B=q();if(B instanceof Promise)await B}catch(B){console.error("[GracefulShutdown] 清理函数执行失败:",B)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var K=()=>{return F.getInstance()},P=(b)=>{return K().registerCleanup(b)},L=()=>{K().initialize()},k=(b=0)=>{K().shutdown("normal",b)};
4
- export{K as ec,P as fc,L as gc,k as hc};
4
+ export{K as yc,P as zc,L as Ac,k as Bc};
@@ -1,4 +1,4 @@
1
- import{$a as bn,Za as jt,_a as Xt,ab as Tn,bb as fn}from"./chunk-nymm525r.js";import{Dd as Ut}from"./chunk-xa05phpw.js";import{$d as Mn,Kd as xt,Ld as tn,Md as en,Nd as zt,Od as B,Pd as rn,Qd as gt,Rd as mt,Td as dn,Ud as En,Vd as U,Wd as on,Xd as pn,Yd as cn,Zd as lt,_d as un,ae as wn,ce as S,fe as yn,ge as Ht,he as Bt,ie as R,je as qt}from"./chunk-yfs9tq3y.js";import{xe as X,ze as x}from"./chunk-zknv3d6y.js";import{Me as vt}from"./chunk-y4c3wwpa.js";import{Ze as nn,_e as sn}from"./chunk-6vsszvgg.js";import{of as ss}from"./chunk-954vmnrn.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{$d as Ut}from"./chunk-zyf1r2j3.js";import{Ae as S,De as yn,Ee as Ht,Fe as Bt,Ge as R,He as qt,ge as xt,he as tn,ie as en,je as zt,ke as B,le as rn,me as gt,ne as mt,pe as dn,qe as En,re as U,se as on,te as pn,ue as cn,ve as lt,we as un,xe as Mn,ye as wn}from"./chunk-d600wn06.js";import{Ye as X,_e as x}from"./chunk-kvx3sb3z.js";import{if as vt}from"./chunk-5s123nbs.js";import{vf as nn,wf as sn}from"./chunk-wnqybbry.js";import{Mf as ss}from"./chunk-g11hq0e5.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -0,0 +1,2 @@
1
+ var _=20,T=5242880,A=32000;
2
+ export{_ as cf,T as df,A as ef};
@@ -0,0 +1 @@
1
+ import{Af as a}from"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as WorkspaceTrustService};
@@ -0,0 +1 @@
1
+ import{$c as m,Pc as a,Qc as b,Rc as c,Sc as d,Tc as e,Uc as f,Vc as g,Wc as h,Xc as i,Yc as j,Zc as k,_c as l,ad as n,bd as o,cd as p,dd as q}from"./chunk-y56s2qww.js";import"./chunk-vmq248m7.js";import"./chunk-ybvdac8k.js";import"./chunk-4dq9y7zn.js";import"./chunk-d600wn06.js";import"./chunk-3aqdjrtm.js";import"./chunk-kvx3sb3z.js";import"./chunk-f4z3gkbs.js";import"./chunk-5s123nbs.js";import"./chunk-s5666ta0.js";import"./chunk-dsj62dcg.js";import"./chunk-wnqybbry.js";import"./chunk-gav4hxcv.js";import"./chunk-afkhzdfc.js";import"./chunk-363pgv1e.js";import"./chunk-g11hq0e5.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,2 +1,2 @@
1
1
  import{createRequire as a}from"node:module";var c=a(import.meta.url);
2
- export{c as of};
2
+ export{c as Mf};
@@ -1,2 +1,2 @@
1
- import{C as o}from"./chunk-van4ysq6.js";import{Hb as i}from"./chunk-a8h3fymk.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
1
+ import{C as o}from"./chunk-ggq4y248.js";import{$b as i}from"./chunk-6kwv8ph0.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
2
  export{m as s};
@@ -1,3 +1,3 @@
1
- import{df as y}from"./chunk-33ave20b.js";import{mf as b}from"./chunk-66hb7kxm.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
1
+ import{Bf as y}from"./chunk-afkhzdfc.js";import{Kf as b}from"./chunk-363pgv1e.js";import{createHash as N}from"node:crypto";import{constants as v,promises as d}from"node:fs";import W from"node:os";import a from"node:path";import{Mutex as A}from"async-mutex";import O from"write-file-atomic";var w=1,x=65536,T=1048576,m=100;function p(e){return e!==null&&typeof e==="object"&&!Array.isArray(e)}function k(e,t=2048){return e.length<=t?e:`${e.slice(0,t-1)}…`}function S(e){if(typeof e!=="string"||!e.trim())return;try{let t=new URL(e);return k(`${t.origin}${t.pathname}`)}catch{return k(e)}}function D(e){return Array.isArray(e)?e.filter((t)=>typeof t==="string"):[]}function R(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.type==="string"?r.type:"unknown",n=typeof r.command==="string"?r.command:void 0,o=D(r.args),c=i==="stdio"?k([n,...o].filter(Boolean).join(" ")):S(r.url);return{kind:"mcp",name:`${t} (${i})`,...c?{target:c}:{}}})}function F(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.command==="string"?k(r.command):void 0,n=p(r.extensionToLanguage)?Object.keys(r.extensionToLanguage).slice(0,12).join(", "):"unknown extensions";return{kind:"lsp",name:`${t} (${n})`,...i?{target:i}:{}}})}function j(e){if(!Array.isArray(e))return[];return e.slice(0,m).flatMap((t)=>{if(!p(t))return[];let s=typeof t.id==="string"?t.id:"unnamed",r=typeof t.provider==="string"?t.provider:"unknown",i=typeof t.model==="string"?t.model:"unknown",n=p(t.overrides)?t.overrides:{},o=S(n.baseUrl);return[{kind:"model",name:`${s}: ${r}/${i}`,...o?{target:o}:{}}]})}function $(e){if(!p(e))return[];return Object.entries(e).slice(0,m).map(([t,s])=>{let r=p(s)?s:{},i=typeof r.wireApi==="string"?r.wireApi:"unknown",n=S(r.baseUrl);return{kind:"model",name:`${t} (${i})`,...n?{target:n}:{}}})}function P(e){if(!p(e))return[];let t=[];for(let s of["allow","ask","deny"])for(let r of D(e[s]).slice(0,m))t.push({kind:"permission",name:`${s}: ${k(r,512)}`});return t}function C(e){let t=[...R(e.mcpServers),...F(e.lspServers),...j(e.models),...$(e.modelProviders),...P(e.permissions)];if(p(e.env))for(let s of Object.keys(e.env).slice(0,m))t.push({kind:"environment",name:s});if(typeof e.permissionMode==="string")t.push({kind:"permission",name:`permissionMode: ${e.permissionMode}`});return t}function I(e){return e!=="hooks"&&e!=="disableAllHooks"}function M(e){return N("sha256").update(e).digest("hex")}function L(e,t){let s=a.relative(e,t);return s===""||!s.startsWith(`..${a.sep}`)&&s!==".."&&!a.isAbsolute(s)}class h{storeDir;static instance=null;mutex=new A;statusCache=new Map;constructor(e=a.join(b(),"workspace-trust")){this.storeDir=e}static getInstance(){if(!h.instance)h.instance=new h;return h.instance}static resetInstance(){h.instance=null}async getStatus(e){let t=await y(e),s;try{s=await this.discoverSensitiveSources(t.projectPath)}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:0,sources:[],decision:"undecided",error:u instanceof Error?u.message:"Workspace trust review failed"};return this.cacheStatus(e,g),g}if(s.length===0){let u={...t,state:"not_required",trusted:!0,sensitiveSources:0,sources:s,decision:"undecided"};return this.cacheStatus(e,u),u}let r;try{r=await this.readDecisions()}catch(u){let g={...t,state:"error",trusted:!1,sensitiveSources:s.length,sources:s,decision:"undecided",error:u instanceof Error?u.message:"Workspace trust store is unavailable"};return this.cacheStatus(e,g),g}let i=r.filter((u)=>L(u.path,t.trustRoot)),n=Math.max(-1,...i.map((u)=>u.path.split(a.sep).length)),o=i.filter((u)=>u.path.split(a.sep).length===n),c=o.length>0&&o.every((u)=>u.trusted),f=o[0],l=f?.path===t.trustRoot,E={...t,state:c?"trusted":"untrusted",trusted:c,sensitiveSources:s.length,sources:s,decision:f?l?f.trusted?"trusted":"untrusted":"inherited":"undecided",...f?.decidedAt?{decidedAt:f.decidedAt}:{},...!l&&f?.path?{inheritedFrom:f.path}:{}};return this.cacheStatus(e,E),E}cacheStatus(e,t){this.statusCache.set(a.resolve(e),t),this.statusCache.set(t.projectPath,t)}getCachedStatus(e){return this.statusCache.get(a.resolve(e))}isTrustedCached(e){return this.getCachedStatus(e)?.state==="trusted"}async trust(e){return this.recordDecision(e,!0)}async revoke(e){return this.recordDecision(e,!1)}async recordDecision(e,t){return this.mutex.runExclusive(async()=>{let s=await y(e);await this.assertSafeTrustRoot(s);let r={version:w,path:s.trustRoot,trusted:t,decidedAt:new Date().toISOString()};return await this.writeDecision(r),this.statusCache.clear(),this.getStatus(e)})}async assertSafeTrustRoot(e){let t=a.parse(e.trustRoot).root,s=await d.realpath(W.homedir()).catch(()=>a.resolve(W.homedir()));if(!a.isAbsolute(e.trustRoot)||e.trustRoot===t||e.trustRoot===s)throw Error("Refusing to trust the filesystem root or user home directory")}async discoverSensitiveSources(e){let t=[],s=await this.reviewPackageScripts(e);if(s)t.push(s);for(let[r,i]of[[".blade/config.json","config"],[".blade/settings.json","settings"],[".blade/settings.local.json","settings"]]){let n=await this.reviewConfigFile(e,r,i);if(n)t.push(n)}for(let r of[".blade/plugins",".claude/plugins"]){let i=await this.reviewResourceDirectory(e,r,"plugins","plugin");if(i)t.push(i)}for(let r of[".blade/commands",".claude/commands"]){let i=await this.reviewResourceDirectory(e,r,"commands","command");if(i)t.push(i)}for(let[r,i,n]of[[".blade/skills","skills","skill"],[".claude/skills","skills","skill"],[".blade/agents","agents","agent"],[".claude/agents","agents","agent"]]){let o=await this.reviewResourceDirectory(e,r,i,n);if(o)t.push(o)}for(let r of["CLAUDE.md","AGENTS.md","BLADE.md"]){let i=await this.reviewInstructionFile(e,r);if(i)t.push(i)}return t}async reviewPackageScripts(e){let t=a.join(e,"package.json"),s;try{s=await d.stat(t)}catch(o){if(o.code==="ENOENT")return;throw o}if(!s.isFile())return;if(s.size>T)throw Error("package.json exceeds the 1 MiB workspace review limit");let r;try{r=JSON.parse(await d.readFile(t,"utf8"))}catch{return{path:"package.json",kind:"package",keys:[],effects:[],warning:"Invalid package.json; project scripts will remain blocked"}}if(!p(r)||!p(r.scripts))return;let i=r.scripts,n=Object.keys(i).filter((o)=>typeof i[o]==="string").sort().slice(0,m);if(n.length===0)return;return{path:"package.json",kind:"package",keys:n,effects:n.map((o)=>({kind:"command",name:`package script: ${o}`}))}}async reviewInstructionFile(e,t){try{if(!(await d.stat(a.join(e,t))).isFile())return}catch(s){if(s.code==="ENOENT")return;throw s}return{path:t,kind:"instructions",keys:[t],effects:[{kind:"instruction",name:t}]}}async reviewConfigFile(e,t,s){let r=a.join(e,t),i;try{i=await d.stat(r)}catch(l){if(l.code==="ENOENT")return;throw l}if(!i.isFile())return;if(i.size>T)throw Error(`${t} exceeds the 1 MiB workspace review limit`);let n;try{n=JSON.parse(await d.readFile(r,"utf8"))}catch{return{path:t,kind:s,keys:[],effects:[],warning:"Invalid JSON; the file will remain blocked"}}if(!p(n))return{path:t,kind:s,keys:[],effects:[],warning:"Configuration root is not an object"};let o=Object.keys(n).filter(I).sort();if(o.length===0)return;let c=C(n),f=new Set(["mcpServers","lspServers","models","modelProviders","permissions","env","permissionMode"]);for(let l of o)if(!f.has(l))c.push({kind:"configuration",name:l});return{path:t,kind:s,keys:o,effects:c}}async reviewResourceDirectory(e,t,s,r){let i=a.join(e,t),n;try{n=await d.readdir(i,{withFileTypes:!0})}catch(c){if(c.code==="ENOENT")return;throw c}let o=n.filter((c)=>s==="plugins"||s==="skills"?c.isDirectory()||c.isSymbolicLink():c.isFile()||c.isDirectory()||c.isSymbolicLink()).slice(0,m);if(o.length===0)return;return{path:t,kind:s,keys:o.map((c)=>c.name),effects:o.map((c)=>({kind:r,name:c.name}))}}async readDecisions(){let e;try{e=await d.lstat(this.storeDir)}catch(r){if(r.code==="ENOENT")return[];throw r}if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700");let t=await d.readdir(this.storeDir,{withFileTypes:!0}),s=[];for(let r of t){if(!r.name.endsWith(".json"))continue;if(!r.isFile())throw Error("Workspace trust store entries must be regular files");s.push(await this.readDecision(a.join(this.storeDir,r.name)))}return s}async readDecision(e){let t;try{t=await d.open(e,v.O_RDONLY|v.O_NOFOLLOW)}catch{throw Error("Workspace trust decision must be a regular file")}try{let s=await t.stat();if(!s.isFile()||s.size>x)throw Error("Workspace trust decision is invalid");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600");let r=JSON.parse(await t.readFile("utf8"));if(!p(r)||r.version!==w||typeof r.path!=="string"||!a.isAbsolute(r.path)||typeof r.trusted!=="boolean"||typeof r.decidedAt!=="string"||!Number.isFinite(Date.parse(r.decidedAt))||Object.keys(r).some((i)=>i!=="version"&&i!=="path"&&i!=="trusted"&&i!=="decidedAt"))throw Error("Workspace trust decision schema is invalid");return{version:w,path:r.path,trusted:r.trusted,decidedAt:r.decidedAt}}finally{await t.close()}}async writeDecision(e){await this.ensureStoreDirectoryForWrite();let t=a.join(this.storeDir,`${M(e.path)}.json`);try{let s=await d.lstat(t);if(!s.isFile()||s.isSymbolicLink())throw Error("Workspace trust decision must be a regular file");if(process.getuid&&s.uid!==process.getuid())throw Error("Workspace trust decisions must be owned by the current user");if((s.mode&511)!==384)throw Error("Workspace trust decision permissions must be 0600")}catch(s){if(s.code!=="ENOENT")throw s}await O(t,`${JSON.stringify(e,null,2)}
2
2
  `,{mode:384}),await d.chmod(t,384)}async ensureStoreDirectoryForWrite(){try{let e=await d.lstat(this.storeDir);if(!e.isDirectory()||e.isSymbolicLink())throw Error("Workspace trust store must be a regular directory");if(process.getuid&&e.uid!==process.getuid())throw Error("Workspace trust store must be owned by the current user");if((e.mode&511)!==448)throw Error("Workspace trust store permissions must be 0700")}catch(e){if(e.code!=="ENOENT")throw e;await d.mkdir(this.storeDir,{recursive:!0,mode:448}),await d.chmod(this.storeDir,448)}}}
3
- export{h as cf};
3
+ export{h as Af};