blade-code 0.10.100 → 0.10.101
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-gkdynynx.js → chunk-2191220r.js} +1 -1
- package/dist/{chunk-rmhgyrgh.js → chunk-2cg8f38t.js} +1 -1
- package/dist/{chunk-hx55j0d0.js → chunk-2f5kkhan.js} +274 -274
- package/dist/chunk-2r0f3b4t.js +1 -0
- package/dist/{chunk-q1cc7kwn.js → chunk-3an3vxzt.js} +1 -1
- package/dist/{chunk-8zm5r6g8.js → chunk-3c01jje5.js} +1 -1
- package/dist/{chunk-ttg3xrsc.js → chunk-8yt4nmyb.js} +1 -1
- package/dist/{chunk-tagtjbw9.js → chunk-8z9d0zd0.js} +1 -1
- package/dist/chunk-9ajkzcqj.js +12 -0
- package/dist/chunk-as2ezx8p.js +1 -0
- package/dist/{chunk-axycs651.js → chunk-bswjne5v.js} +1 -1
- package/dist/{chunk-dfxfcsm1.js → chunk-c663rajb.js} +1 -1
- package/dist/chunk-cjgpas7y.js +23 -0
- package/dist/{chunk-c3yd59qh.js → chunk-dcjh1cj6.js} +1 -1
- package/dist/{chunk-ara0zd89.js → chunk-f8z5v101.js} +1 -1
- package/dist/{chunk-6p9p71qm.js → chunk-fqbc1ppx.js} +1 -1
- package/dist/{chunk-h8qjkxee.js → chunk-hpjnk87v.js} +18 -18
- package/dist/{chunk-qc4fe1j6.js → chunk-j22d84s7.js} +1 -1
- package/dist/{chunk-jac8cc04.js → chunk-jvxskq6a.js} +1 -1
- package/dist/{chunk-sgzqcr55.js → chunk-kdatgrjy.js} +1 -1
- package/dist/{chunk-njctfzqw.js → chunk-kfcs62nw.js} +1 -1
- package/dist/{chunk-3ktsyk2g.js → chunk-mzab7qak.js} +1 -1
- package/dist/{chunk-s15phq98.js → chunk-n5jfmzp2.js} +1 -1
- package/dist/{chunk-cc74b8qp.js → chunk-nh4jy5cs.js} +1 -1
- package/dist/{chunk-x677fstt.js → chunk-qgjgjzbx.js} +1 -1
- package/dist/{chunk-5dkzqgxa.js → chunk-qjeadpj2.js} +1 -1
- package/dist/chunk-qjv5kz7q.js +171 -0
- package/dist/chunk-sa7t9kht.js +6 -0
- package/dist/{chunk-pzp42zf0.js → chunk-tazb5tze.js} +1 -1
- package/dist/chunk-tc9rq0st.js +160 -0
- package/dist/{chunk-1nwc2wt6.js → chunk-tp5bep1y.js} +1 -1
- package/dist/{chunk-6jhndjnq.js → chunk-twhf09qs.js} +1 -1
- package/dist/{chunk-6rd8x9j0.js → chunk-vc7gh3wc.js} +1 -1
- package/dist/{chunk-y7bsjbsa.js → chunk-wbf4qcws.js} +2 -2
- package/dist/chunk-ykf4cqpg.js +8 -0
- package/dist/{chunk-v9pcf4w4.js → chunk-z0dmm227.js} +1 -1
- package/dist/{chunk-gcnke6s4.js → chunk-z5a8ay9s.js} +1 -1
- package/dist/{chunk-gr6e2vsy.js → chunk-zjpph3ys.js} +1 -1
- package/dist/{chunk-6hr7mv7f.js → chunk-zydvg30x.js} +1 -1
- package/dist/web/assets/{ChatView-Cwc3fRAC.js → ChatView-Cc4bXZ6x.js} +14 -14
- package/dist/web/assets/{CodeBlockHighlighter-IGDocZUy.js → CodeBlockHighlighter-DZcVFtJE.js} +1 -1
- package/dist/web/assets/{FilePreview-EWE-k9VN.js → FilePreview-CzNS6kfM.js} +1 -1
- package/dist/web/assets/{KanbanBoard-FiiVQgTQ.js → KanbanBoard-cdh2g0r0.js} +1 -1
- package/dist/web/assets/{MarkdownRenderer-DjhWmikM.js → MarkdownRenderer-BqBOUlXa.js} +3 -3
- package/dist/web/assets/{SettingsModal-bHPx0fVG.js → SettingsModal-meSWhCOP.js} +1 -1
- package/dist/web/assets/{TaskSwitcher-CclOfJEl.js → TaskSwitcher-CiQi64Yl.js} +1 -1
- package/dist/web/assets/{TerminalPanel-Bnep8jE2.js → TerminalPanel-Bze9t5mz.js} +1 -1
- package/dist/web/assets/{arrow-left-CiX0E9Mt.js → arrow-left-DpTnLOBT.js} +1 -1
- package/dist/web/assets/{calendar-clock-Bgfr-twh.js → calendar-clock-DlAXXpl_.js} +1 -1
- package/dist/web/assets/{chevrons-up-down-B4T5fHUs.js → chevrons-up-down-CmAktdaR.js} +1 -1
- package/dist/web/assets/{clock-3-CGIhJjon.js → clock-3-_w8nIuEK.js} +1 -1
- package/dist/web/assets/{external-link-DnQv1VYE.js → external-link-AlymrIfc.js} +1 -1
- package/dist/web/assets/{folder-C5f8TpGj.js → folder-CrxO-9Rc.js} +1 -1
- package/dist/web/assets/{index-DNoVz0u1.js → index-JJH0FKfo.js} +5 -5
- package/dist/web/assets/{pause-Cb0ijwnO.js → pause-GQZaG_P3.js} +1 -1
- package/dist/web/assets/{play-Dsw1qmpk.js → play-BPhmPVpi.js} +1 -1
- package/dist/web/assets/{session-events-B4Cq2TwN.js → session-events-CO2pRY9U.js} +8 -8
- package/dist/web/assets/{teamService-C69fFhny.js → teamService-BqS4iOx0.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +1 -1
- package/dist/chunk-2s86w4yb.js +0 -171
- package/dist/chunk-73t5j9dn.js +0 -160
- package/dist/chunk-8wzn2p00.js +0 -6
- package/dist/chunk-hx3c0qn6.js +0 -9
- package/dist/chunk-p4h3p1at.js +0 -23
- package/dist/chunk-t29x8420.js +0 -1
- package/dist/chunk-tsthz2ex.js +0 -8
- package/dist/chunk-vgevdm8b.js +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-f8z5v101.js";import"./chunk-8z9d0zd0.js";import"./chunk-w9xfks7f.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{h as o}from"./chunk-
|
|
1
|
+
import{h as o}from"./chunk-f8z5v101.js";import"./chunk-8z9d0zd0.js";import"./chunk-w9xfks7f.js";import{execSync as r}from"child_process";var l={command:"update",describe:"Check for updates and install if available",handler:async()=>{console.log("Checking for updates...");try{let e=await o(!0);if(console.log(`Current version: ${e.currentVersion}`),e.error){console.log(`Warning: ${e.error}`);return}if(e.latestVersion)console.log(`Latest version: ${e.latestVersion}`);if(e.hasUpdate&&e.latestVersion){console.log(""),console.log(`\x1B[33mUpdate available: ${e.currentVersion} -> ${e.latestVersion}\x1B[0m`),console.log(""),console.log("Updating...");try{r("npm install -g blade-code@latest --registry https://registry.npmjs.org",{stdio:"inherit"}),console.log(""),console.log("Update complete!")}catch(t){console.error("Error: Update failed. Please run manually:"),console.error(" npm install -g blade-code@latest"),process.exit(1)}}else console.log("You are running the latest version of Blade")}catch(e){console.error(`Error: Failed to check for updates: ${e instanceof Error?e.message:"未知错误"}`),process.exit(1)}}};export{l as updateCommands};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{te as s}from"./chunk-10taec1j.js";import{Me as o}from"./chunk-
|
|
1
|
+
import{te as s}from"./chunk-10taec1j.js";import{Me as o}from"./chunk-z0dmm227.js";import{$g as j,Wg as y,Xg as D,Zg as N,ah as F,ch as R,gh as E,hh as _,ih as f,jh as C,lh as S,mh as m,qh as c,vh as l,wh as n}from"./chunk-z5a8ay9s.js";import{xh as Y}from"./chunk-f9asjkfz.js";import{Bh as k,Eh as Z,zh as x}from"./chunk-czcxx8tb.js";import{Lh as X}from"./chunk-9sx3vsyj.js";import{$h as G,Ph as h,Qh as A,Wh as P,Xh as T,Zh as $,_h as U,bi as L,ci as M,ei as O,fi as I}from"./chunk-70hwyc2w.js";import{ni as d}from"./chunk-d8wzc602.js";import{promises as i}from"node:fs";import t from"node:path";var e=["systemPrompt","appendSystemPrompt","initialMessage","resumeSessionId","forkSession","allowedTools","disallowedTools","mcpConfigPaths","strictMcpConfig","model","addDirs","outputFormat","inputFormat","print","includePartialMessages","replayUserMessages","agentsConfig","settingSources"],v=new Set([...Object.keys(c),...e,"providerRequestConcurrency","providerGlobalConcurrency","providerOwnerConcurrency"]),W=k.Number({exclusiveMinimum:0}),z=k.String({minLength:1}),b=k.Array(k.String()),a=k.Object({currentModelId:k.Optional(k.String()),modelProviders:k.Optional(k.Record(z,k.Object({name:z,baseUrl:z,wireApi:Z(["openai-completions","anthropic-messages"]),apiKeyEnv:k.Optional(z)}))),models:k.Optional(k.Array(k.Object({id:z,displayName:k.Optional(z),provider:z,model:z,overrides:k.Optional(k.Object({baseUrl:k.Optional(k.String()),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),timeout:k.Optional(W),streamIdleTimeout:k.Optional(k.Number({minimum:1000})),apiVersion:k.Optional(k.String()),customHeaders:k.Optional(k.Record(k.String(),k.String())),maxRetries:k.Optional(k.Integer({minimum:0})),enablePromptCaching:k.Optional(k.Boolean())})),fallbackModels:k.Optional(k.Array(k.Object({provider:z,model:z,configId:k.Optional(z)})))}))),temperature:k.Optional(k.Number()),maxOutputTokens:k.Optional(W),stream:k.Optional(k.Boolean()),topP:k.Optional(k.Number()),topK:k.Optional(k.Number()),timeout:k.Optional(W),bashForegroundHandoffMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:y,maximum:D})])),providerForegroundRecoveryMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:h,maximum:A})])),providerCircuitBreakerOpenMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:P,maximum:T})])),providerRequestConcurrency:k.Optional(k.Integer({minimum:$,maximum:U})),providerGlobalConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerOwnerConcurrency:k.Optional(k.Integer({minimum:$,maximum:G})),providerRequestAdmissionMs:k.Optional(k.Union([k.Literal(0),k.Integer({minimum:L,maximum:M})])),providerRequestPendingBytes:k.Optional(k.Integer({minimum:O,maximum:I})),agentTeamsEnabled:k.Optional(k.Boolean()),codeTheme:k.Optional(k.String()),uiTheme:k.Optional(Z(["light","dark","system"])),language:k.Optional(k.String()),fontSize:k.Optional(W),autoSaveSessions:k.Optional(k.Boolean()),notifyBuild:k.Optional(k.Boolean()),notifyErrors:k.Optional(k.Boolean()),notifySounds:k.Optional(k.Boolean()),privacyTelemetry:k.Optional(k.Boolean()),privacyCrash:k.Optional(k.Boolean()),debug:k.Optional(k.Union([k.Boolean(),k.String()])),mcpEnabled:k.Optional(k.Boolean()),mcpServers:k.Optional(k.Record(k.String(),k.Record(k.String(),k.Unknown()))),lspServers:k.Optional(k.Record(z,k.Object({command:z,args:k.Optional(k.Array(k.String())),extensionToLanguage:k.Record(z,z),env:k.Optional(k.Record(k.String(),k.String())),initializationOptions:k.Optional(k.Unknown()),settings:k.Optional(k.Unknown()),enabled:k.Optional(k.Boolean()),priority:k.Optional(k.Integer()),startupTimeout:k.Optional(k.Integer({minimum:100})),shutdownTimeout:k.Optional(k.Integer({minimum:100})),requestTimeout:k.Optional(k.Integer({minimum:100})),diagnosticWaitTimeout:k.Optional(k.Integer({minimum:0})),maxRestarts:k.Optional(k.Integer({minimum:0,maximum:10}))}))),permissionMode:k.Optional(k.Enum(Y)),maxTurns:k.Optional(k.Integer({minimum:-1})),maxConcurrentTasks:k.Optional(k.Integer({minimum:E,maximum:_})),maxQueuedTasks:k.Optional(k.Integer({minimum:f,maximum:C})),maxQueuedTaskBytes:k.Optional(k.Integer({minimum:S,maximum:m})),maxResidentSessionRuntimes:k.Optional(k.Integer({minimum:N,maximum:j})),sessionRuntimeIdleMs:k.Optional(k.Integer({minimum:F,maximum:R})),systemPrompt:k.Optional(k.String()),appendSystemPrompt:k.Optional(k.String()),initialMessage:k.Optional(k.String()),resumeSessionId:k.Optional(k.String()),forkSession:k.Optional(k.Boolean()),allowedTools:k.Optional(k.Array(z)),disallowedTools:k.Optional(k.Array(z)),mcpConfigPaths:k.Optional(k.Array(z)),strictMcpConfig:k.Optional(k.Boolean()),model:k.Optional(z),addDirs:k.Optional(k.Array(z)),outputFormat:k.Optional(Z(["text","json","stream-json","jsonl"])),inputFormat:k.Optional(Z(["text","stream-json"])),print:k.Optional(k.Boolean()),includePartialMessages:k.Optional(k.Boolean()),replayUserMessages:k.Optional(k.Boolean()),agentsConfig:k.Optional(k.String()),settingSources:k.Optional(k.String()),permissions:k.Optional(k.Object({allow:k.Optional(b),ask:k.Optional(b),deny:k.Optional(b)})),env:k.Optional(k.Record(k.String(),k.String())),hooks:k.Optional(k.Record(k.String(),k.Unknown())),enabledPlugins:k.Optional(k.Record(z,k.Boolean())),pluginSourcePolicy:k.Optional(k.Object({restrictToAllowedSources:k.Optional(k.Boolean()),requireGitCommitSha:k.Optional(k.Boolean()),allowedGitHosts:k.Optional(k.Array(z)),allowedMarketplaces:k.Optional(k.Array(z)),allowedLocalRoots:k.Optional(k.Array(z))})),disableAllHooks:k.Optional(k.Boolean())}),g=[["systemPrompt","systemPrompt"],["appendSystemPrompt","appendSystemPrompt"],["initialMessage","initialMessage"],["resumeSessionId","sessionId"],["forkSession","forkSession"],["allowedTools","allowedTools"],["disallowedTools","disallowedTools"],["mcpConfigPaths","mcpConfig"],["strictMcpConfig","strictMcpConfig"],["model","model"],["addDirs","addDir"],["outputFormat","outputFormat"],["inputFormat","inputFormat"],["print","print"],["includePartialMessages","includePartialMessages"],["replayUserMessages","replayUserMessages"],["agentsConfig","agents"],["settingSources","settingSources"],["permissionMode","permissionMode"],["maxTurns","maxTurns"],["maxConcurrentTasks","maxConcurrentTasks"],["maxQueuedTasks","maxQueuedTasks"],["maxQueuedTaskBytes","maxQueuedTaskBytes"],["maxResidentSessionRuntimes","maxResidentSessionRuntimes"],["sessionRuntimeIdleMs","sessionRuntimeIdleMs"]];function V(q,B){let w;try{w=JSON.parse(q)}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Invalid JSON provided to --settings (${B})${K}`)}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("--settings must contain a JSON object");for(let H of Object.keys(w))if(!v.has(H))throw Error(`Unknown --settings field: ${H}`);let J=x(a,w);if(!J.success){let H=J.error.issues.map((K)=>`${K.path.join(".")||"settings"}: ${K.message}`).join("; ");throw Error(`Invalid --settings value: ${H}`)}return J.data}async function p(q){if(q===void 0)return;let B=q.trim();if(!B)throw Error("--settings requires a JSON object or file path");if(B.startsWith("{"))return V(B,"inline JSON");let w=t.resolve(X(),B),J;try{J=await i.readFile(w,"utf8")}catch(H){let K=H instanceof Error?`: ${H.message}`:"";throw Error(`Unable to read --settings file ${w}${K}`)}return V(J,w)}function u(q,B){if(!B)return;let w=B;for(let[J,H]of g){if(J==="permissionMode"&&q.yolo===!0)continue;if(q[H]===void 0&&w[J]!==void 0)q[H]=w[J]}}var Q=d("General"),Dk=(q)=>{if(q.yolo){if(q.permissionMode&&q.permissionMode!=="yolo")throw Error("Cannot use both --yolo and --permission-mode with different values");q.permissionMode="yolo"}if(Array.isArray(q.allowedTools))q.allowedTools=q.allowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.disallowedTools))q.disallowedTools=q.disallowedTools.flatMap((B)=>B.split(",").map((w)=>w.trim()).filter((w)=>w.length>0));if(Array.isArray(q.allowedTools)&&Array.isArray(q.disallowedTools)){let B=q.allowedTools.filter((w)=>q.disallowedTools.includes(w));if(B.length>0)throw Error(`Tools cannot be both allowed and disallowed: ${B.join(", ")}`)}},hk=async(q)=>{let B=await p(typeof q.settings==="string"?q.settings:void 0);if(u(q,B),typeof q.agents==="string")s(q.agents);r(q);try{let J=await l.getInstance().initialize(B),H=n(J,q);if(o().config.actions.setConfig(H),q.debug)Q.info("[CLI] 配置已加载到 Store")}catch(w){Q.error("[CLI] [FAIL] 配置初始化失败",w instanceof Error?w.message:w),console.error(`
|
|
2
2
|
[FAIL] 配置初始化失败
|
|
3
3
|
`),console.error("原因:",w instanceof Error?w.message:"未知错误"),console.error(`
|
|
4
4
|
请检查:`),console.error(" 1. 配置文件格式是否正确 (~/.blade/config.json)"),console.error(" 2. 是否需要运行 blade 进行首次配置"),console.error(` 3. 配置文件权限是否正确
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Me as N}from"./chunk-
|
|
1
|
+
import{Me as N}from"./chunk-z0dmm227.js";import{og as $}from"./chunk-dcjh1cj6.js";import{Nh as _}from"./chunk-9sx3vsyj.js";import{li as Y,ni as Z}from"./chunk-d8wzc602.js";function X(){if(process.stdin.isTTY&&typeof process.stdin.setRawMode==="function")try{process.stdin.setRawMode(!1)}catch{}process.stdout.write("\x1B[<u"),process.stdout.write("\x1B[>4;0m"),process.stdout.write("\x1B[?2004l"),process.stdout.write("\x1B[?1004l"),process.stdout.write("\x1B[?1l\x1B>"),process.stdout.write("\x1B[?25h"),process.stdout.write("\x1B[0m")}var z=Z("Service");function E(b){switch(b){case"SIGINT":return"ctrl_c";case"esc":return"esc";case"uncaughtException":case"unhandledRejection":return"error";case"SIGTERM":case"normal":default:return"user_exit"}}class B{static instance=null;cleanupHandlers=[];isShuttingDown=!1;initialized=!1;lastSigintTime=0;SIGINT_DOUBLE_CLICK_WINDOW=3000;constructor(){}static getInstance(){if(!B.instance)B.instance=new B;return B.instance}initialize(){if(this.initialized){z.debug("[GracefulShutdown] 已初始化,跳过重复初始化");return}process.on("uncaughtException",(b)=>{this.handleFatalError("uncaughtException",b)}),process.on("unhandledRejection",(b)=>{let q=b instanceof Error?b:Error(String(b));this.handleFatalError("unhandledRejection",q)}),process.on("SIGTERM",()=>{z.info("[GracefulShutdown] 收到 SIGTERM 信号"),this.shutdown("SIGTERM",0)}),process.on("SIGINT",()=>{let b=Date.now();if(b-this.lastSigintTime<this.SIGINT_DOUBLE_CLICK_WINDOW)z.info("[GracefulShutdown] 收到第二次 SIGINT 信号,执行退出"),this.shutdown("SIGINT",0);else z.info("[GracefulShutdown] 收到第一次 SIGINT 信号,再按一次退出"),this.lastSigintTime=b,console.log(`
|
|
2
2
|
再按一次 Ctrl+C 退出
|
|
3
3
|
`)}),this.initialized=!0,z.debug("[GracefulShutdown] 全局错误处理器已初始化")}registerCleanup(b){return this.cleanupHandlers.push(b),z.debug(`[GracefulShutdown] 注册清理函数,当前共 ${this.cleanupHandlers.length} 个`),()=>{let q=this.cleanupHandlers.indexOf(b);if(q!==-1)this.cleanupHandlers.splice(q,1),z.debug(`[GracefulShutdown] 取消注册清理函数,剩余 ${this.cleanupHandlers.length} 个`)}}handleFatalError(b,q){if(this.isShuttingDown){console.error(`[GracefulShutdown] 退出过程中发生额外错误 (${b}):`,q);return}if(console.error(""),console.error("═".repeat(60)),console.error(`Uncaught error (${b})`),console.error("═".repeat(60)),console.error(""),console.error("错误信息:",q.message),console.error(""),q.stack)console.error("堆栈跟踪:"),console.error(q.stack);console.error(""),console.error("═".repeat(60)),console.error(""),this.shutdown(b,1)}async shutdown(b,q=0){if(this.isShuttingDown){z.debug("[GracefulShutdown] 已在退出过程中,跳过重复退出");return}this.isShuttingDown=!0;try{N().command.actions.abort("process-shutdown")}catch(A){z.warn("[GracefulShutdown] Failed to abort the active command",A)}z.info(`[GracefulShutdown] 开始优雅退出 (原因: ${b})`);let Q=setTimeout(()=>{X(),process.exit(q)},5000);Q.unref?.();let U=4000,K;try{await Promise.race([this.runCleanupHandlers(),new Promise((A,J)=>{K=setTimeout(()=>{J(Error(`清理超时 (${U}ms)`))},U),K.unref?.()})])}catch(A){console.error("[GracefulShutdown] 清理过程中发生错误:",A)}finally{if(K)clearTimeout(K)}try{let A=$.getInstance(),J=N(),V=J.session?.sessionId||"unknown",W=J.session?.workspaceRoot||_();if(A.isEnabled(W,V)){let v=J.config?.config?.permissionMode||"default";await A.executeSessionEndHooks(E(b),{projectDir:W,sessionId:V,permissionMode:v})}}catch(A){console.error("[GracefulShutdown] SessionEnd hooks 执行失败:",A)}try{await Y()}catch{}clearTimeout(Q),X(),setTimeout(()=>{process.exit(q)},100)}async runCleanupHandlers(){let b=[...this.cleanupHandlers].reverse();for(let q of b)try{let F=q();if(F instanceof Promise)await F}catch(F){console.error("[GracefulShutdown] 清理函数执行失败:",F)}}isExiting(){return this.isShuttingDown}reset(){this.isShuttingDown=!1,this.cleanupHandlers=[],this.initialized=!1}}var O=()=>{return B.getInstance()},y=(b)=>{return O().registerCleanup(b)},j=()=>{O().initialize()},C=(b=0)=>{O().shutdown("normal",b)};
|
|
4
4
|
export{O as ue,y as ve,j as we,C as xe};
|
|
@@ -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.101",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 Ai,p as Bi,v as Ci,g as Di,f as Ei,w as Fi};
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import{m as c,n as v,o as d,p as m,q as l,r as a}from"./chunk-jvxskq6a.js";import{U as O,aa as S}from"./chunk-2f5kkhan.js";import"./chunk-0zhdjaen.js";import"./chunk-2cg8f38t.js";import"./chunk-hz5rsfxv.js";import{Db as M,Mb as E}from"./chunk-qjv5kz7q.js";import"./chunk-8hprmrd5.js";import{Cd as h,Qd as f}from"./chunk-zydvg30x.js";import"./chunk-s0tq8gyx.js";import"./chunk-hpjnk87v.js";import{oe as I}from"./chunk-j22d84s7.js";import{qe as y,re as R,se as g}from"./chunk-3c01jje5.js";import{te as C}from"./chunk-10taec1j.js";import"./chunk-rej5bbbs.js";import{Qe as w}from"./chunk-z0dmm227.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import"./chunk-2hb222re.js";import"./chunk-2191220r.js";import"./chunk-nh4jy5cs.js";import"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-dcjh1cj6.js";import"./chunk-c6tq09mt.js";import"./chunk-z5a8ay9s.js";import{xh as A}from"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import{Nh as P}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-8z9d0zd0.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
|
+
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
|
+
`);else j.io.stdout.write(`${j.response}
|
|
4
|
+
`)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
5
|
+
`);return T.exitCode??0}let Q=T.content,W=await l(j),X=Q.trimStart().startsWith("!")?Q.trimStart().slice(1).trim():void 0;if(X!==void 0&&W)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:J,messages:r,metadata:G}=await a({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),Y=G?.projectPath??P(),b=t(j.permissionMode)??G?.permissionMode??w()?.permissionMode??"default";await f.setSessionPermissionMode(J,Y,b);let N=await E.cancelPendingNonInteractive(Y,J)?await f.loadSessionModelContext(J,Y):r;q=await O.create({sessionId:J,workspaceRoot:Y,modelId:j.model,permissionMode:b,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?C(j.agents):void 0,...N.length>0?{sessionStart:{isResume:!0,resumeSessionId:J}}:{}});let Z=K&&q.getPendingSteeringCount()>0,k=K&&!Z?await q.getGoal():null,L=k?.status==="active"||k?.status==="verifying",U=q.getTurnRecoveryAssessment?.()??{state:"none"};if(K&&!Z&&!L&&U.state==="requires_attention")throw B.stderr.write(`[turn-recovery:${U.state}] ${U.turnId}
|
|
6
|
+
`),Error("Turn recovery requires explicit user attention before continuation");let _=K&&!Z&&!L?await q.getRecoveredFinalResponse():void 0;if(K&&!Z&&!L){if(!_)throw Error("No unfinished turn or active goal to resume");let H=U;if(H.state!=="none")B.stderr.write(`[turn-recovery:${H.state}] ${H.turnId}
|
|
7
|
+
`);return z({io:B,options:j,response:_.content,requestInput:Q,structuredOutput:_.structuredOutput,structuredOutputSchemaDigest:_.structuredOutputSchemaDigest}),0}if(X!==void 0){let H=await q.executeUserShellCommand(X);if(j.outputFormat==="json")B.stdout.write(`${JSON.stringify(H,null,2)}
|
|
8
|
+
`);else if(j.outputFormat==="stream-json")B.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
|
|
9
|
+
`);else B.stdout.write(`${h(H.record)}
|
|
10
|
+
`);return H.record.status==="completed"?0:H.record.status==="aborted"?130:H.record.exitCode??1}let x=await S.createWithRuntime(q,{sessionId:J,systemPrompt:j.systemPrompt,appendSystemPrompt:j.appendSystemPrompt,maxTurns:j.maxTurns,modelId:j.model,permissionMode:b,toolWhitelist:j.allowedTools,toolBlacklist:j.disallowedTools,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig}),F={messages:[...N],userId:"cli-user",sessionId:J,workspaceRoot:Y,permissionMode:b},V=await M(W||K?x.chatStream(Q,F,{...W?{outputSchema:W}:{},pendingInputOnly:Z,goalContinuationOnly:L}):x.chatStream(Q,F),(H)=>{if(H.kind!=="turn_recovery")return;B.stderr.write(`[turn-recovery:${H.assessment.state}] ${H.assessment.turnId}
|
|
11
|
+
`)});if(V.metadata?.recoveryAttention)throw Error("Turn recovery requires explicit user attention before continuation");if(!V.success)throw Error(V.error?.message??"Agent execution failed");let u=V.finalMessage||"",p=V.metadata?.structuredOutput;return z({io:B,options:j,response:u,requestInput:Q,structuredOutput:p,structuredOutputSchemaDigest:V.metadata?.structuredOutputSchemaDigest}),0}catch($){return B.stderr.write(`Error: ${$ instanceof Error?$.message:"未知错误"}
|
|
12
|
+
`),1}finally{await q?.dispose()}}async function fj(){if(process.argv.slice(2).findIndex((q)=>q==="--print"||q==="-p")===-1)return!1;try{let{print:q,"output-format":$,"include-partial-messages":D,"input-format":K,"system-prompt":T,"append-system-prompt":Q,"max-turns":W,...X}=I,J=s(e(process.argv)).scriptName("blade").strict(!1).options(X).middleware([R,y,g]);return n(J),await J.parse(),!0}catch(q){console.error(`Print mode error: ${q instanceof Error?q.message:"未知错误"}`),process.exit(1)}}export{o as runPrint,fj as handlePrintMode};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{oe as a,pe as b}from"./chunk-j22d84s7.js";import"./chunk-8z9d0zd0.js";import"./chunk-w9xfks7f.js";export{a as globalOptions,b as cliConfig};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{a,b as i,c as l,d as m}from"./chunk-
|
|
1
|
+
import{a,b as i,c as l,d as m}from"./chunk-ykf4cqpg.js";import"./chunk-j00px1es.js";import"./chunk-39qzk9nm.js";import"./chunk-fqbc1ppx.js";import"./chunk-tp5bep1y.js";import"./chunk-kdatgrjy.js";import"./chunk-2f5kkhan.js";import"./chunk-0zhdjaen.js";import"./chunk-2cg8f38t.js";import"./chunk-hz5rsfxv.js";import"./chunk-qjv5kz7q.js";import"./chunk-8hprmrd5.js";import"./chunk-zydvg30x.js";import"./chunk-s0tq8gyx.js";import"./chunk-hpjnk87v.js";import{ve as n}from"./chunk-8yt4nmyb.js";import"./chunk-rej5bbbs.js";import{Re as s}from"./chunk-z0dmm227.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import"./chunk-2hb222re.js";import"./chunk-2191220r.js";import"./chunk-nh4jy5cs.js";import"./chunk-fvfc95g3.js";import"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-dcjh1cj6.js";import"./chunk-c6tq09mt.js";import"./chunk-z5a8ay9s.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-8z9d0zd0.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
|
|
@@ -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-z0dmm227.js";import"./chunk-v508x7cg.js";import"./chunk-dg0d3303.js";import"./chunk-z5a8ay9s.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import"./chunk-maebpz1j.js";import"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import"./chunk-k7vv9vne.js";import"./chunk-8z9d0zd0.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.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};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{s as cz,t as pz}from"./chunk-fqbc1ppx.js";import{u as S}from"./chunk-tp5bep1y.js";import{A as Oz,v as gz,w as wz,x as Dz,y as _z,z as Nz}from"./chunk-kdatgrjy.js";import{G as E,P as Bz,Q as Gz,U as Uz,X as jz,Y as Vz,aa as Kz,qa as Az,ra as qz,sa as Pz,ta as Rz}from"./chunk-2f5kkhan.js";import"./chunk-0zhdjaen.js";import{Ha as uz}from"./chunk-2cg8f38t.js";import{Ja as Fz}from"./chunk-hz5rsfxv.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-qjv5kz7q.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{Cd as p,Dd as $z,Fd as h,Id as Wz,Nd as P,Qd as j,ad as zz,kd as y,ld as c,md as Hz,rd as Jz,ud as Qz,wd as Zz}from"./chunk-zydvg30x.js";import"./chunk-s0tq8gyx.js";import"./chunk-hpjnk87v.js";import{ve as mz}from"./chunk-8yt4nmyb.js";import"./chunk-rej5bbbs.js";import{Qe as kz,Re as Iz}from"./chunk-z0dmm227.js";import"./chunk-v508x7cg.js";import{af as m}from"./chunk-dg0d3303.js";import{ff as e}from"./chunk-3awjdsef.js";import"./chunk-53xtssbf.js";import{qf as Cz}from"./chunk-2hb222re.js";import"./chunk-2191220r.js";import"./chunk-nh4jy5cs.js";import"./chunk-fvfc95g3.js";import{gg as fz}from"./chunk-qcy79mva.js";import"./chunk-p0rvgzpx.js";import"./chunk-dcjh1cj6.js";import"./chunk-c6tq09mt.js";import{_g as yz,bh as Mz}from"./chunk-z5a8ay9s.js";import"./chunk-f9asjkfz.js";import"./chunk-czcxx8tb.js";import{Fh as C,Gh as t,Ih as f,Jh as u}from"./chunk-maebpz1j.js";import{Nh as bz}from"./chunk-9sx3vsyj.js";import"./chunk-70hwyc2w.js";import{ni as M}from"./chunk-d8wzc602.js";import"./chunk-425p4nwx.js";import{ui as hz,xi as Sz}from"./chunk-k7vv9vne.js";import"./chunk-8z9d0zd0.js";import"./chunk-cp7xsjj2.js";import"./chunk-2va6ex5v.js";import{Ti as s}from"./chunk-q3vza5gt.js";import"./chunk-w9xfks7f.js";import{Readable as JH,Writable as QH}from"node:stream";import*as k from"@agentclientprotocol/sdk";import Ez from"node:path";import{PROTOCOL_VERSION as zH,RequestError as HH}from"@agentclientprotocol/sdk";import{createHash as lz}from"node:crypto";import{RequestError as Tz}from"@agentclientprotocol/sdk";import{nanoid as I}from"nanoid";var U=M("Agent"),i=4,iz=1000,a=4000,r=120000,o=0.2;function n(z){if(!z)return{};return Object.fromEntries(z.map((J)=>[J.name,J.value]))}function az(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:n(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:n("headers"in z?z.headers:void 0)};return null}function rz(z){let J={};for(let H of z){let W=az(H);if(W)J[H.name]=W}return J}function xz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((J)=>{if(J.type==="text")return J.text?[{type:"text",text:J.text}]:[];let H=J.image_url.url,W=/^data:([^;,]+);base64,(.+)$/s.exec(H);if(!W)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:W[1]??"image/png",data:W[2]??""}]})}function oz(z){let J=$z(z.metadata);return J?[{type:"text",text:p(J)}]:xz(z.content)}function nz(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
|
+
`)}function sz(z){if(!e(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...y("capacity"),resource:z.resource}}function tz(z,J){let H=Math.max(0,J-1),W=Math.min(iz*2**H,a),Y=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*Y;return Math.min(a,Math.max(0,Math.round(W*Z)))}function ez(z){if(!(z instanceof Tz)||!z.data||typeof z.data!=="object")return;let J=z.data;if(!Hz(J.taskFailure)||J.toolExecutionStarted!==!1||!Number.isInteger(J.toolCallsCount)||J.toolCallsCount<0||J.outputStarted!==!1)return;return{taskFailure:J.taskFailure,toolExecutionStarted:J.toolExecutionStarted,toolCallsCount:J.toolCallsCount,outputStarted:J.outputStarted}}class 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,J,H,W,X={}){this.id=z;this.cwd=J;this.connection=H;this.clientCapabilities=W;this.options=X;this.messages=[...X.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode(X.permissionMode),this.updateEgress=new Oz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:(Y)=>Buffer.byteLength(JSON.stringify(Y)),write:async(Y)=>{await H.sessionUpdate(Y)},onFailure:(Y)=>this.handleUpdateEgressFailure(Y)})}async refreshPersistedMessages(){let[z,J]=await Promise.all([j.loadSession(this.id,this.cwd),j.loadSessionModelContext(this.id,this.cwd)]);if(z.length>0)this.messages=z;if(J.length>0)this.contextMessages=J}async loadModelContextOr(z){let J=await j.loadSessionModelContext(this.id,this.cwd);return J.length>0?J:[...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 Kz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){if(U.debug(`[AcpSession ${this.id}] Initializing...`),await j.setSessionPermissionMode(this.id,this.cwd,this.mapModeToPermissionMode()??"default"),E.initializeSession(this.connection,this.id,this.clientCapabilities,this.cwd,async($)=>{await this.sendUpdateAndWait($)}),U.debug(`[AcpSession ${this.id}] ACP service context initialized`),await Lz.resolvePendingWithHandler(this.cwd,this.id,{requestConfirmation:($)=>this.requestPermission($)}))await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let J=this.options.mcpServers?rz(this.options.mcpServers):void 0,H=E.getInstance().getTerminalService(this.id);if(this.runtime=await Uz.create({sessionId:this.id,workspaceRoot:this.cwd,permissionMode:this.mapModeToPermissionMode(),...J?{mcpServers:J}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async($,F)=>{let L=await H.execute($,{cwd:F.cwd,env:F.env,timeout:F.timeoutMs,signal:F.signal,allowLocalFallback:!1,onOutput:(B)=>F.onOutput?.("stdout",B)});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 S.recoverInterrupted(this.cwd,this.id,this.runtime))await this.refreshPersistedMessages();this.agent=await this.createAgent(),await qz(this.cwd),U.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Xz.subscribe(($)=>{if($.sessionId!==this.id||$.projectPath!==this.cwd)return;if($.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":$.properties}}),this.requestPendingResume();return}if($.type==="task.delivery"){if(!$.properties.taskDelivery||typeof $.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":$.properties.taskDelivery,...$.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if($.type.startsWith("team.")){let{teamName:F,messageId:L,content:B}=$.properties,G=$.properties.metadata;if($.type==="team.message.received"&&typeof F==="string"&&typeof L==="string"&&typeof B==="string"&&Gz(G,{messageId:L,teamName:F}))(async()=>{let V=await this.runtime?.enqueueSteering(B,{allowBeforeTurn:!0,messageId:L,origin:"team_message",metadata:G});if(!V?.accepted)return;if(await new Bz(F,s()).markDelivered([L]),V.delivery==="next_turn")this.requestPendingResume()})().catch((V)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,V)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:$.type,...$.properties}}});return}if($.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof $.properties.updatedAt==="string"?$.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":$.properties.taskStatus,...typeof $.properties.taskStatusReason==="string"?{"blade/taskStatusReason":$.properties.taskStatusReason}:{},...$.properties.taskFailure&&typeof $.properties.taskFailure==="object"?{"blade/taskFailure":$.properties.taskFailure}:{},...typeof $.properties.taskStartedAt==="string"?{"blade/taskStartedAt":$.properties.taskStartedAt}:{},...typeof $.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":$.properties.taskCompletedAt}:{},...$.properties.taskDiffStat&&typeof $.properties.taskDiffStat==="object"?{"blade/taskDiffStat":$.properties.taskDiffStat}:{},...typeof $.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":$.properties.taskQueuePosition}:{},...typeof $.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":$.properties.taskQueueDepth}:{},...typeof $.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":$.properties.taskConcurrencyLimit}:{},...typeof $.properties.taskInFlight==="number"?{"blade/taskInFlight":$.properties.taskInFlight}:{}}})});let X=await this.runtime.getGoal(),Y=this.runtime.getPendingSteeringCount()>0,Z=X?.status==="active"||X?.status==="verifying";if(Y||Z)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let $=this.runtime.getTurnRecoveryAssessment();if($.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":$}})}}async replayHistory(){for(let J of this.messages){if(!this.canSendUpdates())return;if(!Zz(J))continue;let H=J.role==="user"?"user_message_chunk":J.role==="assistant"?"agent_message_chunk":void 0;if(!H)continue;for(let W of oz(J)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:H,content:W}))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);U.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendAvailableCommands()},500)}async handleSlashCommand(z,J){try{U.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let H={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(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let $=await this.runtime.rewindSession(Z);return this.messages=[...$.messages],this.contextMessages=await this.loadModelContextOr($.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),$}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Z)=>{if(await this.setReasoningEffort(Z),!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(Z)=>{if(await this.setServiceTier(Z),!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(Z)=>{if(await this.setResponseVerbosity(Z),!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(Z)=>{if(await this.setCommunicationStyle(Z),!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(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:$,onCompleted:(V)=>{if(F)B(V);else L=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.session.id,status:"in_progress",title:`Resuming ${G.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${G.source.id} at depth ${G.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),F=!0,L)B(L);return G}},mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Z)},getPrompt:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,$,F)},complete:async(Z,$,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,$,F)},listTasks:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Z)},getTask:async(Z)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Z)},cancelTask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,$)},getLogs:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,$)},setLoggingLevel:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,$)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:$})}},codeReview:{run:async(Z,$)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=await S.start({sessionId:this.id,projectPath:this.cwd,runtime:this.runtime,request:Z,signal:$,onEvent:(G)=>{if(G.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:G.toolCall.id,status:"in_progress",title:`Review: ${G.toolCall.function.name}`,content:[],kind:this.mapToolKind(G.toolKind)});else if(G.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:G.toolCall.id,status:G.result.success?"completed":"failed",content:[]})}}),L=await F.completion,B=(await S.list(this.cwd,this.id)).find((G)=>G.start.reviewId===F.reviewId);if(!B)throw Error(`Review not found: ${F.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:F.reviewId,status:L.status,findings:L.findings.length,content:zz(B.start,L)}}},signal:J,acp:{sendMessage:(Z)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Z}})},sendToolStart:(Z,$,F)=>{let L=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,B=this.mapToolKind(F);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:L,status:"in_progress",title:`${Z}`,content:[{type:"content",content:{type:"text",text:JSON.stringify($,null,2)}}],kind:B})},sendToolResult:(Z,$)=>{if($.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$.summary}})}}},W=await Pz(z,H),X=W.data?.action;if(X==="start_goal"||X==="resume_goal")this.requestPendingResume();if(X==="rewind_session"&&Array.isArray(W.data?.messages))this.messages=[...W.data.messages],this.contextMessages=await this.loadModelContextOr(W.data.messages);if((W.message==="compact_completed"||W.message==="compact_fallback")&&W.data?.compactedMessages){this.contextMessages=[...W.data.compactedMessages];let Z=await j.loadSession(this.id,this.cwd);if(Z.length>0)this.messages=Z}let Y=W.content||W.message;if(Y)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y}});if(W.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${W.error}`}});return await this.flushUpdates(),{stopReason:W.success?"end_turn":"cancelled"}}catch(H){if(J.aborted||H instanceof Error&&H.name==="AbortError")return{stopReason:"cancelled"};return U.error(`[AcpSession ${this.id}] Slash command error:`,H),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${H instanceof Error?H.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let J=new AbortController,H,W=new Promise((X)=>{H=X});this.pendingSideConversation=J,this.pendingSideConversationCompletion=W;try{return await this.handleSlashCommand(z,J.signal)}catch(X){if(J.signal.aborted||X instanceof Error&&X.name==="AbortError")return{stopReason:"cancelled"};throw X}finally{if(H(),this.pendingSideConversationCompletion===W)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===J){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=Rz(this.cwd,this.runtime?.getAgentResources()),J=["model","permissions","theme","config","exit","ide"],W=z.filter((X)=>!J.includes(X.name)&&(X.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map((X)=>{let Y;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)Y=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;Y=Y?`${Y} | ${Z}`:Z}return{name:X.name,description:X.description,input:Y?{hint:Y}:void 0}});U.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(W.map((X)=>X.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:W}),U.info(`[AcpSession ${this.id}] Sent ${W.length} available commands`)}catch(z){U.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,J={}){if(E.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let H=this.resolvePrompt(z.prompt),W=H.content,X=H.displayText,Y=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((w)=>w.outputSchema)?.outputSchema:void 0),Z;if(Y!==void 0)Z=Wz(Y).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let $=Fz(X);if($){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((w)=>w.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand($.question?`/btw ${$.question}`:"/btw")}if(this.pendingPrompt){if(Z)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test(X.trim()))return this.handleSlashCommand(X,this.pendingPrompt.signal);let w=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!w.accepted)throw Error(w.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(U.debug(`[AcpSession ${this.id}] Queued steering for active turn (${w.queued})`),w.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let F=new AbortController,L=()=>{F.abort(J.abortSignal?.reason)};if(J.abortSignal?.aborted)L();else J.abortSignal?.addEventListener("abort",L,{once:!0});let B=!1,G=!1,V=!1,R,T=new Promise((w)=>{R=w});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Az(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let w={sessionId:this.id,userId:"acp-user",workspaceRoot:this.cwd,messages:[...this.contextMessages],signal:F.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(Q)=>{this.mode=this.mapPermissionModeToMode(Q),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(Q)=>{return this.requestPermission(Q)}}},N=await Yz(this.agent.chatStream(W,w,{pendingInputOnly:J.pendingInputOnly,goalContinuationOnly:J.goalContinuationOnly,outputSchema:Z}),async(Q)=>{switch(Q.kind){case"content_delta":if(Z)break;if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q.delta}});break;case"thinking_delta":if(Q.delta.length>0)G=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:Q.delta}});break;case"tool_start":{V=!0;let K=Q.toolCall,O=K.function.name;if(O===h)break;let q=this.mapToolKind(Q.toolKind),D=`Executing ${O}`;if(O==="Task"&&"function"in K)try{let x=JSON.parse(K.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")D=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:K.id,status:"in_progress",title:D,content:[],kind:q});break}case"tool_progress":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{V=!0;let K=Q.toolCall;if(K.function.name===h)break;let O=Q.result,q=[],D=O.metadata;if(D?.kind==="patch"&&Array.isArray(D.changes))for(let _ of D.changes){if(!_||typeof _!=="object"||!("path"in _)||typeof _.path!=="string")continue;q.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))q.push({type:"diff",path:D.file_path,oldText:D.oldContent,newText:D.newContent??null});else{let _=K.function.name,vz=Vz(Qz(jz(_,O),Jz));q.push({type:"content",content:{type:"text",text:vz}})}if(K.function.name==="Task"&&(D?.verificationVerdict==="pass"||D?.verificationVerdict==="fail"||D?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${D.verificationVerdict.toUpperCase()}`}});let x=O.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:K.id,status:x,content:q});break}case"structured_output":G=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(Q.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
3
|
+
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${Q.contentKind} r${Q.revision} (${Q.serverName}): +${Q.added.length} -${Q.removed.length} ~${Q.updated.length}
|
|
4
|
+
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${Q.revision} (${Q.serverName}): ${Q.uri}
|
|
5
|
+
`}});break;case"mcp_connection_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP connection r${Q.revision} (${Q.serverName}): ${Q.phase} ${Q.attempt}/${Q.maxAttempts}
|
|
6
|
+
`}});break;case"mcp_log":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP log r${Q.revision} (${Q.serverName}) ${Q.level}${Q.logger?` logger=${Q.logger}`:""}: ${Q.message}
|
|
7
|
+
`}});break;case"mcp_instructions_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP instructions r${Q.revision} (${Q.serverName}): ${Q.action}${Q.detailsOmitted?" details-omitted":""}
|
|
8
|
+
`}});break;case"mcp_task_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP task r${Q.revision} ${Q.taskId} (${Q.serverName}/${Q.toolName}): ${Q.status}${Q.hasResult?" result-available":""}
|
|
9
|
+
`}});break;case"project_rules_loaded":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`Project rules loaded: ${Q.files.length}${Q.blockedWrite?" (write retry required)":""}
|
|
10
|
+
`}});break;case"provider_admission":B=Q.phase!=="admitted",this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":Q.phase!=="admitted"?{phase:Q.phase,requestClass:Q.requestClass,resource:Q.resource,scope:Q.scope,...Q.reason!==void 0?{reason:Q.reason}:{},queuePosition:Q.queuePosition,queueDepth:Q.queueDepth,inFlight:Q.inFlight,limit:Q.limit,waitMs:Q.waitMs,maxWaitMs:Q.maxWaitMs,...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}:null}});break;case"provider_circuit":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerCircuit":{phase:Q.phase,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.retryAfterMs!==void 0?{retryAfterMs:Q.retryAfterMs}:{},...Q.nextProbeAt!==void 0?{nextProbeAt:Q.nextProbeAt}:{},openDurationMs:Q.openDurationMs,...Q.sampleCount!==void 0?{sampleCount:Q.sampleCount}:{},...Q.failureCount!==void 0?{failureCount:Q.failureCount}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{}}}});break;case"provider_retry":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerRetry":{phase:Q.phase,attempt:Q.attempt,maxRetries:Q.maxRetries,reason:Q.reason,...Q.statusCode!==void 0?{statusCode:Q.statusCode}:{},...Q.delayMs!==void 0?{delayMs:Q.delayMs}:{},...Q.nextRetryAt!==void 0?{nextRetryAt:Q.nextRetryAt}:{},...Q.mode!==void 0?{mode:Q.mode}:{},...Q.recoveryBudgetMs!==void 0?{recoveryBudgetMs:Q.recoveryBudgetMs}:{},...Q.recoveryElapsedMs!==void 0?{recoveryElapsedMs:Q.recoveryElapsedMs}:{},...Q.recoveryRemainingMs!==void 0?{recoveryRemainingMs:Q.recoveryRemainingMs}:{},...Q.exhaustedBy!==void 0?{exhaustedBy:Q.exhaustedBy}:{}}}});break;case"turn_recovery":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Q.assessment}});break;case"provider_stall":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerStall":{phase:Q.phase,stallCount:Q.stallCount,durationMs:Q.durationMs,warningAfterMs:Q.warningAfterMs,timeoutMs:Q.timeoutMs,outputStarted:Q.outputStarted}}});break;case"action_stationarity":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/actionStationarity":{phase:Q.phase,toolName:Q.toolName,runLength:Q.runLength,nudgeThreshold:Q.nudgeThreshold,haltThreshold:Q.haltThreshold,progressAware:Q.progressAware}}});break;case"task_update":this.sendPlanUpdate(Q.tasks);break;case"steering_applied":break;case"follow_up_started":{let K=0;for(let O of Q.messages){if(!O.recovered||O.persisted)continue;if(J.projectedRecoveredInputIds?.has(O.id))continue;for(let q of xz(O.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(O.id),K++}if(K>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${K} queued instruction${K===1?"":"s"} recovered after restart]
|
|
11
|
+
`}});break}case"goal_updated":if(Q.goal)this.sendUpdate(this.goalSessionUpdate(Q.goal));if(Q.goal&&Q.goal.status!=="active")this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Goal ${Q.goal.status}: ${Q.goal.objective}]
|
|
12
|
+
`}});break;case"goal_continuation_started":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/goalContinuation":{goalId:Q.goal.goalId,continuation:Q.continuation,...Q.prematureStopPattern?{prematureStopPattern:Q.prematureStopPattern}:{},...Q.prematureStopCount!==void 0?{prematureStopCount:Q.prematureStopCount}:{}}}});break;case"compaction":this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/compaction":{phase:Q.phase,...Q.reason?{reason:Q.reason}:{},...Q.strategy?{strategy:Q.strategy}:{},...Q.outcome?{outcome:Q.outcome}:{},...Q.preTokens!==void 0?{preTokens:Q.preTokens}:{},...Q.preTokenSource?{preTokenSource:Q.preTokenSource}:{},...Q.estimatedPendingTokens!==void 0?{estimatedPendingTokens:Q.estimatedPendingTokens}:{},...Q.postTokens!==void 0?{postTokens:Q.postTokens}:{},...Q.sampleAttempts!==void 0?{sampleAttempts:Q.sampleAttempts}:{},...Q.inputReductions!==void 0?{inputReductions:Q.inputReductions}:{},...Q.messagesOmitted!==void 0?{messagesOmitted:Q.messagesOmitted}:{},...Q.filesOmitted!==void 0?{filesOmitted:Q.filesOmitted}:{},...Q.imagesOmitted!==void 0?{imagesOmitted:Q.imagesOmitted}:{},...Q.fallbackTargetTokens!==void 0?{fallbackTargetTokens:Q.fallbackTargetTokens}:{},...Q.fallbackMessagesOmitted!==void 0?{fallbackMessagesOmitted:Q.fallbackMessagesOmitted}:{},...Q.fallbackMessagesTruncated!==void 0?{fallbackMessagesTruncated:Q.fallbackMessagesTruncated}:{},...Q.failureReason?{failureReason:Q.failureReason}:{}}}});break;default:break}if(!await this.flushUpdates())F.abort("acp-egress-failed")});if(!await this.flushUpdates())F.abort("acp-egress-failed");this.contextMessages=[...w.messages];let d=await j.loadSession(this.id,this.cwd);if(this.messages=d.length>0?d:[...w.messages],!N.success){let Q=N.error?.type??"unknown",K=N.error?.details??N.error?.message??"Agent execution failed",O=sz(K)??c(K);throw Tz.internalError({failureType:Q,modelId:this.runtime.getCurrentModelId(),taskFailure:O,outputStarted:G,toolExecutionStarted:V,...Number.isInteger(N.metadata?.toolCallsCount)?{toolCallsCount:N.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...N.metadata?.structuredOutput?{structuredOutput:N.metadata.structuredOutput,outputSchemaDigest:N.metadata.structuredOutputSchemaDigest}:{},...N.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:N.metadata.goalVerificationVerdict,...N.metadata.goalVerifierSessionId?{verifierSessionId:N.metadata.goalVerifierSessionId}:{},...N.metadata.goalVerificationEvidenceSha256?{evidenceSha256:N.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(l).length>0?{_meta:l}:{}}}catch(w){if(F.signal.aborted||w instanceof Error&&w.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,w),w}finally{if(J.abortSignal?.removeEventListener("abort",L),B&&!this.destroyed)this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/providerAdmission":null}}),await this.flushUpdates();if(R(),this.pendingPromptCompletion===T)this.pendingPromptCompletion=null;if(this.pendingPrompt===F){if(this.pendingPrompt=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async handleUserShellCommand(z){if(!this.runtime)throw Error("Session runtime is unavailable");if(this.pendingUserShell)throw Error("A user shell command is already running");let J=z.trimStart().slice(1).trim();if(!J)throw Error("User shell command cannot be empty");let H=new AbortController,W,X=new Promise(($)=>{W=$});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let Y,Z="";try{let $=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if(Y=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"){Z+=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 B=p(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:Z?nz(L.record):B}}]})}}),F={role:"user",content:$.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify($.record))}};if(this.messages.push(F),this.contextMessages.push(F),$.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:$.record.status==="aborted"?"cancelled":"end_turn"}}catch($){if(Y)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:Y,status:"failed",content:[{type:"content",content:{type:"text",text:$ instanceof Error?$.message:String($)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw $}finally{if(W(),this.pendingUserShellCompletion===X)this.pendingUserShellCompletion=null;if(this.pendingUserShell===H){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 J=this.pendingResumeGeneration,H=()=>{if(J!==this.pendingResumeGeneration)return;this.pendingResumeScheduled=!1,this.pendingResumeTimer=null,this.resumePendingIfIdle()};if(z>0)this.pendingResumeTimer=setTimeout(H,z),this.pendingResumeTimer.unref?.();else queueMicrotask(H)}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,J){return{sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/pendingResume":{phase:z,kind:J.kind,attempt:J.attempt,maxAttempts:i,...J.delayMs!==void 0?{delayMs:J.delayMs,nextRetryAt:Date.now()+J.delayMs}:{},...J.taskFailure?{failure:{code:J.taskFailure.code,retryable:J.taskFailure.retryable,...J.taskFailure.resource?{resource:J.taskFailure.resource}:{}}}:{}}}}}async resumePendingIfIdle(){if(!this.pendingResumeRequested)return;if(!this.canSendUpdates()){this.clearPendingResumeRequest();return}if(this.pendingResumeInFlight||this.pendingPrompt||this.pendingUserShell||this.pendingSideConversation||!this.runtime||!this.agent)return;this.pendingResumeInFlight=!0,this.pendingResumeRequested=!1;let z=this.pendingResumeGeneration,J=this.pendingResumeAttempt+1;if(this.pendingResumeAttempt=J,this.pendingResumeRecoveryStartedAt===0)this.pendingResumeRecoveryStartedAt=Date.now();let H="preflight",W=!1,X,Y=null;try{let Z=this.runtime.getPendingSteeringCount()>0,$=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=$?.status==="active"||$?.status==="verifying",L=this.runtime.getTurnRecoveryAssessment();if(L.state!=="none"&&(L.state==="requires_attention"||!Z&&!F))this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":L}});if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}if(L.state==="requires_attention"){this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let B=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(B<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let G=new AbortController;Y=setTimeout(()=>{G.abort("acp-pending-resume-budget-exhausted")},B),Y.unref?.();let V=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:G.signal});if(z!==this.pendingResumeGeneration)return;if(G.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(V.stopReason!=="end_turn"){this.clearPendingResumeRequest();return}if(J>1)this.sendUpdate(this.pendingResumeSessionUpdate("recovered",{attempt:J,kind:H}));this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0}catch(Z){if(z!==this.pendingResumeGeneration)return;let $=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&$?.taskFailure.retryable===!0&&!$.toolExecutionStarted&&$.toolCallsCount===0&&!$.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,V=J<i,R=G+B<=r;if(L&&V&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:$.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!V||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:$?.taskFailure})),U.error(`[AcpSession ${this.id}] Failed to resume pending input (attempt=${J}, retryable=${L}, phase=${T})`,Z),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest()}}finally{if(Y!==null)clearTimeout(Y);if(this.pendingResumeInFlight=!1,this.pendingResumeRequested)this.ensurePendingResumeScheduled(X)}}cancel(){U.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)U.warn(`[AcpSession ${this.id}] No pending prompt to cancel`)}async setMode(z){let H=["default","auto-edit","yolo","plan"].includes(z)?z:"default",W=this.mapModeIdToPermissionMode(H);await j.setSessionPermissionMode(this.id,this.cwd,W),this.mode=H,U.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(U.info(`[AcpSession ${this.id}] Model set to: ${z}`),this.pendingPrompt)throw Error("Cannot switch models while a prompt is active");if(!this.agent)throw Error("Session not initialized");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCurrentModelId();await this.agent.switchModel(z);try{try{await j.updateSessionMetadata(this.id,this.cwd,{selectedModelId:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:z})}}catch(H){if(J&&J!==z)await this.agent.switchModel(J).catch((W)=>{U.error(`[AcpSession ${this.id}] Failed to roll back a non-durable model switch:`,W)});throw H}}getCurrentModelId(){return this.runtime?.getCurrentModelId()}async setReasoningEffort(z){if(this.pendingPrompt)throw Error("Cannot switch reasoning effort while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getReasoningConfiguration();try{this.runtime.resolveReasoningConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid reasoning effort")}if(J.selection===z)return;await this.runtime.refresh({reasoningEffort:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{reasoningEffort:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),reasoningEffort:z})}}catch(H){throw await this.runtime.refresh({reasoningEffort:J.selection}),H}}async setServiceTier(z){if(this.pendingPrompt)throw Error("Cannot switch service tier while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getServiceTierConfiguration();try{this.runtime.resolveServiceTierConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid service tier")}if(J.selection===z)return;await this.runtime.refresh({serviceTier:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{serviceTier:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),serviceTier:z})}}catch(H){throw await this.runtime.refresh({serviceTier:J.selection}),H}}async setResponseVerbosity(z){if(this.pendingPrompt)throw Error("Cannot switch response verbosity while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getResponseVerbosityConfiguration();try{this.runtime.resolveResponseVerbosityConfiguration(z)}catch(H){throw Error(H instanceof Error?H.message:"Invalid response verbosity")}if(J.selection===z)return;await this.runtime.refresh({responseVerbosity:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{responseVerbosity:z})}catch(H){if(!(H instanceof P)&&H.code!=="ENOENT")throw H;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),responseVerbosity:z})}}catch(H){throw await this.runtime.refresh({responseVerbosity:J.selection}),H}}async setCommunicationStyle(z){if(this.pendingPrompt)throw Error("Cannot switch communication style while a prompt is active");if(!this.runtime)throw Error("Session runtime is unavailable");let J=this.runtime.getCommunicationStyleConfiguration(),H=this.runtime.resolveCommunicationStyleConfiguration(z);if(H.source!=="built-in"&&!H.contentSha256)throw Error("Custom communication style has no provenance");if(J.selection===z)return;await this.runtime.refresh({communicationStyle:z});try{try{await j.updateSessionMetadata(this.id,this.cwd,{communicationStyle:z,communicationStyleDigest:H.source==="built-in"?null:H.contentSha256})}catch(W){if(!(W instanceof P)&&W.code!=="ENOENT")throw W;await j.createSessionMetadata(this.id,this.cwd,{taskStatus:"completed",selectedModelId:this.runtime.getCurrentModelId(),communicationStyle:z,...H.source!=="built-in"&&H.contentSha256?{communicationStyleDigest:H.contentSha256}:{}})}}catch(W){throw await this.runtime.refresh({communicationStyle:J.selection}),W}}getModelConfiguration(){if(!this.runtime)return;let z=this.runtime.getConfig();return{currentModelId:this.runtime.getCurrentModelId()??z.currentModelId,models:z.models.map((J)=>structuredClone(J)),modelProviders:structuredClone(z.modelProviders),reasoning:this.runtime.getReasoningConfiguration(),serviceTier:this.runtime.getServiceTierConfiguration(),responseVerbosity:this.runtime.getResponseVerbosityConfiguration(),communicationStyle:this.runtime.getCommunicationStyleConfiguration()}}getMode(){return this.mode}isIdleForResidency(){return!this.destroyed&&this.pendingPrompt===null&&this.pendingUserShell===null&&this.pendingSideConversation===null&&(this.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 Nz("closed","ACP Session was destroyed")),this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer),this.availableCommandsTimer=null;this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=void 0;let J=this.agent,H=this.runtime,W=this.pendingPromptCompletion,X=this.pendingUserShellCompletion,Y=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,$=async(F)=>{try{await F()}catch(L){Z??=L}};if(await $(()=>this.cancel()),W)await $(()=>W);if(X)await $(()=>X);if(Y)await $(()=>Y);if(z&&W&&H)await $(()=>H.discardPendingInput());if(J)await $(()=>J.destroy());if(H)await $(()=>H.dispose());if(await $(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,Y=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
|
|
13
|
+
`}),Y+=1;if(H.push(L),L.type==="text")Y+=L.text.length};for(let L of z)if(L.type==="text")J.push(L.text),Z({type:"text",text:L.text});else if(L.type==="image"){let B=`data:${L.mimeType};base64,${L.data}`;W+=1,X+=B.length,J.push(`[Image: ${L.mimeType}]`),Z({type:"image_url",image_url:{url:B}})}else if(L.type==="resource"){let B=L.resource;if("text"in B){let G=`<file path="${B.uri}">
|
|
14
|
+
${B.text}
|
|
15
|
+
</file>`;J.push(G),Z({type:"text",text:G})}}else if(L.type==="resource_link"){let B=`[Resource: ${L.uri}]`;J.push(B),Z({type:"text",text:B})}if(W>C)throw Error(`ACP prompt contains more than ${C} images`);if(X>t)throw Error("ACP prompt images exceed the 5 MiB limit");if(Y>f)throw Error(`ACP prompt text exceeds ${f} characters`);if(Buffer.byteLength(J.join(`
|
|
16
|
+
`),"utf8")>u)throw Error(`ACP prompt text exceeds ${u} bytes`);let F=J.join(`
|
|
17
|
+
`);return{content:W>0?H:F,displayText:F}}canSendUpdates(){return!this.destroyed&&!this.connection.signal.aborted&&!this.updateEgress.stats().closed}async sendUpdateAndWait(z){if(!this.canSendUpdates())return!1;let J=this.updateEgress.offer({sessionId:this.id,update:z});if(!J.accepted)return!1;try{return await J.completion,this.canSendUpdates()}catch{return!1}}goalSessionUpdate(z){return{sessionUpdate:"session_info_update",updatedAt:z.updatedAt,_meta:{"blade/goal":{goalId:z.goalId,status:z.status,verificationAttempt:z.completionVerification?.attempt,verificationStatus:z.completionVerification?.status,verifierSessionId:z.completionVerification?.verifierSessionId,verificationEvidenceSha256:z.completionVerification?.evidenceSha256,verificationSummary:z.completionVerification?.summary,verificationStallCount:z.verificationStall?.consecutiveCount}}}}sendUpdate(z){if(!this.canSendUpdates())return;this.updateEgress.offer({sessionId:this.id,update:z})}async flushUpdates(){if(!this.canSendUpdates())return!1;try{return await this.updateEgress.flush(),this.canSendUpdates()}catch{return!1}}handleUpdateEgressFailure(z){if(this.destroyed)return;U.warn(`[AcpSession ${this.id}] Update egress closed: kind=${z.kind}`),this.clearPendingResumeRequest(),this.pendingPrompt?.abort("acp-egress-failed"),this.pendingUserShell?.abort("acp-egress-failed"),this.pendingSideConversation?.abort("acp-egress-failed")}sendPlanUpdate(z){let J=z.map((H)=>({content:H.subject,priority:H.priority,status:H.status}));U.debug(`[AcpSession ${this.id}] Sending plan update with ${J.length} entries`),this.sendUpdate({sessionUpdate:"plan",entries:J})}async requestPermission(z){let J=this.pendingPrompt?.signal;if(z.type==="askUserQuestion")return this.requestUserQuestions(z,J);if(z.type==="mcpElicitation")return this.requestMcpElicitation(z,J);let H=z.kind?.toLowerCase()||"execute";if(z.type!=="mcpSampling"&&this.shouldAutoApprove(H))return U.debug(`[AcpSession ${this.id}] Auto-approving ${H} in mode: ${this.mode}`),{approved:!0};if(this.mode==="plan"&&(H==="write"||H==="execute"))return U.debug(`[AcpSession ${this.id}] Rejecting ${H} in plan mode`),{approved:!1,reason:"Write and execute operations are not allowed in Plan mode"};try{let W=I(),X=[];if(z.message)X.push({type:"content",content:{type:"text",text:z.message}});if(z.details)X.push({type:"content",content:{type:"text",text:z.details}});if(z.risks&&z.risks.length>0)X.push({type:"content",content:{type:"text",text:`Risks:
|
|
18
|
+
- ${z.risks.join(`
|
|
19
|
+
- `)}`}});let Y=this.mapToolKind(H),Z={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:W,status:"pending",title:z.title||"Permission Required",content:X,kind:Y}},$=await this.waitForClientInteraction(this.connection.requestPermission(Z),J);if(!$)return{approved:!1,reason:g};let F=$.outcome;if(F.outcome==="cancelled")return{approved:!1,reason:"User cancelled the permission request"};let L=F.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 B=L==="allow_once";return{approved:B,scope:"once",reason:B?void 0:"User denied the operation"}}catch(W){return U.warn(`[AcpSession ${this.id}] Permission request failed:`,W),{approved:!1,reason:"Permission request failed"}}}async requestUserQuestions(z,J){let H=z.questions??[];if(H.length===0)return{approved:!1,reason:"No structured questions were provided"};if(H.some((X)=>X.multiSelect))return{approved:!1,reason:"ACP does not support multi-select question responses"};let W={};try{for(let[X,Y]of H.entries()){let Z=Y.options.map((B,G)=>`answer:${X}:${G}`),$=`answer:${X}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...Y.options.map((B,G)=>({optionId:Z[G],name:B.label,kind:"allow_once"})),{optionId:$,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:Y.header,kind:"think",content:[{type:"content",content:{type:"text",text:[Y.question,...Y.options.map((B)=>`${B.label}: ${B.description}`)].join(`
|
|
20
|
+
`)}}]}}),J);if(!F)return{approved:!1,reason:g};if(F.outcome.outcome!=="selected")return{approved:!1,reason:"User cancelled the question prompt"};let L=Z.indexOf(F.outcome.optionId);if(L<0)return{approved:!1,reason:"User cancelled the question prompt"};W[Y.header]=Y.options[L].label}return{approved:!0,answers:W}}catch(X){return U.warn(`[AcpSession ${this.id}] Question request failed:`,X),{approved:!1,reason:"Question request failed"}}}async requestMcpElicitation(z,J){let H=z.mcpElicitation;if(!H)return{approved:!1,reason:"MCP elicitation details are missing",elicitation:{action:"cancel"}};try{if(H.mode==="url"){let X=await this.requestElicitationChoice("MCP external authorization",[H.message,`Server: ${H.serverName}`,`Domain: ${H.domain??"unknown"}`,`URL: ${H.url??""}`,"Open this URL yourself only if you trust the MCP server."].join(`
|
|
21
|
+
`),[{id:"accept",label:"I will open this URL"},{id:"decline",label:"Decline"}],J);if(X==="accept")return{approved:!0,elicitation:{action:"accept"}};return{approved:!1,reason:X==="decline"?"User declined URL":"User cancelled",elicitation:{action:X==="decline"?"decline":"cancel"}}}let W=Object.create(null);for(let X of H.fields??[]){let Y=await this.collectAcpElicitationField(X,J);if(Y.cancelled)return{approved:!1,reason:Y.reason,elicitation:{action:"cancel"}};if(Y.value!==void 0)W[X.name]=Y.value}return{approved:!0,elicitation:{action:"accept",content:W}}}catch(W){return U.warn(`[AcpSession ${this.id}] MCP elicitation failed:`,W),{approved:!1,reason:"MCP elicitation failed",elicitation:{action:"cancel"}}}}async collectAcpElicitationField(z,J){if(z.type==="select"||z.type==="boolean"){let H=z.type==="boolean"?[{id:"true",label:"Yes",value:!0},{id:"false",label:"No",value:!1}]:(z.options??[]).map((Y,Z)=>({id:`option:${Z}`,label:Y.label,value:Y.value})),W=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
+
`),[...H.map((Y)=>({id:Y.id,label:Y.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(W==="skip")return{cancelled:!1};let X=H.find((Y)=>Y.id===W);if(!X)return{cancelled:!0,reason:"User cancelled MCP elicitation"};return{cancelled:!1,value:X.value}}if(z.defaultValue!==void 0){let H=await this.requestElicitationChoice(z.title,[z.description,`ACP cannot collect ${z.type} input. Use the server default: ${String(z.defaultValue)}?`].filter(Boolean).join(`
|
|
23
|
+
`),[{id:"default",label:"Use default"},...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(H==="default")return{cancelled:!1,value:z.defaultValue};if(H==="skip")return{cancelled:!1};return{cancelled:!0,reason:"User cancelled MCP elicitation"}}if(!z.required)return{cancelled:!1};return{cancelled:!0,reason:`ACP cannot collect required ${z.type} field "${z.name}"`}}async requestElicitationChoice(z,J,H,W){let X=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...H.map((Y)=>({optionId:Y.id,name:Y.label,kind:"allow_once"})),{optionId:"cancel",name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:z,kind:"think",content:[{type:"content",content:{type:"text",text:J}}]}}),W);return X?.outcome.outcome==="selected"?X.outcome.optionId:void 0}async waitForClientInteraction(z,J){if(!J)return z;if(J.aborted)return;return new Promise((H,W)=>{let X=!1,Y=($)=>{if(X)return;X=!0,J.removeEventListener("abort",Z),$()},Z=()=>Y(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then(($)=>Y(()=>H($)),($)=>Y(()=>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 A=M("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=kz();this.runtimeResidencyValue=new pz({maxResident:z?.maxResidentSessionRuntimes??yz,idleMs:z?.sessionRuntimeIdleMs??Mz})}return this.runtimeResidencyValue}async reserveSessionRuntime(z){try{return await this.runtimeResidency.reserve(z,{surface:"acp",allowEviction:!1})}catch(J){if(J instanceof cz)throw HH.internalError({resource:J.resource,limit:J.limit,retryable:J.retryable},J.message);throw J}}async initialize(z){return A.info("[BladeAgent] Initializing ACP connection"),A.debug(`[BladeAgent] Client capabilities: ${JSON.stringify(z.clientCapabilities)}`),this.clientCapabilities=z.clientCapabilities,await Iz(),{protocolVersion:zH,agentCapabilities:{loadSession:!0,sessionCapabilities:{list:{},fork:{},close:{}},promptCapabilities:{image:!0,audio:!1,embeddedContext:!0},mcpCapabilities:{http:!0,sse:!0}}}}async authenticate(z){return}async newSession(z){this.assertNotDestroyed();let J=m("acp"),H=await this.reserveSessionRuntime(J),W=z.cwd||bz(),X=z._meta?.["blade/taskIsolation"],Y=X==="local"||X==="worktree"?X:void 0,Z=z._meta?.["blade/taskPrompt"],$;try{let F=Y?await gz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:Y}):void 0,L=F?.metadata.projectPath??W;return A.info(`[BladeAgent] Creating new session: ${J}`),A.debug(`[BladeAgent] Session cwd: ${L}`),$=new b(J,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...F?.taskWorktree?{taskWorktree:F.taskWorktree}:{},...F?.metadata.taskIsolation?{taskIsolation:F.metadata.taskIsolation}:{}}),await $.initialize(),this.assertNotDestroyed(),this.commitSession(J,$,H),A.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),$.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,F?.metadata,$.getModelConfiguration())}catch(F){throw H.cancel(),await $?.destroy().catch(()=>{return}),F}}async listSessions(z){if(z.cwd!=null&&!Ez.isAbsolute(z.cwd))throw Error("ACP session list cwd must be absolute");let J=await j.listSessionPage({cwd:z.cwd??void 0,cursor:z.cursor??void 0,limit:50,includeSubagents:!1});return{sessions:J.sessions.map((H)=>({sessionId:H.sessionId,cwd:H.projectPath,title:H.title??null,updatedAt:H.lastMessageTime,_meta:{"blade/taskStatus":H.taskStatus,...H.taskStatusReason?{"blade/taskStatusReason":H.taskStatusReason}:{},...H.taskFailure?{"blade/taskFailure":H.taskFailure}:{},...H.taskStartedAt?{"blade/taskStartedAt":H.taskStartedAt}:{},...H.taskCompletedAt?{"blade/taskCompletedAt":H.taskCompletedAt}:{},...H.taskModelId?{"blade/taskModelId":H.taskModelId}:{},...H.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...H.taskRetriedFrom?{"blade/taskRetriedFrom":H.taskRetriedFrom}:{},...H.taskDelivery?{"blade/taskDelivery":H.taskDelivery}:{},...H.taskIsolation?{"blade/taskIsolation":H.taskIsolation}:{},...H.taskSourceProjectPath?{"blade/taskSourceProjectPath":H.taskSourceProjectPath}:{},...H.taskWorktreeBranch?{"blade/taskWorktreeBranch":H.taskWorktreeBranch}:{},...H.taskBaseCommit?{"blade/taskBaseCommit":H.taskBaseCommit}:{},...H.taskDiffStat?{"blade/taskDiffStat":H.taskDiffStat}:{},...H.taskQueuePosition?{"blade/taskQueuePosition":H.taskQueuePosition}:{},...H.taskQueueDepth!==void 0?{"blade/taskQueueDepth":H.taskQueueDepth}:{},...H.taskConcurrencyLimit!==void 0?{"blade/taskConcurrencyLimit":H.taskConcurrencyLimit}:{}}})),nextCursor:J.nextCursor}}async unstable_forkSession(z){if(this.assertNotDestroyed(),!Ez.isAbsolute(z.cwd))throw Error("ACP session fork cwd must be absolute");let J=m("fork"),H=await this.reserveSessionRuntime(J),W;try{let X=await j.forkSession(z.sessionId,{sourceProjectPath:z.cwd,targetProjectPath:z.cwd,newSessionId:J});return this.assertNotDestroyed(),W=new b(X.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:X.messages,permissionMode:X.metadata.permissionMode,mcpServers:z.mcpServers}),await W.initialize(),this.assertNotDestroyed(),this.commitSession(X.sessionId,W,H),W.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(X.sessionId,X.metadata,W.getModelConfiguration())}catch(X){throw H.cancel(),await W?.destroy().catch(()=>{return}),X}}async loadSession(z){this.assertNotDestroyed(),A.info(`[BladeAgent] Loading session: ${z.sessionId}`);let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.replaceSession(z)),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{return await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async replaceSession(z){this.assertNotDestroyed(),await j.assertSessionWritable(z.sessionId,z.cwd),await this.closeResidentSession(z.sessionId);let J=await this.reserveSessionRuntime(z.sessionId),H;try{let[W,X]=await Promise.all([j.loadSession(z.sessionId,z.cwd),j.findSessionMetadata(z.sessionId,z.cwd)]);if(!X)throw Error(`Session not found: ${z.sessionId}`);return H=new b(z.sessionId,z.cwd,this.connection,this.clientCapabilities,{initialMessages:W,permissionMode:X.permissionMode,mcpServers:z.mcpServers}),await H.initialize(),await H.replayHistory(),this.assertNotDestroyed(),this.commitSession(z.sessionId,H,J),H.sendAvailableCommandsDelayed(),this.buildSessionSetup(H.getModelConfiguration(),H.getMode())}catch(W){throw J.cancel(),await H?.destroy().catch(()=>{return}),W}}commitSession(z,J,H){let W=H.commit({key:z,surface:"acp",value:J,canEvict:()=>J.isIdleForResidency(),dispose:async()=>{if(this.sessions.get(z)===J)this.sessions.delete(z);await J.destroy()}});this.sessions.set(z,J),W.release()}async closeResidentSession(z,J={}){let H=this.sessions.get(z);if(!H)return;let W=this.runtimeResidency.owns(z,H),X;try{await H.destroy(J)}catch(Z){X=Z}let Y=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!Y&&X===void 0)throw Error(`ACP Session is still active: ${z}`);if(X!==void 0)throw X}buildChildSessionResponse(z,J,H){return{sessionId:z,...this.buildSessionSetup(H,J?.permissionMode==="autoEdit"?"auto-edit":J?.permissionMode),...J?{_meta:{"blade/taskIsolation":J.taskIsolation,"blade/taskSourceProjectPath":J.taskSourceProjectPath,"blade/taskProjectPath":J.projectPath,...J.taskModelId?{"blade/taskModelId":J.taskModelId}:{},...J.taskRetryAvailable?{"blade/taskRetryAvailable":!0}:{},...J.taskRetriedFrom?{"blade/taskRetriedFrom":J.taskRetriedFrom}:{},...J.taskDelivery?{"blade/taskDelivery":J.taskDelivery}:{},...J.taskWorktreeBranch?{"blade/taskWorktreeBranch":J.taskWorktreeBranch}:{},...J.taskBaseCommit?{"blade/taskBaseCommit":J.taskBaseCommit}:{}}}:{}}}assertNotDestroyed(){if(this.destroyed)throw Error("BladeAgent is destroyed")}getRuntimeResidencyStats(){return this.runtimeResidency.getStats()}buildSessionSetup(z,J="default"){let H=z?.models??[],W=(z?.currentModelId&&H.some((Z)=>Z.id===z.currentModelId)?z.currentModelId:void 0)??H[0]?.id,X=[{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"}],Y=[];if(H.length>0)Y.push({type:"select",id:"model",name:"Model",description:"Active language model",category:"model",currentValue:W,options:H.map((Z)=>({value:Z.id,name:Z.displayName??Z.model,description:`${z?.modelProviders[Z.provider]?.name??Z.provider} · ${Z.model}`}))});if(z?.reasoning)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="off"?"Disable model reasoning":`Use ${Z} reasoning effort`}))]});if(z?.serviceTier)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:Z==="fast"?"Use the provider priority tier":Z==="flex"?"Use the lower-cost flexible tier":"Use the standard provider tier"}))]});if(z?.responseVerbosity)Y.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((Z)=>({value:Z,name:Z[0].toUpperCase()+Z.slice(1),description:`Use ${Z} response verbosity`}))]});if(z?.communicationStyle)Y.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((Z)=>({value:Z.id,name:Z.name,description:`${Z.description} · ${Z.source}`}))});return{modes:{availableModes:X,currentModeId:J},configOptions:Y.length>0?Y:void 0}}async closeSession(z){this.assertNotDestroyed();let H=(this.sessionLoadQueues.get(z.sessionId)??Promise.resolve()).then(()=>this.closeResidentSession(z.sessionId,{discardPendingInput:!0})),W=H.then(()=>{return},()=>{return});this.sessionLoadQueues.set(z.sessionId,W);try{await H}finally{if(this.sessionLoadQueues.get(z.sessionId)===W)this.sessionLoadQueues.delete(z.sessionId)}}async prompt(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{return await J.value.prompt(z)}finally{J.release()}}async cancel(z){A.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){A.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else A.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){A.info(`[BladeAgent] Setting session mode: ${z.modeId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J)try{await J.value.setMode(z.modeId)}finally{J.release()}return{}}async setSessionConfigOption(z){let J=this.runtimeResidency.acquire(z.sessionId);if(!J)throw Error(`Session not found: ${z.sessionId}`);try{let H=J.value;if(z.configId==="model"&&"value"in z&&typeof z.value==="string")A.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Cz(z.value))A.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Sz(z.value))A.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&hz(z.value))A.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&fz(z.value))A.info(`[BladeAgent] Setting communication style: ${z.value}`),await H.setCommunicationStyle(z.value);else throw Error(`Invalid session config option: ${z.configId}`);return{configOptions:this.buildSessionSetup(H.getModelConfiguration(),H.getMode()).configOptions??[]}}finally{J.release()}}destroy(){if(this.destroyPromise)return this.destroyPromise;return this.destroyPromise=this.destroyOwnedResources(),this.destroyPromise}async destroyOwnedResources(){this.destroyed=!0,await Promise.all([...this.sessionLoadQueues.values()]),this.sessionLoadQueues.clear();let z;for(let J of[...this.sessions.keys()])try{await this.closeResidentSession(J)}catch(H){z??=H}try{await this.runtimeResidency.disposeAll()}catch(J){z??=J}this.sessions.clear();try{await uz.getInstance().disconnectAll()}catch(J){z??=J}if(z!==void 0)throw z}}async function eH(){let z=QH.toWeb(process.stdout),J=JH.toWeb(process.stdin),H=k.ndJsonStream(z,J),W,X=new k.AgentSideConnection((Z)=>{return W=new v(Z),W},H),Y=mz(async()=>{await W?.destroy()});try{await X.closed}finally{Y(),await W?.destroy()}}export{eH as runAcpIntegration};
|
|
@@ -25,7 +25,7 @@ import{sg as YO}from"./chunk-c6tq09mt.js";import{Bh as S,Eh as y,zh as qO}from".
|
|
|
25
25
|
`):void 0}}async executeNotificationHooks(O,q,Q){let Z="message"in q?q.message:"";if(O.length===0)return{suppress:!1,message:Z};let Y=[],$=!1,X=Z;for(let W of O)try{let J=await this.executeHook(W,q,Q);if(!J.success){if(J.warning)Y.push(J.warning);continue}if(J.output?.suppressOutput){$=!0;break}if(J.stdout&&J.stdout.trim())X=J.stdout.trim()}catch(J){let G=J instanceof Error?J.message:String(J);Y.push(`Hook failed: ${G}`)}return{suppress:$,message:X,warning:Y.length>0?Y.join(`
|
|
26
26
|
`):void 0}}async executeCompactionHooks(O,q,Q){if(O.length===0)return{blockCompaction:!1};let Z=[];for(let Y of O)try{let $=await this.executeHook(Y,q,Q);if(!$.success){if($.warning)Z.push($.warning);continue}let X=$.output?.hookSpecificOutput;if(X&&"blockCompaction"in X&&X.blockCompaction)return{blockCompaction:!0,blockReason:X.blockReason,warning:Z.length>0?Z.join(`
|
|
27
27
|
`):void 0}}catch($){let X=$ instanceof Error?$.message:String($);Z.push(`Hook failed: ${X}`)}return{blockCompaction:!1,warning:Z.length>0?Z.join(`
|
|
28
|
-
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-
|
|
28
|
+
`):void 0}}async executeHook(O,q,Q){if(O.type!=="function"){let Y=await A.getInstance().getStatus(Q.projectDir,Q.config);if(Y.state!=="trusted"){let $=`${Y.trustRoot}:${Y.currentDigest}:${Y.state}`;if(!this.trustWarnings.has($)){if(this.trustWarnings.size>=512)this.trustWarnings.clear();this.trustWarnings.add($),$O.warn(`[HookTrust] Skipping configured hooks for ${Y.trustRoot}: ${Y.state}`)}return{success:!0,hook:O,warning:`Hook skipped: project hook trust is ${Y.state}`}}}let Z=this.withHookEnvironment(Q,O);if(O.type==="command")return this.executeCommandHook(O,q,Z);if(O.type==="prompt")return this.executePromptHook(O,q,Z);if(O.type==="function")return this.executeFunctionHook(O,q,Z);if(O.type==="http")return this.executeHttpHook(O,q,Z);throw Error(`Hook type ${O.type} not supported`)}async executeCommandHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.processExecutor.execute(O.command,q,Q,Z);return this.outputParser.parse(Y,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executePromptHook(O,q,Q){let Z=(O.timeout??Q.config.defaultTimeout??60)*1000;try{let Y=await this.getOrCreateChatService(O.model,Q),$="hook_event_name"in q?String(q.hook_event_name):"Unknown",X=this.buildPromptHookSystemMessage(O,$),W=JSON.stringify(q,null,2),J=new AbortController,G=setTimeout(()=>J.abort(),Z),L;try{L=(await Y.chat([{role:"system",content:X},{role:"user",content:W}],void 0,J.signal,{providerAdmission:{sessionId:Q.sessionId,ownerId:Q.sessionId,requestClass:"background"}})).content}catch(z){if(J.signal.aborted||z instanceof Error&&z.name==="AbortError")return this.outputParser.parse({stdout:"",stderr:"",exitCode:0,timedOut:!0},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});throw z}finally{clearTimeout(G)}let F=this.extractJsonFromLLMResponse(L);return this.outputParser.parse({stdout:F,stderr:"",exitCode:0,timedOut:!1},O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){return $O.warn(`[PromptHook] 执行失败: ${Y instanceof Error?Y.message:String(Y)}`),{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}async executeFunctionHook(O,q,Q){let Z=(O.timeout??10)*1000;try{let Y=await this.runFunctionWithTimeout(O.handler,q,Q,Z);if(Y===void 0||Y===null)return{success:!0,hook:O};let $={stdout:JSON.stringify(Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(Y){if(Y.isTimeout){let $={stdout:"",stderr:`Function hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};return this.outputParser.parse($,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}return{success:!1,blocking:!1,error:Y instanceof Error?Y.message:String(Y),hook:O}}}runFunctionWithTimeout(O,q,Q,Z){return new Promise((Y,$)=>{let X=!1,W=setTimeout(()=>{if(X)return;X=!0;let G=Object.assign(Error(`Function hook timed out after ${Z}ms`),{isTimeout:!0});$(G)},Z),J=()=>{if(X)return;X=!0,clearTimeout(W),$(Error("Function hook aborted"))};Q.abortSignal?.addEventListener("abort",J,{once:!0}),Promise.resolve().then(()=>O(q,Q)).then((G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),Y(G)},(G)=>{if(X)return;X=!0,clearTimeout(W),Q.abortSignal?.removeEventListener("abort",J),$(G)})})}async executeHttpHook(O,q,Q){let Z=(O.timeout??10)*1000,Y=O.maxResponseBytes??262144,$=Math.max(1,(O.retries??0)+1);try{e(O.url,Q.config.httpPolicy)}catch(G){return{success:!1,blocking:!0,error:G instanceof Error?G.message:String(G),hook:O}}let X={"Content-Type":"application/json",...OO(O.headers)},W=JSON.stringify(q),J;for(let G=0;G<$;G++){if(G>0){let V=Math.min(2**G*200,5000);await new Promise((B)=>setTimeout(B,V))}let L=new AbortController,F=setTimeout(()=>L.abort(),Z),z=()=>L.abort();Q.abortSignal?.addEventListener("abort",z,{once:!0});try{let V=await fetch(O.url,{method:"POST",headers:X,body:W,redirect:"manual",signal:L.signal});if(V.status>=300&&V.status<400){J=Error(`HTTP hook received redirect (${V.status}); redirects are disabled`);continue}if(!V.ok){if(J=Error(`HTTP hook returned ${V.status} ${V.statusText}`),V.status>=400&&V.status<500)break;continue}let U={stdout:await HO(V,Y),stderr:"",exitCode:0,timedOut:!1};return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior})}catch(V){let B=V.name==="AbortError"||V.code==="ABORT_ERR";if(B&&Q.abortSignal?.aborted){J=Error("HTTP hook aborted by caller");break}if(B){let U={stdout:"",stderr:`HTTP hook timeout after ${Z}ms`,exitCode:124,timedOut:!0};if(G===$-1)return this.outputParser.parse(U,O,{timeoutBehavior:Q.config.timeoutBehavior,failureBehavior:Q.config.failureBehavior});J=Error(`HTTP hook timeout attempt ${G+1}`);continue}J=V}finally{clearTimeout(F),Q.abortSignal?.removeEventListener("abort",z)}}return{success:!1,blocking:!1,error:J?.message??"HTTP hook failed",hook:O}}async getOrCreateChatService(O,q){let Q=this.sessionResourceKey(q.sessionId,q.projectDir),Z=`${Q}\x00${O||"__default__"}`,Y=this.chatServiceCache.get(Z);if(Y)return Y;let{ensureStoreInitialized:$,getConfig:X}=await import("./chunk-c663rajb.js"),{createChatServiceAsync:W}=await import("./chunk-p7t010gq.js"),{resolveModelConfig:J}=await import("./chunk-n4cw6vt1.js"),{resolveWorkspaceModelResources:G}=await import("./chunk-vc7gh3wc.js");await $();let L=X();if(!L)throw Error("PromptHook: 配置未初始化");let F=this.sessionModelResources.get(Q)??await G(q.projectDir,L),z=O?F.config.models.find((B)=>B.id===O):F.config.models.find((B)=>B.id===F.config.currentModelId)??F.config.models[0];if(!z)throw Error("PromptHook: 无法获取模型配置。请确保至少配置了一个模型。");let V=await W(J(z,F.config,"off",F.catalog).chat);return this.chatServiceCache.set(Z,V),V}sessionResourceKey(O,q){return`${O}\x00${DO.resolve(q)}`}withSessionEnvironment(O){let q=this.sessionEnvironments.get(this.sessionResourceKey(O.sessionId,O.projectDir));return q?{...O,environment:q}:O}withHookEnvironment(O,q){let Q=this.withSessionEnvironment(O);if(!q.source)return Q;return{...Q,environment:{...Q.environment,BLADE_PLUGIN_ROOT:q.source.pluginRoot,CLAUDE_PLUGIN_ROOT:q.source.pluginRoot,BLADE_PLUGIN_NAME:q.source.pluginName}}}buildPromptHookSystemMessage(O,q){let Q=yO[q]||"{ ... 根据事件类型返回相应字段 }";return`你是一个代码质量评估器,作为 Hook 在 ${q} 事件中被触发。
|
|
29
29
|
|
|
30
30
|
`+`## 评估指令
|
|
31
31
|
${O.prompt}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Bi as S}from"./chunk-
|
|
1
|
+
import{Bi as S}from"./chunk-8z9d0zd0.js";import{Vi as f}from"./chunk-w9xfks7f.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,2 +1,2 @@
|
|
|
1
|
-
import{eh as H,fh as I}from"./chunk-
|
|
1
|
+
import{eh as H,fh as I}from"./chunk-z5a8ay9s.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as s,K as t};
|