blade-code 0.10.104 → 0.10.105
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-0pj7d25e.js +23 -0
- package/dist/{chunk-3rpmd93p.js → chunk-139frcak.js} +1 -1
- package/dist/{chunk-mm762w5r.js → chunk-151cz9k4.js} +1 -1
- package/dist/{chunk-knmvaxsb.js → chunk-1x13nzwe.js} +1 -1
- package/dist/chunk-25n07173.js +1 -0
- package/dist/{chunk-6nc7mcxx.js → chunk-26t2mg1v.js} +1 -1
- package/dist/{chunk-32yfgw9s.js → chunk-2mck84gx.js} +1 -1
- package/dist/{chunk-epdzdv4e.js → chunk-3gf34fv5.js} +1 -1
- package/dist/{chunk-cj0c0ffd.js → chunk-3vqdyer3.js} +1 -1
- package/dist/{chunk-sv9apfmy.js → chunk-48vc39mb.js} +2 -2
- package/dist/{chunk-m5zx8enh.js → chunk-4bwr3rcj.js} +1 -1
- package/dist/chunk-4z79mh8y.js +1 -0
- package/dist/{chunk-mxjsttbc.js → chunk-5y38cfk9.js} +1 -1
- package/dist/{chunk-jntgg3zj.js → chunk-6j482w6k.js} +1 -1
- package/dist/{chunk-vtq52np4.js → chunk-7g984trn.js} +1 -1
- package/dist/{chunk-0tbdbnyp.js → chunk-8hp650gn.js} +1 -1
- package/dist/{chunk-8886s1qa.js → chunk-9dba1pyq.js} +1 -1
- package/dist/{chunk-4m38k0rp.js → chunk-bcbssqsn.js} +1 -1
- package/dist/{chunk-b69xvpah.js → chunk-brjjvs4d.js} +1 -1
- package/dist/{chunk-rnz5zxdw.js → chunk-c0m2vw2q.js} +1 -1
- package/dist/{chunk-w7vhgbhr.js → chunk-c133kq05.js} +1 -1
- package/dist/{chunk-scq56220.js → chunk-djqbqaxn.js} +1 -1
- package/dist/{chunk-zc7snr6f.js → chunk-gz4h2y7j.js} +1 -1
- package/dist/{chunk-050537sc.js → chunk-jqqqg8kv.js} +1 -1
- package/dist/{chunk-r9p130v6.js → chunk-n1qxq9kv.js} +1 -1
- package/dist/{chunk-rx2eax1g.js → chunk-najk5ty4.js} +1 -1
- package/dist/{chunk-pkack2dw.js → chunk-p39mmmbt.js} +1 -1
- package/dist/{chunk-kfcbaj44.js → chunk-p6prp8zc.js} +1 -1
- package/dist/{chunk-x2wsb8w2.js → chunk-pf4je2g7.js} +1 -1
- package/dist/{chunk-sg795gzk.js → chunk-q0fv0efv.js} +1 -1
- package/dist/{chunk-jk209m4h.js → chunk-sy117k4g.js} +1 -1
- package/dist/{chunk-e40ntkjm.js → chunk-szdz1jmj.js} +1 -1
- package/dist/{chunk-496d1ag5.js → chunk-x6z05rfz.js} +1 -1
- package/dist/{chunk-x6m0h59v.js → chunk-xvg14dkr.js} +1 -1
- package/dist/{chunk-stmmw8m8.js → chunk-xzjhfw7y.js} +1 -1
- package/dist/{chunk-terw7qdx.js → chunk-yeq7qzdb.js} +4 -4
- package/dist/{chunk-t55d9bjv.js → chunk-zmfm07hj.js} +1 -1
- package/dist/web/assets/{ChatView-_4ut_-Jh.js → ChatView-p9tMKcFw.js} +4 -4
- package/dist/web/assets/{CodeBlockHighlighter-DkDr6wE9.js → CodeBlockHighlighter-DD7FIfcr.js} +1 -1
- package/dist/web/assets/{FilePreview-DCI-oqhJ.js → FilePreview-DDpZFwlq.js} +1 -1
- package/dist/web/assets/{KanbanBoard-CB5C4tJC.js → KanbanBoard-1Bkr6fIi.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-ychfmIQK.js → MarkdownRenderer-hkB9aVVA.js} +3 -3
- package/dist/web/assets/{SettingsModal-SSdk0Bjr.js → SettingsModal-KpvOJhBi.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-EnaUhn3o.js → TaskSwitcher-2FU_n9lh.js} +1 -1
- package/dist/web/assets/{TerminalPanel-BcWxLSV3.js → TerminalPanel-C-LpIqOw.js} +1 -1
- package/dist/web/assets/{arrow-left-Ob5r20g7.js → arrow-left-Bf8UJl0b.js} +1 -1
- package/dist/web/assets/{calendar-clock-eOALT8DB.js → calendar-clock-BTAxrL8A.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-BkZBwmbt.js → chevrons-up-down-CTzVylwH.js} +1 -1
- package/dist/web/assets/{clock-3-DQp9SzYc.js → clock-3-Cm6_vdYx.js} +1 -1
- package/dist/web/assets/{external-link-BuGUowPD.js → external-link-DJln2WFN.js} +1 -1
- package/dist/web/assets/{folder-c92kw1oI.js → folder-BXj3pohP.js} +1 -1
- package/dist/web/assets/{index-CS8jtO_A.js → index-DQL9otjm.js} +4 -4
- package/dist/web/assets/{pause-DP_CXoH7.js → pause-W092j5bW.js} +1 -1
- package/dist/web/assets/{play-DcRwtohz.js → play-OpsbZ_PE.js} +1 -1
- package/dist/web/assets/{session-events-CrAgnaj2.js → session-events-BuugneNw.js} +1 -1
- package/dist/web/assets/{teamService-JyVbGQhi.js → teamService-Aj-8ajEO.js} +1 -1
- package/dist/web/index.html +1 -2
- package/package.json +1 -1
- package/dist/chunk-31aeh672.js +0 -23
- package/dist/chunk-kfgw21tq.js +0 -1
- package/dist/chunk-z8ddwve9.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{we as W}from"./chunk-
|
|
2
|
+
import{we as W}from"./chunk-7g984trn.js";import{Ae as M,ze as F}from"./chunk-z9gd9spf.js";import"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-6j482w6k.js";import"./chunk-41cg66y0.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import{Oh as N,Ph as B}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{oi as T}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import{Xi as J}from"./chunk-fhfzdyba.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-c133kq05.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-9dba1pyq.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-v4w5b2cq.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-xzjhfw7y.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-bcbssqsn.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-0pj7d25e.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-4z79mh8y.js"),import("./chunk-1x13nzwe.js"),import("./chunk-946wkbmw.js"),import("./chunk-48vc39mb.js"),import("./chunk-szxajr6e.js"),import("./chunk-brjjvs4d.js"),import("./chunk-6wsvgk20.js"),import("./chunk-181ef74x.js"),import("./chunk-n1qxq9kv.js"),import("./chunk-sy117k4g.js"),import("./chunk-jqqqg8kv.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-25n07173.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-gz4h2y7j.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{s as pz,t as mz}from"./chunk-zmfm07hj.js";import{u as h}from"./chunk-3gf34fv5.js";import{A as Nz,v as cz,w as Dz,x as _z,y as Oz,z as qz}from"./chunk-xvg14dkr.js";import{H as x,Q as Bz,R as Vz,V as Gz,Y as Kz,Z as Uz,aa as wz,qa as Pz,ra as Rz,sa as Az,ta as xz}from"./chunk-yeq7qzdb.js";import"./chunk-abd57h72.js";import{Ha as gz}from"./chunk-p6prp8zc.js";import{Ja as Fz}from"./chunk-xm8nyj5z.js";import{Db as Lz,Mb as jz,rb as Xz}from"./chunk-8hp650gn.js";import{Xb as c}from"./chunk-8hprmrd5.js";import{Cd as m,Dd as Hz,Fd as E,Id as Yz,Nd as R,Qd as G,ad as Zz,kd as S,ld as p,md as T,rd as $z,ud as Qz,wd as Wz}from"./chunk-najk5ty4.js";import"./chunk-s0tq8gyx.js";import"./chunk-x3cxmwnz.js";import{ve as dz}from"./chunk-7g984trn.js";import"./chunk-z9gd9spf.js";import{Qe as Iz,Re as Cz}from"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import{af as d}from"./chunk-dg0d3303.js";import{ff as Jz}from"./chunk-rchz6j90.js";import"./chunk-w7hy5wh1.js";import{qf as fz}from"./chunk-2hb222re.js";import"./chunk-p39mmmbt.js";import"./chunk-151cz9k4.js";import"./chunk-kf7whgr7.js";import{ig as uz}from"./chunk-fva7jnjy.js";import"./chunk-41ympwz1.js";import"./chunk-6j482w6k.js";import"./chunk-41cg66y0.js";import{ah as kz,dh as Mz}from"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import{Hh as f,Ih as zz,Kh as u,Lh as g}from"./chunk-c475tfqf.js";import{Ph as hz}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import{pi as y}from"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import{wi as Sz,zi as yz}from"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import{Vi as e}from"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";import{Readable as QJ,Writable as WJ}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as ZJ,RequestError as $J}from"@agentclientprotocol/sdk";import{RequestError as bz}from"@agentclientprotocol/sdk";import{nanoid as C}from"nanoid";import{createHash as lz}from"node:crypto";var M=4,iz=1000,o=4000,I=120000,n=0.2;function rz(z){try{return T(z)&&z.retryable}catch{return!1}}function az(z,Z){let J=Number.isSafeInteger(Z)&&Z>0?Z:1,H=J-1,Y=Math.min(iz*2**H,o),Q=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,W=1-n+2*n*Q;return Math.min(o,Math.max(0,Math.round(Y*W)))}function s(z){let Z=az(z.sessionIdentity,z.failedAttempt),J=z.evidence,H=z.workStillPending===!0&&J!==void 0&&rz(J.taskFailure)&&J.outputStarted===!1&&J.toolExecutionStarted===!1&&Number.isInteger(J.toolCallsCount)&&J.toolCallsCount===0,Y=Number.isSafeInteger(z.failedAttempt)&&z.failedAttempt>0&&z.failedAttempt<M,X=z.now??Date.now(),Q=X-z.recoveryStartedAt,W=Number.isFinite(X)&&Number.isFinite(z.recoveryStartedAt)&&Number.isFinite(Q)&&Q>=0&&Q+Z<=I;return{phase:H?Y&&W?"retry_scheduled":"exhausted":"failed",delayMs:Z,retryable:H,withinAttemptBudget:Y,withinTimeBudget:W}}var V=y("Agent");function t(z){if(!z)return{};return Object.fromEntries(z.map((Z)=>[Z.name,Z.value]))}function nz(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:t(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:t("headers"in z?z.headers:void 0)};return null}function sz(z){let Z={};for(let J of z){let H=nz(J);if(H)Z[J.name]=H}return Z}function Tz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((Z)=>{if(Z.type==="text")return Z.text?[{type:"text",text:Z.text}]:[];let J=Z.image_url.url,H=/^data:([^;,]+);base64,(.+)$/s.exec(J);if(!H)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:H[1]??"image/png",data:H[2]??""}]})}function tz(z){let Z=Hz(z.metadata);return Z?[{type:"text",text:m(Z)}]:Tz(z.content)}function ez(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}function zJ(z){if(!Jz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...S("capacity"),resource:z.resource}}function JJ(z){if(!(z instanceof bz)||!z.data||typeof z.data!=="object")return;let Z=z.data;if(!T(Z.taskFailure)||Z.toolExecutionStarted!==!1||!Number.isInteger(Z.toolCallsCount)||Z.toolCallsCount<0||Z.outputStarted!==!1)return;return{taskFailure:Z.taskFailure,toolExecutionStarted:Z.toolExecutionStarted,toolCallsCount:Z.toolCallsCount,outputStarted:Z.outputStarted}}class b{id;cwd;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;availableCommandsTimer=null;taskStatusUnsubscribe;destroyed=!1;destroyFinished=!1;destroyPromise;messages;contextMessages;mode;updateEgress;constructor(z,Z,J,H,Y={}){this.id=z;this.cwd=Z;this.connection=J;this.clientCapabilities=H;this.options=Y;this.messages=[...Y.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(Y.permissionMode),this.updateEgress=new Nz({maxPendingItems:Dz,maxPendingBytes:_z,writeTimeoutMs:Oz,signal:J.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await J.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,Z]=await Promise.all([G.loadSession(this.id,this.cwd),G.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(Z.length>0)this.contextMessages=Z}async loadModelContextOr(z){let Z=await G.loadSessionModelContext(this.id,this.cwd);return Z.length>0?Z:[...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 wz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(V.debug(`[AcpSession ${this.id}] Initializing...`),await G.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),x.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async(W)=>{await this.sendUpdateAndWait(W)}),V.debug(`[AcpSession ${this.id}] ACP service context initialized`),await jz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:(W)=>this.requestPermission(W)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let Z=this.options.mcpServers?sz(this.options.mcpServers):void 0,J=x.getInstance().getTerminalService(this.id);if(this.runtime=await Gz.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(W,j)=>{let L=await J.execute(W,{cwd:j.cwd,env:j.env,timeout:j.timeoutMs,signal:j.signal,allowLocalFallback:!1,onOutput:(F)=>j.onOutput?.("stdout",F)});return{exitCode:L.exitCode,stdout:L.stdout,stderr:L.stderr,...L.error?{error:L.error}:{},timedOut:L.failureKind==="timeout",aborted:L.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),await h.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await Rz(this.cwd),V.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe((W)=>{if(W.sessionId!==this.id||W.projectPath!==this.cwd)return;if(W.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":W.properties}}),this.requestPendingResume();return}if(W.type==="task.delivery"){if(!W.properties.taskDelivery||typeof W.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":W.properties.taskDelivery,...W.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(W.type.startsWith("team.")){let{teamName:j,messageId:L,content:F}=W.properties,B=W.properties.metadata;if(W.type==="team.message.received"&&typeof j==="string"&&typeof L==="string"&&typeof F==="string"&&Vz(B,{messageId:L,teamName:j}))(async()=>{let K=await this.runtime?.enqueueSteering(F,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:B});if(!K?.accepted)return;if(await new Bz(j,e()).markDelivered([L]),K.delivery==="next_turn")this.requestPendingResume()})().catch((K)=>{V.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,K)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:W.type,...W.properties}}});return}if(W.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof W.properties.updatedAt==="string"?W.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":W.properties.taskStatus,...typeof W.properties.taskStatusReason==="string"?{"blade/taskStatusReason":W.properties.taskStatusReason}:{},...W.properties.taskFailure&&typeof W.properties.taskFailure==="object"?{"blade/taskFailure":W.properties.taskFailure}:{},...typeof W.properties.taskStartedAt==="string"?{"blade/taskStartedAt":W.properties.taskStartedAt}:{},...typeof W.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":W.properties.taskCompletedAt}:{},...W.properties.taskDiffStat&&typeof W.properties.taskDiffStat==="object"?{"blade/taskDiffStat":W.properties.taskDiffStat}:{},...typeof W.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":W.properties.taskQueuePosition}:{},...typeof W.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":W.properties.taskQueueDepth}:{},...typeof W.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":W.properties.taskConcurrencyLimit}:{},...typeof W.properties.taskInFlight==="number"?{"blade/taskInFlight":W.properties.taskInFlight}:{}}})});let Y=await this.runtime.getGoal(),X=this.runtime.getPendingSteeringCount()>0,Q=Y?.status==="active"||Y?.status==="verifying";if(X||Q)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let W=this.runtime.getTurnRecoveryAssessment();if(W.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":W}})}}async replayHistory(){for(let Z of this.messages){if(!this.canSendUpdates())return;if(!Wz(Z))continue;let J=Z.role==="user"?"user_message_chunk":Z.role==="assistant"?"agent_message_chunk":void 0;if(!J)continue;for(let H of tz(Z)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:J,content:H}))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,Z){try{V.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let J={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(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},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()}},subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=!1,L,F=(K)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:K.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:K.result?.message||K.result?.error||`Subagent ${K.status}`}}]})},B=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(K)=>{if(j)F(K);else L=K}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.session.id,status:"in_progress",title:`Resuming ${B.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${B.source.id} at depth ${B.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),j=!0,L)F(L);return B}},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,W,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,j)},complete:async(Q,W,j)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,j)},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,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let j=await h.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Q,signal:W,onEvent:(B)=>{if(B.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:B.toolCall.id,status:"in_progress",title:`Review: ${B.toolCall.function.name}`,content:[],kind:this.mapToolKind(B.toolKind)});else if(B.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:B.toolCall.id,status:B.result.success?"completed":"failed",content:[]})}}),L=await j.completion,F=(await h.list(this.cwd,this.id)).find((B)=>B.start.reviewId===j.reviewId);if(!F)throw Error(`Review not found: ${j.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:j.reviewId,status:L.status,findings:L.findings.length,content:Zz(F.start,L)}}},signal:Z,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,j)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,F=this.mapToolKind(j);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:F})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},H=await Az(z,J),Y=H.data?.action;if(Y==="start_goal"||Y==="resume_goal")this.requestPendingResume();if(Y==="rewind_session"&&Array.isArray(H.data?.messages))this.messages=[...H.data.messages],this.contextMessages=await this.loadModelContextOr(H.data.messages);if((H.message==="compact_completed"||H.message==="compact_fallback")&&H.data?.compactedMessages){this.contextMessages=[...H.data.compactedMessages];let Q=await G.loadSession(this.id,this.cwd);if(Q.length>0)this.messages=Q}let X=H.content||H.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(H.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${H.error}`}});return await this.flushUpdates(),{stopReason:H.success?"end_turn":"cancelled"}}catch(J){if(Z.aborted||J instanceof Error&&J.name==="AbortError")return{stopReason:"cancelled"};return V.error(`[AcpSession ${this.id}] Slash command error:`,J),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${J instanceof Error?J.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let Z=new AbortController,J,H=new Promise((Y)=>{J=Y});this.pendingSideConversation=Z,this.pendingSideConversationCompletion=H;try{return await this.handleSlashCommand(z,Z.signal)}catch(Y){if(Z.signal.aborted||Y instanceof Error&&Y.name==="AbortError")return{stopReason:"cancelled"};throw Y}finally{if(J(),this.pendingSideConversationCompletion===H)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===Z){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=xz(this.cwd,this.runtime?.getAgentResources()),Z=["model","permissions","theme","config","exit","ide"],H=z.filter((Y)=>!Z.includes(Y.name)&&(Y.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((Y)=>{let X;if(Y.usage){let Q=Y.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if(Y.aliases?.length){let Q=`Aliases: ${Y.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:Y.name,description:Y.description,input:X?{hint:X}:void 0}});V.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(H.map((Y)=>Y.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:H}),V.info(`[AcpSession ${this.id}] Sent ${H.length} available commands`)}catch(z){V.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,Z={}){if(x.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let J=this.resolvePrompt(z.prompt),H=J.content,Y=J.displayText,X=z._meta?.outputSchema??(Z.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Yz(X).schema;if(Y.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(Y)}let W=Fz(Y);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(H)&&H.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.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(Y.trim()))return this.handleSlashCommand(Y,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(H,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.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 (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let j=new AbortController,L=()=>{j.abort(Z.abortSignal?.reason)};if(Z.abortSignal?.aborted)L();else Z.abortSignal?.addEventListener("abort",L,{once:!0});let F=!1,B=!1,K=!1,l,i=new Promise((w)=>{l=w});this.pendingPrompt=j,this.pendingPromptCompletion=i;try{if(V.debug(`[AcpSession ${this.id}] Received prompt: ${Y.slice(0,100)}...`),Pz(Y)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(Y,j.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:j.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 Lz(this.agent.chatStream(H,w,{pendingInputOnly:Z.pendingInputOnly,goalContinuationOnly:Z.goalContinuationOnly,outputSchema:Q}),async($)=>{switch($.kind){case"content_delta":if(Q)break;if($.delta.length>0)B=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.delta}});break;case"thinking_delta":if($.delta.length>0)B=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:$.delta}});break;case"tool_start":{K=!0;let U=$.toolCall,q=U.function.name;if(q===E)break;let P=this.mapToolKind($.toolKind),D=`Executing ${q}`;if(q==="Task"&&"function"in U)try{let A=JSON.parse(U.function.arguments),_=A.resume_from??A.resume;if(typeof _==="string")D=`Resuming ${String(A.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.id,status:"in_progress",title:D,content:[],kind:P});break}case"tool_progress":{K=!0;let U=$.toolCall;if(U.function.name===E)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:$.update.message}}]});break}case"tool_result":{K=!0;let U=$.toolCall;if(U.function.name===E)break;let q=$.result,P=[],D=q.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;P.push({type:"diff",path:_.path,oldText:"oldContent"in _&&typeof _.oldContent==="string"?_.oldContent:null,newText:"newContent"in _&&typeof _.newContent==="string"?_.newContent:null})}else if(D?.kind==="edit"&&typeof D.file_path==="string"&&typeof D.oldContent==="string"&&(typeof D.newContent==="string"||D.newContent===void 0))P.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=U.function.name,vz=Uz(Qz(Kz(_,q),$z));P.push({type:"content",content:{type:"text",text:vz}})}if(U.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))P.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let A=q.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.id,status:A,content:P});break}case"structured_output":B=!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":F=$.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 U=0;for(let q of $.messages){if(!q.recovered||q.persisted)continue;if(Z.projectedRecoveredInputIds?.has(q.id))continue;for(let P of Tz(q.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:P});Z.projectedRecoveredInputIds?.add(q.id),U++}if(U>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${U} queued instruction${U===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())j.abort("acp-egress-failed")});if(!await this.flushUpdates())j.abort("acp-egress-failed");this.contextMessages=[...w.messages];let r=await G.loadSession(this.id,this.cwd);if(this.messages=r.length>0?r:[...w.messages],!O.success){let $=O.error?.type??"unknown",U=O.error?.details??O.error?.message??"Agent execution failed",q=zJ(U)??p(U);throw bz.internalError({failureType:$,modelId:this.runtime.getCurrentModelId(),taskFailure:q,outputStarted:B,toolExecutionStarted:K,...Number.isInteger(O.metadata?.toolCallsCount)?{toolCallsCount:O.metadata.toolCallsCount}:{}},`Agent turn failed (${$})`)}if(j.signal.aborted)return{stopReason:"cancelled"};let a={...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(a).length>0?{_meta:a}:{}}}catch(w){if(j.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw V.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(Z.abortSignal?.removeEventListener("abort",L),F&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(l(),this.pendingPromptCompletion===i)this.pendingPromptCompletion=null;if(this.pendingPrompt===j){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 Z=z.trimStart().slice(1).trim();if(!Z)throw Error("User shell command cannot be empty");let J=new AbortController,H,Y=new Promise((W)=>{H=W});this.pendingUserShell=J,this.pendingUserShellCompletion=Y;let X,Q="";try{let W=await this.runtime.executeUserShellCommand(Z,{signal:J.signal,onEvent:async(L)=>{if(X=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 F=m(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?ez(L.record):F}}]})}}),j={role:"user",content:W.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(W.record))}};if(this.messages.push(j),this.contextMessages.push(j),W.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return J.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:W.record.status==="aborted"?"cancelled":"end_turn"}}catch(W){if(X)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:X,status:"failed",content:[{type:"content",content:{type:"text",text:W instanceof Error?W.message:String(W)}}]});if(J.signal.aborted)return{stopReason:"cancelled"};throw W}finally{if(H(),this.pendingUserShellCompletion===Y)this.pendingUserShellCompletion=null;if(this.pendingUserShell===J){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)return;this.pendingResumeScheduled=!0;let Z=this.pendingResumeGeneration,J=()=>{if(Z!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(J,z),this.pendingResumeTimer.unref?.();else queueMicrotask(J)}clearPendingResumeRequest(){let z=this.pendingResumeRequested||this.pendingResumeScheduled||this.pendingResumeInFlight||this.pendingResumeTimer!==null;if(this.pendingResumeRequested=!1,this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0,this.pendingResumeGeneration++,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,Z){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:Z.kind,attempt:Z.attempt,maxAttempts:M,...Z.delayMs!==void 0?{delayMs:Z.delayMs,nextRetryAt:Date.now()+Z.delayMs}:{},...Z.taskFailure?{failure:{code:Z.taskFailure.code,retryable:Z.taskFailure.retryable,...Z.taskFailure.resource?{resource:Z.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,Z=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=Z,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let J="preflight",H=!1,Y,X=null;try{let Q=this.runtime.getPendingSteeringCount()>0,W=Q?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let j=W?.status==="active"||W?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Q&&!j))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Q&&!j){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}J=Q?"pending_input":"goal",H=!0;let F=I-(Date.now()-this.pendingResumeRecoveryStartedAt);if(F<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:Z,kind:J,taskFailure:S("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}let B=new AbortController;X=setTimeout(()=>{B.abort("acp-pending-resume-budget-exhausted")},F),X.unref?.();let K=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Q,goalContinuationOnly:j,projectedRecoveredInputIds:J==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:B.signal});if(z!==this.pendingResumeGeneration)return;if(B.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:Z,kind:J,taskFailure:S("timeout")})),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest();return}if(K.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(Z>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:Z,kind:J}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Q){if(z!==this.pendingResumeGeneration)return;let W=H?JJ(Q):{taskFailure:p(Q),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},j=J==="preflight"||J==="pending_input"&&this.runtime.getPendingSteeringCount()>0,L=s({sessionIdentity:this.id,failedAttempt:Z,recoveryStartedAt:this.pendingResumeRecoveryStartedAt,workStillPending:j,evidence:W});if(L.phase==="retry_scheduled")this.pendingResumeRequested=!0,Y=L.delayMs,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:Z+1,kind:J,taskFailure:W?.taskFailure,delayMs:L.delayMs})),V.warn(`[AcpSession ${this.id}] Pending resume attempt ${Z} failed; retrying in ${L.delayMs}ms`);else{let F=L.phase;if(this.sendUpdate(this.pendingResumeSessionUpdate(F,{attempt:Z,kind:J,taskFailure:W?.taskFailure})),V.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${Z}, retryable=${L.retryable}, phase=${F})`,Q),!this.preserveNewPendingInput(J))this.clearPendingResumeRequest()}}finally{if(X!==null)clearTimeout(X);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(Y)}}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 J=["default","auto-edit","yolo","plan"].includes(z)?z:"default",H=this.mapModeIdToPermissionMode(J);await G.setSessionPermissionMode(this.id,this.cwd,H),this.mode=J,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 Z=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await G.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(J){if(Z&&Z!==z)await this.agent.switchModel(Z).catch((H)=>{V.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,H)});throw J}}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 Z=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid reasoning effort")}if(Z.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(J){throw await this.runtime.refresh({reasoningEffort:Z.selection}),J}}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 Z=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid service tier")}if(Z.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(J){throw await this.runtime.refresh({serviceTier:Z.selection}),J}}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 Z=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(J){throw Error(J instanceof Error?J.message:"Invalid response verbosity")}if(Z.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(J){if(!(J instanceof R)&&J.code!=="ENOENT")throw J;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(J){throw await this.runtime.refresh({responseVerbosity:Z.selection}),J}}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 Z=this.runtime.getCommunicationStyleConfiguration(),J=this.runtime.resolveCommunicationStyleConfiguration(z);if(J.source!=="built-in"&&!J.contentSha256)throw Error("Custom communication style has no provenance");if(Z.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await G.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:J.source==="built-in"?null:J.contentSha256})}catch(H){if(!(H instanceof R)&&H.code!=="ENOENT")throw H;await G.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...J.source!=="built-in"&&J.contentSha256?{communicationStyleDigest:J.contentSha256}:{}})}}catch(H){throw await this.runtime.refresh({communicationStyle:Z.selection}),H}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((Z)=>structuredClone(Z)),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.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 qz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let Z=this.agent,J=this.runtime,H=this.pendingPromptCompletion,Y=this.pendingUserShellCompletion,X=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Q,W=async(j)=>{try{await j()}catch(L){Q??=L}};if(await W(()=>this.cancel()),H)await W(()=>H);if(Y)await W(()=>Y);if(X)await W(()=>X);if(z&&H&&J)await W(()=>J.discardPendingInput());if(Z)await W(()=>Z.destroy());if(J)await W(()=>J.dispose());if(await W(()=>x.destroySession(this.id)),V.debug(`[AcpSession ${this.id}] Destroyed`),Q!==void 0)throw Q}resolvePrompt(z){let Z=[],J=[],H=0,Y=0,X=0,Q=(L)=>{if(J.length>0)J.push({type:"text",text:`
|
|
13
|
+
`}),X+=1;if(J.push(L),L.type==="text")X+=L.text.length};for(let L of z)if(L.type==="text")Z.push(L.text),Q({type:"text",text:L.text});else if(L.type==="image"){let F=`data:${L.mimeType};base64,${L.data}`;H+=1,Y+=F.length,Z.push(`[Image: ${L.mimeType}]`),Q({type:"image_url",image_url:{url:F}})}else if(L.type==="resource"){let F=L.resource;if("text"in F){let B=`<file path="${F.uri}">
|
|
14
|
+
${F.text}
|
|
15
|
+
</file>`;Z.push(B),Q({type:"text",text:B})}}else if(L.type==="resource_link"){let F=`[Resource: ${L.uri}]`;Z.push(F),Q({type:"text",text:F})}if(H>f)throw Error(`ACP prompt contains more than ${f} images`);if(Y>zz)throw Error("ACP prompt images exceed the 5 MiB limit");if(X>u)throw Error(`ACP prompt text exceeds ${u} characters`);if(Buffer.byteLength(Z.join(`
|
|
16
|
+
`),"utf8")>g)throw Error(`ACP prompt text exceeds ${g} bytes`);let j=Z.join(`
|
|
17
|
+
`);return{content:H>0?J:j,displayText:j}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let Z=this.updateEgress.offer({sessionId:this.id,update:z});if(!Z.accepted)return!1;try{return await Z.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 Z=z.map((J)=>({content:J.subject,priority:J.priority,status:J.status}));V.debug(`[AcpSession ${this.id}] Sending plan update with ${Z.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:Z})}async requestPermission(z){let Z=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,Z);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,Z);let J=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(J))return V.debug(`[AcpSession ${this.id}] Auto-approving ${J} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(J==="write"||J==="execute"))return V.debug(`[AcpSession ${this.id}] Rejecting ${J} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let H=C(),Y=[];if(z.message)Y.push({type:"content",content:{type:"text",text:z.message}});if(z.details)Y.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)Y.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
+
- ${z.risks.join(`
|
|
19
|
+
- `)}`}});let X=this.mapToolKind(J),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:H,status:"pending",title:z.title||"Permission Required",content:Y,kind:X}},W=await this.waitForClientInteraction(this.connection.requestPermission(Q),Z);if(!W)return{approved:!1,reason:c};let j=W.outcome;if(j.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=j.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 F=L==="allow_once";return{approved:F,scope:"once",reason:F?void 0:"User denied the operation"}}catch(H){return V.warn(`[AcpSession ${this.id}] Permission request failed:`,H),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,Z){let J=z.questions??[];if(J.length===0)return{approved:!1,reason:"No structured questions were provided"};if(J.some((Y)=>Y.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let H={};try{for(let[Y,X]of J.entries()){let Q=X.options.map((F,B)=>`answer:${Y}:${B}`),W=`answer:${Y}:cancel`,j=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...X.options.map((F,B)=>({optionId:Q[B],name:F.label,kind:"allow_once"})),{optionId:W,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:C(),status:"pending",title:X.header,kind:"think",content:[{type:"content",content:{type:"text",text:[X.question,...X.options.map((F)=>`${F.label}: ${F.description}`)].join(`
|
|
20
|
+
`)}}]}}),Z);if(!j)return{approved:!1,reason:c};if(j.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Q.indexOf(j.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};H[X.header]=X.options[L].label}return{approved:!0,answers:H}}catch(Y){return V.warn(`[AcpSession ${this.id}] Question request failed:`,Y),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,Z){let J=z.mcpElicitation;if(!J)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(J.mode==="url"){let Y=await this.requestElicitationChoice("MCP external authorization",[J.message,`Server: ${J.serverName}`,`Domain: ${J.domain??"unknown"}`,`URL: ${J.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"}],Z);if(Y==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:Y==="decline"?"User declined URL":"User cancelled",elicitation:{action:Y==="decline"?"decline":"cancel"}}}let H=Object.create(null);for(let Y of J.fields??[]){let X=await this.collectAcpElicitationField(Y,Z);if(X.cancelled)return{approved:!1,reason:X.reason,elicitation:{action:"cancel"}};if(X.value!==void 0)H[Y.name]=X.value}return{approved:!0,elicitation:{action:"accept",content:H}}}catch(H){return V.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,H),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,Z){if(z.type==="select"||z.type==="boolean"){let J=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((X,Q)=>({id:`option:${Q}`,label:X.label,value:X.value})),H=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
+
`),[...J.map((X)=>({id:X.id,label:X.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],Z);if(H==="skip")return{cancelled:!1};let Y=J.find((X)=>X.id===H);if(!Y)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:Y.value}}if(z.defaultValue!==void 0){let J=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"}]:[]],Z);if(J==="default")return{cancelled:!1,value:z.defaultValue};if(J==="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,Z,J,H){let Y=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...J.map((X)=>({optionId:X.id,name:X.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:C(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:Z}}]}}),H);return Y?.outcome.outcome==="selected"?Y.outcome.optionId:void 0}async waitForClientInteraction(z,Z){if(!Z)return z;if(Z.aborted)return;return new Promise((J,H)=>{let Y=!1,X=(W)=>{if(Y)return;Y=!0,Z.removeEventListener("abort",Q),W()},Q=()=>X(()=>J(void 0));if(Z.addEventListener("abort",Q,{once:!0}),Z.aborted)Q();z.then((W)=>X(()=>J(W)),(W)=>X(()=>H(W)))})}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 N=y("Agent");class v{connection;sessions=new Map;sessionLoadQueues=new Map;runtimeResidencyValue;clientCapabilities;destroyed=!1;destroyPromise;constructor(z){this.connection=z}get runtimeResidency(){if(!this.runtimeResidencyValue){let z=Iz();this.runtimeResidencyValue=new mz({maxResident:z?.maxResidentSessionRuntimes??kz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(Z){if(Z instanceof pz)throw $J.internalError({resource:Z.resource,limit:Z.limit,retryable:Z.retryable},Z.message);throw Z}}async initialize(z){return N.info("[BladeAgent] Initializing ACP connection"),N.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Cz(),{protocolVersion:ZJ,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 Z=d("acp"),J=await this.reserveSessionRuntime(Z),H=z.cwd||hz(),Y=z._meta?.["blade/taskIsolation"],X=Y==="local"||Y==="worktree"?Y:void 0,Q=z._meta?.["blade/taskPrompt"],W;try{let j=X?await cz.createSessionTask({sessionId:Z,prompt:typeof Q==="string"&&Q.trim()?Q:"ACP task session",sourceProjectPath:H,isolation:X}):void 0,L=j?.metadata.projectPath??H;return N.info(`[BladeAgent] Creating new session: ${Z}`),N.debug(`[BladeAgent] Session cwd: ${L}`),W=new b(Z,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...j?.taskWorktree?{taskWorktree:j.taskWorktree}:{},...j?.metadata.taskIsolation?{taskIsolation:j.metadata.taskIsolation}:{}}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(Z,W,J),N.info(`[BladeAgent] Session ${Z} created, scheduling available commands update`),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Z,j?.metadata,W.getModelConfiguration())}catch(j){throw J.cancel(),await W?.destroy().catch(()=>{return}),j}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let Z=await G.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:Z.sessions.map((J)=>({sessionId:J.sessionId,cwd:J.projectPath,title:J.title??null,updatedAt:J.lastMessageTime,_meta:{"blade/taskStatus":J.taskStatus,...J.taskStatusReason?{"blade/taskStatusReason":J.taskStatusReason}:{},...J.taskFailure?{"blade/taskFailure":J.taskFailure}:{},...J.taskStartedAt?{"blade/taskStartedAt":J.taskStartedAt}:{},...J.taskCompletedAt?{"blade/taskCompletedAt":J.taskCompletedAt}:{},...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskIsolation?{"blade/taskIsolation":J.taskIsolation}:{},...J.taskSourceProjectPath?{"blade/taskSourceProjectPath":J.taskSourceProjectPath}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{},...J.taskDiffStat?{"blade/taskDiffStat":J.taskDiffStat}:{},...J.taskQueuePosition?{"blade/taskQueuePosition":J.taskQueuePosition}:{},...J.taskQueueDepth!==void 0?{"blade/taskQueueDepth":J.taskQueueDepth}:{},...J.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":J.taskConcurrencyLimit}:{}}})),nextCursor:Z.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let Z=d("fork"),J=await this.reserveSessionRuntime(Z),H;try{let Y=await G.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:Z});return this.assertNotDestroyed(),H=new b(Y.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:Y.messages,permissionMode:Y.metadata.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),this.assertNotDestroyed(),this.commitSession(Y.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(Y.sessionId,Y.metadata,H.getModelConfiguration())}catch(Y){throw J.cancel(),await H?.destroy().catch(()=>{return}),Y}}async loadSession(z){this.assertNotDestroyed(),N.info(`[BladeAgent] Loading session: ${z.sessionId}`);let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),H=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,H);try{return await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===H)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await G.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let Z=await this.reserveSessionRuntime(z.sessionId),J;try{let[H,Y]=await Promise.all([G.loadSession(z.sessionId,z.cwd),G.findSessionMetadata(z.sessionId,z.cwd)]);if(!Y)throw Error(`Session not found: ${z.sessionId}`);return J=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:H,permissionMode:Y.permissionMode,mcpServers:z.mcpServers}),await J.initialize(),await J.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,J,Z),J.sendAvailableCommandsDelayed(),this.buildSessionSetup(J.getModelConfiguration(),J.getMode())}catch(H){throw Z.cancel(),await J?.destroy().catch(()=>{return}),H}}commitSession(z,Z,J){let H=J.commit({key:z,surface:"acp",value:Z,canEvict:()=>Z.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===Z)this.sessions.delete(z);await Z.destroy()}});this.sessions.set(z,Z),H.release()}async closeResidentSession(z,Z={}){let J=this.sessions.get(z);if(!J)return;let H=this.runtimeResidency.owns(z,J),Y;try{await J.destroy(Z)}catch(Q){Y=Q}let X=await this.runtimeResidency.forget(z,J);if(this.sessions.get(z)===J)this.sessions.delete(z);if(H&&!X&&Y===void 0)throw Error(`ACP Session is still active: ${z}`);if(Y!==void 0)throw Y}buildChildSessionResponse(z,Z,J){return{sessionId:z,...this.buildSessionSetup(J,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")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,Z="default"){let J=z?.models??[],H=(z?.currentModelId&&J.some((Q)=>Q.id===z.currentModelId)?z.currentModelId:void 0)??J[0]?.id,Y=[{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"}],X=[];if(J.length>0)X.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:H,options:J.map((Q)=>({value:Q.id,name:Q.displayName??Q.model,description:`${z?.modelProviders[Q.provider]?.name??Q.provider} · ${Q.model}`}))});if(z?.reasoning)X.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)X.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)X.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)X.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:Y,currentModeId:Z},configOptions:X.length>0?X:void 0}}async closeSession(z){this.assertNotDestroyed();let J=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),H=J.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,H);try{await J}finally{if(this.sessionLoadQueues.get(z.sessionId)===H)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{return await Z.value.prompt(z)}finally{Z.release()}}async cancel(z){N.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z){N.info("[BladeAgent] Found session, calling session.cancel()");try{Z.value.cancel()}finally{Z.release()}}else N.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){N.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let Z=this.runtimeResidency.acquire(z.sessionId);if(Z)try{await Z.value.setMode(z.modeId)}finally{Z.release()}return{}}async setSessionConfigOption(z){let Z=this.runtimeResidency.acquire(z.sessionId);if(!Z)throw Error(`Session not found: ${z.sessionId}`);try{let J=Z.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")N.info(`[BladeAgent] Setting session model: ${z.value}`),await J.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&fz(z.value))N.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await J.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&yz(z.value))N.info(`[BladeAgent] Setting service tier: ${z.value}`),await J.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&Sz(z.value))N.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await J.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&uz(z.value))N.info(`[BladeAgent] Setting communication style: ${z.value}`),await J.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(J.getModelConfiguration(),J.getMode()).configOptions??[]}}finally{Z.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 Z of[...this.sessions.keys()])try{await this.closeResidentSession(Z)}catch(J){z??=J}try{await this.runtimeResidency.disposeAll()}catch(Z){z??=Z}this.sessions.clear();try{await gz.getInstance().disconnectAll()}catch(Z){z??=Z}if(z!==void 0)throw z}}async function QZ(){let z=WJ.toWeb(process.stdout),Z=QJ.toWeb(process.stdin),J=k.ndJsonStream(z,Z),H,Y=new k.AgentSideConnection((Q)=>{return H=new v(Q),H},J),X=dz(async()=>{await H?.destroy()});try{await Y.closed}finally{X(),await H?.destroy()}}export{QZ as runAcpIntegration};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ah as Y}from"./chunk-sdbbyagy.js";import{Bh as on,Ch as F,Dh as o}from"./chunk-f3426b1c.js";import{Hh as ct,Ih as bt}from"./chunk-c475tfqf.js";import{Ph as x}from"./chunk-0hr050ck.js";import{$h as un,Qh as Jn,Rh as Xt,Sh as pt,Wh as gt,Xh as kn,Yh as it,Zh as Rt,_h as Ct,ai as zt,bi as Bt,ci as On,di as Kt,ei as Ut,fi as jn,gi as Ht,hi as Yt,ii as qt,ji as Vt,ki as Qt,li as Gt}from"./chunk-q69fzq4y.js";import{pi as fn}from"./chunk-n7mzxa8h.js";import{si as $t,vi as J}from"./chunk-s10pmnrd.js";import{Di as Pn,Ei as Ln}from"./chunk-
|
|
1
|
+
import{Ah as Y}from"./chunk-sdbbyagy.js";import{Bh as on,Ch as F,Dh as o}from"./chunk-f3426b1c.js";import{Hh as ct,Ih as bt}from"./chunk-c475tfqf.js";import{Ph as x}from"./chunk-0hr050ck.js";import{$h as un,Qh as Jn,Rh as Xt,Sh as pt,Wh as gt,Xh as kn,Yh as it,Zh as Rt,_h as Ct,ai as zt,bi as Bt,ci as On,di as Kt,ei as Ut,fi as jn,gi as Ht,hi as Yt,ii as qt,ji as Vt,ki as Qt,li as Gt}from"./chunk-q69fzq4y.js";import{pi as fn}from"./chunk-n7mzxa8h.js";import{si as $t,vi as J}from"./chunk-s10pmnrd.js";import{Di as Pn,Ei as Ln}from"./chunk-4bwr3rcj.js";import{Ki as h}from"./chunk-wyhyw9rq.js";import{Vi as Tn}from"./chunk-tgdhsm5t.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Xf as b1,Yf as L0,Zf as z1,cg as N0}from"./chunk-kf7whgr7.js";import{jg as jO,kg as wO}from"./chunk-fva7jnjy.js";import{ng as A1}from"./chunk-41ympwz1.js";import{og as b0,qg as J0}from"./chunk-
|
|
1
|
+
import{Xf as b1,Yf as L0,Zf as z1,cg as N0}from"./chunk-kf7whgr7.js";import{jg as jO,kg as wO}from"./chunk-fva7jnjy.js";import{ng as A1}from"./chunk-41ympwz1.js";import{og as b0,qg as J0}from"./chunk-6j482w6k.js";import{sh as S0,th as GO,xh as I0}from"./chunk-139frcak.js";import{Bh as u,Dh as L,Gh as c1}from"./chunk-f3426b1c.js";import{Ph as M}from"./chunk-0hr050ck.js";import{pi as k,qi as S}from"./chunk-n7mzxa8h.js";import{Di as u0}from"./chunk-4bwr3rcj.js";import{Ki as N}from"./chunk-wyhyw9rq.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{qe as a,re as b,se as c}from"./chunk-
|
|
1
|
+
import{qe as a,re as b,se as c}from"./chunk-szdz1jmj.js";import"./chunk-j2dyprdy.js";import"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-41ympwz1.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-2mck84gx.js";import"./chunk-4bwr3rcj.js";import"./chunk-fhfzdyba.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{qa as F,sa as L}from"./chunk-
|
|
1
|
+
import{qa as F,sa as L}from"./chunk-yeq7qzdb.js";import{Gd as $,Id as B,Qd as Q}from"./chunk-najk5ty4.js";import{Sf as y}from"./chunk-151cz9k4.js";import{Ph as V}from"./chunk-0hr050ck.js";async function j(){await y(V())}async function I(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let K of z)G.push(K);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function M(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(z.isTTY)return;let G=[];for await(let Z of z)G.push(Buffer.isBuffer(Z)?Z:Buffer.from(Z));return Buffer.concat(G).toString("utf-8").trim()||void 0}async function R(b){if(!F(b))return{mode:"agent",content:b};let q=await L(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:K}=z;return{mode:"agent",content:K?`Please use the "${G}" skill to help me with: ${K}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
|
|
2
2
|
|
|
3
3
|
${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as D,stat as H}from"node:fs/promises";import J from"node:path";function x(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return B(z).schema}async function _(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return x(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=J.resolve(b.outputSchema),z=await H(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>$)throw Error(`Output schema exceeds ${$} bytes: ${q}`);return x(await D(q,"utf8"),q)}function N(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function W(b){try{return await Q.loadSessionModelContext(b,V())}catch(q){if(N(q))return null;throw q}}async function C(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),K=await Q.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}let[q,z]=await Promise.all([Q.loadSessionModelContext(b.resume),Q.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await Q.listSessions({cwd:V()}):await Q.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),K=await Q.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...K,messages:await Q.loadSessionModelContext(K.sessionId,G)}}return{sessionId:z,messages:await Q.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await W(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await Q.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
|
|
4
4
|
export{j as m,I as n,M as o,R as p,_ as q,C as r};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Di as S}from"./chunk-
|
|
1
|
+
import{Di as S}from"./chunk-4bwr3rcj.js";import{Xi as f}from"./chunk-fhfzdyba.js";import*as $ from"fs/promises";import*as K from"path";import j from"semver";import{ProxyAgent as H,fetch as I}from"undici";function R(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.https_proxy||process.env.http_proxy}function N(){let q=R();if(q)try{return new H(q)}catch(z){console.warn(`[proxyFetch] Invalid proxy URL: ${q}`)}return}async function M(q,z={}){let{timeout:W=30000,signal:Q,...B}=z;if(Q?.aborted)throw new DOMException("The operation was aborted.","AbortError");let J=N(),X=new AbortController,Y=!1,F=setTimeout(()=>{Y=!0,X.abort()},W),b=()=>X.abort();Q?.addEventListener("abort",b);try{let Z={method:B.method,headers:B.headers,body:B.body,signal:X.signal,dispatcher:J};return await I(q.toString(),Z)}catch(Z){if(Z instanceof Error&&Z.name==="AbortError"){if(Y)throw Error(`Request timeout after ${W}ms`);throw Z}throw Z}finally{clearTimeout(F),Q?.removeEventListener("abort",b)}}var w="blade-code",y="https://cdn.jsdelivr.net/npm/blade-code@latest/CHANGELOG.md",G=K.join(process.env.HOME||process.env.USERPROFILE||".",".blade"),O=K.join(G,"version-cache.json"),P=3600000,k=`https://registry.npmjs.org/${w}/latest`;async function L(){try{if(process.env.BLADE_VERSION)return process.env.BLADE_VERSION;return S()}catch{return"unknown"}}async function T(){try{let q=await $.readFile(O,"utf-8"),z=JSON.parse(q);if(Date.now()-z.checkedAt<P)return z;return{...z,checkedAt:0}}catch{return null}}async function D(q){try{await $.mkdir(G,{recursive:!0,mode:493}),await $.writeFile(O,JSON.stringify(q,null,2))}catch{}}async function x(){try{let q=await M(k,{timeout:5000,headers:{Accept:"application/json"}});if(!q.ok)return null;return(await q.json()).version||null}catch{return null}}async function _(q=!1){let z=await L(),W=y;if(z==="unknown")return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to determine current version"};let Q=await T(),B=Q?.skipUntilVersion,J=null;if(!q&&Q?.latestVersion&&Q.checkedAt>0)J=Q.latestVersion;else if(J=await x(),J)await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});else if(Q?.latestVersion)await D({checkedAt:0,skipUntilVersion:B});if(!J||!j.valid(J))return{currentVersion:z,latestVersion:null,hasUpdate:!1,shouldPrompt:!1,releaseNotesUrl:W,error:"Unable to check for updates"};if(j.lt(J,z))J=z,await D({latestVersion:J,checkedAt:Date.now(),skipUntilVersion:B});let X=j.gt(J,z),Y=X;if(X&&B)Y=j.gt(J,B);return{currentVersion:z,latestVersion:J,hasUpdate:X,shouldPrompt:Y,releaseNotesUrl:W}}async function u(q){let z=await T();await D({latestVersion:z?.latestVersion??q,checkedAt:z?.checkedAt||Date.now(),skipUntilVersion:q})}function g(){return`npm install -g ${w}@latest --registry https://registry.npmjs.org`}async function C(){let{spawn:q}=await import("child_process");return new Promise((z)=>{let W=g(),Q=q(W,{stdio:"inherit",shell:!0});Q.on("close",(B)=>{if(B===0)z({success:!0,message:"Upgrade successful! Please restart blade."});else z({success:!1,message:`Upgrade failed (exit code: ${B})`})}),Q.on("error",(B)=>{z({success:!1,message:`Upgrade failed: ${B.message}`})})})}async function V(){try{let q=await _();return q.shouldPrompt?q:null}catch{return null}}
|
|
2
2
|
export{_ as h,u as i,g as j,C as k,V as l};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{W as P}from"./chunk-
|
|
1
|
+
import{W as P}from"./chunk-yeq7qzdb.js";import{tb as K}from"./chunk-8hp650gn.js";import{$c as S,Qd as B,Zc as G,_c as N,ad as O,bd as s}from"./chunk-najk5ty4.js";import{$d as j}from"./chunk-x3cxmwnz.js";import{af as q}from"./chunk-dg0d3303.js";import{yf as v}from"./chunk-151cz9k4.js";import{Ri as z}from"./chunk-tgdhsm5t.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
|
|
3
3
|
`).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
|
|
4
4
|
`)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-
|
|
1
|
+
import{$e as q,Le as a,Me as b,Ne as c,Oe as d,Pe as e,Qe as f,Re as g,Se as h,Te as i,Ue as j,Ve as k,We as l,Xe as m,Ye as n,Ze as o,_e as p}from"./chunk-5y38cfk9.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import"./chunk-fhfzdyba.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import"./chunk-v508x7cg.js";import{xh as Q}from"./chunk-
|
|
2
|
-
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-bt18xsc6.js"),{SessionService:B}=await import("./chunk-
|
|
1
|
+
import"./chunk-v508x7cg.js";import{xh as Q}from"./chunk-139frcak.js";import"./chunk-sdbbyagy.js";import"./chunk-f3426b1c.js";import"./chunk-c475tfqf.js";import{Ph as L}from"./chunk-0hr050ck.js";import"./chunk-q69fzq4y.js";import"./chunk-n7mzxa8h.js";import"./chunk-s10pmnrd.js";import"./chunk-9p20hhs0.js";import"./chunk-4bwr3rcj.js";import"./chunk-wyhyw9rq.js";import"./chunk-rvk9r2cm.js";import"./chunk-tgdhsm5t.js";import{Xi as F}from"./chunk-fhfzdyba.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
|
|
2
|
+
`);try{let{rebuildProjectionIndex:z}=await import("./chunk-bt18xsc6.js"),{SessionService:B}=await import("./chunk-x6z05rfz.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
|
|
3
3
|
`);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
|
|
4
4
|
Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.
|
|
1
|
+
import{readFileSync as l}from"node:fs";import{dirname as o,join as u}from"node:path";import{fileURLToPath as a}from"node:url";var e={name:"blade-code",version:"0.10.105",private:!1,description:"🗡️ Blade Code - 智能代码助手命令行工具",type:"module",bin:{blade:"dist/blade.js"},files:["dist","vendor/ripgrep/**","README.md"],scripts:{dev:"node scripts/run-bun.js --watch src/blade.tsx","dev:serve":"node scripts/run-bun.js --watch src/blade.tsx serve --port 4097",build:"rm -rf dist && node scripts/run-bun.js run scripts/build.ts",start:"node scripts/run-bun.js run dist/blade.js",test:"node scripts/test.js","test:all":"vitest run --config vitest.config.ts --project='!performance' && vitest run --config vitest.config.ts --project=performance","test:unit":"node scripts/test.js unit","test:integration":"node scripts/test.js integration","test:real-api":"node scripts/test.js realApi","test:real-api:qualification":"node scripts/test.js realApiQualification","test:cli":"node scripts/test.js cli","test:headless-core":"node scripts/test.js headlessCore","test:e2e":"node scripts/test.js e2e","test:performance":"node scripts/test.js performance","test:snapshot":"node scripts/test.js snapshot","test:security":"node scripts/test.js security","browser:install":"playwright install chromium","browser:check":"node scripts/run-bun.js run scripts/browser-check.ts","test:coverage":"node scripts/test.js all --coverage","test:watch":"vitest --watch --config vitest.config.ts","qualify:local":"node scripts/run-bun.js run scripts/qualify.ts local","qualify:production":"node scripts/run-bun.js run scripts/qualify.ts production","benchmark:repo":"node scripts/run-bun.js run scripts/run-real-repo-benchmark.ts","test:update-snapshots":"node scripts/test.js snapshot --update",lint:"biome lint src tests","lint:fix":"biome lint --write src tests","type-check":"tsc --noEmit","format:check":"biome format src tests",ready:"node scripts/run-bun.js run scripts/qualify.ts production","detect-unused":"node scripts/run-bun.js run scripts/detect-unused.ts",prepack:"node scripts/run-bun.js run build",release:"node scripts/release.js","release:dry":"node scripts/release.js --dry-run","release:major":"node scripts/release.js --major","release:minor":"node scripts/release.js --minor","release:patch":"node scripts/release.js --patch"},keywords:["cli","blade","ai","assistant","agent","llm"],author:"echoVic",license:"MIT",repository:{type:"git",url:"git+https://github.com/echoVic/blade-code.git"},homepage:"https://github.com/echoVic/blade-code#readme",bugs:{url:"https://github.com/echoVic/blade-code/issues"},engines:{node:">=22.19.0"},optionalDependencies:{"@vscode/ripgrep":"^1.18.0","better-sqlite3":"^11.8.1","bun-pty":"^0.4.8","node-pty":"1.1.0"},dependencies:{"@agentclientprotocol/sdk":"^1.3.0","@anthropic-ai/sandbox-runtime":"0.0.67","@earendil-works/pi-ai":"0.84.2","@inkjs/ui":"^2.0.0","@modelcontextprotocol/sdk":"^1.30.0",ahooks:"^3.9.7",ajv:"^8.17.1","ansi-escapes":"^7.3.0","async-mutex":"^0.5.0",axios:"^1.19.0",chalk:"^5.4.1",diff:"^8.0.2","fast-glob":"^3.3.3","fuse.js":"^7.5.0","gray-matter":"^4.0.3",hono:"^4.13.0",ink:"npm:@jrichman/ink@6.4.10","ink-big-text":"^2.0.0","ink-gradient":"^3.0.0","ink-select-input":"^6.2.0","ink-spinner":"^5.0.0","ink-text-input":"^6.0.0","js-tiktoken":"^1.0.21","lodash-es":"^4.18.1",lowlight:"^3.3.0","lru-cache":"^11.5.2",nanoid:"^5.1.6",open:"^10.1.2",picomatch:"^4.0.5",playwright:"1.62.1","proper-lockfile":"^4.1.2",react:"19.2.4","react-dom":"19.2.4",semver:"^7.8.5","string-width":"^8.2.2",typebox:"1.3.10",undici:"^7.16.0","vscode-jsonrpc":"8.2.1","vscode-languageserver-protocol":"3.17.5","vscode-languageserver-types":"3.17.5","write-file-atomic":"^7.0.0",ws:"^8.21.2",yaml:"^2.9.0",yargs:"^18.1.0",zustand:"^5.0.14"},devDependencies:{"@biomejs/biome":"2.5.7","@types/bun":"^1.3.14","@types/json-schema":"^7.0.15","@types/lodash-es":"^4.17.12","@types/node":"^22.15.24","@types/picomatch":"^4.0.3","@types/proper-lockfile":"^4.1.4","@types/react":"19.2.10","@types/react-dom":"19.2.3","@types/semver":"^7.8.0","@types/write-file-atomic":"^4.0.3","@types/ws":"^8.18.1","@types/yargs":"^17.0.35","@vitest/coverage-v8":"^4.1.10",jsdom:"^26.0.0",typescript:"^5.9.2",vitest:"^4.1.10"}};var s;function r(){if(s)return s;let i=o(a(import.meta.url));for(let n=0;n<5;n++){try{let t=JSON.parse(l(u(i,"package.json"),"utf8"));if(t.name===e.name&&typeof t.version==="string"&&typeof t.description==="string")return s=t,s}catch{}i=o(i)}return s={name:e.name,version:process.env.BLADE_VERSION??e.version,description:e.description},s}function y(){return{...r()}}function p(){return r().version}function v(){return r().name}function g(){return r().description}function f(){return`v${p()}`}function w(){return`v${p()} © 2025 Blade Code`}
|
|
2
2
|
export{y as Ci,p as Di,v as Ei,g as Fi,f as Gi,w as Hi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{oe as a,pe as b}from"./chunk-djqbqaxn.js";import"./chunk-4bwr3rcj.js";import"./chunk-fhfzdyba.js";export{a as globalOptions,b as cliConfig};
|