blade-code 0.10.29 → 0.10.30
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.
- package/dist/blade.js +2 -2
- package/dist/{chunk-5jxm20vq.js → chunk-1444wfhr.js} +1 -1
- package/dist/{chunk-xn5zf98b.js → chunk-1sswefqp.js} +1 -1
- package/dist/chunk-2wdmt91f.js +1 -0
- package/dist/{chunk-1p45ytbg.js → chunk-3y97cpzv.js} +1 -1
- package/dist/{chunk-1yyyt228.js → chunk-56hphybe.js} +1 -1
- package/dist/{chunk-bk649qwy.js → chunk-64hndcnj.js} +41 -41
- package/dist/{chunk-js9g83ty.js → chunk-6h9d9ykg.js} +1 -1
- package/dist/{chunk-m9rg16w4.js → chunk-7brnbdq8.js} +1 -1
- package/dist/{chunk-x1p5dmfv.js → chunk-7e7zgzag.js} +1 -1
- package/dist/{chunk-s0txchah.js → chunk-82jdnt03.js} +1 -1
- package/dist/{chunk-k98n1xwg.js → chunk-9mamc250.js} +1 -1
- package/dist/{chunk-66f2fv34.js → chunk-b634n0ts.js} +199 -199
- package/dist/{chunk-0mq1yd3k.js → chunk-btfxa4w8.js} +1 -1
- package/dist/chunk-d38t0wa2.js +6 -0
- package/dist/{chunk-mqezgpcw.js → chunk-e269454y.js} +1 -1
- package/dist/{chunk-fewpzx8s.js → chunk-e3qzedvj.js} +1 -1
- package/dist/{chunk-33wkt12h.js → chunk-f90v5vza.js} +1 -1
- package/dist/{chunk-amm31k3r.js → chunk-fr3kysfm.js} +1 -1
- package/dist/{chunk-c2sxy022.js → chunk-h9c7xec5.js} +1 -1
- package/dist/{chunk-tf9jmrwk.js → chunk-j3k3xdac.js} +1 -1
- package/dist/{chunk-b5btamzc.js → chunk-j7ebts5c.js} +1 -1
- package/dist/{chunk-z9ytq8tq.js → chunk-kk071ywk.js} +2 -2
- package/dist/{chunk-bbfeb6ry.js → chunk-kkpxmhjv.js} +3 -3
- package/dist/chunk-m3epqvpc.js +1 -0
- package/dist/{chunk-qv9xa4h1.js → chunk-m8jen593.js} +1 -1
- package/dist/{chunk-pamjbphm.js → chunk-mbrgz77y.js} +1 -1
- package/dist/{chunk-rfybbxab.js → chunk-n1byt26d.js} +1 -1
- package/dist/chunk-q9ghq6jw.js +204 -0
- package/dist/chunk-qs9wwe8d.js +9 -0
- package/dist/{chunk-q0c3fww1.js → chunk-qv1v32ts.js} +12 -12
- package/dist/{chunk-grt2wftd.js → chunk-rh5g6em4.js} +1 -1
- package/dist/{chunk-0yy41vwq.js → chunk-vx8a7e1j.js} +1 -1
- package/dist/{chunk-h45x1nem.js → chunk-x96czg8t.js} +1 -1
- package/dist/{chunk-fvfwmdp0.js → chunk-x9940mcy.js} +1 -1
- package/dist/{chunk-vz7hpwf0.js → chunk-xh2c6ycd.js} +1 -1
- package/dist/{chunk-v5q235ny.js → chunk-ze8rmhs1.js} +1 -1
- package/dist/web/assets/{ChatView-BtSSERlQ.js → ChatView-CjEyCR8V.js} +3 -3
- package/dist/web/assets/{CodeBlockHighlighter-CAuanOO0.js → CodeBlockHighlighter-DZxXrhQO.js} +1 -1
- package/dist/web/assets/{FilePreview-BKQ-EBj3.js → FilePreview-8fbolCzV.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BdYjJ_NM.js → MarkdownRenderer-Bfm5TG2z.js} +3 -3
- package/dist/web/assets/{SettingsModal-CB6hM8fT.js → SettingsModal-KATzS3Iy.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-sSD4B7C_.js → TaskSwitcher-BrfN6F0-.js} +1 -1
- package/dist/web/assets/{TerminalPanel-ZnEoQU6o.js → TerminalPanel-sbqhmFcK.js} +1 -1
- package/dist/web/assets/{index-DtOztVFd.js → index-xB4mFHWl.js} +3 -3
- package/dist/web/index.html +1 -1
- package/package.json +1 -1
- package/dist/chunk-5dt6199b.js +0 -1
- package/dist/chunk-5x26t0c4.js +0 -204
- package/dist/chunk-qgp7sqh2.js +0 -1
- package/dist/chunk-wxzsnptj.js +0 -6
- package/dist/chunk-zx8ktpc4.js +0 -9
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import{m as R,n as c,o as g,p as d,q as m,r as l}from"./chunk-n1byt26d.js";import{G as M,M as y}from"./chunk-b634n0ts.js";import"./chunk-1sswefqp.js";import"./chunk-1zpqxjj7.js";import{ab as h,jb as A}from"./chunk-q9ghq6jw.js";import"./chunk-ej1z75jf.js";import{ac as w,oc as U}from"./chunk-x9940mcy.js";import"./chunk-4djps7bz.js";import"./chunk-rezjy4mp.js";import{Kc as C}from"./chunk-btfxa4w8.js";import{Mc as I,Nc as S,Oc as v}from"./chunk-1444wfhr.js";import{Pc as O}from"./chunk-48tz6s0s.js";import"./chunk-d9gthet1.js";import{kd as P}from"./chunk-mbrgz77y.js";import"./chunk-v508x7cg.js";import"./chunk-6kc12pma.js";import"./chunk-4qtb8yf6.js";import"./chunk-4p9cwr9s.js";import"./chunk-vz0zsct0.js";import"./chunk-rh5g6em4.js";import"./chunk-9mamc250.js";import"./chunk-0prp87ys.js";import"./chunk-9pww3s5m.js";import"./chunk-0rwz7tm0.js";import"./chunk-m8jen593.js";import"./chunk-s3zfyy7r.js";import"./chunk-vx8a7e1j.js";import{nf as F}from"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import{Af as z}from"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";import p from"yargs";import{hideBin as e}from"yargs/helpers";var s=new Set(Object.values(F));function t(j){if(j&&s.has(j))return j;return}function x(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
|
+
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
|
+
`);else j.io.stdout.write(`${j.response}
|
|
4
|
+
`)}function i(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await n(B);process.exit(q)})}async function n(j,B=process){let q;try{await R();let _=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await g({message:j.message,_:j._}):await c({message:j.message,_:j._,defaultMessage:"Hello"}),J=_===void 0,T=J?{mode:"agent",content:""}:await d(_);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
5
|
+
`);return T.exitCode??0}let K=T.content,V=await m(j),W=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(W!==void 0&&V)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:H,messages:a,metadata:D}=await l({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),X=D?.projectPath??z(),$=t(j.permissionMode)??D?.permissionMode??P()?.permissionMode??"default";await U.setSessionPermissionMode(H,X,$);let E=await A.cancelPendingNonInteractive(X,H)?await U.loadSessionModelContext(H,X):a;q=await M.create({sessionId:H,workspaceRoot:X,modelId:j.model,permissionMode:$,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?O(j.agents):void 0,...E.length>0?{sessionStart:{isResume:!0,resumeSessionId:H}}:{}});let b=J&&q.getPendingSteeringCount()>0,G=J&&!b?await q.getGoal():null,f=G?.status==="active"||G?.status==="verifying",L=J&&!b&&!f?await q.getRecoveredFinalResponse():void 0;if(J&&!b&&!f){if(!L)throw Error("No unfinished turn or active goal to resume");return x({io:B,options:j,response:L.content,requestInput:K,structuredOutput:L.structuredOutput,structuredOutputSchemaDigest:L.structuredOutputSchemaDigest}),0}if(W!==void 0){let Q=await q.executeUserShellCommand(W);if(j.outputFormat==="json")B.stdout.write(`${JSON.stringify(Q,null,2)}
|
|
6
|
+
`);else if(j.outputFormat==="stream-json")B.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:Q.executionId,record:Q.record})}
|
|
7
|
+
`);else B.stdout.write(`${w(Q.record)}
|
|
8
|
+
`);return Q.record.status==="completed"?0:Q.record.status==="aborted"?130:Q.record.exitCode??1}let N=await y.createWithRuntime(q,{sessionId:H,systemPrompt:j.systemPrompt,appendSystemPrompt:j.appendSystemPrompt,maxTurns:j.maxTurns,modelId:j.model,permissionMode:$,toolWhitelist:j.allowedTools,toolBlacklist:j.disallowedTools,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig}),k={messages:[...E],userId:"cli-user",sessionId:H,workspaceRoot:X,permissionMode:$},Y=await h(V||J?N.chatStream(K,k,{...V?{outputSchema:V}:{},pendingInputOnly:b,goalContinuationOnly:f}):N.chatStream(K,k));if(!Y.success)throw Error(Y.error?.message??"Agent execution failed");let r=Y.finalMessage||"",u=Y.metadata?.structuredOutput;return x({io:B,options:j,response:r,requestInput:K,structuredOutput:u,structuredOutputSchemaDigest:Y.metadata?.structuredOutputSchemaDigest}),0}catch(Z){return B.stderr.write(`Error: ${Z instanceof Error?Z.message:"未知错误"}
|
|
9
|
+
`),1}finally{await q?.dispose()}}async function _j(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":Z,"include-partial-messages":_,"input-format":J,"system-prompt":T,"append-system-prompt":K,"max-turns":V,...W}=C,H=p(e(process.argv)).scriptName("blade").strict(!1).options(W).middleware([S,I,v]);return i(H),await H.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{n as runPrint,_j as handlePrintMode};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{s as E}from"./chunk-
|
|
2
|
-
`)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}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 a.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(j.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),j.debug(`[AcpSession ${this.id}] ACP service context initialized`),await d.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?BJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await l.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 F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(G)=>$.onOutput?.("stdout",G)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.failureKind==="timeout",aborted:F.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await n(this.cwd),j.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=v.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"||H?.status==="verifying")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 LJ(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.contextMessages],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 F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=!1,X,B=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},L=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(G)B(W);else X=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),G=!0,X)B(X);return L}},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($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,G)},complete:async($,F,G)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,G)},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let G=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),X=await G.completion,B=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===G.reviewId);if(!B)throw Error(`Review not found: ${G.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:G.reviewId,status:X.status,findings:X.findings.length,content:f(B.start,X)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,G)=>{let X=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(G);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:X,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:B})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await t(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.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=s(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=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(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),j.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){j.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((G)=>G.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=p(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 G=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!G.accepted)throw Error(G.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 (${G.queued})`),G.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(j.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),o(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let G={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},X=await m(this.agent.chatStream(Y,G,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,q=w.function.name;if(q===R)break;let N=this.mapToolKind(W.toolKind),V=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:N});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let q=W.result,N=[],V=q.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;N.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))N.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,GJ=r(g(i(K,q),u));N.push({type:"content",content:{type:"text",text:GJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:N});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
1
|
+
import{s as E}from"./chunk-h9c7xec5.js";import{t as FJ}from"./chunk-e3qzedvj.js";import{$ as o,G as l,J as i,K as r,M as a,_ as n,aa as t,ba as s,w as A}from"./chunk-b634n0ts.js";import{la as HJ}from"./chunk-1sswefqp.js";import"./chunk-1zpqxjj7.js";import{Na as v,ab as m,jb as d}from"./chunk-q9ghq6jw.js";import{rb as T}from"./chunk-ej1z75jf.js";import{Kb as f,Rb as u,Ub as g,ac as M,bc as c,dc as R,gc as p,lc as _,oc as D}from"./chunk-x9940mcy.js";import"./chunk-4djps7bz.js";import"./chunk-rezjy4mp.js";import"./chunk-d9gthet1.js";import"./chunk-mbrgz77y.js";import"./chunk-v508x7cg.js";import{wd as zJ}from"./chunk-6kc12pma.js";import"./chunk-4qtb8yf6.js";import"./chunk-4p9cwr9s.js";import{Hd as WJ}from"./chunk-vz0zsct0.js";import"./chunk-rh5g6em4.js";import"./chunk-9mamc250.js";import"./chunk-0prp87ys.js";import{me as YJ}from"./chunk-9pww3s5m.js";import"./chunk-0rwz7tm0.js";import"./chunk-m8jen593.js";import"./chunk-s3zfyy7r.js";import"./chunk-vx8a7e1j.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import{uf as I,vf as S,wf as y}from"./chunk-s6rdv601.js";import{Af as QJ}from"./chunk-1ggxyyar.js";import{Ef as b}from"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import{Lf as ZJ,Of as $J}from"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";import{Readable as KJ,Writable as UJ}from"node:stream";import*as x from"@agentclientprotocol/sdk";import{PROTOCOL_VERSION as wJ}from"@agentclientprotocol/sdk";import JJ from"node:path";import{RequestError as GJ}from"@agentclientprotocol/sdk";import{nanoid as h}from"nanoid";var G=b("Agent");function C(J){if(!J)return{};return Object.fromEntries(J.map((Z)=>[Z.name,Z.value]))}function DJ(J){if("command"in J)return{type:"stdio",command:J.command,args:J.args,env:C(J.env)};if("url"in J)return{type:J.type,url:J.url,headers:C("headers"in J?J.headers:void 0)};return null}function BJ(J){let Z={};for(let Q of J){let Y=DJ(Q);if(Y)Z[Q.name]=Y}return Z}function e(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,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Q);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function LJ(J){let Z=c(J.metadata);return Z?[{type:"text",text:M(Z)}]:e(J.content)}function VJ(J){return[`Status: ${J.status}`,`Exit code: ${J.exitCode??"null"}`,`Duration: ${(J.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}class O{id;cwd;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingUserShell=null;pendingResumeRequested=!1;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;messages;contextMessages;mode;constructor(J,Z,Q,Y,H={}){this.id=J;this.cwd=Z;this.connection=Q;this.clientCapabilities=Y;this.options=H;this.messages=[...H.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(H.permissionMode)}async refreshPersistedMessages(){let[J,Z]=await Promise.all([D.loadSession(this.id,this.cwd),D.loadSessionModelContext(this.id,this.cwd)]);if(J.length>0)this.messages=J;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(J){let Z=await D.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...J]}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 a.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(G.debug(`[AcpSession ${this.id}] Initializing...`),await D.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),A.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd),G.debug(`[AcpSession ${this.id}] ACP service context initialized`),await d.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(z)=>this.requestPermission(z)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?BJ(this.options.mcpServers):void 0,Q=A.getInstance().getTerminalService(this.id);if(this.runtime=await l.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 F=await Q.execute(z,{cwd:$.cwd,env:$.env,timeout:$.timeoutMs,signal:$.signal,allowLocalFallback:!1,onOutput:(X)=>$.onOutput?.("stdout",X)});return{exitCode:F.exitCode,stdout:F.stdout,stderr:F.stderr,...F.error?{error:F.error}:{},timedOut:F.failureKind==="timeout",aborted:F.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await E.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await o(this.cwd),G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=v.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"||H?.status==="verifying")if(this.options.initialMessages===void 0)this.schedulePendingResume();else this.pendingResumeRequested=!0}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;let Q=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!Q)continue;for(let Y of LJ(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Q,content:Y}))return}}let J=await this.runtime?.getGoal();if(J&&!await this.sendUpdateAndWait(this.goalSessionUpdate(J)))return;if(this.pendingResumeRequested)this.schedulePendingResume()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(J,Z){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${J}`);let Q={cwd:this.cwd,surface:"acp",workspaceRoot:this.cwd,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async($)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await this.runtime.rewindSession($);return this.messages=[...F.messages],this.contextMessages=await this.loadModelContextOr(F.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),F}},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=!1,j,B=(W)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:W.id,status:W.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:W.result?.message||W.result?.error||`Subagent ${W.status}`}}]})},L=this.runtime.resumeSubagent({agentId:$,prompt:F,onCompleted:(W)=>{if(X)B(W);else j=W}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.session.id,status:"in_progress",title:`Resuming ${L.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${L.source.id} at depth ${L.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),X=!0,j)B(j);return L}},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($,F,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt($,F,X)},complete:async($,F,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument($,F,X)},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($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask($,F)},getLogs:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs($,F)},setLoggingLevel:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel($,F)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},codeReview:{run:async($,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await E.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:$,signal:F,onEvent:(L)=>{if(L.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.toolCall.id,status:"in_progress",title:`Review: ${L.toolCall.function.name}`,content:[],kind:this.mapToolKind(L.toolKind)});else if(L.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.toolCall.id,status:L.result.success?"completed":"failed",content:[]})}}),j=await X.completion,B=(await E.list(this.cwd,this.id)).find((L)=>L.start.reviewId===X.reviewId);if(!B)throw Error(`Review not found: ${X.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:X.reviewId,status:j.status,findings:j.findings.length,content:f(B.start,j)}}},signal:Z,acp:{sendMessage:($)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}})},sendToolStart:($,F,X)=>{let j=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(X);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j,status:"in_progress",title:`${$}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(F,null,2)}}],kind:B})},sendToolResult:($,F)=>{if(F.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:F.summary}})}}},Y=await t(J,Q),H=Y.data?.action;if(H==="start_goal"||H==="resume_goal")this.schedulePendingResume();if(H==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let $=await D.loadSession(this.id,this.cwd);if($.length>0)this.messages=$}let z=Y.content||Y.message;if(z)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:z}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return{stopReason:Y.success?"end_turn":"cancelled"}}catch(Q){return G.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=s(this.cwd),Z=["model","permissions","theme","config","exit","ide"],Y=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}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((H)=>H.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(J){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,J)}}async prompt(J,Z={}){if(A.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Q=this.resolvePrompt(J.prompt),Y=Q.content,H=Q.displayText,z=J._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((X)=>X.outputSchema)?.outputSchema:void 0),$;if(z!==void 0)$=p(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 X=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!X.accepted)throw Error(X.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${X.queued})`),X.delivery==="next_turn")this.schedulePendingResume();return{stopReason:"end_turn"}}let F=new AbortController;this.pendingPrompt=F;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${H.slice(0,100)}...`),n(H)){if($)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(H,F.signal)}let X={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(W)=>{this.mode=this.mapPermissionModeToMode(W),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(W)=>{return this.requestPermission(W)}}},j=await m(this.agent.chatStream(Y,X,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:$}),async(W)=>{switch(W.kind){case"content_delta":if($)break;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.delta}});break;case"thinking_delta":this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:W.delta}});break;case"tool_start":{let w=W.toolCall,q=w.function.name;if(q===R)break;let N=this.mapToolKind(W.toolKind),V=`Executing ${q}`;if(q==="Task"&&"function"in w)try{let P=JSON.parse(w.function.arguments),K=P.resume_from??P.resume;if(typeof K==="string")V=`Resuming ${String(P.subagent_type||"subagent")} from ${K}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:w.id,status:"in_progress",title:V,content:[],kind:N});break}case"tool_progress":{let w=W.toolCall;if(w.function.name===R)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:W.update.message}}]});break}case"tool_result":{let w=W.toolCall;if(w.function.name===R)break;let q=W.result,N=[],V=q.metadata;if(V?.kind==="patch"&&Array.isArray(V.changes))for(let K of V.changes){if(!K||typeof K!=="object"||!("path"in K)||typeof K.path!=="string")continue;N.push({type:"diff",path:K.path,oldText:"oldContent"in K&&typeof K.oldContent==="string"?K.oldContent:null,newText:"newContent"in K&&typeof K.newContent==="string"?K.newContent:null})}else if(V?.kind==="edit"&&typeof V.file_path==="string"&&typeof V.oldContent==="string"&&(typeof V.newContent==="string"||V.newContent===void 0))N.push({type:"diff",path:V.file_path,oldText:V.oldContent,newText:V.newContent??null});else{let K=w.function.name,XJ=r(g(i(K,q),u));N.push({type:"content",content:{type:"text",text:XJ}})}if(w.function.name==="Task"&&(V?.verificationVerdict==="pass"||V?.verificationVerdict==="fail"||V?.verificationVerdict==="partial"))N.unshift({type:"content",content:{type:"text",text:`Verification result: ${V.verificationVerdict.toUpperCase()}`}});let P=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:w.id,status:P,content:N});break}case"structured_output":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(W.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${W.contentKind} r${W.revision} (${W.serverName}): +${W.added.length} -${W.removed.length} ~${W.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${W.revision} (${W.serverName}): ${W.uri}
|
|
5
5
|
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${W.revision} (${W.serverName}): ${W.phase} ${W.attempt}/${W.maxAttempts}
|
|
@@ -8,15 +8,15 @@ import{s as E}from"./chunk-c2sxy022.js";import{t as FJ}from"./chunk-fewpzx8s.js"
|
|
|
8
8
|
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${W.revision} ${W.taskId} (${W.serverName}/${W.toolName}): ${W.status}${W.hasResult?" result-available":""}
|
|
9
9
|
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${W.files.length}${W.blockedWrite?" (write retry required)":""}
|
|
10
10
|
`}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:W.phase,attempt:W.attempt,maxRetries:W.maxRetries,reason:W.reason,...W.statusCode!==void 0?{statusCode:W.statusCode}:{},...W.delayMs!==void 0?{delayMs:W.delayMs}:{},...W.nextRetryAt!==void 0?{nextRetryAt:W.nextRetryAt}:{}}}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:W.phase,stallCount:W.stallCount,durationMs:W.durationMs,warningAfterMs:W.warningAfterMs,timeoutMs:W.timeoutMs,outputStarted:W.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:W.phase,toolName:W.toolName,runLength:W.runLength,nudgeThreshold:W.nudgeThreshold,haltThreshold:W.haltThreshold,progressAware:W.progressAware}}});break;case"task_update":this.sendPlanUpdate(W.tasks);break;case"steering_applied":break;case"follow_up_started":for(let w of W.messages){if(!w.recovered||w.persisted)continue;for(let q of e(w.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q})}if(W.recovered>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${W.recovered} queued instruction${W.recovered===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break;case"goal_updated":if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:W.phase,...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}}}});break;default:break}});this.contextMessages=[...G.messages];let B=await D.loadSession(this.id,this.cwd);if(this.messages=B.length>0?B:[...G.messages],!X.success){let W=X.error?.type??"unknown";throw jJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(F.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(G){if(F.signal.aborted||G instanceof Error&&G.name==="AbortError")return{stopReason:"cancelled"};throw j.error(`[AcpSession ${this.id}] Prompt error:`,G),G}finally{if(this.pendingPrompt===F){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 Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(F)=>{if(Y=F.executionId,F.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.executionId,status:"in_progress",title:`! ${F.command}`,content:[],kind:"execute"});return}if(F.type==="output"){H+=F.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:F.chunk}}]});return}let G=M(F.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:F.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?VJ(F.record):G}}]})}}),$={role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}};if(this.messages.push($),this.contextMessages.push($),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,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,Z=J?null:await this.runtime.getGoal(),Q=Z?.status==="active"||Z?.status==="verifying";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}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",Y=this.mapModeIdToPermissionMode(Q);await D.setSessionPermissionMode(this.id,this.cwd,Y),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 D.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{j.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});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 D.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.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 D.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.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 D.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.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 D.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof _)&&Y.code!=="ENOENT")throw Y;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}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,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>A.destroySession(this.id)),j.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(G)=>{if(Q.length>0)Q.push({type:"text",text:`
|
|
13
|
-
`}),z+=1;if(Q.push(
|
|
14
|
-
${
|
|
15
|
-
</file>`;Z.push(B),$({type:"text",text:B})}}else if(
|
|
16
|
-
`);return{content:Y>0?Q:F,displayText:F}}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)=>{
|
|
11
|
+
`}});break;case"goal_updated":if(W.goal)this.sendUpdate(this.goalSessionUpdate(W.goal));if(W.goal&&W.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${W.goal.status}: ${W.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:W.phase,...W.reason?{reason:W.reason}:{},...W.strategy?{strategy:W.strategy}:{},...W.outcome?{outcome:W.outcome}:{},...W.preTokens!==void 0?{preTokens:W.preTokens}:{},...W.postTokens!==void 0?{postTokens:W.postTokens}:{}}}});break;default:break}});this.contextMessages=[...X.messages];let B=await D.loadSession(this.id,this.cwd);if(this.messages=B.length>0?B:[...X.messages],!j.success){let W=j.error?.type??"unknown";throw GJ.internalError({failureType:W},`Agent turn failed (${W})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let L={...j.metadata?.structuredOutput?{structuredOutput:j.metadata.structuredOutput,outputSchemaDigest:j.metadata.structuredOutputSchemaDigest}:{},...j.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:j.metadata.goalVerificationVerdict,...j.metadata.goalVerifierSessionId?{verifierSessionId:j.metadata.goalVerifierSessionId}:{},...j.metadata.goalVerificationEvidenceSha256?{evidenceSha256:j.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(L).length>0?{_meta:L}:{}}}catch(X){if(F.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw G.error(`[AcpSession ${this.id}] Prompt error:`,X),X}finally{if(this.pendingPrompt===F){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 Y,H="";try{let z=await this.runtime.executeUserShellCommand(Z,{signal:Q.signal,onEvent:async(F)=>{if(Y=F.executionId,F.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:F.executionId,status:"in_progress",title:`! ${F.command}`,content:[],kind:"execute"});return}if(F.type==="output"){H+=F.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:F.chunk}}]});return}let X=M(F.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:F.executionId,status:F.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:H?VJ(F.record):X}}]})}}),$={role:"user",content:z.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(z.record))}};if(this.messages.push($),this.contextMessages.push($),z.delivery==="next_turn")this.schedulePendingResume();return{stopReason:z.record.status==="aborted"?"cancelled":"end_turn"}}catch(z){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,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,Z=J?null:await this.runtime.getGoal(),Q=Z?.status==="active"||Z?.status==="verifying";if(!J&&!Q){this.pendingResumeRequested=!1;return}this.pendingResumeRequested=!1,await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:J,goalContinuationOnly:Q}).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to resume pending input:`,Y)})}cancel(){G.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)G.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(J){let Q=["default","auto-edit","yolo","plan"].includes(J)?J:"default",Y=this.mapModeIdToPermissionMode(Q);await D.setSessionPermissionMode(this.id,this.cwd,Y),this.mode=Q,G.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(G.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 D.updateSessionMetadata(this.id,this.cwd,{selectedModelId:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:J})}}catch(Q){if(Z&&Z!==J)await this.agent.switchModel(Z).catch((Y)=>{G.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});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 D.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.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 D.updateSessionMetadata(this.id,this.cwd,{serviceTier:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.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 D.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:J})}catch(Q){if(!(Q instanceof _)&&Q.code!=="ENOENT")throw Q;await D.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 D.updateSessionMetadata(this.id,this.cwd,{communicationStyle:J,communicationStyleDigest:Q.source==="built-in"?null:Q.contentSha256})}catch(Y){if(!(Y instanceof _)&&Y.code!=="ENOENT")throw Y;await D.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:J,...Q.source!=="built-in"&&Q.contentSha256?{communicationStyleDigest:Q.contentSha256}:{}})}}catch(Y){throw await this.runtime.refresh({communicationStyle:Z.selection}),Y}}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,Y=async(H)=>{try{await H()}catch(z){Q??=z}};if(await Y(()=>this.cancel()),J)await Y(()=>J.destroy());if(Z)await Y(()=>Z.dispose());if(await Y(()=>A.destroySession(this.id)),G.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(J){let Z=[],Q=[],Y=0,H=0,z=0,$=(X)=>{if(Q.length>0)Q.push({type:"text",text:`
|
|
13
|
+
`}),z+=1;if(Q.push(X),X.type==="text")z+=X.text.length};for(let X of J)if(X.type==="text")Z.push(X.text),$({type:"text",text:X.text});else if(X.type==="image"){let j=`data:${X.mimeType};base64,${X.data}`;Y+=1,H+=j.length,Z.push(`[Image: ${X.mimeType}]`),$({type:"image_url",image_url:{url:j}})}else if(X.type==="resource"){let j=X.resource;if("text"in j){let B=`<file path="${j.uri}">
|
|
14
|
+
${j.text}
|
|
15
|
+
</file>`;Z.push(B),$({type:"text",text:B})}}else if(X.type==="resource_link"){let j=`[Resource: ${X.uri}]`;Z.push(j),$({type:"text",text:j})}if(Y>I)throw Error(`ACP prompt contains more than ${I} images`);if(H>S)throw Error("ACP prompt images exceed the 5 MiB limit");if(z>y)throw Error(`ACP prompt text exceeds ${y} characters`);let F=Z.join(`
|
|
16
|
+
`);return{content:Y>0?Q:F,displayText:F}}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()}goalSessionUpdate(J){return{sessionUpdate:"session_info_update",updatedAt:J.updatedAt,_meta:{"blade/goal":{goalId:J.goalId,status:J.status,verificationAttempt:J.completionVerification?.attempt,verificationStatus:J.completionVerification?.status,verifierSessionId:J.completionVerification?.verifierSessionId,verificationEvidenceSha256:J.completionVerification?.evidenceSha256}}}}sendUpdate(J){if(!this.canSendUpdates())return;let Z={sessionId:this.id,update:J};this.connection.sessionUpdate(Z).catch((Q)=>{G.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}));G.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 G.debug(`[AcpSession ${this.id}] Auto-approving ${Q} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Q==="write"||Q==="execute"))return G.debug(`[AcpSession ${this.id}] Rejecting ${Q} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=h(),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:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},F=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!F)return{approved:!1,reason:T};let
|
|
19
|
-
`)}}]}}),Z);if(!
|
|
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 Y=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)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return
|
|
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:Y,status:"pending",title:J.title||"Permission Required",content:H,kind:z}},F=await this.waitForClientInteraction(this.connection.requestPermission($),Z);if(!F)return{approved:!1,reason:T};let X=F.outcome;if(X.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let j=X.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 B=j==="allow_once";return{approved:B,scope:"once",reason:B?void 0:"User denied the operation"}}catch(Y){return G.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{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 Y={};try{for(let[H,z]of Q.entries()){let $=z.options.map((B,L)=>`answer:${H}:${L}`),F=`answer:${H}:cancel`,X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...z.options.map((B,L)=>({optionId:$[L],name:B.label,kind:"allow_once"})),{optionId:F,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:h(),status:"pending",title:z.header,kind:"think",content:[{type:"content",content:{type:"text",text:[z.question,...z.options.map((B)=>`${B.label}: ${B.description}`)].join(`
|
|
19
|
+
`)}}]}}),Z);if(!X)return{approved:!1,reason:T};if(X.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let j=$.indexOf(X.outcome.optionId);if(j<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[z.header]=z.options[j].label}return{approved:!0,answers:Y}}catch(H){return G.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 Y=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)Y[H.name]=z.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return G.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{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})),Y=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(Y==="skip")return{cancelled:!1};let H=Q.find((z)=>z.id===Y);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,Y){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:h(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);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,Y)=>{let H=!1,z=(F)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),F()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((F)=>z(()=>Q(F)),(F)=>z(()=>Y(F)))})}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 U=b("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:wJ,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=zJ("acp"),Q=J.cwd||QJ(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await FJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,F=$?.metadata.projectPath??Q;U.info(`[BladeAgent] Creating new session: ${Z}`),U.debug(`[BladeAgent] Session cwd: ${F}`);let G=new O(Z,F,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await G.initialize(),this.assertNotDestroyed()}catch(X){throw await G.destroy().catch(()=>{return}),X}return this.sessions.set(Z,G),U.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),G.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,G.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!JJ.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await D.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(),!JJ.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await D.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new O(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(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),U.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await D.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,Y]=await Promise.all([D.loadSession(J.sessionId,J.cwd),D.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new O(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.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??[],Y=(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:Y,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){U.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)U.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){U.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")U.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&WJ(J.value))U.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&$J(J.value))U.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&ZJ(J.value))U.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&YJ(J.value))U.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 HJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function ZQ(){let J=UJ.toWeb(process.stdout),Z=KJ.toWeb(process.stdin),Q=x.ndJsonStream(J,Z);await new x.AgentSideConnection((H)=>new k(H),Q).closed}export{ZQ 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,Y){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:h(),status:"pending",title:J,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),Y);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,Y)=>{let H=!1,z=(F)=>{if(H)return;H=!0,Z.removeEventListener("abort",$),F()},$=()=>z(()=>Q(void 0));if(Z.addEventListener("abort",$,{once:!0}),Z.aborted)$();J.then((F)=>z(()=>Q(F)),(F)=>z(()=>Y(F)))})}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 U=b("Agent");class k{connection;sessions=new Map;sessionLoadQueues=new Map;clientCapabilities;destroyed=!1;constructor(J){this.connection=J}async initialize(J){return U.info("[BladeAgent] Initializing ACP connection"),U.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(J.clientCapabilities)}`),this.clientCapabilities=J.clientCapabilities,{protocolVersion:wJ,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=zJ("acp"),Q=J.cwd||QJ(),Y=J._meta?.["blade/taskIsolation"],H=Y==="local"||Y==="worktree"?Y:void 0,z=J._meta?.["blade/taskPrompt"],$=H?await FJ.createSessionTask({sessionId:Z,prompt:typeof z==="string"&&z.trim()?z:"ACP task session",sourceProjectPath:Q,isolation:H}):void 0,F=$?.metadata.projectPath??Q;U.info(`[BladeAgent] Creating new session: ${Z}`),U.debug(`[BladeAgent] Session cwd: ${F}`);let X=new O(Z,F,this.connection,this.clientCapabilities,{mcpServers:J.mcpServers,...$?.taskWorktree?{taskWorktree:$.taskWorktree}:{},...$?.metadata.taskIsolation?{taskIsolation:$.metadata.taskIsolation}:{}});try{await X.initialize(),this.assertNotDestroyed()}catch(j){throw await X.destroy().catch(()=>{return}),j}return this.sessions.set(Z,X),U.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),X.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,$?.metadata,X.getModelConfiguration())}async listSessions(J){if(J.cwd!=null&&!JJ.isAbsolute(J.cwd))throw Error("ACP session list cwd must be absolute");let Z=await D.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(),!JJ.isAbsolute(J.cwd))throw Error("ACP session fork cwd must be absolute");let Z=await D.forkSession(J.sessionId,{sourceProjectPath:J.cwd,targetProjectPath:J.cwd});this.assertNotDestroyed();let Q=new O(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(Y){throw await Q.destroy().catch(()=>{return}),Y}return this.sessions.set(Z.sessionId,Q),Q.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z.sessionId,Z.metadata,Q.getModelConfiguration())}async loadSession(J){this.assertNotDestroyed(),U.info(`[BladeAgent] Loading session: ${J.sessionId}`);let Q=(this.sessionLoadQueues.get(J.sessionId)??Promise.resolve()).then(()=>this.replaceSession(J)),Y=Q.then(()=>{return},()=>{return});this.sessionLoadQueues.set(J.sessionId,Y);try{return await Q}finally{if(this.sessionLoadQueues.get(J.sessionId)===Y)this.sessionLoadQueues.delete(J.sessionId)}}async replaceSession(J){this.assertNotDestroyed(),await D.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,Y]=await Promise.all([D.loadSession(J.sessionId,J.cwd),D.findSessionMetadata(J.sessionId,J.cwd)]);if(!Y)throw Error(`Session not found: ${J.sessionId}`);let H=new O(J.sessionId,J.cwd,this.connection,this.clientCapabilities,{initialMessages:Q,permissionMode:Y.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??[],Y=(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:Y,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){U.info(`[BladeAgent] Cancel notification received for session: ${J.sessionId}`);let Z=this.sessions.get(J.sessionId);if(Z)U.info("[BladeAgent] Found session, calling session.cancel()"),Z.cancel();else U.warn(`[BladeAgent] Session not found for cancel: ${J.sessionId}`)}async setSessionMode(J){U.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")U.info(`[BladeAgent] Setting session model: ${J.value}`),await Z.setModel(J.value);else if(J.configId==="reasoning_effort"&&"value"in J&&WJ(J.value))U.info(`[BladeAgent] Setting reasoning effort: ${J.value}`),await Z.setReasoningEffort(J.value);else if(J.configId==="service_tier"&&"value"in J&&$J(J.value))U.info(`[BladeAgent] Setting service tier: ${J.value}`),await Z.setServiceTier(J.value);else if(J.configId==="response_verbosity"&&"value"in J&&ZJ(J.value))U.info(`[BladeAgent] Setting response verbosity: ${J.value}`),await Z.setResponseVerbosity(J.value);else if(J.configId==="communication_style"&&"value"in J&&YJ(J.value))U.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 HJ.getInstance().disconnectAll()}catch(Z){J??=Z}if(J!==void 0)throw J}}async function ZQ(){let J=UJ.toWeb(process.stdout),Z=KJ.toWeb(process.stdin),Q=x.ndJsonStream(J,Z);await new x.AgentSideConnection((H)=>new k(H),Q).closed}export{ZQ as runAcpIntegration};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{lf as F}from"./chunk-
|
|
1
|
+
import{lf as F}from"./chunk-vx8a7e1j.js";import{Jf as D,Kf as E}from"./chunk-8gv6hsrf.js";import G from"node:path";function A(b){if(Array.isArray(b))return b.map((q)=>A(q));if(b!==null&&typeof b==="object"&&Object.getPrototypeOf(b)===Object.prototype)return Object.fromEntries(Object.entries(b).map(([q,w])=>[q,A(w)]));return b}function H(b){return A(b)}function I(b,q){let w=new D(q?.credentials??E().credentials);return w.configureModelProviders(b.modelProviders,b.models),w}async function Q(b,q){let w=G.resolve(b),x=F.getInstance(),[J,K]=await Promise.all([x.loadWorkspaceModelConfig(w,q),x.loadWorkspaceRuntimeSettings(w,q)]),z={...H(q),...J,...K},B=I(z);return x.validateConfig(z,B),{projectRoot:w,config:z,catalog:B}}function T(b){let q=H(b.config);return{projectRoot:G.resolve(b.projectRoot),config:q,catalog:I(q,b.catalog)}}
|
|
2
2
|
export{H as Jd,Q as Kd,T as Ld};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{of as En,pf as j,qf as T}from"./chunk-4qyhtrhx.js";import{uf as On,vf as Zn}from"./chunk-s6rdv601.js";import{Af as L}from"./chunk-1ggxyyar.js";import{Ef as $n}from"./chunk-ekv4hpy8.js";import{Hf as rt,Kf as p}from"./chunk-8gv6hsrf.js";import{Sf as sn,Tf as wn}from"./chunk-
|
|
1
|
+
import{of as En,pf as j,qf as T}from"./chunk-4qyhtrhx.js";import{uf as On,vf as Zn}from"./chunk-s6rdv601.js";import{Af as L}from"./chunk-1ggxyyar.js";import{Ef as $n}from"./chunk-ekv4hpy8.js";import{Hf as rt,Kf as p}from"./chunk-8gv6hsrf.js";import{Sf as sn,Tf as wn}from"./chunk-7e7zgzag.js";import{Xf as $}from"./chunk-2d35rmyg.js";import{fg as Sn}from"./chunk-heydawsf.js";var et=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function St(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function B(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&St(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{B(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function y(n){let t=n.oauth;if(!t)return;let M=t;for(let S of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[S]!==void 0)throw Error(`MCP OAuth "${S}" 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(B(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((S)=>S.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let e=t.scopes?.map((S)=>S.trim());if(e){if(e.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(e.some((S)=>!S||S.length>128||!et.test(S)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(e).size!==e.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...e?.length?{scopes:e}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as l}from"node:crypto";import xt from"node:http";import{auth as Tn}from"@modelcontextprotocol/sdk/client/auth.js";import $t from"open";import{createHash as Et,randomUUID as mt}from"node:crypto";import{constants as D,promises as P}from"node:fs";import W from"node:path";import{Mutex as At}from"async-mutex";import Tt from"write-file-atomic";var mn=1,bt=1048576,ct=5000,ot=50,st=/^[a-f0-9]{64}$/,wt=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),Lt=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),ft=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),An=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(wt),tokens:T.Optional(Lt),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(ft),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),rn=T.Object({version:T.Literal(mn),credentials:T.Record(T.String(),An)},{additionalProperties:!1});function q(n,t){return n instanceof Error&&"code"in n&&n.code===t}function Pt(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return q(t,"EPERM")}}function k(n){return structuredClone(n)}function en(n){if(Object.keys(n.credentials).some((t)=>!st.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function G(n){let t=new URL(n);return t.hash="",t.toString()}function F(n,t,M=[]){return Et("sha256").update(JSON.stringify({serverUrl:G(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static mutexes=new Map;stateRoot;tokenFilePath;mutex;constructor(n=Sn()){this.stateRoot=W.join(n,"mcp"),this.tokenFilePath=W.join(this.stateRoot,"oauth-credentials.json");let t=I.mutexes.get(this.tokenFilePath);if(!t)t=new At,I.mutexes.set(this.tokenFilePath,t);this.mutex=t}async getCredential(n){return this.mutex.runExclusive(async()=>{let M=(await this.readStore()).credentials[n];return M?k(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let u=M.credentials[n],_=await t(u?k(u):null);if(_)M.credentials[n]=j(An,_);else delete M.credentials[n];return _?k(M.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 M=await this.readStore(),u=await n(M);return await this.writeStore(M),u}finally{await t()}})}async ensureStateRoot(){await P.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await P.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await P.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>bt)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await P.readFile(this.tokenFilePath,"utf8")),M=En(rn,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return en(M.data),M.data}catch(n){if(q(n,"ENOENT"))return{version:mn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=j(rn,n);en(t),await Tt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await P.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=W.join(this.stateRoot,".oauth-credentials.lock"),t=mt(),M=Date.now()+ct;while(Date.now()<M)try{let u=await P.open(n,D.O_CREAT|D.O_EXCL|D.O_WRONLY,384);return await u.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await u.close(),async()=>{try{if(JSON.parse(await P.readFile(n,"utf8")).token===t)await P.unlink(n)}catch(_){if(!q(_,"ENOENT"))throw _}}}catch(u){if(!q(u,"EEXIST"))throw u;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,ot))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await P.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await P.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!Pt(M.pid))await P.unlink(n)}}var bn="127.0.0.1",cn=7777,on="/oauth/callback",dt=300000;class v 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 Ln extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function Xt(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Mc as a,Nc as b,Oc as c}from"./chunk-
|
|
1
|
+
import{Mc as a,Nc as b,Oc as c}from"./chunk-1444wfhr.js";import"./chunk-48tz6s0s.js";import"./chunk-mbrgz77y.js";import"./chunk-v508x7cg.js";import"./chunk-6kc12pma.js";import"./chunk-0rwz7tm0.js";import"./chunk-vx8a7e1j.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ac as _$,Bc as x$,Dc as g0,Gc as J$,Hc as Uf,sc as u,tc as Hf,uc as C$,vc as Yf,wc as I,xc as N$,yc as Wf,zc as G$}from"./chunk-rezjy4mp.js";import{Hd as V0}from"./chunk-vz0zsct0.js";import{me as Z0}from"./chunk-9pww3s5m.js";import{ye as i$}from"./chunk-s3zfyy7r.js";import{uf as Qf,vf as Xf}from"./chunk-s6rdv601.js";import{Af as A$}from"./chunk-1ggxyyar.js";import{Ef as U0}from"./chunk-ekv4hpy8.js";import{Lf as x0,Of as J0}from"./chunk-5m5nxkfs.js";import{Sf as p}from"./chunk-
|
|
1
|
+
import{Ac as _$,Bc as x$,Dc as g0,Gc as J$,Hc as Uf,sc as u,tc as Hf,uc as C$,vc as Yf,wc as I,xc as N$,yc as Wf,zc as G$}from"./chunk-rezjy4mp.js";import{Hd as V0}from"./chunk-vz0zsct0.js";import{me as Z0}from"./chunk-9pww3s5m.js";import{ye as i$}from"./chunk-s3zfyy7r.js";import{uf as Qf,vf as Xf}from"./chunk-s6rdv601.js";import{Af as A$}from"./chunk-1ggxyyar.js";import{Ef as U0}from"./chunk-ekv4hpy8.js";import{Lf as x0,Of as J0}from"./chunk-5m5nxkfs.js";import{Sf as p}from"./chunk-7e7zgzag.js";import{$f as Kf,Zf as Ff,_f as q0,ag as A,bg as m,dg as G0,eg as c,fg as C0}from"./chunk-heydawsf.js";import{readdir as L$,readFile as a,rm as $0,stat as E0}from"node:fs/promises";import*as V from"node:path";import{nanoid as j}from"nanoid";import{createHash as yf,randomUUID as Sf}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as Mf}from"node:child_process";import{createHash as gf}from"node:crypto";import{readFileSync as Ef}from"node:fs";var bf=/^[a-f0-9]{64}$/;function Y$($){if(!$||typeof $!=="object")return!1;let f=$;return(f.platform==="linux"||f.platform==="darwin"||f.platform==="win32")&&typeof f.fingerprint==="string"&&bf.test(f.fingerprint)}var W$={readFile:($)=>Ef($,"utf8"),execFile:($,f)=>Mf($,f,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},wf=($)=>{try{return process.kill($,0),!0}catch(f){return f instanceof Error&&"code"in f&&f.code==="EPERM"}};function u0($,f){return{platform:$,fingerprint:gf("sha256").update(`${$}\x00${f}`).digest("hex")}}function kf($,f){let T=f.readFile(`/proc/${$}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function Q0($,f=process.platform,T=W$){if(!Number.isInteger($)||$<=1)return;try{if(f==="linux")return u0(f,kf($,T));if(f==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String($)]).trim();return q?u0(f,q):void 0}if(f==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0(f,B):void 0}}catch{return}return}function U$($,f){return Q0($,f.platform)?.fingerprint===f.fingerprint}function o1($,f,T=W$,q=wf){if(!Number.isInteger($)||$<=1)return!1;let B=Q0($,f.platform,T);if(B)return B.fingerprint===f.fingerprint;return!q($)}var z$=1;function jf($,f){let T=yf("sha256").update(f).digest("hex");return H0.join(q0($),".locks",`${T}.lock`)}function X0($,f){return $ instanceof Error&&"code"in $&&$.code===f}async function P0($){try{let f=JSON.parse(await v.readFile($,"utf8"));if(f.version!==z$||typeof f.sessionId!=="string"||typeof f.ownerId!=="string"||!Number.isInteger(f.pid)||(f.pid??0)<=0||f.processIdentity!==void 0&&!Y$(f.processIdentity)||typeof f.acquiredAt!=="string")return;return f}catch{return}}async function D$($){let f=await P0($);if(f)return f;return await new Promise((T)=>setTimeout(T,10)),P0($)}function mf($){try{return process.kill($,0),!0}catch(f){return X0(f,"EPERM")}}async function R$($,f){let T;try{return T=await v.open($,"wx",384),await T.writeFile(`${JSON.stringify(f)}
|
|
2
2
|
`,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink($).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class h extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class n{filePath;record;released=!1;constructor($,f){this.filePath=$;this.record=f}static async acquire($,f=A$()){let T=jf(f,$),q={version:z$,sessionId:$,ownerId:Sf(),pid:process.pid,processIdentity:Q0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await R$(T,q))return new n(T,q);let B=await D$(T);if(B&&mf(B.pid)&&(!B.processIdentity||U$(B.pid,B.processIdentity)))throw new h(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await R$(T,q))return new n(T,q);throw new h((await D$(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await P0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch((f)=>{if(!X0(f,"ENOENT"))throw f})}}var TT=1;function h0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function If($){if(!h0($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&h0($.image_url)&&typeof $.image_url.url==="string"}function vf($){if(!h0($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(If)}function M$($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let f=JSON.stringify($);if(Buffer.byteLength(f)>16777216)return;let T=JSON.parse(f);if(!Array.isArray(T)||!T.every(vf))return;return T}function qT($){let f=M$($);if(!f)throw Error("Compaction replacement context is invalid or exceeds limits");return f}function g$($){return M$($)}function uf($,f){for(let T of $){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===f||T.data.partId===f||T.data.messageId===f)return B}return}function E$($){let f=u($),T=new Map;for(let q of f){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=uf(f,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function b$($){return E$($).reverse().find((f)=>!f.response&&!f.recovery)}function OT($){let f=new Map;for(let T of E$($))f.set(T.request.toolCallId,T);return[...f.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function w$($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function Y0($){let f=new Map,T=[];for(let q of $){if(q.type==="review_started"){if(!f.has(q.data.reviewId))T.push(q.data.reviewId),f.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=f.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>f.get(q)).filter((q)=>q!==void 0)}function NT($){return Y0($).reverse().find((f)=>f.completion===void 0)}function n0($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function k$($,f){let T=["## Code Review","",`Target: ${$.target.label}`,`Status: ${n0(f.status)}`,"",f.overallExplanation||"No overall explanation was provided."];if(f.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of f.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if(f.error)T.push("",`Error: ${f.error}`);return T.join(`
|
|
3
3
|
`)}function y$($,f){return{reviewId:$.reviewId,phase:"completed",status:f.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:f.overallExplanation,findings:f.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...f.error?{error:f.error}:{}}}var l0={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},runtime:{message:"Agent execution failed.",retryable:!0}};function Pf($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function hf($){let f=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(f))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(f))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(f))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(f))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(f))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(f))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(f))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(f))return"unsupported_input";return"runtime"}function nf($){return{code:$,...l0[$]}}function c0($){return nf(hf(Pf($)))}function p0($){if(!$||typeof $!=="object")return!1;let f=$;if(typeof f.code!=="string"||!(f.code in l0))return!1;let T=l0[f.code];return f.message===T.message&&f.retryable===T.retryable}import{promises as L0,realpathSync as cf}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var S$=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor($,f){super($);this.code=f;this.name="PathSecurityError"}}class i0{static normalize($,f){let T=H.isAbsolute($)?$:H.resolve(f,$),q=H.normalize(T),B=H.normalize(f);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${$} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted($){let f=$.split(H.sep);for(let T of S$)if(f.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new d(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,f){this.checkTraversal($);let T=this.normalize($,f);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${$}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink($,f){try{let T=await r.realpath($),q=await r.realpath(f);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${$} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return $}}static getRelativePath($,f){return H.relative(f,$)}static isWithinWorkspace($,f){let T=H.resolve($),q=H.resolve(f),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved($,f){let T=H.resolve(f),q=H.isAbsolute($)?H.resolve($):H.resolve(T,$);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let C=await r.realpath(L);return this.isWithinWorkspace(C,B)}catch(C){let _=C.code;if(_!=="ENOENT"&&_!=="ENOTDIR")return!1}let O=H.dirname(L);if(O===L)return!1;L=O}}static isRestricted($){let f=$.split(H.sep);return S$.some((T)=>f.includes(T))}}var B0=U0("Tool");class l{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!l.instance)l.instance=new l;return l.instance}async recordFileRead($,f){try{let T=await L0.stat($),q={filePath:W0.resolve($),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:f,lastOperation:"read"};this.setRecord(q),await this.recordAliases($,q.filePath),B0.debug(`记录文件读取: ${$}`)}catch(T){B0.warn(`记录文件读取失败: ${$}`,T)}}async recordFileEdit($,f,T="edit"){try{let q=await L0.stat($),B={filePath:W0.resolve($),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:f,lastOperation:T};this.setRecord(B),await this.recordAliases($,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${$}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${$}`,q)}}hasFileBeenRead($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return!1;return f?T.has(f):T.size>0}async checkFileModification($,f){let T=this.getFileRecord($,f);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification($,f){let T=this.getFileRecord($,f);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat($);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${$}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord($,f){let T=this.accessedFiles.get(this.resolveTrackedPath($));if(!T)return;if(f)return T.get(f);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,f){let T=this.resolveTrackedPath($);if(!f){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete(f),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,f){for(let[T,q]of this.accessedFiles.entries()){if(f&&!i0.isWithinWorkspace(T,f))continue;if(q.delete($),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){l.instance=null}setRecord($){let f=this.accessedFiles.get($.filePath);if(!f)f=new Map,this.accessedFiles.set($.filePath,f);f.set($.sessionId,$)}async recordAliases($,f){this.pathAliases.set(W0.resolve($),f);let T=await L0.realpath($).catch(()=>{return});if(T)this.pathAliases.set(T,f)}resolveTrackedPath($){let f=W0.resolve($);if(this.accessedFiles.has(f))return f;let T=this.pathAliases.get(f);if(T)return T;try{let q=cf.native(f);return this.pathAliases.get(q)??q}catch{return f}}removeAliases($){for(let[f,T]of this.pathAliases)if(T===$)this.pathAliases.delete(f)}}import*as O0 from"node:crypto";import{promises as F}from"node:fs";import*as Q from"node:path";import d0 from"write-file-atomic";var j$="missing";class D0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(A($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!Q.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?Q.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let f=C0();this.snapshotDir=Q.join(f,"file-history",this.sessionId),this.manifestPath=Q.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=C0(),f=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=O0.createHash("sha256").update(f).digest("hex").slice(0,24),q=Q.join($,"file-history",this.sessionId),B=Q.join($,"file-history","workspaces",T,this.sessionId),L=Q.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,f)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir($,f,T){let q;try{q=JSON.parse(await F.readFile(Q.join($,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(Q.dirname(f),{recursive:!0,mode:493});try{await F.rename($,f)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace($,f){if(!Q.isAbsolute($))return!1;let T=Q.relative(f,Q.resolve($));return T===""||T!==".."&&!T.startsWith(`..${Q.sep}`)&&!Q.isAbsolute(T)}async createSnapshot($,f){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity($),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,O=this.generateFileHash(T,L),C=this.getSnapshotPath(O,L),_=new Date;if(q){let G=await F.readFile(T);await F.writeFile(C,G)}let N={backupFileName:O,version:L,backupTime:_};return this.trackedFileBackups.set(T,N),this.snapshots.push({messageId:f,backupFileName:O,timestamp:_,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),N}async recordPostEditState($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot($,f){if(!this.enableCheckpoints||!f.backupFileName)return;let T=await this.resolveFileIdentity($),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===f.backupFileName&&B.version===f.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let f=await this.resolveFileIdentity($),T=this.snapshots.slice().reverse().find((L)=>L.filePath===f&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${f}`);if(await this.hashFile(f)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${f}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(f),{recursive:!0}),await F.writeFile(f,L)}else await F.rm(f,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot($,f){let T=await this.resolveFileIdentity($),q=this.snapshots.slice().reverse().find((L)=>L.messageId===f&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${f}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(Q.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots($){let f=await this.resolveFileIdentity($);return this.snapshots.filter((T)=>T.filePath===f)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let f=this.buildRewindPlan($);return{files:f.map((T)=>T.filePath),snapshotCount:f.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots($){let f=this.buildRewindPlan($);if(f.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of f){let L,O=!0;try{L=await F.readFile(B.filePath)}catch(_){if(_.code!=="ENOENT")throw _;O=!1}if((L?O0.createHash("sha256").update(L).digest("hex"):j$)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:O,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of f)if(L.target.existedBefore){let O=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(Q.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,O)}else await F.rm(L.filePath,{force:!0});let B=new Set(f.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[O,C]of T)try{if(C.existed&&C.content)await d0(O,C.content);else await F.rm(O,{force:!0})}catch(_){L.push(_)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:f.map((B)=>B.filePath),snapshotCount:f.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots($){let f=this.buildRewindPlan($),T=new Set(f.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:f.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan($){let f=new Set($),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>f.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let O=T.filter((G)=>G.filePath===L),C=O.filter((G)=>f.has(G.messageId)),_=O.indexOf(C[0]),N=O.slice(_);if(N.length!==C.length||N.some((G)=>!f.has(G.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:C,target:C[0],latest:C.at(-1)}})}async loadManifest(){try{let $=await F.readFile(this.manifestPath,"utf-8"),f=JSON.parse($);if(f.schemaVersion!==1||!Array.isArray(f.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(f.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((f)=>({...f,timestamp:f.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let T=this.snapshots.filter((q)=>q.filePath===$).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup($=0){let f=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set(f.slice(0,$));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=f.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,f){return Q.join(this.snapshotDir,`${$}@v${f}`)}async resolveFileIdentity($){let f=Q.resolve($),T=[],q=f;while(!0){try{let L=await F.realpath(q);return Q.join(L,...T.reverse())}catch(L){let O=L.code;if(O!=="ENOENT"&&O!=="ENOTDIR")throw L}let B=Q.dirname(q);if(B===q)return f;T.push(Q.basename(q)),q=B}}async hashFile($){try{let f=await F.readFile($);return O0.createHash("sha256").update(f).digest("hex")}catch(f){if(f.code==="ENOENT")return j$;throw f}}removeSnapshot($){let f=this.snapshots.indexOf($);if(f>=0)this.snapshots.splice(f,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let f=this.trackedFileBackups.get($.filePath);if(!f||f.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,f){let T=O0.createHash("md5");return T.update(`${$}:${f}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var DT=1200,RT=2000,AT=2000,zT=2000;function I$($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function pf($){if(typeof $==="string"&&$.length>0)return $;if(I$($)&&typeof $.message==="string")return $.message;return}function df($,f){if($===null||$===void 0)return f??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function v$($){let f=$.error!==null&&$.error!==void 0,T=f?pf($.error)??"Tool execution failed":void 0,q=I$($.metadata)?$.metadata:void 0;return{success:!f,llmContent:df($.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0($,f){if($.length<=f)return $;let T=Math.max(0,f);if(T>0&&T<$.length&&/[\uD800-\uDBFF]/.test($.charAt(T-1)))T-=1;return $.slice(0,T)}function m$($,f){if($.length<=f)return $;let T=Math.max(0,$.length-f);if(T<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(T)))T+=1;return $.slice(T)}function r0($,f){if($.length<=f)return $;if(f<=0)return"";let T=`
|
|
4
4
|
... (display clipped) ...
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$a as e,Ta as a,Ua as b,Wa as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,kb as l,lb as m,mb as n,nb as o,ob as p,pb as q,qb as r}from"./chunk-
|
|
1
|
+
import{$a as e,Ta as a,Ua as b,Wa as c,_a as d,ab as f,bb as g,cb as h,db as i,eb as j,fb as k,kb as l,lb as m,mb as n,nb as o,ob as p,pb as q,qb as r}from"./chunk-q9ghq6jw.js";import"./chunk-ej1z75jf.js";import"./chunk-x9940mcy.js";import"./chunk-4djps7bz.js";import"./chunk-rezjy4mp.js";import"./chunk-6kc12pma.js";import"./chunk-4qtb8yf6.js";import"./chunk-vz0zsct0.js";import"./chunk-0prp87ys.js";import"./chunk-9pww3s5m.js";import"./chunk-m8jen593.js";import"./chunk-s3zfyy7r.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{Jd as a,Kd as b,Ld as c}from"./chunk-
|
|
1
|
+
import{Jd as a,Kd as b,Ld as c}from"./chunk-rh5g6em4.js";import"./chunk-vx8a7e1j.js";import"./chunk-gdp6fg4e.js";import"./chunk-4qyhtrhx.js";import"./chunk-s6rdv601.js";import"./chunk-1ggxyyar.js";import"./chunk-ekv4hpy8.js";import"./chunk-8gv6hsrf.js";import"./chunk-5m5nxkfs.js";import"./chunk-7e7zgzag.js";import"./chunk-2d35rmyg.js";import"./chunk-d4327k1v.js";import"./chunk-heydawsf.js";import"./chunk-37se34rx.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
|