blade-code 0.10.31 → 0.10.33
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-08fww0yh.js +1 -0
- package/dist/{chunk-ktwp84cv.js → chunk-0k0k5qjr.js} +2 -2
- package/dist/{chunk-0ew7vmkb.js → chunk-189drzww.js} +1 -1
- package/dist/{chunk-b63dfss4.js → chunk-20qedxrp.js} +1 -1
- package/dist/chunk-23bhwgwm.js +204 -0
- package/dist/{chunk-7hs1n09m.js → chunk-23bkpq26.js} +2 -2
- package/dist/chunk-25j7tjr6.js +1 -0
- package/dist/{chunk-km155c83.js → chunk-2rsr3bte.js} +1 -1
- package/dist/chunk-2s24zvjm.js +22 -0
- package/dist/{chunk-aa4xya8p.js → chunk-3j57nm6f.js} +2 -2
- package/dist/{chunk-t857g6s9.js → chunk-3r0yfspg.js} +1 -1
- package/dist/{chunk-2nga4tsd.js → chunk-40654rh3.js} +2 -2
- package/dist/{chunk-pqsg5265.js → chunk-4kratdhc.js} +1 -1
- package/dist/{chunk-2rmt821w.js → chunk-5fm0qywg.js} +2 -2
- package/dist/chunk-5hn788xk.js +2 -0
- package/dist/{chunk-86phvby9.js → chunk-6b2w2132.js} +1 -1
- package/dist/{chunk-2q06pq10.js → chunk-6bqd2hkz.js} +1 -1
- package/dist/chunk-74js4dnw.js +1 -0
- package/dist/chunk-7dt49b6q.js +8 -0
- package/dist/chunk-7ncx3vzw.js +1 -0
- package/dist/{chunk-fs1r9hyz.js → chunk-8vxxmdhd.js} +1 -1
- package/dist/{chunk-at2krx3x.js → chunk-91sne4g4.js} +2 -2
- package/dist/{chunk-d0sej62r.js → chunk-91vwv4ph.js} +2 -2
- package/dist/{chunk-93zgz6v6.js → chunk-97mzk53w.js} +1 -1
- package/dist/chunk-9c4fvem6.js +1 -0
- package/dist/chunk-9qj6y0sj.js +2 -0
- package/dist/chunk-agw7bq0h.js +1 -0
- package/dist/{chunk-xhxvde2k.js → chunk-amm23yvd.js} +2 -2
- package/dist/chunk-bhj7dqe8.js +1 -0
- package/dist/{chunk-jmyxhygx.js → chunk-bvnxztsj.js} +1 -1
- package/dist/{chunk-byqg8qby.js → chunk-ctn675zn.js} +2 -2
- package/dist/{chunk-9wy7xryc.js → chunk-d3h8cgs8.js} +1 -1
- package/dist/chunk-dkz757cv.js +1 -0
- package/dist/{chunk-7gsqx900.js → chunk-f20mb84y.js} +2 -2
- package/dist/{chunk-tb1hr6w9.js → chunk-f5yx8s8t.js} +1 -1
- package/dist/{chunk-qat3ara1.js → chunk-f9graf2n.js} +1 -1
- package/dist/{chunk-fqrt55g3.js → chunk-g2yj0chw.js} +1 -1
- package/dist/chunk-gmpgmh7s.js +1 -0
- package/dist/{chunk-1905jhyj.js → chunk-gw51xyz9.js} +2 -2
- package/dist/{chunk-q1v03abc.js → chunk-h9v4tzdt.js} +2 -2
- package/dist/{chunk-anm5phza.js → chunk-hs3yryjm.js} +2 -2
- package/dist/{chunk-9jkbhaec.js → chunk-k05xt45s.js} +1 -1
- package/dist/{chunk-07t42c40.js → chunk-k9px24b5.js} +1 -1
- package/dist/{chunk-bqmd7hp7.js → chunk-kqe9y6ka.js} +43 -43
- package/dist/{chunk-v1jxren4.js → chunk-m06gcr4k.js} +1 -1
- package/dist/chunk-m6srq209.js +1 -0
- package/dist/{chunk-vw6z3t41.js → chunk-mdrdafpa.js} +1 -1
- package/dist/{chunk-pgs555fv.js → chunk-mt3nrz7x.js} +2 -2
- package/dist/{chunk-s8889acm.js → chunk-mxyb9hn6.js} +1 -1
- package/dist/chunk-np2vrjpc.js +10 -0
- package/dist/{chunk-0qjzgs1d.js → chunk-qj6gafse.js} +1 -1
- package/dist/chunk-sfvt4ef0.js +1610 -0
- package/dist/{chunk-qfd0tees.js → chunk-tzragyzm.js} +1 -1
- package/dist/{chunk-1v251p73.js → chunk-vm0w0jt9.js} +1 -1
- package/dist/{chunk-khvbwbtv.js → chunk-vp7n0w9w.js} +2 -2
- package/dist/{chunk-c2bgj76r.js → chunk-vybzvxf9.js} +1 -1
- package/dist/{chunk-9afqfajf.js → chunk-vzf17snk.js} +2 -2
- package/dist/{chunk-s4zvf2tf.js → chunk-w45ngpy1.js} +2 -2
- package/dist/chunk-wgnzghhc.js +6 -0
- package/dist/{chunk-44ep1v89.js → chunk-wzjhwr2p.js} +3 -3
- package/dist/chunk-xfpne7cm.js +1 -0
- package/dist/{chunk-ayx03d6y.js → chunk-y1bb5391.js} +1 -1
- package/dist/chunk-ycvwc7hb.js +1 -0
- package/dist/{chunk-zzkzmrjd.js → chunk-z2k6q0k1.js} +2 -2
- package/dist/chunk-z7s2138c.js +1 -0
- package/dist/chunk-zfezz6ew.js +1 -0
- package/dist/{chunk-3fzevvzm.js → chunk-zftb9s2h.js} +2 -2
- package/dist/{chunk-x36dp4pj.js → chunk-zhbpatxr.js} +1 -1
- package/dist/chunk-ztyt12kf.js +2 -0
- package/dist/{chunk-c913zbnw.js → chunk-zvjvbhc4.js} +2 -2
- package/dist/web/assets/{ChatView-SgrwGFY6.js → ChatView-B7_Um8KR.js} +2 -2
- package/dist/web/assets/{CodeBlockHighlighter-BgvTBcCD.js → CodeBlockHighlighter-JzE91vkT.js} +1 -1
- package/dist/web/assets/{FilePreview-D1ZOOgV-.js → FilePreview-BTbtoUBJ.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-BdBwdGfs.js → MarkdownRenderer-IaPtOh2w.js} +3 -3
- package/dist/web/assets/{SettingsModal-y7zf5Dbj.js → SettingsModal-CPgWPfZ2.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-YYFAqV6o.js → TaskSwitcher-D4RZxQKp.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BjA-x8tb.js → TerminalPanel-yWbQfbYa.js} +1 -1
- package/dist/web/assets/{index-B6QL61mx.js → index-BnCT8SxR.js} +8 -8
- package/dist/web/assets/session-events-BZao_jMQ.js +22 -0
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-1pr72n4c.js +0 -1
- package/dist/chunk-1y3jpc4s.js +0 -1
- package/dist/chunk-321dpgd3.js +0 -2
- package/dist/chunk-3gbrc75h.js +0 -1
- package/dist/chunk-6pwgtmw3.js +0 -1
- package/dist/chunk-7b81rbkw.js +0 -1
- package/dist/chunk-a83cdn7b.js +0 -1
- package/dist/chunk-hev5sqxy.js +0 -1
- package/dist/chunk-hrfdc0dt.js +0 -6
- package/dist/chunk-nnby8asg.js +0 -10
- package/dist/chunk-rj3cmn4b.js +0 -1
- package/dist/chunk-s6exb18e.js +0 -3
- package/dist/chunk-tps0kwhy.js +0 -1
- package/dist/chunk-tsfv04af.js +0 -1
- package/dist/chunk-v0sfs2b6.js +0 -1
- package/dist/chunk-vd17dtg7.js +0 -1
- package/dist/chunk-vy59rm9j.js +0 -2
- package/dist/chunk-xtaq5ck1.js +0 -2
- package/dist/chunk-xv1bz8f4.js +0 -1608
- package/dist/chunk-y7m792w3.js +0 -1
- package/dist/chunk-y9v884rp.js +0 -204
- package/dist/chunk-ykjpwdba.js +0 -1
- package/dist/chunk-zfpbkkdh.js +0 -22
- package/dist/web/assets/session-events-Bgb4zeFL.js +0 -22
package/dist/chunk-ykjpwdba.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{Ed as a}from"./chunk-s4zvf2tf.js";import"./chunk-xhxvde2k.js";import"./chunk-2nga4tsd.js";import"./chunk-07t42c40.js";import"./chunk-7gsqx900.js";import"./chunk-9wy7xryc.js";export{a as createChatServiceAsync};
|
package/dist/chunk-zfpbkkdh.js
DELETED
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
import{s as E}from"./chunk-t857g6s9.js";import{t as FJ}from"./chunk-xtaq5ck1.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-xv1bz8f4.js";import{la as HJ}from"./chunk-byqg8qby.js";import"./chunk-321dpgd3.js";import{Na as v,ab as m,jb as d}from"./chunk-y9v884rp.js";import{sb as T}from"./chunk-fs1r9hyz.js";import{Lb as f,Sb as u,Vb as g,bc as M,cc as c,ec as R,hc as p,mc as _,pc as D}from"./chunk-at2krx3x.js";import"./chunk-86phvby9.js";import"./chunk-khvbwbtv.js";import"./chunk-q1v03abc.js";import"./chunk-aa4xya8p.js";import"./chunk-v508x7cg.js";import{xd as zJ}from"./chunk-c2bgj76r.js";import"./chunk-s4zvf2tf.js";import"./chunk-3fzevvzm.js";import{Id as WJ}from"./chunk-ayx03d6y.js";import"./chunk-pgs555fv.js";import"./chunk-zzkzmrjd.js";import"./chunk-v1jxren4.js";import{ne as YJ}from"./chunk-0ew7vmkb.js";import"./chunk-s8889acm.js";import"./chunk-44ep1v89.js";import"./chunk-jmyxhygx.js";import"./chunk-9afqfajf.js";import"./chunk-9jkbhaec.js";import"./chunk-0qjzgs1d.js";import{vf as I,wf as S,xf as y}from"./chunk-vy59rm9j.js";import{Bf as QJ}from"./chunk-km155c83.js";import{Ff as b}from"./chunk-xhxvde2k.js";import"./chunk-2nga4tsd.js";import{Mf as ZJ,Pf as $J}from"./chunk-07t42c40.js";import"./chunk-d0sej62r.js";import"./chunk-7hs1n09m.js";import"./chunk-b63dfss4.js";import"./chunk-7gsqx900.js";import"./chunk-9wy7xryc.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
|
-
`}});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
|
-
`}});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
|
-
`}});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}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${W.revision} (${W.serverName}) ${W.level}${W.logger?` logger=${W.logger}`:""}: ${W.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${W.revision} (${W.serverName}): ${W.action}${W.detailsOmitted?" details-omitted":""}
|
|
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
|
-
`}});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
|
-
`}});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)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
|
-
- ${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 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
|
-
`),[...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 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,22 +0,0 @@
|
|
|
1
|
-
var ce=Object.defineProperty;var ge=(e,t,n)=>t in e?ce(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var K=(e,t,n)=>ge(e,typeof t!="symbol"?t+"":t,n);function M(){return{timeline:[],textBefore:"",toolCalls:[],textAfter:"",thinkingContent:"",tasks:[],subagent:null,subagents:[],confirmation:null,question:null,elicitation:null}}function N(e){return e?e.subagents&&e.subagents.length>0?e.subagents:e.subagent?[e.subagent]:[]:[]}function B(e,t,n){const r=(n?t.find(a=>a.id===n||a.sessionId===n):void 0)??t[t.length-1]??null;return{...e,subagents:t,subagent:r}}function ne(e,t){const n=[...N(e)];let r=n.findIndex(s=>s.id===t.id||!!(s.sessionId&&t.sessionId&&s.sessionId===t.sessionId));if(r===-1&&t.sessionId&&(r=n.findIndex(s=>!s.sessionId&&s.status==="running"&&s.type===t.type&&s.description===t.description)),r===-1)return n.push(t),B(e,n,t.id);const a=n[r],u={...a,...t,id:a.id};return n[r]=u,B(e,n,u.id)}function H(e,t){return`${t}-${e.length}`}function me(e,t){if(!t)return e;const n=[...j(e)],r=n[n.length-1];return(r==null?void 0:r.type)==="text"?n[n.length-1]={...r,content:r.content+t}:n.push({id:H(n,"text"),type:"text",content:t}),{...e,timeline:n}}function fe(e,t){if(!t)return e;const n=[...j(e)],r=n[n.length-1];return(r==null?void 0:r.type)==="thinking"?n[n.length-1]={...r,content:r.content+t}:n.push({id:H(n,"thinking"),type:"thinking",content:t}),{...e,timeline:n}}function se(e,t){const n=e.toolCalls.some(s=>s.toolCallId===t.toolCallId),r=n?e.toolCalls:[...e.toolCalls,t];if(n)return{...e,toolCalls:r};const a=[...j(e)],u=a[a.length-1];return(u==null?void 0:u.type)==="tool_group"?a[a.length-1]={...u,toolCallIds:[...u.toolCallIds,t.toolCallId]}:a.push({id:H(a,"tool_group"),type:"tool_group",toolCallIds:[t.toolCallId]}),{...e,timeline:a,toolCalls:r}}function j(e){if(e.timeline&&e.timeline.length>0)return e.timeline;const t=[];return e.thinkingContent&&t.push({id:"legacy-thinking",type:"thinking",content:e.thinkingContent}),e.textBefore&&t.push({id:"legacy-text-before",type:"text",content:e.textBefore}),e.toolCalls.length>0&&t.push({id:"legacy-tool-group",type:"tool_group",toolCallIds:e.toolCalls.map(n=>n.toolCallId)}),e.textAfter&&t.push({id:"legacy-text-after",type:"text",content:e.textAfter}),t}function Ie(e){return j(e).filter(t=>t.type==="text").map(t=>t.content).filter(Boolean).join(`
|
|
2
|
-
|
|
3
|
-
`)}const Se=2166136261,he=16777619;function J(e){return e==null?"":typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.map(t=>J(t)).join(",")}]`:typeof e=="object"?`{${Object.entries(e).sort(([n],[r])=>n.localeCompare(r)).map(([n,r])=>`${JSON.stringify(n)}:${J(r)}`).join(",")}}`:JSON.stringify(e)}function oe(e){let t=Se>>>0;for(let n=0;n<e.length;n+=1)t^=e.charCodeAt(n),t=Math.imul(t,he);return(t>>>0).toString(16)}function ae(e){return typeof e=="string"?e:J(e??{})}function G(e){return e==="completed"?"completed":e==="failed"?"failed":"running"}function L({explicitId:e,messageId:t,toolName:n,argumentsValue:r,toolKind:a,output:u}){if(e)return e;const s=[t||"unknown-message",n||"Unknown",ae(r),a||"",u||""].join("|");return`tool-${oe(s)}`}function q({explicitId:e,sessionId:t,messageId:n,agentType:r,description:a,summary:u}){if(e)return e;if(t)return t;const s=[n||"unknown-message",r||"subagent",a||"",u||""].join("|");return`subagent-${oe(s)}`}const ye=(e,t)=>{if(!t||typeof t!="object")return null;const n=G(t.status),r=typeof t.summary=="string"?t.summary:void 0;return{id:q({explicitId:typeof t.subagentId=="string"?t.subagentId:void 0,sessionId:t.childSessionId,messageId:e,agentType:t.agentType,description:t.description,summary:t.summary}),type:t.agentType||"subagent",description:t.description||t.summary||"",status:n,startTime:Date.now(),sessionId:t.childSessionId,resumedFrom:t.resumedFrom,rootAgentId:t.rootAgentId,resumeDepth:typeof t.resumeDepth=="number"?t.resumeDepth:void 0,verificationVerdict:t.verificationVerdict==="pass"||t.verificationVerdict==="fail"||t.verificationVerdict==="partial"?t.verificationVerdict:void 0,output:n==="running"?void 0:r}},Ce=(e,t)=>!t||typeof t!="object"?[]:(Array.isArray(t.subtaskRefs)?t.subtaskRefs:t.subtaskRef&&typeof t.subtaskRef=="object"?[t.subtaskRef]:[]).map(r=>ye(e,r)).filter(r=>r!==null);function x(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join(`
|
|
4
|
-
`)}function be(e){var r,a,u;const t=[];let n=null;for(const s of e)if(s.role!=="system"){if(s.role==="user")n&&(t.push(n),n=null),t.push({id:s.id,role:s.role,content:s.content,timestamp:s.timestamp||Date.now(),metadata:s.metadata});else if(s.role==="assistant"){n&&t.push(n);const i=s.metadata;let o=M();s.thinkingContent&&(o=fe(o,s.thinkingContent),o.thinkingContent=s.thinkingContent);const d=x(s.content);d&&(o=me(o,d),o.textBefore=d);const c=Ce(s.id,i);if(s.tool_calls&&Array.isArray(s.tool_calls))for(const l of s.tool_calls){const g=((r=l.function)==null?void 0:r.name)||"Unknown",I=ae((a=l.function)==null?void 0:a.arguments);if(g==="Task"){let m={};try{m=JSON.parse(I)}catch{}const y=typeof m.subagent_type=="string"?m.subagent_type:"subagent",S=typeof m.description=="string"?m.description:y;o=ne(o,{id:q({explicitId:l.id,sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,messageId:s.id,agentType:y,description:S}),type:y,description:S,status:"running",startTime:Date.now(),sessionId:typeof m.subagent_session_id=="string"?m.subagent_session_id:void 0,resumedFrom:typeof m.resume_from=="string"?m.resume_from:typeof m.resume=="string"?m.resume:void 0});continue}const h={toolCallId:L({explicitId:l.id,messageId:s.id,toolName:g,argumentsValue:(u=l.function)==null?void 0:u.arguments}),toolName:g,arguments:I,status:"running",startTime:Date.now()};o=se(o,h)}for(const l of c)o=ne(o,l);n={id:s.id,role:"assistant",content:x(s.content),timestamp:s.timestamp||Date.now(),metadata:i,agentContent:o}}else if(s.role==="tool"&&n&&n.agentContent){const i=s,o=s.metadata,d=i.tool_call_id||(o==null?void 0:o.toolCallId),c=i.name||(o==null?void 0:o.toolName)||"Tool",l=o!=null&&o.metadata&&typeof o.metadata=="object"&&!Array.isArray(o.metadata)?o.metadata:o,g=o!=null&&o.independentVerification&&typeof o.independentVerification=="object"&&!Array.isArray(o.independentVerification)?o.independentVerification:void 0,I=(o==null?void 0:o.status)==="failed"||(o==null?void 0:o.status)==="error"||typeof(o==null?void 0:o.error)=="string"&&o.error.length>0,h=N(n.agentContent),m=h.findIndex(S=>S.id===d);if(m>=0){const S=h[m],f=typeof(l==null?void 0:l.subagentStatus)=="string"?G(l.subagentStatus):I?"failed":"completed";h[m]={...S,sessionId:typeof(l==null?void 0:l.subagentSessionId)=="string"?l.subagentSessionId:S.sessionId,type:typeof(l==null?void 0:l.subagentType)=="string"?l.subagentType:S.type,status:f,resumedFrom:typeof(l==null?void 0:l.subagentResumedFrom)=="string"?l.subagentResumedFrom:S.resumedFrom,rootAgentId:typeof(l==null?void 0:l.subagentRootId)=="string"?l.subagentRootId:S.rootAgentId,resumeDepth:typeof(l==null?void 0:l.subagentResumeDepth)=="number"?l.subagentResumeDepth:S.resumeDepth,verificationVerdict:(l==null?void 0:l.verificationVerdict)==="pass"||(l==null?void 0:l.verificationVerdict)==="fail"||(l==null?void 0:l.verificationVerdict)==="partial"?l.verificationVerdict:(g==null?void 0:g.verificationVerdict)==="pass"||(g==null?void 0:g.verificationVerdict)==="fail"||(g==null?void 0:g.verificationVerdict)==="partial"?g.verificationVerdict:S.verificationVerdict,output:typeof(l==null?void 0:l.subagentSummary)=="string"?l.subagentSummary:x(s.content)||S.output},n.agentContent=B(n.agentContent,h,S.id);continue}const y=n.agentContent.toolCalls.find(S=>S.toolCallId===d);y?(y.output=x(s.content),y.status=I?"error":"success",y.metadata=l,y.summary=typeof(l==null?void 0:l.summary)=="string"?l.summary:y.summary,(!y.toolName||y.toolName==="Unknown")&&(y.toolName=c)):n.agentContent=se(n.agentContent,{toolCallId:L({explicitId:d,messageId:n.id,toolName:c,output:x(s.content)}),toolName:c,output:x(s.content),status:I?"error":"success",startTime:Date.now(),metadata:l,summary:typeof(l==null?void 0:l.summary)=="string"?l.summary:void 0})}}return n&&t.push(n),t}const re={authentication:"task.failure.authentication",permission:"task.failure.permission",rate_limit:"task.failure.rateLimit",timeout:"task.failure.timeout",network:"task.failure.network",model_unavailable:"task.failure.modelUnavailable",context_limit:"task.failure.contextLimit",unsupported_input:"task.failure.unsupportedInput",runtime:"task.failure.runtime"},ve={authentication:!1,permission:!1,rate_limit:!0,timeout:!0,network:!0,model_unavailable:!0,context_limit:!1,unsupported_input:!1,runtime:!0};function Ae(e){if(typeof e=="string"&&Object.keys(re).includes(e))return e}function jt(e){return re[e]}function qt(e){return ve[e]}const Te={flushTimeout:80};class ke{constructor(t){K(this,"config");K(this,"channels",new Map);this.config={...Te,...t}}append(t,n,r){let a=this.channels.get(t);a||(a={buffer:"",timer:null,flushFn:null},this.channels.set(t,a)),a.buffer+=n,a.flushFn=r,a.timer||(a.timer=setTimeout(()=>{this.flushChannel(t)},this.config.flushTimeout))}flushChannel(t){const n=this.channels.get(t);if(!n||!n.buffer)return;const r=n.buffer,a=n.flushFn;n.buffer="",n.timer&&(clearTimeout(n.timer),n.timer=null),a==null||a(r)}drainAll(){for(const[t]of this.channels)this.flushChannel(t);this.channels.clear()}drainAllExcept(t){for(const[n]of this.channels)n!==t&&this.flushChannel(n);for(const[n,r]of this.channels)n!==t&&!r.buffer&&this.channels.delete(n)}reset(){for(const[,t]of this.channels)t.timer&&clearTimeout(t.timer);this.channels.clear()}}const $=new ke,b=(e,t,n)=>{if(t)for(const r of e){const a=N(r.agentContent).find(u=>u.id===t||u.sessionId===t);if(a)return{messageId:r.id,subagent:a}}if(n){const r=e.find(s=>s.id===n),a=N(r==null?void 0:r.agentContent),u=a.find(s=>s.status==="running")??a[a.length-1];if(u)return{messageId:n,subagent:u}}for(const r of[...e].reverse()){const a=N(r.agentContent),u=a.find(s=>s.status==="running")??a[a.length-1];if(u)return{messageId:r.id,subagent:u}}},v=(e,t,n,r=!1)=>{const{currentAssistantMessageId:a,messages:u,addMessage:s,startAgentResponse:i}=e();if(n&&r){const l=u.find(I=>I.id===n&&I.role==="assistant");if(l)return i(l.id),l.id;const g={id:n,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return s(g),i(n),n}if(a&&!a.startsWith("call_")&&u.some(l=>l.id===a&&l.role==="assistant"))return a;if(n){const l=u.find(g=>g.id===n&&g.role==="assistant");if(l)return i(l.id),l.id}const o=u[u.length-1];if((o==null?void 0:o.role)==="assistant")return o.id;const d=n||`assistant-${Date.now()}`,c={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};return s(c),i(d),t(l=>({messages:l.messages.map(g=>g.id===d?{...g,agentContent:{...g.agentContent||M()}}:g)})),d},$e=(e,t,n)=>{const{currentSessionId:r,addMessage:a,startAgentResponse:u,messages:s,updateMessage:i}=t();if(e.sessionId!==r)return;const o=e.messageId,d=e.role||"assistant",c=s.find(g=>g.id===o),l={id:o,role:d,content:e.content||"",timestamp:Date.now(),agentContent:d==="assistant"?M():void 0};c?i(o,{role:d,content:l.content,agentContent:d==="assistant"?{...c.agentContent||M()}:void 0}):a(l),d==="assistant"&&u(o)},Ne=(e,t,n)=>{const{currentSessionId:r,appendDelta:a,currentAssistantMessageId:u,hasToolCalls:s,addMessage:i,startAgentResponse:o}=t();if(e.sessionId!==r)return;const d=e.messageId,c=e.delta;if(!u){const g={id:d,role:"assistant",content:"",timestamp:Date.now(),agentContent:M()};i(g),o(d),t().appendDelta(d,c,"before");return}a(u,c,s?"after":"before")},Me=(e,t)=>{const{currentSessionId:n,updateMessage:r,messages:a}=t();if(e.sessionId!==n)return;const u=e.messageId,s=a.find(i=>i.id===u);s!=null&&s.agentContent&&r(u,{content:Ie(s.agentContent)})},Re=(e,t,n)=>{var o;const{currentSessionId:r}=t();if(e.sessionId!==r)return;const a=e.output;if(!a||typeof a!="object"||Array.isArray(a))return;const u=v(t,n,e.messageId);if(!u)return;const s=t().messages.find(d=>d.id===u);if(!s)return;const i=JSON.stringify(a,null,2);t().updateMessage(u,{content:i,metadata:{...s.metadata,structuredOutput:{output:a,schemaDigest:e.schemaDigest}},agentContent:s.agentContent?{...s.agentContent,textBefore:"",textAfter:"",timeline:(o=s.agentContent.timeline)==null?void 0:o.filter(d=>d.type!=="text")}:void 0})},xe=(e,t,n)=>{const{currentSessionId:r,appendThinking:a}=t();if(e.sessionId!==r)return;const u=v(t,n,e.messageId);u&&a(u,e.delta)},we=()=>{},ue=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a,setHasToolCalls:u,setSubagent:s}=t();if(e.sessionId!==r)return;const i=v(t,n,e.messageId||e.toolCallId,typeof e.messageId=="string");if(!i)return;u(!0);const o=e.toolName||"Unknown",d=e.arguments;let c,l="",g,I;if(o==="Task")try{const m=JSON.parse(d);c=m.subagent_type,l=m.description||m.query||c||"",g=m.subagent_session_id,I=m.resume_from||m.resume}catch{}if(c){s(i,{id:q({explicitId:e.toolCallId,sessionId:g,messageId:i,agentType:c,description:l}),type:c,description:l,status:"running",startTime:Date.now(),sessionId:g,resumedFrom:I,output:"",thinking:""});return}const h={toolCallId:L({explicitId:e.toolCallId,messageId:i,toolName:o,argumentsValue:d,toolKind:e.toolKind}),toolName:o,arguments:d,toolKind:e.toolKind,status:"running",startTime:Date.now()};a(i,h)},de=(e,t)=>{const{currentSessionId:n,updateToolCall:r,messages:a}=t();if(e.sessionId!==n)return;const u=e.toolCallId;if(!u)return;const s=a.find(i=>{var o;return(o=i.agentContent)==null?void 0:o.toolCalls.some(d=>d.toolCallId===u)});s&&r(s.id,u,{summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message})},le=(e,t,n)=>{var ee;const{currentSessionId:r,appendToolCall:a,setHasToolCalls:u,updateToolCall:s,updateSubagent:i,messages:o}=t();if(e.sessionId!==r)return;const d=e.toolCallId;if(!d)return;const c=o.find(A=>{var k;return(k=A.agentContent)==null?void 0:k.toolCalls.some(R=>R.toolCallId===d)}),l=o.find(A=>N(A.agentContent).some(k=>k.id===d)),g=(c==null?void 0:c.id)||(l==null?void 0:l.id)||v(t,n,e.messageId,!0);if(!g)return;const I=typeof e.output=="string"?e.output:"",h=e.success===!0||e.status==="completed",m=e.summary||(I&&I.trim()?I.trim().split(`
|
|
5
|
-
`)[0].slice(0,120):h?"执行成功":"执行失败"),y=(ee=c==null?void 0:c.agentContent)==null?void 0:ee.toolCalls.find(A=>A.toolCallId===d),S=typeof e.toolName=="string"?e.toolName:(y==null?void 0:y.toolName)??"Unknown",f=e.metadata;c?s(g,d,{status:h?"success":"error",summary:m,output:I,metadata:f}):l||(u(!0),a(g,{toolCallId:d,toolName:S,status:h?"success":"error",summary:m,output:I,startTime:Date.now(),metadata:f}));const F=t().messages.find(A=>A.id===g),T=N(F==null?void 0:F.agentContent).find(A=>A.id===d),w=f&&typeof f.subagentSessionId=="string"?f.subagentSessionId:void 0,P=f&&typeof f.subagentStatus=="string"?f.subagentStatus:void 0,z=f&&typeof f.subagentType=="string"?f.subagentType:void 0,W=f&&typeof f.subagentSummary=="string"?f.subagentSummary:void 0,Y=f&&typeof f.subagentResumedFrom=="string"?f.subagentResumedFrom:void 0,X=f&&typeof f.subagentRootId=="string"?f.subagentRootId:void 0,Z=f&&typeof f.subagentResumeDepth=="number"?f.subagentResumeDepth:void 0,p=(f==null?void 0:f.verificationVerdict)==="pass"||(f==null?void 0:f.verificationVerdict)==="fail"||(f==null?void 0:f.verificationVerdict)==="partial"?f.verificationVerdict:void 0;T&&i(g,T.id,{sessionId:T.sessionId||w,type:z||T.type,status:P?G(P):e.success?"completed":"failed",resumedFrom:Y||T.resumedFrom,rootAgentId:X||T.rootAgentId,resumeDepth:Z??T.resumeDepth,verificationVerdict:p??T.verificationVerdict,output:W||T.output}),w&&P&&n(A=>({messages:A.messages.map(k=>{if(k.id!==g)return k;const R=k.metadata??{},O=Array.isArray(R.subtaskRefs)?R.subtaskRefs:[],D=O.findIndex(te=>te.childSessionId===w||te.subagentId===d),C=D>=0?O[D]:R.subtaskRef??{},V={...C,subagentId:d,childSessionId:w,agentType:z||(typeof(C==null?void 0:C.agentType)=="string"?C.agentType:"subagent"),status:P,summary:W||(typeof(C==null?void 0:C.summary)=="string"?C.summary:""),resumedFrom:Y||(typeof(C==null?void 0:C.resumedFrom)=="string"?C.resumedFrom:void 0),rootAgentId:X||(typeof(C==null?void 0:C.rootAgentId)=="string"?C.rootAgentId:w),resumeDepth:Z??(typeof(C==null?void 0:C.resumeDepth)=="number"?C.resumeDepth:0),verificationVerdict:p||(typeof(C==null?void 0:C.verificationVerdict)=="string"?C.verificationVerdict:void 0)},E=[...O];return D>=0?E[D]=V:E.push(V),{...k,metadata:{...R,subtaskRef:V,subtaskRefs:E}}})}))},Pe=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=v(t,n,e.messageId||`mcp-catalog-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],o=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP catalog r${String(e.revision)}: +${s.length} -${i.length} ~${o.length}`;a(u,{toolCallId:`mcp-catalog:${String(e.revision)}`,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:s,removed:i,updated:o}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",o.length>0?`Updated: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
6
|
-
`)})},De=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=v(t,n,e.messageId||`mcp-content-${String(e.revision)}`);if(!u)return;const s=Array.isArray(e.added)?e.added.map(String):[],i=Array.isArray(e.removed)?e.removed.map(String):[],o=Array.isArray(e.updated)?e.updated.map(String):[],d=`MCP ${String(e.contentKind)} r${String(e.revision)}: +${s.length} -${i.length} ~${o.length}`;a(u,{toolCallId:`mcp-content:${String(e.revision)}`,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:s,removed:i,updated:o}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:d,output:[s.length>0?`Added: ${s.join(", ")}`:"",i.length>0?`Removed: ${i.join(", ")}`:"",o.length>0?`Updated: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
7
|
-
`)})},_e=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=v(t,n,e.messageId||`mcp-resource-${String(e.revision)}`);u&&a(u,{toolCallId:`mcp-resource:${String(e.revision)}`,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`,output:`${String(e.serverName)} · revision ${String(e.revision)}`})},je=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=v(t,n,e.messageId||`mcp-connection-${String(e.revision)}`);if(!u)return;const s=String(e.phase),i=`MCP ${String(e.serverName)} ${s}`+(s==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:"");a(u,{toolCallId:`mcp-connection:${String(e.revision)}`,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:s,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:s==="failed"?"error":"success",startTime:Date.now(),summary:i,output:[`Reason: ${String(e.reason)}`,e.error?`Error: ${String(e.error)}`:""].filter(Boolean).join(`
|
|
8
|
-
`)})},qe=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=v(t,n,e.messageId||`mcp-log-${String(e.revision)}`);if(!u)return;const s=String(e.level),i=typeof e.logger=="string"?e.logger:void 0,o=`MCP ${s} · ${String(e.serverName)}`+(i?` · ${i}`:"");a(u,{toolCallId:`mcp-log:${String(e.revision)}`,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:s,logger:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:o,output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
9
|
-
`)})},Fe=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=String(e.serverName),s=String(e.action),i=v(t,n,e.messageId||`mcp-instructions-${String(e.revision)}-${u}`);if(!i)return;const o=`MCP instructions ${s}: ${u}`+(e.truncated===!0?" (truncated)":"");a(i,{toolCallId:`mcp-instructions:${String(e.revision)}:${u}:${s}`,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:u,action:s,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:o,output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
10
|
-
`)})},Oe=(e,t,n)=>{var I,h;const{currentSessionId:r,appendToolCall:a,updateToolCall:u}=t();if(e.sessionId!==r)return;const s=String(e.taskId),i=String(e.status),o=`mcp-task:${s}`,d=v(t,n,e.messageId||`mcp-task-${s}`);if(!d)return;const c=`MCP task ${i}: ${s} · ${String(e.serverName)}/${String(e.toolName)}`,l={status:i==="failed"||i==="cancelled"?"error":i==="completed"?"success":"running",summary:c,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
|
|
11
|
-
`)};if((h=(I=t().messages.find(m=>m.id===d))==null?void 0:I.agentContent)==null?void 0:h.toolCalls.some(m=>m.toolCallId===o)){u(d,o,l);return}a(d,{toolCallId:o,toolName:"MCP Task",arguments:JSON.stringify({taskId:s,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:l.status,startTime:Number(e.createdAt)||Date.now(),summary:l.summary,output:l.output})},Ve=(e,t,n)=>{const{currentSessionId:r,appendToolCall:a}=t();if(e.sessionId!==r)return;const u=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],s=v(t,n,e.messageId||`project-rules-${Date.now()}`);if(!s)return;const i=e.blockedWrite===!0,o=`Project rules loaded: ${u.length}`+(i?" (write retry required)":"");a(s,{toolCallId:`project-rules:${u.map(d=>String(d.id)).join(",")}`,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:i}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:o,output:u.map(d=>`${String(d.relativePath)} ${String(d.source)} SHA-256: ${String(d.contentSha256)}`).join(`
|
|
12
|
-
`)})},Q=e=>`user-shell-${e}`,Ee=(e,t,n)=>{const{currentSessionId:r,addMessage:a,messages:u,updateMessage:s}=t();if(e.sessionId!==r||typeof e.executionId!="string"||typeof e.command!="string")return;const i=Q(e.executionId),o={id:i,role:"user",content:`! ${e.command}`,timestamp:Date.now(),metadata:{userShellExecution:{executionId:e.executionId,command:e.command,status:"running",output:""}}};u.some(d=>d.id===i)?s(i,o):a(o),e.auxiliary!==!0&&n({isStreaming:!0,agentPhase:"running",error:null,errorContext:null})},Ke=(e,t)=>{var d;const{currentSessionId:n,messages:r,updateMessage:a}=t();if(e.sessionId!==n||typeof e.executionId!="string"||typeof e.chunk!="string")return;const u=Q(e.executionId),s=r.find(c=>c.id===u);if(!s)return;const i=(d=s.metadata)!=null&&d.userShellExecution&&typeof s.metadata.userShellExecution=="object"?s.metadata.userShellExecution:{},o=`${typeof i.output=="string"?i.output:""}${e.chunk}`;a(u,{content:`! ${String(i.command??"")}
|
|
13
|
-
${o}`,metadata:{...s.metadata,userShellExecution:{...i,output:o,streamTruncated:e.streamTruncated===!0}}})},Ue=(e,t,n)=>{const{currentSessionId:r,messages:a,addMessage:u,updateMessage:s}=t();if(e.sessionId!==r||typeof e.executionId!="string"||!e.record||typeof e.record!="object"||Array.isArray(e.record))return;const i=e.record,o=typeof i.command=="string"?i.command:"",d=typeof i.stdout=="string"?i.stdout:"",c=typeof i.stderr=="string"?i.stderr:"",l=[d,c?`stderr:
|
|
14
|
-
${c}`:""].filter(Boolean).join(`
|
|
15
|
-
`),g=Q(e.executionId),I={role:"user",content:[`! ${o}`,l||"(no output)"].join(`
|
|
16
|
-
`),metadata:{userShellCommand:i}};a.some(h=>h.id===g)?s(g,I):u({id:g,...I,timestamp:Date.now()}),e.auxiliary!==!0&&n({isStreaming:!1,isStopping:!1,agentPhase:"idle"}),(e.delivery==="current_turn"||e.delivery==="next_turn")&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):0,pendingInputDelivery:e.delivery==="current_turn"?"current_turn":"next_turn"})},Be=(e,t)=>{const{currentSessionId:n,updateTokenUsage:r,setMaxContextTokens:a}=t();e.sessionId===n&&(r({inputTokens:e.inputTokens,outputTokens:e.outputTokens,totalTokens:e.totalTokens,cacheReadTokens:e.cacheReadTokens??0,cacheWriteTokens:e.cacheWriteTokens??0,costUsd:e.costUsd}),e.maxContextTokens&&a(e.maxContextTokens,!1))},Je=(e,t)=>{const{currentSessionId:n,setTasks:r,currentAssistantMessageId:a}=t();if(e.sessionId!==n||!a)return;const u=e.tasks||[];r(a,u)},Le=(e,t)=>{const{currentSessionId:n,setSubagent:r,currentAssistantMessageId:a}=t();if(e.sessionId!==n||!a)return;const u={id:q({explicitId:e.subagentId,sessionId:e.subagentSessionId,messageId:a,agentType:e.type,description:e.description}),type:e.type||"unknown",description:e.description||"",status:"running",startTime:Date.now(),sessionId:e.subagentSessionId,resumedFrom:e.resumedFrom,rootAgentId:e.rootAgentId,resumeDepth:typeof e.resumeDepth=="number"?e.resumeDepth:void 0};r(a,u)},He=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.subagentSessionId,i=b(a,s,r);i&&u(i.messageId,i.subagent.id,{sessionId:i.subagent.sessionId||s,currentTool:e.toolName})},Ge=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.delta;if(!s)return;const i=e.subagentSessionId,o=b(a,i,r);o&&u(o.messageId,o.subagent.id,d=>({sessionId:d.sessionId||i,output:(d.output||"")+s}))},Qe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.delta;if(!s)return;const i=e.subagentSessionId,o=b(a,i,r);o&&u(o.messageId,o.subagent.id,d=>({sessionId:d.sessionId||i,thinking:(d.thinking||"")+s}))},ze=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.subagentSessionId,i=b(a,s,r);i&&u(i.messageId,i.subagent.id,{sessionId:i.subagent.sessionId||s,status:e.success?"completed":"failed",currentTool:void 0,verificationVerdict:e.verificationVerdict==="pass"||e.verificationVerdict==="fail"||e.verificationVerdict==="partial"?e.verificationVerdict:i.subagent.verificationVerdict})},We=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId,i=e.toolName;if(!s||!i)return;const o=e.subagentSessionId,d=b(a,o,r);if(!d)return;const c={toolCallId:s,toolName:i,arguments:e.arguments,toolKind:e.toolKind,status:"running",startTime:Date.now()};u(d.messageId,d.subagent.id,l=>{const g=l.toolCalls||[];return{sessionId:l.sessionId||o,currentTool:i,toolCalls:g.some(I=>I.toolCallId===s)?g:[...g,c]}})},Ye=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId;if(!s)return;const i=e.toolName,o=e.subagentSessionId,d=b(a,o,r);if(!d)return;const c=e.output,l=e.success===!0,g=l?"success":"error",I=e.summary||(c&&c.trim()?c.trim().split(`
|
|
17
|
-
`)[0].slice(0,120):l?"执行成功":"执行失败");u(d.messageId,d.subagent.id,h=>({sessionId:h.sessionId||o,currentTool:h.currentTool===i?void 0:h.currentTool,toolCalls:(h.toolCalls||[]).map(m=>m.toolCallId===s?{...m,status:g,summary:I,output:c,metadata:e.metadata}:m)}))},Xe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=e.toolCallId;if(!s)return;const i=b(a,e.subagentSessionId,r);i&&u(i.messageId,i.subagent.id,o=>({toolCalls:(o.toolCalls||[]).map(d=>d.toolCallId===s?{...d,summary:e.message,progress:typeof e.progress=="number"?e.progress:void 0,progressTotal:typeof e.total=="number"?e.total:void 0,progressMessage:e.message}:d)}))},Ze=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=Array.isArray(e.added)?e.added.map(String):[],o=Array.isArray(e.removed)?e.removed.map(String):[],d=Array.isArray(e.updated)?e.updated.map(String):[],c=`mcp-catalog:${String(e.revision)}`;u(s.messageId,s.subagent.id,l=>({toolCalls:[...(l.toolCalls||[]).filter(g=>g.toolCallId!==c),{toolCallId:c,toolName:"MCP Catalog",arguments:JSON.stringify({serverName:e.serverName,added:i,removed:o,updated:d}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP catalog r${String(e.revision)}: +${i.length} -${o.length} ~${d.length}`,output:[i.length>0?`Added: ${i.join(", ")}`:"",o.length>0?`Removed: ${o.join(", ")}`:"",d.length>0?`Updated: ${d.join(", ")}`:""].filter(Boolean).join(`
|
|
18
|
-
`)}]}))},pe=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=Array.isArray(e.added)?e.added.map(String):[],o=Array.isArray(e.removed)?e.removed.map(String):[],d=Array.isArray(e.updated)?e.updated.map(String):[],c=`mcp-content:${String(e.revision)}`;u(s.messageId,s.subagent.id,l=>({toolCalls:[...(l.toolCalls||[]).filter(g=>g.toolCallId!==c),{toolCallId:c,toolName:"MCP Content",arguments:JSON.stringify({serverName:e.serverName,contentKind:e.contentKind,added:i,removed:o,updated:d}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP ${String(e.contentKind)} r${String(e.revision)}: +${i.length} -${o.length} ~${d.length}`}]}))},et=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=`mcp-resource:${String(e.revision)}`;u(s.messageId,s.subagent.id,o=>({toolCalls:[...(o.toolCalls||[]).filter(d=>d.toolCallId!==i),{toolCallId:i,toolName:"MCP Resource",arguments:JSON.stringify({serverName:e.serverName,uri:e.uri}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP resource updated: ${String(e.uri)}`}]}))},tt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=String(e.phase),o=`mcp-connection:${String(e.revision)}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==o),{toolCallId:o,toolName:"MCP Connection",arguments:JSON.stringify({serverName:e.serverName,phase:i,reason:e.reason,attempt:e.attempt,maxAttempts:e.maxAttempts}),toolKind:"readonly",status:i==="failed"?"error":"success",startTime:Date.now(),summary:`MCP ${String(e.serverName)} ${i}`+(i==="reconnecting"?` (${String(e.attempt)}/${String(e.maxAttempts)})`:""),output:e.error?`Error: ${String(e.error)}`:void 0}]}))},nt=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=String(e.level),o=typeof e.logger=="string"?e.logger:void 0,d=`mcp-log:${String(e.revision)}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Log",arguments:JSON.stringify({serverName:e.serverName,level:i,logger:o}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP ${i} · ${String(e.serverName)}`+(o?` · ${o}`:""),output:[String(e.message),`SHA-256: ${String(e.dataSha256)}`,e.truncated===!0?"Truncated":"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
19
|
-
`)}]}))},st=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=String(e.serverName),o=String(e.action),d=`mcp-instructions:${String(e.revision)}:${i}:${o}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Instructions",arguments:JSON.stringify({serverName:i,action:o,reason:e.reason}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`MCP instructions ${o}: ${i}`+(e.truncated===!0?" (truncated)":""),output:[typeof e.text=="string"?e.text:"",e.sha256?`SHA-256: ${String(e.sha256)}`:"",e.detailsOmitted===!0?"Details omitted by runtime policy":""].filter(Boolean).join(`
|
|
20
|
-
`)}]}))},it=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=String(e.taskId),o=String(e.status),d=`mcp-task:${i}`;u(s.messageId,s.subagent.id,c=>({toolCalls:[...(c.toolCalls||[]).filter(l=>l.toolCallId!==d),{toolCallId:d,toolName:"MCP Task",arguments:JSON.stringify({taskId:i,serverName:e.serverName,toolName:e.toolName}),toolKind:"readonly",status:o==="failed"||o==="cancelled"?"error":o==="completed"?"success":"running",startTime:Number(e.createdAt)||Date.now(),summary:`MCP task ${o}: ${i} · ${String(e.serverName)}/${String(e.toolName)}`,output:[typeof e.statusMessage=="string"?e.statusMessage:"",e.hasResult===!0?"Result available via TaskOutput":"",typeof e.error=="string"?`Error: ${e.error}`:""].filter(Boolean).join(`
|
|
21
|
-
`)}]}))},ot=(e,t)=>{const{currentSessionId:n,currentAssistantMessageId:r,messages:a,updateSubagent:u}=t();if(e.sessionId!==n)return;const s=b(a,e.subagentSessionId,r);if(!s)return;const i=Array.isArray(e.files)?e.files.filter(d=>!!d&&typeof d=="object"&&!Array.isArray(d)):[],o=`project-rules:${i.map(d=>String(d.id)).join(",")}`;u(s.messageId,s.subagent.id,d=>({toolCalls:[...(d.toolCalls||[]).filter(c=>c.toolCallId!==o),{toolCallId:o,toolName:"Project Rules",arguments:JSON.stringify({triggerPaths:e.triggerPaths,blockedWrite:e.blockedWrite}),toolKind:"readonly",status:"success",startTime:Date.now(),summary:`Project rules loaded: ${i.length}`,output:i.map(c=>`${String(c.relativePath)} ${String(c.source)} SHA-256: ${String(c.contentSha256)}`).join(`
|
|
22
|
-
`)}]}))},at=(e,t,n)=>{const{currentSessionId:r,setConfirmation:a}=t();if(e.sessionId!==r)return;const u=e.requestId||"",s=v(t,n,u?`assistant-permission-${u}`:void 0);if(!s)return;const i=e.details,o=e.toolName||(i==null?void 0:i.toolName)||"Tool";a(s,{toolCallId:u,toolName:o,description:e.description,diff:(i==null?void 0:i.details)||(i==null?void 0:i.diff)||"",allowRemember:(i==null?void 0:i.type)!=="mcpSampling",status:"pending"}),n(d=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:d.sessions.map(c=>c.sessionId===e.sessionId&&c.projectPath===e.projectPath?{...c,pendingInteraction:{type:"permission",requestId:u}}:c)}))},rt=(e,t,n)=>{var I,h;const{currentSessionId:r,currentSessionRef:a,messages:u,setConfirmation:s,setElicitation:i}=t();if(e.sessionId!==r)return;const o=e.requestId,d=u.find(m=>{var y,S;return((S=(y=m.agentContent)==null?void 0:y.confirmation)==null?void 0:S.toolCallId)===o}),c=(I=d==null?void 0:d.agentContent)==null?void 0:I.confirmation;d&&(c==null?void 0:c.status)==="pending"&&s(d.id,{...c,status:"denied"});const l=u.find(m=>{var y,S;return((S=(y=m.agentContent)==null?void 0:y.elicitation)==null?void 0:S.toolCallId)===o}),g=(h=l==null?void 0:l.agentContent)==null?void 0:h.elicitation;l&&(g==null?void 0:g.status)==="pending"&&i(l.id,{...g,status:"cancelled"}),n({agentPhase:"running",error:"Permission request timed out",errorContext:{kind:"interaction",...a?{sessionRef:a}:{}}})},ie=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",isStreaming:!0})},ut=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:e.reason==="context_limit"?"recovering_context":"compacting"})},dt=(e,t,n)=>{e.sessionId===t().currentSessionId&&(t().resetContextUsage(),n({agentPhase:"running"}))},lt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"switching_model",providerRetry:null,providerStall:null,actionStationarity:null})},ct=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerRetry:e.phase==="recovered"?null:e})},gt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",providerStall:e.phase==="detected"?e:null})},mt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({agentPhase:"running",actionStationarity:e.phase==="recovered"?null:e})},ft=(e,t,n)=>{const{currentSessionId:r,setQuestion:a}=t();if(e.sessionId!==r)return;const u=e.requestId||e.toolCallId||"",s=v(t,n,u?`assistant-question-${u}`:void 0);s&&(a(s,{toolCallId:u,questions:e.questions,status:"pending"}),n(i=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:i.sessions.map(o=>o.sessionId===e.sessionId&&o.projectPath===e.projectPath?{...o,pendingInteraction:{type:"question",requestId:u}}:o)})))},It=(e,t,n)=>{const{currentSessionId:r,setElicitation:a}=t();if(e.sessionId!==r)return;const u=e.requestId||e.toolCallId||"",s=v(t,n,u?`assistant-elicitation-${u}`:void 0),i=e.elicitation;!s||!i||(a(s,{toolCallId:u,details:i,status:"pending"}),n(o=>({agentPhase:"waiting_permission",isStreaming:!0,sessions:o.sessions.map(d=>d.sessionId===e.sessionId&&d.projectPath===e.projectPath?{...d,pendingInteraction:{type:"elicitation",requestId:u}}:d)})))},St=(e,t,n)=>{const{currentSessionId:r}=t();if(e.sessionId!==r)return;const a=e.requestId;n(u=>({agentPhase:"running",sessions:u.sessions.map(s=>{var i;return s.sessionId===e.sessionId&&s.projectPath===e.projectPath&&((i=s.pendingInteraction)==null?void 0:i.requestId)===a?{...s,pendingInteraction:void 0}:s})}))},U=(e,t)=>{const{currentSessionId:n,endAgentResponse:r}=t();e.sessionId===n&&r()},ht=(e,t,n)=>{const{currentSessionId:r,currentSessionRef:a,endAgentResponse:u}=t();if(e.sessionId!==r)return;const s=e.taskFailure&&typeof e.taskFailure=="object"&&!Array.isArray(e.taskFailure)?e.taskFailure:void 0,i=Ae(s==null?void 0:s.code);n({agentPhase:"error",error:e.error||"An error occurred",errorContext:{kind:"execution",...a?{sessionRef:a}:{},...i?{failureCode:i}:{}}}),u()},yt=(e,t,n)=>{const{currentSessionId:r}=t();if(e.sessionId===r)if(e.status==="idle")n({isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0});else if(e.status==="queued"||e.status==="running"||e.status==="waiting_permission"){const a=typeof e.queued=="number"?Math.max(0,e.queued):0;n({isStreaming:!0,agentPhase:e.status==="waiting_permission"?"waiting_permission":"running",currentRunId:typeof e.runId=="string"?e.runId:t().currentRunId,pendingSteeringCount:a,pendingInputDelivery:a>0&&(e.pendingInputDelivery==="current_turn"||e.pendingInputDelivery==="next_turn")?e.pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})}else e.status==="error"&&n({isStreaming:!1,isStopping:!1,agentPhase:"error",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null})},Ct=(e,t,n)=>{const{currentSessionId:r,endAgentResponse:a,messages:u,updateSubagent:s}=t();if(e.sessionId===r){n(i=>({isStreaming:!1,agentPhase:"idle",messages:i.messages.map(o=>{var c;const d=(c=o.agentContent)==null?void 0:c.elicitation;return(d==null?void 0:d.status)!=="pending"||!o.agentContent?o:{...o,agentContent:{...o.agentContent,elicitation:{...d,status:"cancelled"}}}})}));for(const i of u)for(const o of N(i.agentContent))o.status==="running"&&s(i.id,o.id,{status:"failed"});a()}},bt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"current_turn"})},vt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({pendingSteeringCount:typeof e.queued=="number"?Math.max(0,e.queued):1,pendingInputDelivery:"next_turn"})},At=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const r=typeof e.queued=="number"?Math.max(0,e.queued):0;n({pendingSteeringCount:r,pendingInputDelivery:r>0?t().pendingInputDelivery:null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},Tt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId)return;const r=typeof e.queued=="number"?Math.max(0,e.queued):0;n({agentPhase:"running",pendingSteeringCount:r,pendingInputDelivery:r>0?"current_turn":null,recoveredSteeringCount:typeof e.recovered=="number"?Math.max(0,e.recovered):t().recoveredSteeringCount})},kt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??null})},$t=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:null})},Nt=(e,t,n)=>{e.sessionId===t().currentSessionId&&n({goal:e.goal??t().goal,isStreaming:!0,agentPhase:"running"})},Mt=(e,t,n)=>{if(e.sessionId!==t().currentSessionId||!Array.isArray(e.messages))return;const r=Date.now(),a=e.messages.flatMap((u,s)=>{if(typeof u!="object"||u===null)return[];const i=u;return!["user","assistant","system","tool"].includes(String(i.role))||!Array.isArray(i.content)&&typeof i.content!="string"?[]:[{id:`rewind-${s}-${r}`,role:i.role,content:i.content,timestamp:r+s,metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:void 0,thinkingContent:typeof i.thinkingContent=="string"?i.thinkingContent:typeof i.reasoningContent=="string"?i.reasoningContent:void 0,tool_call_id:typeof i.tool_call_id=="string"?i.tool_call_id:void 0,name:typeof i.name=="string"?i.name:void 0,tool_calls:i.tool_calls}]});n({messages:be(a),isStreaming:!1,isStopping:!1,agentPhase:"idle",providerRetry:null,providerStall:null,actionStationarity:null,currentRunId:null,pendingSteeringCount:0,pendingInputDelivery:null,recoveredSteeringCount:0,currentAssistantMessageId:null,hasToolCalls:!1})},Rt=(e,t,n)=>{const r=t().currentSessionRef;if(!r||e.sessionId!==r.sessionId||e.projectPath!==r.projectPath)return;const a=e.status,u=a==="completed"||a==="stale"?"completed":a==="aborted"?"cancelled":a==="interrupted"?"interrupted":"failed";n(s=>({sessions:s.sessions.map(i=>i.sessionId===r.sessionId&&i.projectPath===r.projectPath?{...i,taskStatus:u,taskStatusReason:void 0,taskFailure:void 0,taskCompletedAt:new Date().toISOString()}:i)})),t().selectSession(r)},xt=(e,t,n)=>{ue({...e,messageId:`review-${String(e.reviewId??"active")}`,arguments:"{}"},t,n)},wt=(e,t,n)=>{de(e,t)},Pt=(e,t,n)=>{le(e,t,n)},_={"message.created":$e,"message.delta":Ne,"message.complete":Me,"structured.output":Re,"thinking.delta":xe,"thinking.completed":we,"tool.start":ue,"tool.progress":de,"tool.result":le,"mcp.catalog.changed":Pe,"mcp.content.changed":De,"mcp.resource.updated":_e,"mcp.connection.changed":je,"mcp.log":qe,"mcp.instructions.changed":Fe,"mcp.task.changed":Oe,"project.rules.loaded":Ve,"user.shell.started":Ee,"user.shell.output":Ke,"user.shell.completed":Ue,"token.usage":Be,"task.updated":Je,"subagent.start":Le,"subagent.update":He,"subagent.delta":Ge,"subagent.thinking.delta":Qe,"subagent.tool.start":We,"subagent.tool.progress":Xe,"subagent.tool.result":Ye,"subagent.mcp.catalog.changed":Ze,"subagent.mcp.content.changed":pe,"subagent.mcp.resource.updated":et,"subagent.mcp.connection.changed":tt,"subagent.mcp.log":nt,"subagent.mcp.instructions.changed":st,"subagent.mcp.task.changed":it,"subagent.project.rules.loaded":ot,"subagent.complete":ze,"permission.asked":at,"permission.timeout":rt,"turn.started":ie,"committed.turn_started":ie,"committed.turn_completed":U,"committed.turn_aborted":U,"provider.retry":ct,"provider.stall":gt,"action.stationarity":mt,"compaction.started":ut,"compaction.completed":dt,"model.fallback":lt,"question.required":ft,"elicitation.required":It,"interaction.resolved":St,"session.completed":U,"session.error":ht,"session.status":yt,"run.cancelled":Ct,"steering.queued":bt,"follow_up.queued":vt,"follow_up.started":Tt,"steering.applied":At,"goal.updated":kt,"goal.cleared":$t,"goal.continuation.started":Nt,"session.rewound":Mt,"review.tool.started":xt,"review.tool.progress":wt,"review.tool.completed":Pt,"review.completed":Rt},Dt=new Set(["message.complete","thinking.completed","session.completed","session.error","run.cancelled","committed.turn_completed","committed.turn_aborted"]),Ft=(e,t)=>n=>{const r=e().currentSessionRef,a=n.properties;if(!r||a.sessionId!==r.sessionId||a.projectPath!==r.projectPath)return;if(Dt.has(n.type)){$.drainAll();const s=_[n.type];s&&s(n.properties,e,t);return}if(n.type==="tool.start"&&$.drainAll(),n.type==="message.delta"){const{currentSessionId:s,currentAssistantMessageId:i,hasToolCalls:o}=e();if(a.sessionId!==s)return;const d=a.messageId||i,c=a.delta;if(!i){const I=_["message.delta"];I&&I(a,e,t);return}const l=o?"after":"before",g=`content:${d}:${l}`;$.drainAllExcept(g),$.append(g,c,I=>{const{appendDelta:h}=e();d&&h(d,I,l)});return}if(n.type==="thinking.delta"){const{currentSessionId:s,currentAssistantMessageId:i}=e();if(a.sessionId!==s)return;if(!i){const l=_["thinking.delta"];l&&l(a,e,t);return}const o=a.delta,d=a.messageId||i,c=`thinking:${d}`;$.drainAllExcept(c),$.append(c,o,l=>{const{appendThinking:g}=e();d&&g(d,l)});return}if(n.type==="subagent.delta"){const{currentSessionId:s}=e();if(a.sessionId!==s)return;const i=a.delta;if(!i)return;const o=a.subagentSessionId||"",d=`subagent:${o}`,{currentAssistantMessageId:c,messages:l}=e(),g=b(l,o||void 0,c);$.append(d,i,I=>{const{currentAssistantMessageId:h,messages:m,updateSubagent:y}=e(),S=g||b(m,o||void 0,h);S&&y(S.messageId,S.subagent.id,f=>({sessionId:f.sessionId||o,output:(f.output||"")+I}))});return}if(n.type==="subagent.thinking.delta"){const{currentSessionId:s}=e();if(a.sessionId!==s)return;const i=a.delta;if(!i)return;const o=a.subagentSessionId||"",d=`subagent-thinking:${o}`,{currentAssistantMessageId:c,messages:l}=e(),g=b(l,o||void 0,c);$.append(d,i,I=>{const{currentAssistantMessageId:h,messages:m,updateSubagent:y}=e(),S=g||b(m,o||void 0,h);S&&y(S.messageId,S.subagent.id,f=>({sessionId:f.sessionId||o,thinking:(f.thinking||"")+I}))});return}const u=_[n.type];u&&u(n.properties,e,t)};export{fe as a,se as b,M as c,me as d,be as e,Ft as f,N as g,$ as h,Ae as i,qt as j,Ie as k,j as l,jt as t,ne as u,B as w};
|