blade-code 0.10.132 → 0.10.136
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-0qq64xqm.js +25 -0
- package/dist/{chunk-gmqpfm52.js → chunk-13sdjfks.js} +2 -2
- package/dist/{chunk-t8rjxqp2.js → chunk-1cbaqh71.js} +2 -2
- package/dist/chunk-1dscf8xj.js +23 -0
- package/dist/chunk-1n5d6b5k.js +1 -0
- package/dist/{chunk-zwjrensv.js → chunk-1p9sjb8d.js} +1 -1
- package/dist/{chunk-dvb89529.js → chunk-1pmvyqed.js} +1 -1
- package/dist/chunk-1qdemrkr.js +1 -0
- package/dist/{chunk-6p6ts4kv.js → chunk-24rsvr6e.js} +2 -2
- package/dist/{chunk-qcydkn1n.js → chunk-46jmq302.js} +1 -1
- package/dist/{chunk-sx77dpxw.js → chunk-5sknjz9b.js} +1 -1
- package/dist/{chunk-td2jk2xn.js → chunk-6rvrx275.js} +2 -2
- package/dist/{chunk-g4xny949.js → chunk-77x1rrz9.js} +1 -1
- package/dist/{chunk-e371f7xk.js → chunk-82x77b2p.js} +2 -2
- package/dist/chunk-83nxcfz3.js +1 -0
- package/dist/{chunk-fag8rk53.js → chunk-91pb41e7.js} +1 -1
- package/dist/{chunk-g1bqjdeq.js → chunk-9y7j565j.js} +2 -2
- package/dist/{chunk-bavzm721.js → chunk-9z9v8v4j.js} +1 -1
- package/dist/{chunk-ajsw4te2.js → chunk-acsfh1cw.js} +2 -2
- package/dist/chunk-as8stb2j.js +10 -0
- package/dist/chunk-azaqc1b6.js +1 -0
- package/dist/{chunk-tkydv9k8.js → chunk-bdtpq7j9.js} +1 -1
- package/dist/chunk-c5rfnzhf.js +171 -0
- package/dist/{chunk-pqsvz99n.js → chunk-c85xvthj.js} +1 -1
- package/dist/{chunk-zssz8hc4.js → chunk-cgkbdh2m.js} +1 -1
- package/dist/chunk-e1warjkn.js +171 -0
- package/dist/{chunk-aaxc81jc.js → chunk-f7hsagj6.js} +1 -1
- package/dist/{chunk-prt6y5fv.js → chunk-ffh4c30x.js} +1 -1
- package/dist/chunk-fnc97xg7.js +2 -0
- package/dist/chunk-g13jmewd.js +1 -0
- package/dist/{chunk-9gs4eqt8.js → chunk-g45camrd.js} +1 -1
- package/dist/{chunk-6q3g5e3m.js → chunk-g4vgnxh4.js} +1 -1
- package/dist/{chunk-ar5np5h5.js → chunk-g7h0peka.js} +2 -2
- package/dist/{chunk-jkfkyedn.js → chunk-gdnyt8a7.js} +1 -1
- package/dist/chunk-gq7fdc8c.js +2 -0
- package/dist/chunk-gwjah260.js +1 -0
- package/dist/{chunk-7dy3mzgz.js → chunk-hqwpnb0x.js} +2 -2
- package/dist/{chunk-sbc90z9j.js → chunk-hx10bph0.js} +2 -2
- package/dist/{chunk-2y1qngw7.js → chunk-jb8stg10.js} +1 -1
- package/dist/{chunk-44jtpg8y.js → chunk-jc28ddt0.js} +1 -1
- package/dist/{chunk-a60cmnmz.js → chunk-kbnxbb23.js} +2 -2
- package/dist/{chunk-0bkhpd72.js → chunk-mm1atkae.js} +2 -2
- package/dist/{chunk-b5z1rec4.js → chunk-mq1mk3v5.js} +27 -27
- package/dist/{chunk-rj8mmwc6.js → chunk-mxe4pr8t.js} +2 -2
- package/dist/chunk-n238rdz8.js +1 -0
- package/dist/{chunk-pj69j4zp.js → chunk-na3nregt.js} +1 -1
- package/dist/{chunk-sj1dzeta.js → chunk-nfzad4te.js} +1 -1
- package/dist/{chunk-zkzhm39s.js → chunk-ntd69c0k.js} +1 -1
- package/dist/{chunk-sfe4810k.js → chunk-nzwh9v6t.js} +1 -1
- package/dist/chunk-pnanbvn3.js +1 -0
- package/dist/chunk-pz91qga3.js +1 -0
- package/dist/{chunk-mdew58v9.js → chunk-q0s3gcjm.js} +1 -1
- package/dist/chunk-qjydadex.js +14 -0
- package/dist/{chunk-r7kevfd3.js → chunk-qm96k94k.js} +3 -3
- package/dist/{chunk-grhsv55v.js → chunk-r51afpkk.js} +1 -1
- package/dist/{chunk-dfjmvj3d.js → chunk-s3a017q7.js} +2 -2
- package/dist/{chunk-mg1s861p.js → chunk-s4b1r3my.js} +1 -1
- package/dist/{chunk-93x9xbew.js → chunk-sv5z5sna.js} +1 -1
- package/dist/{chunk-xjrmq0pg.js → chunk-sy0vxdc3.js} +379 -377
- package/dist/{chunk-749jzrbk.js → chunk-t6cajkaj.js} +2 -2
- package/dist/chunk-tah2002b.js +1 -0
- package/dist/{chunk-mvm1rzc4.js → chunk-tev70rzj.js} +2 -2
- package/dist/chunk-tzfd2fza.js +1 -0
- package/dist/{chunk-y0kqkewg.js → chunk-v2qxszks.js} +2 -2
- package/dist/chunk-v3veeja5.js +1 -0
- package/dist/chunk-vptn8fhx.js +2 -0
- package/dist/{chunk-edtxcqxa.js → chunk-vvawhvea.js} +1 -1
- package/dist/chunk-w2n1vwzg.js +2 -0
- package/dist/{chunk-p00f53yq.js → chunk-wj16pvvn.js} +1 -1
- package/dist/chunk-wj813rcc.js +1 -0
- package/dist/{chunk-77efqpdc.js → chunk-wzkh3e6a.js} +1 -1
- package/dist/{chunk-8y08fytr.js → chunk-xtngc0th.js} +1 -1
- package/dist/{chunk-z03dtyh6.js → chunk-yacv7f7h.js} +1 -1
- package/dist/{chunk-53h87fmt.js → chunk-z3hpstky.js} +1 -1
- package/dist/{chunk-qcvxff27.js → chunk-zy2etr3v.js} +2 -2
- package/dist/web/assets/ChatView-Bc9twpWM.js +63 -0
- package/dist/web/assets/{CodeBlockHighlighter-DR5RLA1_.js → CodeBlockHighlighter-41xRPXs2.js} +1 -1
- package/dist/web/assets/{FilePreview-C4tqzUOM.js → FilePreview-lcc_hL7J.js} +15 -20
- package/dist/web/assets/{KanbanBoard-D7HJQXE2.js → KanbanBoard-BHgM338V.js} +4 -4
- package/dist/web/assets/{MarkdownRenderer-Ct8vtONO.js → MarkdownRenderer-BMAuTkc6.js} +3 -3
- package/dist/web/assets/{ScrollArea-CMSE6nO4.js → ScrollArea-DJq2Kdpi.js} +1 -1
- package/dist/web/assets/{SessionHistorySurface-BPwnF9ND.js → SessionHistorySurface-DSe8ePBJ.js} +2 -2
- package/dist/web/assets/{SettingsModal-KW5WYAov.js → SettingsModal-Cih4bWul.js} +1 -1
- package/dist/web/assets/{Sidebar-8BUNEHHQ.js → Sidebar-DnWlUKmO.js} +2 -2
- package/dist/web/assets/{TaskSwitcher-CZfkp2L_.js → TaskSwitcher-D3mrXv_i.js} +2 -2
- package/dist/web/assets/{TerminalPanel-DBBMaU_6.js → TerminalPanel-BNKHhBVM.js} +2 -2
- package/dist/web/assets/{archive-tBd5snSF.js → archive-Dof4YpyT.js} +1 -1
- package/dist/web/assets/{arrow-left-Cs_sFMp-.js → arrow-left-DGFXaGox.js} +1 -1
- package/dist/web/assets/{calendar-clock-C0ue6XTy.js → calendar-clock-BoxUNOvH.js} +1 -1
- package/dist/web/assets/{chevron-right-DZHCUfAH.js → chevron-right-Brb1rhaA.js} +1 -1
- package/dist/web/assets/chevrons-up-down-N-VshXV_.js +16 -0
- package/dist/web/assets/{clock-3-DstAM2AR.js → clock-3-gdZEKe2U.js} +1 -1
- package/dist/web/assets/{copy-BfnFXTgG.js → copy-d9M8JUfQ.js} +1 -1
- package/dist/web/assets/{download-XKyNtMnj.js → download-CQ-Pwfq0.js} +1 -1
- package/dist/web/assets/{external-link-3bcWFMya.js → external-link-GRAtjoO2.js} +1 -1
- package/dist/web/assets/{folder-D7hQLvy7.js → folder-CqLD0IBh.js} +1 -1
- package/dist/web/assets/index-CPpIFWLG.css +1 -0
- package/dist/web/assets/index-DiRs2_w4.js +203 -0
- package/dist/web/assets/{pause-CBR55GXy.js → pause-BqsFgQi0.js} +1 -1
- package/dist/web/assets/{pencil-8yqeFHC4.js → pencil-Ca9289F-.js} +1 -1
- package/dist/web/assets/{play-F_Spkp4p.js → play-DmEPnYDS.js} +1 -1
- package/dist/web/assets/{plus-CJCqq3rG.js → plus-kIBLgk0p.js} +1 -1
- package/dist/web/assets/session-events-BqQQkbAN.js +29 -0
- package/dist/web/assets/{settings-G6riyt4S.js → settings-BuSrJl6s.js} +1 -1
- package/dist/web/assets/teamService-B7Fp8Oyg.js +1 -0
- package/dist/web/assets/{terminal-_Nebc2yj.js → terminal-Qkr_gcNu.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
- package/dist/chunk-0gmbvtpp.js +0 -1
- package/dist/chunk-0z9nqbd0.js +0 -2
- package/dist/chunk-14z94k0r.js +0 -1
- package/dist/chunk-3e0t25rq.js +0 -171
- package/dist/chunk-53j6nh8j.js +0 -1
- package/dist/chunk-64kg5a9r.js +0 -1
- package/dist/chunk-9d49tj9y.js +0 -2
- package/dist/chunk-9s8saznq.js +0 -1
- package/dist/chunk-dhzbac1c.js +0 -1
- package/dist/chunk-f8gb685p.js +0 -2
- package/dist/chunk-g12kqs1b.js +0 -1
- package/dist/chunk-j3nmt09e.js +0 -25
- package/dist/chunk-kd3k1q9z.js +0 -1
- package/dist/chunk-m9mw8ppy.js +0 -1
- package/dist/chunk-pkg1bvzc.js +0 -1
- package/dist/chunk-q7m0tvhw.js +0 -1
- package/dist/chunk-sf9sbm6y.js +0 -1
- package/dist/chunk-sm9p1fkf.js +0 -14
- package/dist/chunk-v52wc8yg.js +0 -2
- package/dist/chunk-xyxjcehh.js +0 -23
- package/dist/chunk-z28dcrr9.js +0 -10
- package/dist/chunk-z83xk6jn.js +0 -1
- package/dist/chunk-znqt5g8v.js +0 -170
- package/dist/web/assets/ChatView-CkmlibKO.js +0 -53
- package/dist/web/assets/chevrons-up-down-BSa16Scz.js +0 -11
- package/dist/web/assets/index-B4186fIT.css +0 -1
- package/dist/web/assets/index-CCdnLriX.js +0 -210
- package/dist/web/assets/session-events-C6fPz20c.js +0 -22
- package/dist/web/assets/teamService-Cixkq48S.js +0 -1
package/dist/chunk-xyxjcehh.js
DELETED
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import{v as tz,w as ez}from"./chunk-bavzm721.js";import{A as S,x as yz,y as Iz,z as kz}from"./chunk-qcydkn1n.js";import{B as sz,C as Pz,D as Ez,E as Tz,F as xz,G as bz}from"./chunk-6q3g5e3m.js";import{Aa as Mz,N as R,W as wz,X as Fz,aa as Oz,da as Nz,ea as Az,ha as qz,xa as Rz,ya as Sz,za as hz}from"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import{Oa as nz}from"./chunk-sbc90z9j.js";import{Qa as Dz}from"./chunk-v52wc8yg.js";import{Kb as Kz,Tb as d,yb as _z}from"./chunk-3e0t25rq.js";import{cc as m}from"./chunk-77efqpdc.js";import{Dd as Uz,Gd as jz,Id as h,Ld as Gz,Qd as Vz,Td as K,md as Wz,wd as M,xd as v,yd as Bz}from"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import{pe as Hz,we as l,xe as Xz}from"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import{hf as zJ}from"./chunk-y0kqkewg.js";import"./chunk-a60cmnmz.js";import{Cf as iz,Df as az}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import{Of as n}from"./chunk-mdew58v9.js";import{Tf as Lz}from"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import{cg as rz}from"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import{Yg as oz}from"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import{$h as dz,ci as lz}from"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import{Ai as g,Bi as Yz,Di as c,Ei as p}from"./chunk-f8gb685p.js";import{Ii as o}from"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import{oj as y}from"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import{vj as mz,yj as vz}from"./chunk-tkydv9k8.js";import"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import{Mj as Qz,Nj as cz,Rj as s,Vj as t,Wj as pz,Xj as e}from"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import{Readable as VJ,Writable as _J}from"node:stream";import*as f from"@agentclientprotocol/sdk";import i from"node:path";import{PROTOCOL_VERSION as XJ,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as Cz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var V=y("Agent");function T(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function $z(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function $J(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:$z(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:$z("headers"in z?z.headers:void 0)};return null}function QJ(z){let J={};for(let Z of z){let Y=$J(Z);if(Y)J[Z.name]=Y}return J}function fz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let Z=J.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(Z);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function YJ(z){let J=Xz(z.metadata);return J?[{type:"text",text:l(J)}]:fz(z.content)}function LJ(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
-
`)}function WJ(z){if(!Lz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...M("capacity"),resource:z.resource}}function HJ(z){if(!(z instanceof Cz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Bz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,J,Z,Y,W={}){this.id=z;this.roots=J;this.connection=Z;this.clientCapabilities=Y;this.options=W;this.messages=[...W.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(W.permissionMode),this.updateEgress=new bz({maxPendingItems:Pz,maxPendingBytes:Ez,writeTimeoutMs:Tz,signal:Z.signal,sizeOf:(H)=>Buffer.byteLength(JSON.stringify(H)),write:async(H)=>{await Z.sessionUpdate(H)},onFailure:(H)=>this.handleUpdateEgressFailure(H)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await this.loadPersistedModelContext();return J.length>0?J:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?K.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?K.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):K.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,J=z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await K.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(Z){if(!(Z instanceof Vz)&&Z.code!=="ENOENT")throw Z;await K.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...J})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await K.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await K.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){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 qz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){V.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(L)=>{await this.sendUpdateAndWait(L)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(V.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await d.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(L)=>this.requestPermission(L)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?QJ(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),W=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Oz.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...W?{workspace:W}:{},permissionMode:this.mapModeToPermissionMode(),...Z?{mcpServers:Z}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(L,U)=>{let j=await Y.execute(L,{cwd:U.cwd,env:U.env,timeout:U.timeoutMs,signal:U.signal,allowLocalFallback:!1,onOutput:(G)=>U.onOutput?.("stdout",G)});return{exitCode:j.exitCode,stdout:j.stdout,stderr:j.stderr,...j.error?{error:j.error}:{},timedOut:j.failureKind==="timeout",aborted:j.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await Sz(this.roots.hostStateRoot);V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=_z.subscribe((L)=>{if(L.sessionId!==this.id||L.projectPath!==this.roots.hostStateRoot)return;if(L.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":L.properties}}),this.requestPendingResume();return}if(L.type==="task.delivery"){if(!L.properties.taskDelivery||typeof L.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":L.properties.taskDelivery,...L.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(L.type.startsWith("team.")){let{teamName:U,messageId:j,content:G}=L.properties,P=L.properties.metadata;if(L.type==="team.message.received"&&typeof U==="string"&&typeof j==="string"&&typeof G==="string"&&Fz(P,{messageId:j,teamName:U}))(async()=>{let E=await this.runtime?.enqueueSteering(G,{allowBeforeTurn:!0,messageId:j,origin:"team_message",metadata:P});if(!E?.accepted)return;if(await new wz(U,Qz()).markDelivered([j]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:L.type,...L.properties}}});return}if(L.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof L.properties.updatedAt==="string"?L.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":L.properties.taskStatus,...typeof L.properties.taskStatusReason==="string"?{"blade/taskStatusReason":L.properties.taskStatusReason}:{},...L.properties.taskFailure&&typeof L.properties.taskFailure==="object"?{"blade/taskFailure":L.properties.taskFailure}:{},...typeof L.properties.taskStartedAt==="string"?{"blade/taskStartedAt":L.properties.taskStartedAt}:{},...typeof L.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":L.properties.taskCompletedAt}:{},...L.properties.taskDiffStat&&typeof L.properties.taskDiffStat==="object"?{"blade/taskDiffStat":L.properties.taskDiffStat}:{},...typeof L.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":L.properties.taskQueuePosition}:{},...typeof L.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":L.properties.taskQueueDepth}:{},...typeof L.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":L.properties.taskConcurrencyLimit}:{},...typeof L.properties.taskInFlight==="number"?{"blade/taskInFlight":L.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(X||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Hz(J))continue;let Z=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!Z)continue;for(let Y of YJ(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:Z,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);V.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(z,J){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let Z={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let X=await this.runtime.rewindSession(Q);return this.messages=[...X.messages],this.contextMessages=await this.loadModelContextOr(X.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),X}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!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(Q)=>{if(await this.setServiceTier(Q),!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(Q)=>{if(await this.setResponseVerbosity(Q),!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(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,L,U=(G)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.id,status:G.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:G.result?.message||G.result?.error||`Subagent ${G.status}`}}]})},j=this.runtime.resumeSubagent({agentId:Q,prompt:X,onCompleted:(G)=>{if(B)U(G);else L=G}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.session.id,status:"in_progress",title:`Resuming ${j.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${j.source.id} at depth ${j.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,L)U(L);return j}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,X,B)},complete:async(Q,X,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,X,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,X)},getLogs:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,X)},setLoggingLevel:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,X)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:X})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,X)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:X,onEvent:(j)=>{if(j.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:j.toolCall.id,status:"in_progress",title:`Review: ${j.toolCall.function.name}`,content:[],kind:this.mapToolKind(j.toolKind)});else if(j.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:j.toolCall.id,status:j.result.success?"completed":"failed",content:[]})}}),L=await B.completion,U=(await S.list(this.roots.hostStateRoot,this.id)).find((j)=>j.start.reviewId===B.reviewId);if(!U)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:L.status,findings:L.findings.length,content:Wz(U.start,L)}}}}:{},signal:J,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,X,B)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,U=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(X,null,2)}}],kind:U})},sendToolResult:(Q,X)=>{if(X.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X.summary}})}}},Y=await hz(z,Z),W=Y.data?.action;if(W==="start_goal"||W==="resume_goal")this.requestPendingResume();if(W==="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 Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let H=Y.content||Y.message;if(H)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:H}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(Z){if(J.aborted||Z instanceof Error&&Z.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,Z),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${Z instanceof Error?Z.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,Z,Y=new Promise((W)=>{Z=W});this.pendingSideConversation=J,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,J.signal)}catch(W){if(J.signal.aborted||W instanceof Error&&W.name==="AbortError")return{stopReason:"cancelled"};throw W}finally{if(Z(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Mz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),J=["model","permissions","theme","config","exit","ide"],Y=z.filter((W)=>!J.includes(W.name)&&(W.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((W)=>{let H;if(W.usage){let Q=W.usage.replace(/^\/\w+\s*/,"").trim();if(Q)H=Q}if(W.aliases?.length){let Q=`Aliases: ${W.aliases.join(", ")}`;H=H?`${H} | ${Q}`:Q}return{name:W.name,description:W.description,input:H?{hint:H}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map((W)=>W.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),V.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let Z=this.resolvePrompt(z.prompt),Y=Z.content,W=Z.displayText,H=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((D)=>D.outputSchema)?.outputSchema:void 0),Q;if(H!==void 0)Q=Gz(H).schema;if(W.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(W)}let X=Dz(W);if(X){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((D)=>D.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(X.question?`/btw ${X.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(W.trim()))return this.handleSlashCommand(W,this.pendingPrompt.signal);let D=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!D.accepted)throw Error(D.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(V.debug(`[AcpSession ${this.id}] Queued steering for active turn (${D.queued})`),D.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,L=()=>{B.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let U=!1,j=!1,G=!1,P,E=new Promise((D)=>{P=D});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${W.slice(0,100)}...`),Rz(W)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(W,B.signal)}let D={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async($)=>{this.mode=this.mapPermissionModeToMode($),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async($)=>{return this.requestPermission($)}}},O=await Kz(this.agent.chatStream(Y,D,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)j=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{G=!0;let _=$.toolCall,N=_.function.name;if(N===h)break;let q=this.mapToolKind($.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in _)try{let b=JSON.parse(_.function.arguments),F=b.resume_from??b.resume;if(typeof F==="string")w=`Resuming ${String(b.subagent_type||"subagent")} from ${F}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:_.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{G=!0;let _=$.toolCall;if(_.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{G=!0;let _=$.toolCall;if(_.function.name===h)break;let N=$.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let F of w.changes){if(!F||typeof F!=="object"||!("path"in F)||typeof F.path!=="string")continue;q.push({type:"diff",path:F.path,oldText:"oldContent"in F&&typeof F.oldContent==="string"?F.oldContent:null,newText:"newContent"in F&&typeof F.newContent==="string"?F.newContent:null})}else if(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let F=_.function.name,JJ=Az(jz(Nz(F,N),Uz));q.push({type:"content",content:{type:"text",text:JJ}})}if(_.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let b=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:_.id,status:b,content:q});break}case"structured_output":j=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify($.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
3
|
-
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${$.contentKind} r${$.revision} (${$.serverName}): +${$.added.length} -${$.removed.length} ~${$.updated.length}
|
|
4
|
-
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${$.revision} (${$.serverName}): ${$.uri}
|
|
5
|
-
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${$.revision} (${$.serverName}): ${$.phase} ${$.attempt}/${$.maxAttempts}
|
|
6
|
-
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${$.revision} (${$.serverName}) ${$.level}${$.logger?` logger=${$.logger}`:""}: ${$.message}
|
|
7
|
-
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${$.revision} (${$.serverName}): ${$.action}${$.detailsOmitted?" details-omitted":""}
|
|
8
|
-
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${$.revision} ${$.taskId} (${$.serverName}/${$.toolName}): ${$.status}${$.hasResult?" result-available":""}
|
|
9
|
-
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${$.files.length}${$.blockedWrite?" (write retry required)":""}
|
|
10
|
-
`}});break;case"provider_admission":U=$.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":$.phase!=="admitted"?{phase:$.phase,requestClass:$.requestClass,resource:$.resource,scope:$.scope,...$.reason!==void 0?{reason:$.reason}:{},queuePosition:$.queuePosition,queueDepth:$.queueDepth,inFlight:$.inFlight,limit:$.limit,waitMs:$.waitMs,maxWaitMs:$.maxWaitMs,...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:$.phase,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.retryAfterMs!==void 0?{retryAfterMs:$.retryAfterMs}:{},...$.nextProbeAt!==void 0?{nextProbeAt:$.nextProbeAt}:{},openDurationMs:$.openDurationMs,...$.sampleCount!==void 0?{sampleCount:$.sampleCount}:{},...$.failureCount!==void 0?{failureCount:$.failureCount}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:$.phase,attempt:$.attempt,maxRetries:$.maxRetries,reason:$.reason,...$.statusCode!==void 0?{statusCode:$.statusCode}:{},...$.delayMs!==void 0?{delayMs:$.delayMs}:{},...$.nextRetryAt!==void 0?{nextRetryAt:$.nextRetryAt}:{},...$.mode!==void 0?{mode:$.mode}:{},...$.recoveryBudgetMs!==void 0?{recoveryBudgetMs:$.recoveryBudgetMs}:{},...$.recoveryElapsedMs!==void 0?{recoveryElapsedMs:$.recoveryElapsedMs}:{},...$.recoveryRemainingMs!==void 0?{recoveryRemainingMs:$.recoveryRemainingMs}:{},...$.exhaustedBy!==void 0?{exhaustedBy:$.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:$.phase,stallCount:$.stallCount,durationMs:$.durationMs,warningAfterMs:$.warningAfterMs,timeoutMs:$.timeoutMs,outputStarted:$.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:$.phase,toolName:$.toolName,runLength:$.runLength,nudgeThreshold:$.nudgeThreshold,haltThreshold:$.haltThreshold,progressAware:$.progressAware}}});break;case"task_update":this.sendPlanUpdate($.tasks);break;case"goal_frontier_updated":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:$.frontier.observedAt,_meta:{"blade/goalFrontier":{goalId:$.goal.goalId,status:$.goal.status,taskListId:$.frontier.taskListId,total:$.frontier.total,completed:$.frontier.completed,inProgress:$.frontier.inProgress,pending:$.frontier.pending,blocked:$.frontier.blocked,nextTask:$.frontier.nextTask,digestSha256:$.frontier.digestSha256,...$.goal.frontierStall?{stall:{category:$.goal.frontierStall.category,consecutiveCount:$.goal.frontierStall.consecutiveCount}}:{}}}}),this.sendPlanUpdate($.tasks);break;case"steering_applied":break;case"follow_up_started":{let _=0;for(let N of $.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let q of fz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(N.id),_++}if(_>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${_} queued instruction${_===1?"":"s"} recovered after restart]
|
|
11
|
-
`}});break}case"goal_updated":if($.goal)this.sendUpdate(this.goalSessionUpdate($.goal));if($.goal&&$.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${$.goal.status}: ${$.goal.objective}]
|
|
12
|
-
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:$.goal.goalId,continuation:$.continuation,...$.prematureStopPattern?{prematureStopPattern:$.prematureStopPattern}:{},...$.prematureStopCount!==void 0?{prematureStopCount:$.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:$.phase,...$.reason?{reason:$.reason}:{},...$.strategy?{strategy:$.strategy}:{},...$.outcome?{outcome:$.outcome}:{},...$.preTokens!==void 0?{preTokens:$.preTokens}:{},...$.preTokenSource?{preTokenSource:$.preTokenSource}:{},...$.estimatedPendingTokens!==void 0?{estimatedPendingTokens:$.estimatedPendingTokens}:{},...$.postTokens!==void 0?{postTokens:$.postTokens}:{},...$.sampleAttempts!==void 0?{sampleAttempts:$.sampleAttempts}:{},...$.inputReductions!==void 0?{inputReductions:$.inputReductions}:{},...$.messagesOmitted!==void 0?{messagesOmitted:$.messagesOmitted}:{},...$.filesOmitted!==void 0?{filesOmitted:$.filesOmitted}:{},...$.imagesOmitted!==void 0?{imagesOmitted:$.imagesOmitted}:{},...$.fallbackTargetTokens!==void 0?{fallbackTargetTokens:$.fallbackTargetTokens}:{},...$.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:$.fallbackMessagesOmitted}:{},...$.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:$.fallbackMessagesTruncated}:{},...$.failureReason?{failureReason:$.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())B.abort("acp-egress-failed")});if(!await this.flushUpdates())B.abort("acp-egress-failed");this.contextMessages=[...D.messages];let Jz=await this.loadPersistedMessages();if(this.messages=Jz.length>0?Jz:[...D.messages],!O.success){let $=O.error?.type??"unknown",_=O.error?.details??O.error?.message??"Agent execution failed",N=WJ(_)??v(_);throw Cz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:N,outputStarted:j,toolExecutionStarted:G,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(B.signal.aborted)return{stopReason:"cancelled"};let Zz={...O.metadata?.structuredOutput?{structuredOutput:O.metadata.structuredOutput,outputSchemaDigest:O.metadata.structuredOutputSchemaDigest}:{},...O.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:O.metadata.goalVerificationVerdict,...O.metadata.goalVerifierSessionId?{verifierSessionId:O.metadata.goalVerifierSessionId}:{},...O.metadata.goalVerificationEvidenceSha256?{evidenceSha256:O.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(Zz).length>0?{_meta:Zz}:{}}}catch(D){if(B.signal.aborted||D instanceof Error&&D.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,D),D}finally{if(J.abortSignal?.removeEventListener("abort",L),U&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(P(),this.pendingPromptCompletion===E)this.pendingPromptCompletion=null;if(this.pendingPrompt===B){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let Z=new AbortController,Y,W=new Promise((X)=>{Y=X});this.pendingUserShell=Z,this.pendingUserShellCompletion=W;let H,Q="";try{let X=await this.runtime.executeUserShellCommand(J,{signal:Z.signal,onEvent:async(L)=>{if(H=L.executionId,L.type==="started"){this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L.executionId,status:"in_progress",title:`! ${L.command}`,content:[],kind:"execute"});return}if(L.type==="output"){Q+=L.chunk,this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:"in_progress",content:[{type:"content",content:{type:"text",text:L.chunk}}]});return}let U=l(L.record);this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:L.executionId,status:L.record.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:Q?LJ(L.record):U}}]})}}),B={role:"user",content:X.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(X.record))}};if(this.messages.push(B),this.contextMessages.push(B),X.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return Z.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:X.record.status==="aborted"?"cancelled":"end_turn"}}catch(X){if(H)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:H,status:"failed",content:[{type:"content",content:{type:"text",text:X instanceof Error?X.message:String(X)}}]});if(Z.signal.aborted)return{stopReason:"cancelled"};throw X}finally{if(Y(),this.pendingUserShellCompletion===W)this.pendingUserShellCompletion=null;if(this.pendingUserShell===Z){if(this.pendingUserShell=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}requestPendingResume(z={}){if(!this.canSendUpdates())return;if(!this.pendingResumeRequested){if(this.pendingResumeRequested=!0,!this.pendingResumeInFlight)this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}if(!z.defer)this.ensurePendingResumeScheduled()}ensurePendingResumeScheduled(z=0){if(!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeCompletion!==null)return;this.pendingResumeScheduled=!0;let J=this.pendingResumeGeneration,Z=()=>{if(J!==this.pendingResumeGeneration)return;this.startPendingResumeRun(J)};if(z>0)this.pendingResumeTimer=setTimeout(Z,z),this.pendingResumeTimer.unref?.();else queueMicrotask(Z)}startPendingResumeRun(z){if(z!==this.pendingResumeGeneration)return;if(this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,!this.pendingResumeRequested||!this.canSendUpdates()||this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;let J=this.resumePendingIfIdle();this.pendingResumeCompletion=J,J.then(()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}},()=>{if(this.pendingResumeCompletion===J){this.pendingResumeCompletion=null;let Z=this.pendingResumeNextDelayMs;if(this.pendingResumeNextDelayMs=null,Z!==null&&!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled(Z)}})}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null||this.pendingResumeCompletion!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,this.pendingResumeNextDelayMs=null,this.pendingResumeScheduled=!1,this.pendingResumeTimer!==null)clearTimeout(this.pendingResumeTimer),this.pendingResumeTimer=null;return z}preserveNewPendingInput(z){if(z==="pending_input"||!this.pendingResumeRequested||!this.runtime||this.runtime.getPendingSteeringCount()===0)return!1;return this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,!0}pendingResumeSessionUpdate(z,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:yz,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingResumeCompletion!==null||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let Z="preflight",Y=!1,W,H=null;try{let Q=this.runtime.getPendingSteeringCount()>0,X=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let B=X?.status==="active"||X?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Q&&!B))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Q&&!B){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}Z=Q?"pending_input":"goal",Y=!0;let U=Iz-(Date.now()-this.pendingResumeRecoveryStartedAt);if(U<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}let j=new AbortController;H=setTimeout(()=>{j.abort("acp-pending-resume-budget-exhausted")},U),H.unref?.();let G=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:B,projectedRecoveredInputIds:Z==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:j.signal});if(z!==this.pendingResumeGeneration)return;if(j.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:Z,taskFailure:M("timeout")})),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest();return}if(G.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1){if(!await this.sendUpdateAndWait(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:Z})))return;if(z!==this.pendingResumeGeneration)return}this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let X=Y?HJ(Q):{taskFailure:v(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},B=Z==="preflight"||Z==="pending_input"&&this.runtime.getPendingSteeringCount()>0,L=kz({sessionIdentity:this.id,failedAttempt:J,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:B,evidence:X});if(L.phase==="retry_scheduled")this.pendingResumeRequested=!0,W=L.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:Z,taskFailure:X?.taskFailure,delayMs:L.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${L.delayMs}ms`);else{let U=L.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(U,{attempt:J,kind:Z,taskFailure:X?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L.retryable}, phase=${U})`,Q),!this.preserveNewPendingInput(Z))this.clearPendingResumeRequest()}}finally{if(H!==null)clearTimeout(H);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.pendingResumeNextDelayMs=W??0}}cancel(){V.info(`[AcpSession ${this.id}] Cancel requested`);let z=this.clearPendingResumeRequest();if(this.pendingPrompt)this.pendingPrompt.abort(),this.pendingPrompt=null,z=!0;if(this.pendingUserShell)this.pendingUserShell.abort(),this.pendingUserShell=null,z=!0;if(this.pendingSideConversation)this.pendingSideConversation.abort(),this.pendingSideConversation=null,z=!0;if(!z)V.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let Z=["default","auto-edit","yolo","plan"].includes(z)?z:"default",Y=this.mapModeIdToPermissionMode(Z);await this.persistPermissionMode(Y),this.mode=Z,V.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(z){switch(z){case"yolo":return"yolo";case"auto-edit":return"autoEdit";case"plan":return"plan";case"default":default:return"default"}}shouldAutoApprove(z){switch(this.mode){case"yolo":return!0;case"auto-edit":return z==="readonly"||z==="write";case"plan":return z==="readonly";case"default":default:return!1}}async setModel(z){if(V.info(`[AcpSession ${this.id}] Model set to: ${z}`),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 J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{await this.persistMetadataUpdate({selectedModelId:z})}catch(Z){if(J&&J!==z)await this.agent.switchModel(J).catch((Y)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,Y)});throw Z}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{await this.persistMetadataUpdate({reasoningEffort:z},{selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}catch(Z){throw await this.runtime.refresh({reasoningEffort:J.selection}),Z}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{await this.persistMetadataUpdate({serviceTier:z},{selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}catch(Z){throw await this.runtime.refresh({serviceTier:J.selection}),Z}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(Z){throw Error(Z instanceof Error?Z.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{await this.persistMetadataUpdate({responseVerbosity:z},{selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}catch(Z){throw await this.runtime.refresh({responseVerbosity:J.selection}),Z}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),Z=this.runtime.resolveCommunicationStyleConfiguration(z);if(Z.source!=="built-in"&&!Z.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{await this.persistMetadataUpdate({communicationStyle:z,communicationStyleDigest:Z.source==="built-in"?null:Z.contentSha256},{selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...Z.source!=="built-in"&&Z.contentSha256?{communicationStyleDigest:Z.contentSha256}:{}})}catch(Y){throw await this.runtime.refresh({communicationStyle:J.selection}),Y}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&!this.pendingResumeRequested&&!this.pendingResumeScheduled&&!this.pendingResumeInFlight&&this.pendingResumeTimer===null&&this.pendingResumeCompletion===null&&(this.runtime?.isIdleForResidency()??!1)}destroy(z={}){if(this.destroyPromise)return this.destroyFinished?Promise.resolve():this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(z.discardPendingInput===!0).finally(()=>{this.destroyFinished=!0}),this.destroyPromise}async destroyOwnedResources(z){if(this.destroyed=!0,this.clearPendingResumeRequest(),this.updateEgress.close(new xz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,Z=this.runtime,Y=this.pendingPromptCompletion,W=this.pendingUserShellCompletion,H=this.pendingSideConversationCompletion,Q=this.pendingResumeCompletion;this.agent=null,this.runtime=null;let X,B=async(L)=>{try{await L()}catch(U){X??=U}};if(await B(()=>this.cancel()),Y)await B(()=>Y);if(W)await B(()=>W);if(H)await B(()=>H);if(Q)await B(()=>Q);if(z&&Y&&Z)await B(()=>Z.discardPendingInput());if(J)await B(()=>J.destroy());if(Z)await B(()=>Z.dispose());if(await B(()=>R.destroyRegisteredSession(this.serviceRegistration)),this.serviceRegistration=void 0,V.debug(`[AcpSession ${this.id}] Destroyed`),X!==void 0)throw X}resolvePrompt(z){let J=[],Z=[],Y=0,W=0,H=0,Q=(L)=>{if(Z.length>0)Z.push({type:"text",text:`
|
|
13
|
-
`}),H+=1;if(Z.push(L),L.type==="text")H+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Q({type:"text",text:L.text});else if(L.type==="image"){let U=`data:${L.mimeType};base64,${L.data}`;Y+=1,W+=U.length,J.push(`[Image: ${L.mimeType}]`),Q({type:"image_url",image_url:{url:U}})}else if(L.type==="resource"){let U=L.resource;if("text"in U){let j=`<file path="${U.uri}">
|
|
14
|
-
${U.text}
|
|
15
|
-
</file>`;J.push(j),Q({type:"text",text:j})}}else if(L.type==="resource_link"){let U=`[Resource: ${L.uri}]`;J.push(U),Q({type:"text",text:U})}if(Y>g)throw Error(`ACP prompt contains more than ${g} images`);if(W>Yz)throw Error("ACP prompt images exceed the 5 MiB limit");if(H>c)throw Error(`ACP prompt text exceeds ${c} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
-
`),"utf8")>p)throw Error(`ACP prompt text exceeds ${p} bytes`);let B=J.join(`
|
|
17
|
-
`);return{content:Y>0?Z:B,displayText:B}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;V.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((Z)=>({content:Z.subject,priority:Z.priority,status:Z.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let Z=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(Z))return V.debug(`[AcpSession ${this.id}] Auto-approving ${Z} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(Z==="write"||Z==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${Z} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let Y=u(),W=[];if(z.message)W.push({type:"content",content:{type:"text",text:z.message}});if(z.details)W.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)W.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
-
- ${z.risks.join(`
|
|
19
|
-
- `)}`}});let H=this.mapToolKind(Z),Q={sessionId:this.id,options:z.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:z.title||"Permission Required",content:W,kind:H}},X=await this.waitForClientInteraction(this.connection.requestPermission(Q),J);if(!X)return{approved:!1,reason:m};let B=X.outcome;if(B.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=B.optionId;if(L==="allow_always")return{approved:!0,scope:"project"};if(L==="reject_always")return{approved:!1,scope:"project",reason:"User permanently denied the permission request"};let U=L==="allow_once";return{approved:U,scope:"once",reason:U?void 0:"User denied the operation"}}catch(Y){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,Y),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let Z=z.questions??[];if(Z.length===0)return{approved:!1,reason:"No structured questions were provided"};if(Z.some((W)=>W.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let Y={};try{for(let[W,H]of Z.entries()){let Q=H.options.map((U,j)=>`answer:${W}:${j}`),X=`answer:${W}:cancel`,B=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.options.map((U,j)=>({optionId:Q[j],name:U.label,kind:"allow_once"})),{optionId:X,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:H.header,kind:"think",content:[{type:"content",content:{type:"text",text:[H.question,...H.options.map((U)=>`${U.label}: ${U.description}`)].join(`
|
|
20
|
-
`)}}]}}),J);if(!B)return{approved:!1,reason:m};if(B.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Q.indexOf(B.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};Y[H.header]=H.options[L].label}return{approved:!0,answers:Y}}catch(W){return V.warn(`[AcpSession ${this.id}] Question request failed:`,W),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let Z=z.mcpElicitation;if(!Z)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(Z.mode==="url"){let W=await this.requestElicitationChoice("MCP external authorization",[Z.message,`Server: ${Z.serverName}`,`Domain: ${Z.domain??"unknown"}`,`URL: ${Z.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
-
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(W==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:W==="decline"?"User declined URL":"User cancelled",elicitation:{action:W==="decline"?"decline":"cancel"}}}let Y=Object.create(null);for(let W of Z.fields??[]){let H=await this.collectAcpElicitationField(W,J);if(H.cancelled)return{approved:!1,reason:H.reason,elicitation:{action:"cancel"}};if(H.value!==void 0)Y[W.name]=H.value}return{approved:!0,elicitation:{action:"accept",content:Y}}}catch(Y){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,Y),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let Z=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((H,Q)=>({id:`option:${Q}`,label:H.label,value:H.value})),Y=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
-
`),[...Z.map((H)=>({id:H.id,label:H.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Y==="skip")return{cancelled:!1};let W=Z.find((H)=>H.id===Y);if(!W)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:W.value}}if(z.defaultValue!==void 0){let Z=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
-
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(Z==="default")return{cancelled:!1,value:z.defaultValue};if(Z==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,Z,Y){let W=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Z.map((H)=>({optionId:H.id,name:H.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:u(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),Y);return W?.outcome.outcome==="selected"?W.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((Z,Y)=>{let W=!1,H=(X)=>{if(W)return;W=!0,J.removeEventListener("abort",Q),X()},Q=()=>H(()=>Z(void 0));if(J.addEventListener("abort",Q,{once:!0}),J.aborted)Q();z.then((X)=>H(()=>Z(X)),(X)=>H(()=>Y(X)))})}mapToolKind(z){return{readonly:"read",write:"edit",execute:"execute",read:"read",edit:"edit",delete:"delete",move:"move",search:"search",think:"think",fetch:"fetch"}[z||""]||"other"}}var A=y("Agent"),BJ="remote task isolation is not supported";function I(z){return z?.fs?.readTextFile===!0||z?.fs?.writeTextFile===!0}function UJ(z){return C.invalidParams({code:z.code,reason:z.reason})}function jJ(){return C.invalidParams({code:"acp_remote_task_isolation_unsupported",reason:BJ})}function uz(){return C.invalidParams({code:"acp_remote_workspace_mismatch",reason:"exact-identity-mismatch"})}function gz(z){return z instanceof Error&&"code"in z&&z.code==="acp_remote_workspace_mismatch"&&"reason"in z&&z.reason==="exact-identity-mismatch"}function k(z){try{return s(z)}catch(J){if(J instanceof cz)throw UJ(J);throw J}}function a(z,J){let Z=t(z);return Object.freeze({kind:"acp-remote",hostStateRoot:e(Z.collisionIdentity),executionRoot:Z.wirePath,hostResourceRoot:J,profile:z,descriptor:Z})}function r(z,J){let Z=pz(z.remoteWorkspace),Y=e(Z.collisionIdentity);if(z.projectPath!==Y)throw Error("ACP remote workspace durable state is invalid");let W=s(Z.wirePath);return Object.freeze({kind:"acp-remote",hostStateRoot:Y,executionRoot:Z.wirePath,hostResourceRoot:J,profile:W,descriptor:Z})}function GJ(z){if(!z.remoteWorkspace)throw Error("ACP remote workspace durable state is invalid");return z.remoteWorkspace.wirePath}class zz{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;hostResourceRoot;constructor(z){this.connection=z;this.hostResourceRoot=i.resolve(o())}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=iz();this.runtimeResidencyValue=new ez({maxResident:z?.maxResidentSessionRuntimes??dz,idleMs:z?.sessionRuntimeIdleMs??lz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof tz)throw C.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await az(),{protocolVersion:XJ,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=n("acp"),Z=z.cwd||o(),Y=I(this.clientCapabilities),W=Y?k(Z):void 0,H=z._meta?.["blade/taskIsolation"],Q=H==="local"||H==="worktree"?H:void 0;if(Y&&Q)throw jJ();let X=z._meta?.["blade/taskPrompt"],B=await this.reserveSessionRuntime(J),L;try{let U,j;if(W){let P=a(W,this.hostResourceRoot);U=await K.createRemoteSessionMetadata(J,P.hostStateRoot,P.descriptor,{}),j=r(U,this.hostResourceRoot)}else j=T(Z);let G=!Y&&Q?await sz.createSessionTask({sessionId:J,prompt:typeof X==="string"&&X.trim()?X:"ACP task session",sourceProjectPath:Z,isolation:Q}):void 0;if(G)j=T(G.metadata.projectPath);return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session kind: ${j.kind}`),L=new x(J,j,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...G?.taskWorktree?{taskWorktree:G.taskWorktree}:{},...G?.metadata.taskIsolation?{taskIsolation:G.metadata.taskIsolation}:{}}),await L.initialize(),this.assertNotDestroyed(),this.commitSession(J,L,B),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),L.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,G?.metadata,L.getModelConfiguration())}catch(U){throw B.cancel(),await L?.destroy().catch(()=>{return}),U}}async listSessions(z){let J=I(this.clientCapabilities);if(!J&&z.cwd!=null&&!i.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=J?await K.listRemoteSessionPage({...z.cwd!=null?{descriptor:t(k(z.cwd))}:{},cursor:z.cursor??void 0,limit:50,includeSubagents:!1}):await K.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((Y)=>({sessionId:Y.sessionId,cwd:J?GJ(Y):Y.projectPath,title:Y.title??null,updatedAt:Y.lastMessageTime,_meta:{"blade/taskStatus":Y.taskStatus,...Y.taskStatusReason?{"blade/taskStatusReason":Y.taskStatusReason}:{},...Y.taskFailure?{"blade/taskFailure":Y.taskFailure}:{},...Y.taskStartedAt?{"blade/taskStartedAt":Y.taskStartedAt}:{},...Y.taskCompletedAt?{"blade/taskCompletedAt":Y.taskCompletedAt}:{},...Y.taskModelId?{"blade/taskModelId":Y.taskModelId}:{},...Y.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...Y.taskRetriedFrom?{"blade/taskRetriedFrom":Y.taskRetriedFrom}:{},...Y.taskDelivery?{"blade/taskDelivery":Y.taskDelivery}:{},...Y.taskIsolation?{"blade/taskIsolation":Y.taskIsolation}:{},...Y.taskSourceProjectPath?{"blade/taskSourceProjectPath":Y.taskSourceProjectPath}:{},...Y.taskWorktreeBranch?{"blade/taskWorktreeBranch":Y.taskWorktreeBranch}:{},...Y.taskBaseCommit?{"blade/taskBaseCommit":Y.taskBaseCommit}:{},...Y.taskDiffStat?{"blade/taskDiffStat":Y.taskDiffStat}:{},...Y.taskQueuePosition?{"blade/taskQueuePosition":Y.taskQueuePosition}:{},...Y.taskQueueDepth!==void 0?{"blade/taskQueueDepth":Y.taskQueueDepth}:{},...Y.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":Y.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){this.assertNotDestroyed();let J=I(this.clientCapabilities),Z=J?a(k(z.cwd),this.hostResourceRoot):void 0;if(!J&&!i.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Y=n("fork"),W=await this.reserveSessionRuntime(Y),H;try{let Q;try{Q=await K.forkSession(z.sessionId,{sourceProjectPath:Z?.hostStateRoot??z.cwd,targetProjectPath:Z?.hostStateRoot??z.cwd,newSessionId:Y,...Z?{remote:{expectedDescriptor:Z.descriptor}}:{}})}catch(B){if(gz(B))throw uz();throw B}this.assertNotDestroyed();let X=J?r(Q.metadata,this.hostResourceRoot):T(Q.projectPath??z.cwd);return H=new x(Q.sessionId,X,this.connection,this.clientCapabilities,{initialMessages:Q.messages,permissionMode:Q.metadata.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),this.assertNotDestroyed(),this.commitSession(Q.sessionId,H,W),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Q.sessionId,J?void 0:Q.metadata,H.getModelConfiguration())}catch(Q){throw W.cancel(),await H?.destroy().catch(()=>{return}),Q}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{return await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){if(this.assertNotDestroyed(),!I(this.clientCapabilities)){await K.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let X=await this.reserveSessionRuntime(z.sessionId),B;try{let[L,U]=await Promise.all([K.loadSession(z.sessionId,z.cwd),K.findSessionMetadata(z.sessionId,z.cwd)]);if(!U)throw Error(`Session not found: ${z.sessionId}`);return B=new x(z.sessionId,T(z.cwd),this.connection,this.clientCapabilities,{initialMessages:L,permissionMode:U.permissionMode,mcpServers:z.mcpServers}),await B.initialize(),await B.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,B,X),B.sendAvailableCommandsDelayed(),this.buildSessionSetup(B.getModelConfiguration(),B.getMode())}catch(L){throw X.cancel(),await B?.destroy().catch(()=>{return}),L}}let Z=a(k(z.cwd),this.hostResourceRoot),Y;try{Y=await K.assertRemoteSessionWritable(z.sessionId,Z.hostStateRoot,Z.descriptor)}catch(X){if(gz(X))throw uz();throw X}let W=r(Y,this.hostResourceRoot);await this.closeResidentSession(z.sessionId);let H=await this.reserveSessionRuntime(z.sessionId),Q;try{let X=await K.loadRemoteSession(z.sessionId,W.hostStateRoot,W.descriptor);return Q=new x(z.sessionId,W,this.connection,this.clientCapabilities,{initialMessages:X,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await Q.initialize(),await Q.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,Q,H),Q.sendAvailableCommandsDelayed(),this.buildSessionSetup(Q.getModelConfiguration(),Q.getMode())}catch(X){throw H.cancel(),await Q?.destroy().catch(()=>{return}),X}}commitSession(z,J,Z){let Y=Z.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),Y.release()}async closeResidentSession(z,J={}){let Z=this.sessions.get(z);if(!Z)return;let Y=this.runtimeResidency.owns(z,Z),W;try{await Z.destroy(J)}catch(Q){W=Q}let H=await this.runtimeResidency.forget(z,Z);if(this.sessions.get(z)===Z)this.sessions.delete(z);if(Y&&!H&&W===void 0)throw Error(`ACP Session is still active: ${z}`);if(W!==void 0)throw W}buildChildSessionResponse(z,J,Z){return{sessionId:z,...this.buildSessionSetup(Z,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let Z=z?.models??[],Y=(z?.currentModelId&&Z.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??Z[0]?.id,W=[{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"}],H=[];if(Z.length>0)H.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:Y,options:Z.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)H.push({type:"select",id:"reasoning_effort",name:"Reasoning effort",description:"Session-owned model reasoning intensity",category:"model",currentValue:z.reasoning.selection,options:[{value:"auto",name:"Auto",description:`Resolve near high for this model (currently ${z.reasoning.effective})`},...z.reasoning.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="off"?"Disable model reasoning":`Use ${Q} reasoning effort`}))]});if(z?.serviceTier)H.push({type:"select",id:"service_tier",name:"Service tier",description:"Session-owned provider latency and pricing tier",category:"model",currentValue:z.serviceTier.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default tier"},...z.serviceTier.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:Q==="fast"?"Use the provider priority tier":Q==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)H.push({type:"select",id:"response_verbosity",name:"Response verbosity",description:"Session-owned model response detail",category:"model",currentValue:z.responseVerbosity.selection,options:[{value:"auto",name:"Auto",description:"Use the provider or model default verbosity"},...z.responseVerbosity.supported.map((Q)=>({value:Q,name:Q[0].toUpperCase()+Q.slice(1),description:`Use ${Q} response verbosity`}))]});if(z?.communicationStyle)H.push({type:"select",id:"communication_style",name:"Communication style",description:"Session-owned tone and explanatory framing",category:"model",currentValue:z.communicationStyle.selection,options:z.communicationStyle.supported.map((Q)=>({value:Q.id,name:Q.name,description:`${Q.description} · ${Q.source}`}))});return{modes:{availableModes:W,currentModeId:J},configOptions:H.length>0?H:void 0}}async closeSession(z){this.assertNotDestroyed();let Z=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),Y=Z.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,Y);try{await Z}finally{if(this.sessionLoadQueues.get(z.sessionId)===Y)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let Z=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await Z.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&rz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await Z.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&vz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await Z.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&mz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await Z.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&oz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await Z.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(Z.getModelConfiguration(),Z.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(Z){z??=Z}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await nz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function GZ(){let z=_J.toWeb(process.stdout),J=VJ.toWeb(process.stdin),Z=f.ndJsonStream(z,J),Y,W=new f.AgentSideConnection((Q)=>{return Y=new zz(Q),Y},Z),H=zJ(async()=>{await Y?.destroy()});try{await W.closed}finally{H(),await Y?.destroy()}}export{GZ as runAcpIntegration,T as createLocalAcpSessionRoots};
|
package/dist/chunk-z28dcrr9.js
DELETED
|
@@ -1,10 +0,0 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-sm9p1fkf.js";import"./chunk-dvb89529.js";import"./chunk-grhsv55v.js";import"./chunk-bavzm721.js";import"./chunk-qcydkn1n.js";import"./chunk-6q3g5e3m.js";import"./chunk-xjrmq0pg.js";import"./chunk-6p6ts4kv.js";import"./chunk-sbc90z9j.js";import"./chunk-v52wc8yg.js";import"./chunk-3e0t25rq.js";import"./chunk-77efqpdc.js";import"./chunk-rj8mmwc6.js";import"./chunk-53h87fmt.js";import"./chunk-b5z1rec4.js";import"./chunk-0z9nqbd0.js";import{hf as R}from"./chunk-y0kqkewg.js";import"./chunk-a60cmnmz.js";import{Df as Q}from"./chunk-j3nmt09e.js";import"./chunk-v508x7cg.js";import"./chunk-mdew58v9.js";import"./chunk-ajsw4te2.js";import"./chunk-mvm1rzc4.js";import"./chunk-edtxcqxa.js";import"./chunk-e371f7xk.js";import"./chunk-t8rjxqp2.js";import"./chunk-sx77dpxw.js";import"./chunk-aaxc81jc.js";import"./chunk-93x9xbew.js";import"./chunk-r7kevfd3.js";import"./chunk-g4xny949.js";import"./chunk-0bkhpd72.js";import"./chunk-jkfkyedn.js";import"./chunk-f8gb685p.js";import"./chunk-44jtpg8y.js";import"./chunk-sj1dzeta.js";import"./chunk-2y1qngw7.js";import"./chunk-ar5np5h5.js";import"./chunk-dfjmvj3d.js";import"./chunk-tkydv9k8.js";import{Cj as M}from"./chunk-9d49tj9y.js";import"./chunk-qcvxff27.js";import"./chunk-zwjrensv.js";import"./chunk-pj69j4zp.js";import"./chunk-zkzhm39s.js";import m from"chalk";import K from"open";var A=`
|
|
2
|
-
____ _ _
|
|
3
|
-
| __ )| | __ _ __| | ___
|
|
4
|
-
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
5
|
-
| |_) | | (_| | (_| | __/
|
|
6
|
-
|____/|_|\\__,_|\\__,_|\\___|
|
|
7
|
-
`,C={command:"web",describe:"Start Blade server and open web interface",builder:T,handler:async(Z)=>{let H=W(Z);if(await Q(),!process.env.BLADE_SERVER_PASSWORD)console.log(m.yellow("[WARN] BLADE_SERVER_PASSWORD is not set; server is unsecured.")),console.log(m.gray(` Set this environment variable to enable Basic Auth.
|
|
8
|
-
`));let F=await Y.listenAsync(H);if(console.log(m.cyan(A)),console.log(m.gray(` v${M()}
|
|
9
|
-
`)),H.hostname==="0.0.0.0"){let q=`http://localhost:${F.port}`;console.log(m.blue.bold(" Local access: "),m.white(q));let x=X();for(let z of x)console.log(m.blue.bold(" Network access: "),m.white(`http://${z}:${F.port}`));K(q).catch(()=>{})}else{let q=F.url.toString();console.log(m.blue.bold(" Web interface: "),m.white(q)),K(q).catch(()=>{})}console.log(""),console.log(m.gray(` Press Ctrl+C to stop the server.
|
|
10
|
-
`));let J,$=new Promise((q)=>{J=q}),b=R(async()=>{await F.stop(),J()});try{await $}finally{b(),await F.stop()}}};export{C as webCommand};
|
package/dist/chunk-z83xk6jn.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-fag8rk53.js";import"./chunk-9d49tj9y.js";import"./chunk-zkzhm39s.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|