blade-code 0.10.97 → 0.10.98
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-8htbttg5.js → chunk-0bsn86gg.js} +1 -1
- package/dist/{chunk-q5t2rnx0.js → chunk-17ck16tq.js} +1 -1
- package/dist/{chunk-2mwgykjs.js → chunk-1j3mmdbt.js} +1 -1
- package/dist/{chunk-csr9d8yx.js → chunk-3wjb3bhw.js} +2 -2
- package/dist/{chunk-88mf53ak.js → chunk-4004spc1.js} +1 -1
- package/dist/{chunk-88ykfsbv.js → chunk-4crf8nvz.js} +2 -2
- package/dist/chunk-4n7zxjk0.js +1 -0
- package/dist/{chunk-0v74fhhc.js → chunk-4ytvrkks.js} +1 -1
- package/dist/{chunk-zvms9ap7.js → chunk-54syvhtz.js} +2 -2
- package/dist/{chunk-t5es94zk.js → chunk-63wahkkf.js} +1 -1
- package/dist/chunk-6b232wd7.js +1 -0
- package/dist/chunk-78bmtbzh.js +1 -0
- package/dist/chunk-7k38nj7a.js +23 -0
- package/dist/{chunk-s47ypj8n.js → chunk-7kbtqzy0.js} +3 -3
- package/dist/{chunk-sdvfyzv0.js → chunk-7wgtj7w4.js} +2 -2
- package/dist/{chunk-630jj776.js → chunk-7yn3d4cf.js} +1 -1
- package/dist/{chunk-7wtbhnfr.js → chunk-8dtggj9c.js} +1 -1
- package/dist/{chunk-2c2cxrc0.js → chunk-8jtwm19d.js} +1 -1
- package/dist/{chunk-dsnz4a1d.js → chunk-8v8frtnd.js} +1 -1
- package/dist/{chunk-qm83ezt6.js → chunk-9qqhkwbw.js} +1 -1
- package/dist/{chunk-t5y1ebdn.js → chunk-a7hz8scf.js} +1 -1
- package/dist/{chunk-31g86axj.js → chunk-a9ek5zt1.js} +2 -2
- package/dist/{chunk-23qhbq46.js → chunk-azcca8bk.js} +1 -1
- package/dist/{chunk-bztsz28c.js → chunk-b4ahgdtn.js} +2 -2
- package/dist/chunk-d1je4wzc.js +2 -0
- package/dist/{chunk-g2yaghbk.js → chunk-d2f41jxt.js} +1 -1
- package/dist/chunk-d3z12cgn.js +1 -0
- package/dist/chunk-d62jkv36.js +1 -0
- package/dist/chunk-dc3k9999.js +1 -0
- package/dist/{chunk-qhsmhx0y.js → chunk-dp9xbrjy.js} +2 -2
- package/dist/{chunk-p5ewrebt.js → chunk-drqezf1p.js} +1 -1
- package/dist/{chunk-ps2rv1gg.js → chunk-e6wgta3m.js} +1 -1
- package/dist/{chunk-xjyr40bn.js → chunk-e99cqtmv.js} +2 -2
- package/dist/{chunk-3saxqsn7.js → chunk-ef5b0ysc.js} +1 -1
- package/dist/{chunk-c6p5mj1k.js → chunk-fra0nwzj.js} +2 -2
- package/dist/{chunk-9mnspb2d.js → chunk-gaj6kkb6.js} +1 -1
- package/dist/{chunk-3229684w.js → chunk-gcy8nczq.js} +1 -1
- package/dist/{chunk-xtm0sp0k.js → chunk-h1wvtdh4.js} +1 -1
- package/dist/{chunk-p87j2g40.js → chunk-hdhxzmw7.js} +1 -1
- package/dist/chunk-hdrap16m.js +1 -0
- package/dist/{chunk-6qxzcx0a.js → chunk-hmgxkjbx.js} +2 -2
- package/dist/{chunk-g2hxj68b.js → chunk-hphdt9ph.js} +2 -2
- package/dist/chunk-hvz0wk1j.js +1 -0
- package/dist/{chunk-825r9sfe.js → chunk-hy9tkb5x.js} +3 -3
- package/dist/{chunk-mybhqpc7.js → chunk-j0ndrqv6.js} +1 -1
- package/dist/{chunk-zyfacwgn.js → chunk-j9cnp8ms.js} +1 -1
- package/dist/{chunk-fm93hym6.js → chunk-krhr8xbg.js} +2 -2
- package/dist/{chunk-ycr6tsfs.js → chunk-ks3f9h9n.js} +2 -2
- package/dist/chunk-kv6w817v.js +10 -0
- package/dist/chunk-m4bg4jp9.js +1 -0
- package/dist/{chunk-21ycnzsv.js → chunk-mf2s05b7.js} +1 -1
- package/dist/chunk-mpm2kdf6.js +1 -0
- package/dist/{chunk-qeznbnd1.js → chunk-my7nr1sx.js} +2 -2
- package/dist/{chunk-s36efnxd.js → chunk-nvypaz88.js} +1 -1
- package/dist/{chunk-vchv2x9y.js → chunk-p47hbq3a.js} +2 -2
- package/dist/{chunk-jy4s51bt.js → chunk-ps9vc0m3.js} +2 -2
- package/dist/{chunk-j1t2qedg.js → chunk-q74f1pj9.js} +1 -1
- package/dist/{chunk-n407vvwt.js → chunk-qb1wev32.js} +1 -1
- package/dist/{chunk-cvpvncza.js → chunk-qdf2a3vf.js} +1 -1
- package/dist/{chunk-nxmn37zx.js → chunk-rmkw6dpm.js} +1 -1
- package/dist/{chunk-dretwm9j.js → chunk-rzcm8hw3.js} +1 -1
- package/dist/chunk-rztsp1jj.js +1 -0
- package/dist/{chunk-h5xw792m.js → chunk-s6n0cgg5.js} +2 -2
- package/dist/{chunk-fbs90qgx.js → chunk-szccdrah.js} +1 -1
- package/dist/{chunk-v2bvrk83.js → chunk-tae9c030.js} +2 -2
- package/dist/{chunk-n7p994w1.js → chunk-v2p30pe1.js} +1 -1
- package/dist/{chunk-m67hdwk8.js → chunk-vw2j0avq.js} +1 -1
- package/dist/{chunk-z6we2tr8.js → chunk-wkfhpjkf.js} +1 -1
- package/dist/chunk-wq8zryfj.js +1 -0
- package/dist/{chunk-a1vhp8sa.js → chunk-wzgdm617.js} +2 -2
- package/dist/{chunk-7bhk8qk5.js → chunk-wzx5s1dm.js} +2 -2
- package/dist/chunk-ysckkpw0.js +1 -0
- package/dist/chunk-zppdqh51.js +1 -0
- package/package.json +1 -1
- package/dist/chunk-0p6qkcft.js +0 -1
- package/dist/chunk-0pdkfzgc.js +0 -1
- package/dist/chunk-2vt67deg.js +0 -1
- package/dist/chunk-64kpbdpc.js +0 -1
- package/dist/chunk-6tzphr1p.js +0 -10
- package/dist/chunk-7t2nf0rz.js +0 -1
- package/dist/chunk-ah15z613.js +0 -1
- package/dist/chunk-b9thsjxh.js +0 -2
- package/dist/chunk-cp9mj5he.js +0 -1
- package/dist/chunk-g7yfjy30.js +0 -1
- package/dist/chunk-krym2q8y.js +0 -23
- package/dist/chunk-perp57h6.js +0 -1
- package/dist/chunk-pxmfnkf3.js +0 -1
- package/dist/chunk-qkmsw3km.js +0 -1
- package/dist/chunk-s91r4emx.js +0 -1
- package/dist/chunk-wgg7ysqn.js +0 -1
- package/dist/chunk-zr27h1p0.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{
|
|
2
|
+
import{te as W}from"./chunk-7wgtj7w4.js";import{we as F,xe as M}from"./chunk-ps9vc0m3.js";import"./chunk-p47hbq3a.js";import"./chunk-v508x7cg.js";import"./chunk-ef5b0ysc.js";import"./chunk-7kbtqzy0.js";import"./chunk-h1wvtdh4.js";import"./chunk-4crf8nvz.js";import"./chunk-4ytvrkks.js";import"./chunk-nvypaz88.js";import"./chunk-d1je4wzc.js";import{Jh as N,Kh as B}from"./chunk-j0ndrqv6.js";import"./chunk-8jtwm19d.js";import{ji as T}from"./chunk-54syvhtz.js";import"./chunk-krhr8xbg.js";import"./chunk-63wahkkf.js";import"./chunk-tae9c030.js";import"./chunk-fra0nwzj.js";import"./chunk-j9cnp8ms.js";import"./chunk-s6n0cgg5.js";import{Si as J}from"./chunk-d2f41jxt.js";import p from"node:path";var E=process.argv.slice(2),I=c(E),u=I!==null;if(I!==null)T.setGlobalDebug(I);function c(Q){for(let Y=0;Y<Q.length;Y+=1){let U=Q[Y];if(U==="--debug"||U==="-d"){let X=Q[Y+1];return X&&!X.startsWith("-")?X:!0}if(U.startsWith("--debug="))return U.slice(8)||!0}return null}function m(Q){return Q.length===1&&(Q[0]==="--version"||Q[0]==="-V")}function q(Q,...Y){return Q.some((U)=>Y.some((X)=>U===X||U.startsWith(`${X}=`)))}function t(Q,...Y){let U=[];for(let X=0;X<Q.length;X+=1){let G=Q[X],z=Y.find(($)=>G.startsWith(`${$}=`));if(z){let $=G.slice(z.length+1);if($)U.push($);continue}if(Y.includes(G)){let $=Q[X+1];if($&&!$.startsWith("-"))U.push($),X+=1}}return U}async function l(){if(m(E)){let{getVersion:K}=await import("./chunk-zppdqh51.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=t(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-d3z12cgn.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-hdrap16m.js");await K.getInstance().trust(B())}if(process.getuid&&process.getuid()===0){let K=!!process.env.SUDO_USER,Z=!!process.env.BLADE_ALLOW_ROOT;if(K&&!Z)console.error(""),console.error("Error: 请不要使用 sudo 运行 blade"),console.error(""),console.error("原因:"),console.error(" 使用 sudo 会创建属于 root 的配置文件,"),console.error(" 导致普通用户无法访问。"),console.error(""),console.error("正确用法:"),console.error(" blade # 直接运行,不要加 sudo"),console.error(""),console.error("如果遇到权限错误,请运行:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("如果你确实需要以 root 运行(容器/CI),设置环境变量:"),console.error(" BLADE_ALLOW_ROOT=1 blade"),console.error(""),process.exit(1)}if(q(E,"--headless")){let{handleHeadlessMode:K}=await import("./chunk-rmkw6dpm.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-drqezf1p.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-7k38nj7a.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{browserCommands:S},{doctorCommands:k},{installCommands:O},{mcpCommands:y},{projectsCommands:V},{scheduleCommands:b},{serveCommand:P},{updateCommands:x},{webCommand:A}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-wq8zryfj.js"),import("./chunk-ysckkpw0.js"),import("./chunk-vw2j0avq.js"),import("./chunk-ks3f9h9n.js"),import("./chunk-8v8frtnd.js"),import("./chunk-wkfhpjkf.js"),import("./chunk-hdhxzmw7.js"),import("./chunk-9qqhkwbw.js"),import("./chunk-mpm2kdf6.js"),import("./chunk-v2p30pe1.js"),import("./chunk-kv6w817v.js")]),h=X(G(process.argv)).scriptName(z.scriptName).usage(z.usage).version(z.version).locale(z.locale).showHelpOnFail(z.showHelpOnFail).demandCommand(0,"").recommendCommands().strict(z.strict).parserConfiguration({"populate--":!0}).options($).middleware([_,R,D]).command(S).command(y).command(V).command(b).command(k).command(x).command(O).command(A).command(P).completion("completion",!1).help("help","Show help").alias("help","h").alias("version","V").fail((K,Z,L)=>{if(Z){if(console.error("An error occurred:"),console.error(Z.message),u&&Z.stack)console.error(`
|
|
3
3
|
Stack trace:`),console.error(Z.stack);else console.error(`
|
|
4
4
|
Run with --debug to show the stack trace.`);process.exit(1)}if(K)console.error("Error: Invalid arguments:"),console.error(K),console.error(`
|
|
5
|
-
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-
|
|
5
|
+
Hint: Did you mean:`),L.showHelp(),process.exit(1)}).command("$0",!1,()=>{},async(K)=>{let Z=K._.slice(1),L=Z.length>0?Z.join(" "):void 0,f=import("./chunk-78bmtbzh.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-szccdrah.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:f};delete H._,delete H.$0,delete H.message,w(j(C,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await h.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)l().catch(console.error);export{l as main};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{V as P}from"./chunk-
|
|
1
|
+
import{V as P}from"./chunk-hy9tkb5x.js";import{tb as K}from"./chunk-hphdt9ph.js";import{$c as O,Pd as B,Yc as G,Zc as N,_c as S,ad as s}from"./chunk-hmgxkjbx.js";import{Yd as j}from"./chunk-wzx5s1dm.js";import{Ze as q}from"./chunk-ef5b0ysc.js";import{vf as v}from"./chunk-3wjb3bhw.js";import{Mi as z}from"./chunk-s6n0cgg5.js";import R from"node:path";import{nanoid as cf}from"nanoid";import{execFile as I}from"node:child_process";import{createHash as p}from"node:crypto";import{lstat as o,readFile as ff,realpath as V}from"node:fs/promises";import A from"node:path";import{promisify as af}from"node:util";var tf=af(I),L=8388608,U=500,Y=200;async function y(n,a){try{return(await tf("git",["-c","core.pager=cat",...a],{cwd:n,encoding:"utf8",timeout:30000,maxBuffer:L+1024,env:{...process.env,GIT_CONFIG_NOSYSTEM:"1",GIT_PAGER:"cat",GIT_OPTIONAL_LOCKS:"0"}})).stdout}catch(f){let t=f instanceof Error&&f.message.includes("maxBuffer")?`Review target exceeds the ${L} byte limit`:f instanceof Error?f.message:String(f);throw Error(`Git review target failed: ${t}`)}}function Q(n,a){let f=n?.trim();if(!f||f.length>Y||f.includes("\x00")||f.includes(`
|
|
2
2
|
`)||f.includes("\r"))throw Error(`${a} must contain 1-${Y} characters`);return f}function W(n){return n.split("\x00").filter(Boolean)}async function _(n,a){return(await y(n,["rev-parse","--verify",`${a}^{commit}`])).trim()}async function nf(n,a,f,t,g){let w=g,c=await V(n);for(let e of a){let $=A.resolve(c,e),l=A.relative(c,$);if(!l||l.startsWith("..")||A.isAbsolute(l))throw Error(`Untracked review path escapes the workspace: ${e}`);let i=await o($);if(!i.isFile()||i.isSymbolicLink())throw Error(`Untracked review target must be a regular file: ${e}`);if(w+=i.size,w>L)throw Error(`Review target exceeds ${L} bytes`);f.update("\x00untracked\x00"),f.update(l.replaceAll(A.sep,"/")),f.update("\x00");let b=await ff($);f.update(b);let m=Math.max(1,b.toString("utf8").split(`
|
|
3
3
|
`).length);t.set(l.replaceAll(A.sep,"/"),[{start:1,end:m}])}}function M(n,a){let f=new Map,t,g,w,c,e=!1,$=(l,i)=>{let b=f.get(l)??[],m=b.at(-1);if(m&&i<=m.end+1)m.end=Math.max(m.end,i);else b.push({start:i,end:i});f.set(l,b)};for(let l of n.split(`
|
|
4
4
|
`)){if(l.startsWith("--- ")){let i=l.slice(4).split("\t")[0]?.trim();t=i&&i!=="/dev/null"?i.replace(/^a\//,"").replaceAll("\\","/"):void 0;continue}if(l.startsWith("+++ ")){let i=l.slice(4).split("\t")[0]?.trim();e=i==="/dev/null",g=e?t:i?i.replace(/^b\//,"").replaceAll("\\","/"):void 0,w=void 0,c=void 0;continue}if(l.startsWith("@@ ")){let i=/-(\d+)(?:,\d+)? \+(\d+)(?:,\d+)?/.exec(l);w=i?Math.max(1,Number(i[1])):void 0,c=i?Math.max(1,Number(i[2])):void 0;continue}if(!g||w===void 0||c===void 0)continue;if(l.startsWith("+")&&!l.startsWith("+++"))$(g,c),c++;else if(l.startsWith("-")&&!l.startsWith("---"))$(g,e?w:c),w++;else if(!l.startsWith("\\"))w++,c++}for(let l of a)if(!f.has(l))f.set(l,[{start:1,end:1}]);return f}function D(n){if(n.length>U)throw Error(`Review target exceeds the ${U} file limit`)}class d{static async resolve(n,a){let f=await V(n);await y(f,["rev-parse","--is-inside-work-tree"]);let t=await _(f,"HEAD"),g=p("sha256");g.update(`kind\x00${a.kind}\x00head\x00${t}\x00`);let w="",c=[],e,$,l,i,b=new Map;switch(a.kind){case"uncommitted":{w=await y(f,["diff","--binary","--no-ext-diff","--relative","HEAD","--","."]);let m=W(await y(f,["diff","--name-only","-z","--relative","HEAD","--","."])),h=W(await y(f,["ls-files","--others","--exclude-standard","-z","--","."]));if(c=[...new Set([...m,...h])].sort(),D(c),c.length===0)throw Error("No uncommitted changes to review");g.update(w),b=M(w,m),await nf(f,h,g,b,Buffer.byteLength(w)),l="uncommitted changes",i=["Review the uncommitted working tree against HEAD.","Use git status --short, git diff --cached, and git diff, then inspect","every relevant untracked file listed by git status."].join(" ");break}case"base":{let m=Q(a.ref,"Base ref");e=await _(f,m);let h=(await y(f,["merge-base",e,t])).trim();if(w=await y(f,["diff","--binary","--no-ext-diff","--relative",`${h}..${t}`,"--","."]),c=W(await y(f,["diff","--name-only","-z","--relative",`${h}..${t}`,"--","."])),D(c),c.length===0)throw Error(`No changes between ${m} and HEAD`);g.update(w),g.update(`\x00merge-base\x00${h}`),b=M(w,c),l=`changes against ${m}`,i=`Review changes introduced by ${h}..${t}.`;break}case"commit":{let m=Q(a.ref,"Commit ref");if($=await _(f,m),w=await y(f,["show","--format=","--binary","--no-ext-diff","--relative",$,"--","."]),c=W(await y(f,["diff-tree","--root","--no-commit-id","--name-only","-r","-z",$,"--","."])),D(c),c.length===0)throw Error(`Commit has no changes in this workspace: ${m}`);g.update(w),g.update(`\x00commit\x00${$}`),b=M(w,c),l=`commit ${m}`,i=`Review only the changes introduced by commit ${$}.`;break}}if(Buffer.byteLength(w)>L)throw Error(`Review diff exceeds ${L} bytes`);return{info:{kind:a.kind,label:l,headSha:t,...e?{baseSha:e}:{},...$?{commitSha:$}:{},digest:g.digest("hex"),fileCount:c.length},instruction:i,changedLines:b}}}var wf=131072,X=50,E=new Set;function Z(n,a){return`${R.resolve(n)}\x00${a}`}function J(n){return`/review ${n.kind}${n.kind==="uncommitted"?"":` ${n.ref?.trim()??""}`}`}function C(n,a,f,t=!1){if(typeof n!=="string")throw Error(`${a} must be a string`);let g=n.trim();if(!t&&!g||g.length>f)throw Error(`${a} exceeds its allowed length`);return g}function lf(n,a,f){if(!n||typeof n!=="object"||Array.isArray(n))throw Error("Review finding must be an object");let t=n,g=typeof t.line==="number"&&Number.isInteger(t.line)?t.line:void 0,w=t.code_location??(typeof t.file==="string"&&g!==void 0?{path:t.file,line_start:g,line_end:g}:void 0);if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Review finding has no code_location");let c=w,e=C(c.path,"Finding path",1000),$=R.posix.normalize(e.replaceAll("\\","/"));if(R.posix.isAbsolute($)||$===".."||$.startsWith("../"))throw Error("Review finding path must be workspace-relative");let l=R.resolve(a,$),i=R.relative(R.resolve(a),l);if(i.startsWith("..")||R.isAbsolute(i))throw Error("Review finding path escapes the workspace");let b=typeof t.severity==="string"?t.severity.toLowerCase():"",m=b==="critical"?0:b==="high"?1:b==="medium"?2:b==="low"?3:void 0,h=t.priority??m;if(h!==0&&h!==1&&h!==2&&h!==3)throw Error("Review finding priority must be 0-3");let x=t.confidence_score??t.confidence??0.8;if(typeof x!=="number"||!Number.isFinite(x)||x<0||x>1)throw Error("Review finding confidence_score must be between 0 and 1");let{line_start:r,line_end:u}=c;if(!Number.isInteger(r)||!Number.isInteger(u)||r<1||u<r||u-r>=10)throw Error("Review finding line range is invalid");let F=f.changedLines.get($);if(!F)throw Error("Review finding path is outside the review target");if(!F.some((T)=>r<=T.end&&u>=T.start))throw Error("Review finding line range does not overlap the changed lines");let k=C(t.title??`[P${h}] ${String(t.type??"Review finding").replaceAll("-"," ").replace(/\b\w/g,(T)=>T.toUpperCase())}`,"Finding title",120);if(!k.startsWith(`[P${h}] `))throw Error("Review finding title priority does not match priority");return{title:k,body:C(t.body??t.description,"Finding body",4000),priority:h,confidenceScore:x,codeLocation:{path:$,lineStart:r,lineEnd:u}}}function mf(n,a,f){if(Buffer.byteLength(n)>wf)throw Error("Review output exceeds the 128 KiB limit");let t=n.indexOf("{"),g=n.lastIndexOf("}");if(t<0||g<=t)throw Error("Reviewer did not return a JSON object");let w;try{w=JSON.parse(n.slice(t,g+1))}catch{throw Error("Reviewer returned invalid JSON")}if(!w||typeof w!=="object"||Array.isArray(w))throw Error("Reviewer output must be an object");let c=w;if(!Array.isArray(c.findings))throw Error("Reviewer output must contain findings");if(c.findings.length>X)throw Error(`Reviewer returned more than ${X} findings`);return{overallExplanation:C(c.overall_explanation??c.summary,"Review explanation",1e4,!0),findings:c.findings.map((e)=>lf(e,a,f))}}async function H(n,a){return new j(z(n,a)).readAll()}class gf{static async start(n){let{sessionId:a,projectPath:f,runtime:t,request:g,onEvent:w}=n;if(t.sessionId!==a||R.resolve(t.workspaceRoot)!==R.resolve(f))throw Error("Review runtime does not own the requested Session");if(t.hasTurnOwner())throw Error("Cannot start a review during an active turn");await B.assertSessionWritable(a,f);let c=Z(f,a);if(E.has(c))throw Error("Session already has an active review");let e=await H(f,a);if(N(e))throw Error("Session has an interrupted review that must be recovered");let $=g.instructions?.trim();if($&&$.length>4000)throw Error("Review instructions exceed 4,000 characters");let l=await d.resolve(f,g),i=cf(16),b=q("review"),m=new Date().toISOString(),h={reviewId:i,reviewerSessionId:b,target:l.info,startedAt:m},x=new K(f);await x.saveReviewStart(a,h),await x.saveMessage(a,"user",J(g),null,{codeReview:{reviewId:i,phase:"started",targetKind:l.info.kind,targetDigest:l.info.digest}}),await B.updateSessionMetadata(a,f,{taskStatus:"running",taskStatusReason:`Reviewing ${l.info.label}`,taskPromptSummary:J(g),taskStartedAt:m,taskCompletedAt:null,taskFailure:null}),E.add(c);let r=this.execute({...n,target:l,reviewId:i,reviewerSessionId:b,instructions:$,store:x,onEvent:w}).finally(()=>{E.delete(c)});return{reviewId:i,completion:r}}static async execute(n){let{sessionId:a,projectPath:f,runtime:t,request:g,signal:w,onEvent:c,target:e,reviewId:$,reviewerSessionId:l,instructions:i,store:b}=n,m;try{let x=[e.instruction,"Bash already starts in the review workspace. Never prefix a command with cd.",`Authoritative target digest: ${e.info.digest}`,`Changed file count: ${e.info.fileCount}`,i?`Additional review instructions:
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var n="verification",o="goal-verification",r="review";function e(t){return t==="verification"||t==="goal-verification"}function i(t){return e(t)||t==="review"}var s=["active","verifying","paused","blocked","usage_limited","budget_limited","complete"],p=["pending","pass","fail","partial"],c=4000,S=3,u=["unable_to_proceed","stopping_here","internal_wait","self_deferral","handoff"],l=3;
|
|
2
|
-
export{n as
|
|
2
|
+
export{n as Uf,o as Vf,r as Wf,e as Xf,i as Yf,s as Zf,p as _f,c as $f,S as ag,u as bg,l as cg};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{O as I}from"./chunk-
|
|
1
|
+
import{O as I}from"./chunk-hy9tkb5x.js";import{Pd as M}from"./chunk-hmgxkjbx.js";import P from"node:path";function w(s){let a=s.replace(/\s+/g," ").trim();return a.length<=72?a:`${a.slice(0,69)}...`}function W(s){let a=s.replace(/\s+/g," ").trim();return a.length<=500?a:`${a.slice(0,497)}...`}function A(s){return`task/${s.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class C{static async createSessionTask(s){if(!s.prompt.trim())throw Error("Task prompt must not be blank");if(!P.isAbsolute(s.sourceProjectPath))throw Error("Task source project path must be absolute");let a=P.resolve(s.sourceProjectPath),t;try{return t=s.isolation==="worktree"?await I.enter({sessionId:s.sessionId,workspaceRoot:a,name:A(s.sessionId)}):void 0,{metadata:await M.createSessionMetadata(s.sessionId,t?.workspaceRoot??a,{title:s.title?.trim()||w(s.prompt),taskPromptSummary:W(s.prompt),taskPriority:s.taskPriority,taskKind:s.taskKind,taskDueAt:s.taskDueAt,taskDispatch:s.dispatch,taskModelId:s.dispatch?.modelId,selectedModelId:s.dispatch?.modelId,permissionMode:s.dispatch?.permissionMode,reasoningEffort:s.dispatch?.reasoningEffort,serviceTier:s.dispatch?.serviceTier,responseVerbosity:s.dispatch?.responseVerbosity,communicationStyle:s.dispatch?.communicationStyle,communicationStyleDigest:s.dispatch?.communicationStyleDigest,projectInstructionsDigest:s.dispatch?.projectInstructionsDigest,taskRetriedFrom:s.retriedFrom,taskIsolation:s.isolation,taskSourceProjectPath:a,taskWorktree:t}),taskWorktree:t}}catch(k){if(t)await I.exit({sessionId:s.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var $=256,V=8388608,x=30000;class i extends Error{kind;pendingItems;pendingBytes;constructor(s,a,t){super(a,t);this.kind=s;this.name="BoundedSerialEgressError",this.pendingItems=t?.pendingItems,this.pendingBytes=t?.pendingBytes}}function T(s){s.catch(()=>{return})}class K{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(s){this.options=s;if(this.assertPositiveInteger(s.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(s.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(s.writeTimeoutMs,"writeTimeoutMs"),s.signal?.addEventListener("abort",this.handleAbort,{once:!0}),s.signal?.aborted)this.handleAbort()}offer(s){if(this.closed)return{accepted:!1,error:this.failure??new i("closed","Egress is already closed")};let a;try{a=this.options.sizeOf(s)}catch(h){return this.rejectAdmission(new i("invalid_size","Egress size calculation failed",{cause:h}))}if(!Number.isSafeInteger(a)||a<0)return this.rejectAdmission(new i("invalid_size","Egress size must be a non-negative safe integer"));if(a>this.options.maxPendingBytes)return this.rejectAdmission(new i("oversized",`Egress value requires ${a} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+a>this.options.maxPendingBytes)return this.rejectAdmission(new i("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let t,k,c=new Promise((h,m)=>{t=h,k=m});return T(c),this.nextSequence+=1,this.pending.push({value:s,bytes:a,sequence:this.nextSequence,resolve:t,reject:k,completion:c}),this.pendingBytes+=a,this.startDrain(),{accepted:!0,completion:c}}flush(){if(this.failure){let c=Promise.reject(this.failure);return T(c),c}let s=this.nextSequence;if(s<=this.completedSequence)return Promise.resolve();let a,t,k=new Promise((c,h)=>{a=c,t=h});return T(k),this.flushWaiters.push({targetSequence:s,resolve:a,reject:t}),k}close(s){let a=s instanceof i?s:new i("closed","Egress was closed",{cause:s});this.fail(a)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new i("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(s){return this.fail(s),{accepted:!1,error:s}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let s=this.drain();T(s)}async drain(){try{while(!this.closed){let s=this.pending[0];if(!s)return;try{await this.writeOne(s.value)}catch(a){this.fail(this.normalizeWriteError(a));return}if(this.closed||this.pending[0]!==s)return;this.pending.shift(),this.pendingBytes-=s.bytes,this.completedSequence=s.sequence,s.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(s){let a=new AbortController;this.activeWriteAbort=a;let t,k,c=new Promise((S,f)=>{k=f});T(c),this.activeWriteStop=k;let h=Promise.resolve().then(()=>this.options.write(s,a.signal));T(h);let m=new Promise((S,f)=>{t=setTimeout(()=>{let D=new i("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);a.abort(D),f(D)},this.options.writeTimeoutMs),this.activeWriteTimeout=t});T(m);try{await Promise.race([h,m,c])}finally{if(t!==void 0)clearTimeout(t);if(this.activeWriteTimeout===t)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===a)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(s){if(s instanceof i)return s;return new i("write_failed","Egress write failed",{cause:s})}fail(s){if(this.closed)return;if(s.pendingItems??=this.pending.length,s.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=s,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(s),this.activeWriteStop?.(s),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let a=this.pending.splice(0);this.pendingBytes=0;for(let t of a)t.reject(s);for(let t of this.flushWaiters.splice(0))t.reject(s);try{this.options.onFailure?.(s)}catch{}}settleFlushWaiters(){for(let s=0;s<this.flushWaiters.length;){let a=this.flushWaiters[s];if(a.targetSequence>this.completedSequence){s+=1;continue}this.flushWaiters.splice(s,1),a.resolve()}}assertPositiveInteger(s,a){if(!Number.isSafeInteger(s)||s<=0)throw RangeError(`${a} must be a positive safe integer`)}}
|
|
2
2
|
export{C as v,$ as w,V as x,x as y,i as z,K as A};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{$f as N0,Uf as b1,Vf as L0,Wf as z1}from"./chunk-17ck16tq.js";import{eg as jO,fg as wO}from"./chunk-gaj6kkb6.js";import{ig as A1}from"./chunk-rzcm8hw3.js";import{jg as b0,lg as J0}from"./chunk-7kbtqzy0.js";import{nh as S0,oh as GO,sh as I0}from"./chunk-4crf8nvz.js";import{Bh as c1,wh as u,yh as L}from"./chunk-nvypaz88.js";import{Kh as M}from"./chunk-j0ndrqv6.js";import{ki as k,li as S}from"./chunk-54syvhtz.js";import{yi as u0}from"./chunk-tae9c030.js";import{Fi as N}from"./chunk-fra0nwzj.js";import H1 from"node:path";import LO from"node:path";import v0 from"node:fs";import W0 from"node:os";import E from"node:path";import dO from"yaml";var U1=2000,V1=50,j1=1000,Y4={type:"object",properties:{verdict:{type:"string",enum:["pass","fail","partial"]},summary:{type:"string",minLength:1,maxLength:U1},findings:{type:"array",maxItems:V1,items:{type:"string",minLength:1,maxLength:j1}}},required:["verdict","summary","findings"],additionalProperties:!1};function F1(O,$){let Q=O.trim().replaceAll(/\s+/g," ");if($)Q=Q.replaceAll($,".");return Q.replace(/\bBearer\s+[^\s"'`]+/gi,"Bearer [redacted]").replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,"[redacted-key]").replace(/\b(api(?:[_-]?|\s+)key|access(?:[_-]?|\s+)token|authorization|cookie|password|passwd|refresh(?:[_-]?|\s+)token|secret|session(?:[_-]?|\s+)token)\b(\s*[:=]\s*)([^\s,;]+)/gi,"$1$2[redacted]")}function hO(O){if(O.length<=N0)return O;let $=" [verification feedback truncated]",Q=O.slice(0,N0-$.length);if(/[\uD800-\uDBFF]$/.test(Q))Q=Q.slice(0,-1);return Q.trimEnd()+$}function B1(O){if(!O||typeof O!=="object"||Array.isArray(O))return;let $=O;if($.verdict!=="pass"&&$.verdict!=="fail"&&$.verdict!=="partial"||typeof $.summary!=="string"||!$.summary.trim()||$.summary.length>U1||!Array.isArray($.findings)||$.findings.length>V1||!$.findings.every((Q)=>typeof Q==="string"&&Q.trim().length>0&&Q.length<=j1))return;return{verdict:$.verdict,summary:$.summary.trim(),findings:$.findings.map((Q)=>Q.trim())}}function X4(O,$){let Q=B1(O);if(!Q)return;let Z=F1(Q.summary,$),J=Q.findings.map((K)=>F1(K,$));return hO([Z,J.length>0?`Findings:
|
|
2
2
|
${J.map((K)=>`- ${K}`).join(`
|
|
3
3
|
`)}`:""].filter(Boolean).join(`
|
|
4
4
|
|
|
@@ -722,4 +722,4 @@ ${Z.join(`
|
|
|
722
722
|
</${Q}>`:"";return{content:K,files:[...O],references:O.map(O4),triggerPaths:[...$],contentBytes:Buffer.byteLength(K,"utf8"),provenanceSha256:w0(O.map((q)=>`${q.id}:${q.contentSha256}`).join(`
|
|
723
723
|
`))}}function AO(O,$){let Q=$,Z=[];for(let J=O.length-1;J>=0;J-=1){let K=O[J];if(!K)continue;let q=Buffer.byteLength(K.content,"utf8");if(q>Q)continue;Z.push(K),Q-=q}return Z.reverse()}class m{projectRoot;catalogSha256;definitions;byId;constructor(O,$=[]){this.projectRoot=O;this.projectRoot=K1(O),this.definitions=Object.freeze([...$].sort(L1).map((Q)=>Object.freeze({...Q}))),this.byId=new Map(this.definitions.map((Q)=>[Q.id,Q])),this.catalogSha256=w0(this.definitions.map((Q)=>`${Q.id}:${Q.contentSha256}`).join(`
|
|
724
724
|
`))}static empty(O){return new m(O)}list(){return this.definitions.map((O)=>({id:O.id,relativePath:O.relativePath,source:O.source,kind:O.kind,conditional:O.conditional,contentSha256:O.contentSha256}))}snapshot(){return new m(this.projectRoot,this.definitions.map((O)=>({...O,patterns:O.patterns?[...O.patterns]:void 0})))}staticRules(O,$=c$){if(this.definitions.length===0)return q0([],[],"project-instructions");let Q=this.relativeSourcePath(O),Z=this.definitions.filter((J)=>!J.conditional&&G1(J.scopeDirectory,Q));return q0(AO(Z,$),[],"project-instructions")}contextualRules(O,$,Q,Z=l$){if(this.definitions.length===0)return q0([],[],"contextual-project-instructions");let J=this.relativeSourcePath(O),K=[...new Set($.map((G)=>W1(z.relative(this.projectRoot,K1(G)))).filter(Y1))].sort(),q=new Map;for(let G of K)for(let Y of this.definitions){if(Q.has(Y.id))continue;if(!G1(Y.scopeDirectory,G))continue;if(Y.conditional){let X=z.posix.relative(Y.scopeDirectory||".",G);if(!Y.patterns?.some((U)=>xO(U,{dot:!0})(X)))continue}else if(G1(Y.scopeDirectory,J))continue;q.set(Y.id,Y)}let W=AO([...q.values()].sort(L1),Z);return q0(W,K,"contextual-project-instructions")}hydrate(O){let $=O.map((Q)=>{let Z=this.byId.get(Q.id);if(!Z||Z.contentSha256!==Q.contentSha256||Z.relativePath!==Q.relativePath||Z.source!==Q.source)throw Error(`Project rule provenance mismatch: ${Q.relativePath}`);return Z});return q0([...new Map($.map((Q)=>[Q.id,Q])).values()].sort(L1),[],"contextual-project-instructions")}relativeSourcePath(O){let $=W1(z.relative(this.projectRoot,K1(O)));if($&&!Y1($))throw Error("Project instruction source is outside the catalog root");return $}}async function $4(O,$){let Q=await d.lstat($);if(!Q.isFile()||Q.isSymbolicLink())throw Error("Project rule must be a regular file");if(Q.size>zO)throw Error(`Project rule exceeds ${zO} bytes`);let Z=await d.realpath($),J=W1(z.relative(O,Z));if(!Y1(J))throw Error("Project rule escapes its repository root");let K=await d.readFile(Z,"utf8");if(TO(K))throw Error("Project rule contains hidden control characters");let q=u$(K),W=q.content.trim();if(!W)throw Error("Project rule content must not be empty");let G=r$(q.data.paths),Y=e$(J),X=w0(JSON.stringify({relativePath:J,patterns:G??[],content:W}));return{id:`${Y.source}:${w0(J).slice(0,20)}`,relativePath:J,source:Y.source,kind:Y.kind,scopeDirectory:Y.scopeDirectory,priority:Y.priority,conditional:Boolean(G),...G?{patterns:G}:{},content:W,contentSha256:X}}async function _O(O,$){let Q=t$(O);if(!$.projectTrusted)return m.empty(Q);let Z=await d.realpath(Q),J=g$.stream([...o$],{cwd:Z,absolute:!0,dot:!0,deep:s$,onlyFiles:!0,followSymbolicLinks:!1,unique:!0,ignore:[...a$]}),K=[];for await(let Y of J)if(K.push(Y.toString()),K.length>SO)throw Error(`Project rule catalog exceeds ${SO} files`);K.sort();let q=new Set(K.filter((Y)=>z.basename(Y)==="AGENTS.override.md").map((Y)=>z.dirname(Y))),W=[],G=0;for(let Y of K){if(z.basename(Y)==="AGENTS.md"&&q.has(z.dirname(Y)))continue;try{let X=await $4(Z,Y);if(G+=Buffer.byteLength(X.content,"utf8"),G>MO)throw Error(`Project rule catalog exceeds ${MO} bytes`);W.push(X)}catch(X){i$.warn(`[ProjectRules] Ignoring rule: ${X instanceof Error?X.message:String(X)}`)}}return new m(Z,W)}var DO=32,D0=64;class CO extends Error{capacity=D0;constructor(){super(`Workspace agent resource capacity is full (${D0})`);this.name="WorkspaceAgentResourceCapacityError"}}var x=new Map,X1=0,NO=[];async function Q4(O){let $=await N.getInstance().getStatus(O.workspaceRoot);O.communicationStyles=await q1(O.workspaceRoot,{projectTrusted:$.state==="trusted",plugins:O.plugins.getActive()})}function Z4(O){let $={...O};for(let Q of Object.values(b0))$[Q]=(O[Q]??[]).map((Z)=>({...Z,matcher:Z.matcher?{...Z.matcher}:void 0,hooks:Z.hooks.map((J)=>({...J}))}));return $}function J5(O){NO=[...new Set(O.map(($)=>H1.resolve($)))]}function EO(O,$){YO(O,$.plugins),C.releaseInstance(O,$.subagents),P.releaseInstance({cwd:O},$.skills),T.releaseInstance(O,$.commands),D.releaseInstance(O,$.plugins)}function vO(O){EO(O.workspaceRoot,O)}function K0(){while(x.size>DO){let O=!1;for(let[$,Q]of x){if(!Q.resources||Q.users>0)continue;if(x.get($)!==Q)continue;x.delete($),vO(Q.resources),O=!0;break}if(!O)return}}function J4(O){setImmediate(()=>{O.users=Math.max(0,O.users-1),K0()}).unref?.()}async function q4(O,$){let Q=await N.getInstance().getStatus(O),Z=o(O),J=g({cwd:O}),K=T.getInstance(O),q=Q0(O);try{if(Z.getAllNames().length===0)Z.loadFromStandardLocations(Q.state==="trusted");await Promise.all([J.initialize(),K.isInitialized()?void 0:K.initialize(O),q.isInitialized()?void 0:q.initialize(O,[...$.cliPluginDirs??NO])]),A0(O),await Z1(O);let W=await q1(O,{projectTrusted:Q.state==="trusted",plugins:q.getActive()}),G=await _O(O,{projectTrusted:Q.state==="trusted"});return{workspaceRoot:O,subagents:Z,skills:J,commands:K,plugins:q,communicationStyles:W,projectRules:G}}catch(W){throw EO(O,{subagents:Z,skills:J,commands:K,plugins:q}),W}}function K4(O,$){let Q={generation:X1,users:0};return Q.promise=q4(O,$).then((Z)=>{if(Q.generation!==X1||x.get(O)!==Q)return vO(Z),Z;return Q.resources=Z,K0(),Z},(Z)=>{if(x.get(O)===Q)x.delete(O);throw Z}),x.set(O,Q),Q}async function RO(O,$){let Q=H1.resolve(O),Z=x.get(Q);if(!Z){if(K0(),x.size>=D0)throw new CO;Z=K4(Q,$)}else x.delete(Q),x.set(Q,Z);Z.users++;let J;try{J=await Z.promise}catch(K){throw Z.users=Math.max(0,Z.users-1),K0(),K}return{entry:Z,resources:J}}async function yO(O,$){if(!$)return;A0(O.workspaceRoot),await Z1(O.workspaceRoot),await Q4(O)}async function q5(O,$={}){let Q=await RO(O,$);try{return await yO(Q.resources,$.reconcilePlugins),Q.resources}finally{J4(Q.entry)}}async function K5(O,$,Q={}){let Z=await RO(O,Q);try{return await yO(Z.resources,Q.reconcilePlugins),await $(Z.resources)}finally{Z.entry.users=Math.max(0,Z.entry.users-1),K0()}}function G5(){let O=0,$=0;for(let Q of x.values()){if(Q.resources)O++;$+=Q.users}return{capacity:DO,activeCapacity:D0,entries:x.size,initialized:O,inFlight:x.size-O,activeUsers:$}}function L5(O){let $="projectRoot"in O?O.projectRoot:O.workspaceRoot;return{projectRoot:H1.resolve($),subagents:O.subagents.snapshot(),skills:O.skills.snapshot(),commands:O.commands.snapshot(),communicationStyles:O.communicationStyles?.snapshot()??wO.snapshot(),projectRules:O.projectRules?.snapshot()??m.empty($),hooks:Z4("hooks"in O&&O.hooks?O.hooks:J0.getInstance().getConfig($))}}function W5(){X1++;for(let[O,$]of x)if($.resources)A0(O);x.clear(),C.resetInstances(),P.resetInstance(),T.resetInstance(),D.resetInstance()}
|
|
725
|
-
export{Y4 as
|
|
725
|
+
export{Y4 as sf,X4 as tf,H4 as uf,M1 as vf,B4 as wf,S4 as xf,o as yf,y4 as zf,w1 as Af,g as Bf,T as Cf,r0 as Df,M0 as Ef,D as Ff,Q0 as Gf,Z1 as Hf,A0 as If,m as Jf,DO as Kf,D0 as Lf,CO as Mf,Q4 as Nf,J5 as Of,q5 as Pf,K5 as Qf,G5 as Rf,L5 as Sf,W5 as Tf};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
|
|
2
|
-
export{s as
|
|
2
|
+
export{s as nf,g as of};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{vh as Y}from"./chunk-4ytvrkks.js";import{wh as on,xh as F,yh as o}from"./chunk-nvypaz88.js";import{Ch as ct,Dh as bt}from"./chunk-d1je4wzc.js";import{Kh as x}from"./chunk-j0ndrqv6.js";import{$h as Ut,Lh as Jn,Mh as Xt,Nh as pt,Rh as gt,Sh as kn,Th as it,Uh as Rt,Vh as Ct,Wh as un,Xh as zt,Yh as Bt,Zh as On,_h as Kt,ai as jn,bi as Ht,ci as Yt,di as qt,ei as Vt,fi as Qt,gi as Gt}from"./chunk-8jtwm19d.js";import{ki as fn}from"./chunk-54syvhtz.js";import{ni as $t,qi as J}from"./chunk-krhr8xbg.js";import{yi as Pn,zi as Ln}from"./chunk-tae9c030.js";import{Fi as h}from"./chunk-fra0nwzj.js";import{Qi as Tn}from"./chunk-s6n0cgg5.js";var Wt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function Zt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function R(n,t="MCP OAuth URL"){let M=new URL(n);if(M.username||M.password)throw Error(`${t} must not contain credentials`);if(M.protocol!=="https:"&&!(M.protocol==="http:"&&Zt(M.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return M}var U=async(n,t)=>{R(n,"MCP OAuth request URL");let M=await fetch(n,{...t,redirect:"manual"});if(M.status>=300&&M.status<400)throw await M.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return M};function k(n){let t=n.oauth;if(!t)return;let M=t;for(let u of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(M[u]!==void 0)throw Error(`MCP OAuth "${u}" is not supported; use standards-based discovery`);if(t.enabled!==!0)return{enabled:!1};if(n.type!=="http"&&n.type!=="sse")throw Error("MCP OAuth is supported only for HTTP and SSE transports");if(!n.url)throw Error("MCP OAuth requires an MCP server URL");if(R(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((u)=>u.toLowerCase()==="authorization"))throw Error("MCP OAuth cannot be combined with a configured Authorization header");let _=t.clientId?.trim();if(_&&_.length>4096)throw Error("MCP OAuth clientId exceeds 4096 characters");let S=t.scopes?.map((u)=>u.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((u)=>!u||u.length>128||!Wt.test(u)))throw Error("MCP OAuth scopes contain an invalid value");if(new Set(S).size!==S.length)throw Error("MCP OAuth scopes must not contain duplicates")}let r=t.callbackPort;if(r!==void 0&&(!Number.isInteger(r)||r<1024||r>65535))throw Error("MCP OAuth callbackPort must be between 1024 and 65535");return{enabled:!0,..._?{clientId:_}:{},...S?.length?{scopes:S}:{},...r!==void 0?{callbackPort:r}:{}}}import{randomUUID as v}from"node:crypto";import MM from"node:http";import{auth as cn}from"@modelcontextprotocol/sdk/client/auth.js";import _M from"open";import{createHash as Dt,randomUUID as Jt}from"node:crypto";import{constants as O,promises as L}from"node:fs";import j from"node:path";import kt from"write-file-atomic";var An=1,Ot=1048576,jt=5000,yt=50,Ft=/^[a-f0-9]{64}$/,lt=o.Object({client_id:o.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),vt=o.Object({access_token:o.String({minLength:1,maxLength:65536}),token_type:o.String({minLength:1,maxLength:64}),expires_in:o.Optional(o.Number({minimum:0})),refresh_token:o.Optional(o.String({minLength:1,maxLength:65536})),scope:o.Optional(o.String({maxLength:16384})),id_token:o.Optional(o.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),nM=o.Unsafe({type:"object",properties:{authorizationServerUrl:o.String({format:"uri"}),resourceMetadataUrl:o.Optional(o.String({format:"uri"})),resourceMetadata:o.Optional(o.Unknown()),authorizationServerMetadata:o.Optional(o.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),sn=o.Object({serverUrl:o.String({format:"uri"}),clientId:o.Optional(o.String({minLength:1,maxLength:4096})),clientInformation:o.Optional(lt),tokens:o.Optional(vt),tokenExpiresAt:o.Optional(o.Number({minimum:0})),discoveryState:o.Optional(nM),updatedAt:o.String({format:"date-time"})},{additionalProperties:!1}),En=o.Object({version:o.Literal(An),credentials:o.Record(o.String(),sn)},{additionalProperties:!1});function H(n,t){return n instanceof Error&&"code"in n&&n.code===t}function tM(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return H(t,"EPERM")}}function y(n){return structuredClone(n)}function mn(n){if(Object.keys(n.credentials).some((t)=>!Ft.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function q(n){let t=new URL(n);return t.hash="",t.toString()}function l(n,t,M=[]){return Dt("sha256").update(JSON.stringify({serverUrl:q(n),clientId:t?.trim()||null,scopes:[...M].sort()})).digest("hex")}class I{static locks=new Y;stateRoot;tokenFilePath;constructor(n=Tn()){this.stateRoot=j.join(n,"mcp"),this.tokenFilePath=j.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let M=(await this.readStore()).credentials[n];return M?y(M):null})}async updateCredential(n,t){return this.runMutation(async(M)=>{let e=M.credentials[n],_=await t(e?y(e):null);if(_)M.credentials[n]=F(sn,_);else delete M.credentials[n];return _?y(M.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return I.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return I.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let M=await this.readStore(),e=await n(M);return await this.writeStore(M),e}finally{await t()}})}async ensureStateRoot(){await L.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await L.lstat(this.stateRoot);if(!n.isDirectory()||n.isSymbolicLink())throw Error("MCP OAuth credential root must be a regular directory");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential root must be owned by the current user");if((n.mode&63)!==0)throw Error("MCP OAuth credential root permissions must not allow group access")}async readStore(){try{let n=await L.lstat(this.tokenFilePath);if(!n.isFile()||n.isSymbolicLink())throw Error("MCP OAuth credential store must be a regular file");if(process.getuid&&n.uid!==process.getuid())throw Error("MCP OAuth credential store must be owned by the current user");if((n.mode&511)!==384)throw Error("MCP OAuth credential store permissions must be 0600");if(n.size>Ot)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await L.readFile(this.tokenFilePath,"utf8")),M=on(En,t);if(!M.success)throw Error("MCP OAuth credential store has an invalid schema");return mn(M.data),M.data}catch(n){if(H(n,"ENOENT"))return{version:An,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=F(En,n);mn(t),await kt(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await L.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=j.join(this.stateRoot,".oauth-credentials.lock"),t=Jt(),M=Date.now()+jt;while(Date.now()<M)try{let e=await L.open(n,O.O_CREAT|O.O_EXCL|O.O_WRONLY,384);return await e.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await e.close(),async()=>{try{if(JSON.parse(await L.readFile(n,"utf8")).token===t)await L.unlink(n)}catch(_){if(!H(_,"ENOENT"))throw _}}}catch(e){if(!H(e,"EEXIST"))throw e;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,yt))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await L.lstat(n);if(!t.isFile()||t.isSymbolicLink())throw Error("MCP OAuth credential lock must be a regular file");if(process.getuid&&t.uid!==process.getuid()||(t.mode&511)!==384)throw Error("MCP OAuth credential lock ownership or permissions are invalid");let M=JSON.parse(await L.readFile(n,"utf8"));if(typeof M.pid!=="number"||!Number.isInteger(M.pid)||M.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!tM(M.pid))await L.unlink(n)}}var bn="127.0.0.1",wn=7777,xn="/oauth/callback",eM=300000;class nn extends Error{constructor(n){super(`MCP server "${n}" requires OAuth authorization; run "blade mcp login ${n}" or use the Web MCP panel`);this.name="McpOAuthAuthorizationRequiredError"}}class an extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function rM(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -41,4 +41,4 @@ ${M.map((e)=>` - ${e}`).join(`
|
|
|
41
41
|
]
|
|
42
42
|
}
|
|
43
43
|
`)}}function ze(n,t={}){let M={...n};if(t.debug!==void 0)M.debug=t.debug===""?!0:t.debug;if(t.model){if(!n.models.some((_)=>_.id===t.model))throw Error(`模型配置未找到: ${t.model}`);M.currentModelId=t.model}if(t.yolo===!0)M.permissionMode="yolo";else if(t.permissionMode!==void 0)M.permissionMode=t.permissionMode;if(t.maxTurns!==void 0)M.maxTurns=t.maxTurns;if(t.maxConcurrentTasks!==void 0)M.maxConcurrentTasks=t.maxConcurrentTasks;if(t.maxQueuedTasks!==void 0)M.maxQueuedTasks=t.maxQueuedTasks;if(t.maxQueuedTaskBytes!==void 0)M.maxQueuedTaskBytes=t.maxQueuedTaskBytes;if(t.maxResidentSessionRuntimes!==void 0)M.maxResidentSessionRuntimes=t.maxResidentSessionRuntimes;if(t.sessionRuntimeIdleMs!==void 0)M.sessionRuntimeIdleMs=t.sessionRuntimeIdleMs;return M.systemPrompt=t.systemPrompt,M.appendSystemPrompt=t.appendSystemPrompt,M.model=t.model,M.resumeSessionId=t.sessionId,M.forkSession=t.forkSession,M.allowedTools=t.allowedTools,M.disallowedTools=t.disallowedTools,M.mcpConfigPaths=t.mcpConfig,M.strictMcpConfig=t.strictMcpConfig,M.addDirs=t.addDir,M.outputFormat=t.outputFormat,M.inputFormat=t.inputFormat,M.print=t.print,M.includePartialMessages=t.includePartialMessages,M.replayUserMessages=t.replayUserMessages,M.agentsConfig=t.agents,M.settingSources=t.settingSources,M}
|
|
44
|
-
export{U as
|
|
44
|
+
export{U as qg,k as rg,I as sg,nn as tg,an as ug,$ as vg,nt as wg,i_ as xg,Q as yg,z_ as zg,B_ as Ag,K_ as Bg,rt as Cg,PM as Dg,U_ as Eg,LM as Fg,H_ as Gg,wt as Hg,V_ as Ig,Q_ as Jg,W_ as Kg,Z_ as Lg,D_ as Mg,Pt as Ng,J_ as Og,k_ as Pg,O_ as Qg,j_ as Rg,s_ as Sg,Nn as Tg,$n as Ug,b_ as Vg,Xn as Wg,pn as Xg,gn as Yg,Rn as Zg,Cn as _g,zn as $g,x_ as ah,Bn as bh,Kn as ch,Un as dh,Hn as eh,Yn as fh,qn as gh,Vn as hh,Qn as ih,Gn as jh,Wn as kh,Zn as lh,Dn as mh,A as nh,d as oh,mM as ph,B as qh,D as rh,g as sh,ze as th};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{Jd as a,Kd as b,Ld as c,Md as d,Nd as e,Od as f,Pd as g}from"./chunk-hmgxkjbx.js";import"./chunk-8dtggj9c.js";import"./chunk-wzx5s1dm.js";import"./chunk-4004spc1.js";import"./chunk-gaj6kkb6.js";import"./chunk-h1wvtdh4.js";import"./chunk-d1je4wzc.js";import"./chunk-j0ndrqv6.js";import"./chunk-54syvhtz.js";import"./chunk-63wahkkf.js";import"./chunk-tae9c030.js";import"./chunk-s6n0cgg5.js";import"./chunk-d2f41jxt.js";export{b as __setSessionSnapshotIOForTesting,c as __resetSessionSnapshotIOForTesting,g as SessionService,d as SessionMissingCreationError,e as SessionArchivedError,f as SessionArchiveConflictError,a as STALE_EMPTY_SESSION_AGE_MS};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var F;((D)=>{D.DEFAULT="default";D.AUTO_EDIT="autoEdit";D.YOLO="yolo";D.PLAN="plan"})(F||={});import{Mutex as G}from"async-mutex";class H{entries=new Map;async runExclusive(C,E){let B=this.entries.get(C);if(!B)B={mutex:new G,operations:0},this.entries.set(C,B);B.operations++;try{return await B.mutex.runExclusive(E)}finally{if(B.operations--,B.operations===0&&this.entries.get(C)===B)this.entries.delete(C)}}getStats(){let C=0;for(let E of this.entries.values())C+=E.operations;return{keys:this.entries.size,operations:C}}}
|
|
2
|
-
export{F as
|
|
2
|
+
export{F as uh,H as vh};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Qi as j}from"./chunk-s6n0cgg5.js";import{appendFileSync as E,existsSync as O,mkdirSync as R,readdirSync as U,statSync as B,unlinkSync as k}from"node:fs";import W from"node:path";var X;((H)=>{H[H.DEBUG=0]="DEBUG";H[H.INFO=1]="INFO";H[H.WARN=2]="WARN";H[H.ERROR=3]="ERROR"})(X||={});var T=null,_=null,$=!1;function m(q){if(T!==q)T=q}async function I(){}function w(){if($)return _;$=!0;try{let q=W.join(j(),"logs");if(!O(q))R(q,{recursive:!0,mode:493});if(B(q).uid===0&&process.getuid&&process.getuid()!==0)return console.error(""),console.error("[FAIL] 权限错误:~/.blade/logs 目录属于 root 用户"),console.error(""),console.error("这通常是因为您曾经使用 sudo 运行过 blade。"),console.error(""),console.error("解决方法:"),console.error(" sudo chown -R $USER:$USER ~/.blade/"),console.error(""),console.error("然后重新运行 blade(不要使用 sudo)"),console.error(""),null;return z(q,30),_=q,q}catch(q){return console.error("[Logger] 无法创建日志目录:",q),null}}function z(q,G){try{let J=U(q),K=Date.now(),H=G*24*60*60*1000;for(let Q of J){if(!Q.startsWith("blade-")||!Q.endsWith(".log")&&!Q.endsWith(".jsonl"))continue;let Y=W.join(q,Q);try{let Z=B(Y);if(K-Z.mtimeMs>H)k(Y)}catch(Z){}}}catch(J){}}function F(){let q=w();if(!q)return null;let G=T||"default";return W.join(q,`blade-${G}.jsonl`)}function A(q,G,J){let K=F();if(!K)return;try{let H={timestamp:new Date().toISOString(),level:X[G],category:q,message:J};E(K,JSON.stringify(H)+`
|
|
2
2
|
`)}catch(H){}}class M{static globalDebugConfig=null;enabled;minLevel;category;constructor(q={}){if(q.enabled!==void 0)this.enabled=q.enabled;else if(M.globalDebugConfig!==null)this.enabled=Boolean(M.globalDebugConfig);else this.enabled=!1;this.minLevel=q.minLevel??0,this.category=q.category??"General"}static setGlobalDebug(q){M.globalDebugConfig=q}static clearGlobalDebug(){M.globalDebugConfig=null}setEnabled(q){this.enabled=q}parseDebugFilter(q){if(!q)return{enabled:!1};if(q===!0||q==="true"||q==="1")return{enabled:!0};let G=String(q).trim();if(!G)return{enabled:!0};if(G.startsWith("!"))return{enabled:!0,filter:{mode:"exclude",categories:G.split(",").map((H)=>H.trim().replace(/^!/,"")).filter(Boolean)}};return{enabled:!0,filter:{mode:"include",categories:G.split(",").map((K)=>K.trim()).filter(Boolean)}}}shouldLogCategory(q){if(!q)return!0;let G=this.category.toLowerCase();if(q.mode==="include")return q.categories.some((J)=>G.includes(J.toLowerCase()));return!q.categories.some((J)=>G.includes(J.toLowerCase()))}shouldLogToConsole(q){if(M.globalDebugConfig!==null){let{enabled:G,filter:J}=this.parseDebugFilter(M.globalDebugConfig);if(!G)return!1;if(q<this.minLevel)return!1;return this.shouldLogCategory(J)}return this.enabled&&q>=this.minLevel}log(q,...G){let J=G.map((K)=>typeof K==="object"?JSON.stringify(K):String(K)).join(" ");if(A(this.category,q,J),this.shouldLogToConsole(q)){let K=X[q],H=`[${this.category}] [${K}]`;console.error(H,...G)}}debug(...q){this.log(0,...q)}info(...q){this.log(1,...q)}warn(...q){this.log(2,...q)}error(...q){this.log(3,...q)}}function V(q,G){return new M({...G,category:q})}var h=new M({category:"General"});
|
|
3
|
-
export{m as
|
|
3
|
+
export{m as hi,I as ii,M as ji,V as ki,h as li};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
var t=["auto","low","medium","high"],s=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function n(e){return/(?:^|[/.:_-])gpt-5(?:$|[/.:_-])/i.test(e.id)}function f(e){return typeof e==="string"&&t.includes(e)}function p(e){if(e.api==="openai-codex-responses"||s.has(e.api)&&n(e))return["low","medium","high"];return[]}function u(e,r){let i=p(e);if(r!=="auto"&&!i.includes(r))throw Error(`Response verbosity ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};return{selection:r,effective:r,supported:i,providerValue:r}}var a=["auto","standard","fast","flex"],o=new Set(["openai-completions","openai-responses","openai-codex-responses","azure-openai-responses"]);function S(e){return typeof e==="string"&&a.includes(e)}function c(e){if(o.has(e.api))return["standard","fast","flex"];if(e.api==="anthropic-messages"&&/(?:^|-)claude-opus-4-6(?:-|$)/i.test(e.id))return["standard","fast"];return["standard"]}function l(e,r){let i=c(e);if(r!=="auto"&&!i.includes(r))throw Error(`Service tier ${r} is not supported by ${e.name}`);if(r==="auto")return{selection:r,effective:"provider-default",supported:i};if(r==="standard")return{selection:r,effective:"standard",supported:i,...o.has(e.api)?{providerValue:"default"}:{}};if(r==="fast")return{selection:r,effective:"fast",supported:i,providerValue:e.api==="anthropic-messages"?"fast":"priority"};return{selection:r,effective:"flex",supported:i,providerValue:"flex"}}
|
|
2
|
-
export{f as
|
|
2
|
+
export{f as ri,p as si,u as ti,S as ui,c as vi,l as wi};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{kf as a,lf as b,mf as c}from"./chunk-wzgdm617.js";import"./chunk-4004spc1.js";import"./chunk-krhr8xbg.js";import"./chunk-63wahkkf.js";import"./chunk-s6n0cgg5.js";import"./chunk-d2f41jxt.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{h as a,i as b,j as c,k as d,l as e}from"./chunk-7yn3d4cf.js";import"./chunk-tae9c030.js";import"./chunk-d2f41jxt.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import{s as cz,t as pz}from"./chunk-gcy8nczq.js";import{u as S}from"./chunk-0bsn86gg.js";import{A as Nz,v as gz,w as wz,x as Dz,y as _z,z as Az}from"./chunk-1j3mmdbt.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 Oz,ra as qz,sa as Pz,ta as Rz}from"./chunk-hy9tkb5x.js";import"./chunk-q74f1pj9.js";import{Ha as uz}from"./chunk-qdf2a3vf.js";import{Ja as Fz}from"./chunk-qb1wev32.js";import{Db as Yz,Mb as Lz,rb as Xz}from"./chunk-hphdt9ph.js";import{Xb as g}from"./chunk-8hprmrd5.js";import{$c as zz,Bd as p,Cd as $z,Ed as h,Hd as Wz,Md as P,Pd as j,jd as y,kd as c,ld as Hz,qd as Jz,td as Qz,vd as Zz}from"./chunk-hmgxkjbx.js";import"./chunk-8dtggj9c.js";import"./chunk-wzx5s1dm.js";import{se as mz}from"./chunk-7wgtj7w4.js";import"./chunk-ps9vc0m3.js";import{Ne as kz,Oe as Iz}from"./chunk-p47hbq3a.js";import"./chunk-v508x7cg.js";import{Ze as m}from"./chunk-ef5b0ysc.js";import{cf as e}from"./chunk-a9ek5zt1.js";import"./chunk-wzgdm617.js";import{nf as Cz}from"./chunk-4004spc1.js";import"./chunk-dp9xbrjy.js";import"./chunk-3wjb3bhw.js";import"./chunk-17ck16tq.js";import{dg as fz}from"./chunk-gaj6kkb6.js";import"./chunk-rzcm8hw3.js";import"./chunk-7kbtqzy0.js";import"./chunk-h1wvtdh4.js";import{Xg as yz,_g as Mz}from"./chunk-4crf8nvz.js";import"./chunk-4ytvrkks.js";import"./chunk-nvypaz88.js";import{Ch as C,Dh as t,Fh as f,Gh as u}from"./chunk-d1je4wzc.js";import{Kh as bz}from"./chunk-j0ndrqv6.js";import"./chunk-8jtwm19d.js";import{ki as M}from"./chunk-54syvhtz.js";import"./chunk-krhr8xbg.js";import{ri as hz,ui as Sz}from"./chunk-63wahkkf.js";import"./chunk-tae9c030.js";import"./chunk-fra0nwzj.js";import"./chunk-j9cnp8ms.js";import{Qi as s}from"./chunk-s6n0cgg5.js";import"./chunk-d2f41jxt.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),$=lz("sha256").update(`${z}\x00${J}`).digest().readUInt32BE(0)/4294967295,Z=1-o+2*o*$;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 Nz({maxPendingItems:wz,maxPendingBytes:Dz,writeTimeoutMs:_z,signal:H.signal,sizeOf:($)=>Buffer.byteLength(JSON.stringify($)),write:async($)=>{await H.sessionUpdate($)},onFailure:($)=>this.handleUpdateEgressFailure($)})}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($,Z)=>{let Y=await H.execute($,{cwd:Z.cwd,env:Z.env,timeout:Z.timeoutMs,signal:Z.signal,allowLocalFallback:!1,onOutput:(F)=>Z.onOutput?.("stdout",F)});return{exitCode:Y.exitCode,stdout:Y.stdout,stderr:Y.stderr,...Y.error?{error:Y.error}:{},timedOut:Y.failureKind==="timeout",aborted:Y.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:Z,messageId:Y,content:F}=$.properties,L=$.properties.metadata;if($.type==="team.message.received"&&typeof Z==="string"&&typeof Y==="string"&&typeof F==="string"&&Gz(L,{messageId:Y,teamName:Z}))(async()=>{let B=await this.runtime?.enqueueSteering(F,{allowBeforeTurn:!0,messageId:Y,origin:"team_message",metadata:L});if(!B?.accepted)return;if(await new Bz(Z,s()).markDelivered([Y]),B.delivery==="next_turn")this.requestPendingResume()})().catch((B)=>{U.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,B)});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();if(this.runtime.getPendingSteeringCount()>0||X?.status==="active"||X?.status==="verifying")this.requestPendingResume({defer:this.options.initialMessages!==void 0})}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 Y=await this.runtime.rewindSession(Z);return this.messages=[...Y.messages],this.contextMessages=await this.loadModelContextOr(Y.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),Y}},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,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let F=!1,L,B=(D)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:D.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:D.result?.message||D.result?.error||`Subagent ${D.status}`}}]})},G=this.runtime.resumeSubagent({agentId:Z,prompt:Y,onCompleted:(D)=>{if(F)B(D);else L=D}});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,Y,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Z,Y,F)},complete:async(Z,Y,F)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Z,Y,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,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Z,Y)},getLogs:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Z,Y)},setLoggingLevel:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Z,Y)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}},sideConversation:{ask:async(Z,Y)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Z,{signal:Y})}},codeReview:{run:async(Z,Y)=>{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:Y,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,Y,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(Y,null,2)}}],kind:B})},sendToolResult:(Z,Y)=>{if(Y.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Y.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 $=W.content||W.message;if($)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:$}});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 $;if(X.usage){let Z=X.usage.replace(/^\/\w+\s*/,"").trim();if(Z)$=Z}if(X.aliases?.length){let Z=`Aliases: ${X.aliases.join(", ")}`;$=$?`${$} | ${Z}`:Z}return{name:X.name,description:X.description,input:$?{hint:$}: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,$=z._meta?.outputSchema??(J.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((K)=>K.outputSchema)?.outputSchema:void 0),Z;if($!==void 0)Z=Wz($).schema;if(X.trimStart().startsWith("!")){if(Z)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand(X)}let Y=Fz(X);if(Y){if(Z)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(W)&&W.some((K)=>K.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(Y.question?`/btw ${Y.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 K=await this.runtime.enqueueSteering(W,{allowBeforeTurn:!0});if(!K.accepted)throw Error(K.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 (${K.queued})`),K.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,D=!1,R,T=new Promise((K)=>{R=K});this.pendingPrompt=F,this.pendingPromptCompletion=T;try{if(U.debug(`[AcpSession ${this.id}] Received prompt: ${X.slice(0,100)}...`),Oz(X)){if(Z)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand(X,F.signal)}let K={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)}}},A=await Yz(this.agent.chatStream(W,K,{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":{D=!0;let V=Q.toolCall,N=V.function.name;if(N===h)break;let q=this.mapToolKind(Q.toolKind),w=`Executing ${N}`;if(N==="Task"&&"function"in V)try{let x=JSON.parse(V.function.arguments),_=x.resume_from??x.resume;if(typeof _==="string")w=`Resuming ${String(x.subagent_type||"subagent")} from ${_}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:V.id,status:"in_progress",title:w,content:[],kind:q});break}case"tool_progress":{D=!0;let V=Q.toolCall;if(V.function.name===h)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:Q.update.message}}]});break}case"tool_result":{D=!0;let V=Q.toolCall;if(V.function.name===h)break;let N=Q.result,q=[],w=N.metadata;if(w?.kind==="patch"&&Array.isArray(w.changes))for(let _ of w.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(w?.kind==="edit"&&typeof w.file_path==="string"&&typeof w.oldContent==="string"&&(typeof w.newContent==="string"||w.newContent===void 0))q.push({type:"diff",path:w.file_path,oldText:w.oldContent,newText:w.newContent??null});else{let _=V.function.name,vz=Vz(Qz(jz(_,N),Jz));q.push({type:"content",content:{type:"text",text:vz}})}if(V.function.name==="Task"&&(w?.verificationVerdict==="pass"||w?.verificationVerdict==="fail"||w?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${w.verificationVerdict.toUpperCase()}`}});let x=N.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.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"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 V=0;for(let N of Q.messages){if(!N.recovered||N.persisted)continue;if(J.projectedRecoveredInputIds?.has(N.id))continue;for(let q of xz(N.content))this.sendUpdate({sessionUpdate:"user_message_chunk",content:q});J.projectedRecoveredInputIds?.add(N.id),V++}if(V>0)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[Resuming ${V} queued instruction${V===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=[...K.messages];let d=await j.loadSession(this.id,this.cwd);if(this.messages=d.length>0?d:[...K.messages],!A.success){let Q=A.error?.type??"unknown",V=A.error?.details??A.error?.message??"Agent execution failed",N=sz(V)??c(V);throw Tz.internalError({failureType:Q,taskFailure:N,outputStarted:G,toolExecutionStarted:D,...Number.isInteger(A.metadata?.toolCallsCount)?{toolCallsCount:A.metadata.toolCallsCount}:{}},`Agent turn failed (${Q})`)}if(F.signal.aborted)return{stopReason:"cancelled"};let l={...A.metadata?.structuredOutput?{structuredOutput:A.metadata.structuredOutput,outputSchemaDigest:A.metadata.structuredOutputSchemaDigest}:{},...A.metadata?.goalCompletionVerified?{goalCompletion:{verified:!0,verdict:A.metadata.goalVerificationVerdict,...A.metadata.goalVerifierSessionId?{verifierSessionId:A.metadata.goalVerifierSessionId}:{},...A.metadata.goalVerificationEvidenceSha256?{evidenceSha256:A.metadata.goalVerificationEvidenceSha256}:{}}}:{}};return{stopReason:"end_turn",...Object.keys(l).length>0?{_meta:l}:{}}}catch(K){if(F.signal.aborted||K instanceof Error&&K.name==="AbortError")return{stopReason:"cancelled"};throw U.error(`[AcpSession ${this.id}] Prompt error:`,K),K}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((Y)=>{W=Y});this.pendingUserShell=H,this.pendingUserShellCompletion=X;let $,Z="";try{let Y=await this.runtime.executeUserShellCommand(J,{signal:H.signal,onEvent:async(L)=>{if($=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:Y.modelContent,metadata:{userShellCommand:JSON.parse(JSON.stringify(Y.record))}};if(this.messages.push(F),this.contextMessages.push(F),Y.delivery==="next_turn")this.requestPendingResume();if(!await this.flushUpdates())return H.abort("acp-egress-failed"),{stopReason:"cancelled"};return{stopReason:Y.record.status==="aborted"?"cancelled":"end_turn"}}catch(Y){if($)this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:$,status:"failed",content:[{type:"content",content:{type:"text",text:Y instanceof Error?Y.message:String(Y)}}]});if(H.signal.aborted)return{stopReason:"cancelled"};throw Y}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,$=null;try{let Z=this.runtime.getPendingSteeringCount()>0,Y=Z?null:await this.runtime.getGoal();if(z!==this.pendingResumeGeneration)return;let F=Y?.status==="active"||Y?.status==="verifying";if(!Z&&!F){if(this.pendingResumeRequested){this.pendingResumeAttempt=0,this.projectedPendingResumeInputIds.clear(),this.pendingResumeRecoveryStartedAt=0;return}this.clearPendingResumeRequest();return}H=Z?"pending_input":"goal",W=!0;let L=r-(Date.now()-this.pendingResumeRecoveryStartedAt);if(L<=0){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}let B=new AbortController;$=setTimeout(()=>{B.abort("acp-pending-resume-budget-exhausted")},L),$.unref?.();let G=await this.prompt({sessionId:this.id,prompt:[]},{pendingInputOnly:Z,goalContinuationOnly:F,projectedRecoveredInputIds:H==="pending_input"?this.projectedPendingResumeInputIds:void 0,abortSignal:B.signal});if(z!==this.pendingResumeGeneration)return;if(B.signal.aborted){if(this.sendUpdate(this.pendingResumeSessionUpdate("exhausted",{attempt:J,kind:H,taskFailure:y("timeout")})),!this.preserveNewPendingInput(H))this.clearPendingResumeRequest();return}if(G.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 Y=W?ez(Z):{taskFailure:c(Z),toolExecutionStarted:!1,toolCallsCount:0,outputStarted:!1},L=(H==="preflight"||H==="pending_input"&&this.runtime.getPendingSteeringCount()>0)&&Y?.taskFailure.retryable===!0&&!Y.toolExecutionStarted&&Y.toolCallsCount===0&&!Y.outputStarted,B=tz(this.id,J),G=Date.now()-this.pendingResumeRecoveryStartedAt,D=J<i,R=G+B<=r;if(L&&D&&R)this.pendingResumeRequested=!0,X=B,this.sendUpdate(this.pendingResumeSessionUpdate("retry_scheduled",{attempt:J+1,kind:H,taskFailure:Y.taskFailure,delayMs:B})),U.warn(`[AcpSession ${this.id}] Pending resume attempt ${J} failed; retrying in ${B}ms`);else{let T=L&&(!D||!R)?"exhausted":"failed";if(this.sendUpdate(this.pendingResumeSessionUpdate(T,{attempt:J,kind:H,taskFailure:Y?.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($!==null)clearTimeout($);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 Az("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,$=this.pendingSideConversationCompletion;this.agent=null,this.runtime=null;let Z,Y=async(F)=>{try{await F()}catch(L){Z??=L}};if(await Y(()=>this.cancel()),W)await Y(()=>W);if(X)await Y(()=>X);if($)await Y(()=>$);if(z&&W&&H)await Y(()=>H.discardPendingInput());if(J)await Y(()=>J.destroy());if(H)await Y(()=>H.dispose());if(await Y(()=>E.destroySession(this.id)),U.debug(`[AcpSession ${this.id}] Destroyed`),Z!==void 0)throw Z}resolvePrompt(z){let J=[],H=[],W=0,X=0,$=0,Z=(L)=>{if(H.length>0)H.push({type:"text",text:`
|
|
13
|
+
`}),$+=1;if(H.push(L),L.type==="text")$+=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($>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 $=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(!Y)return{approved:!1,reason:g};let F=Y.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,$]of H.entries()){let Z=$.options.map((B,G)=>`answer:${X}:${G}`),Y=`answer:${X}:cancel`,F=await this.waitForClientInteraction(this.connection.requestPermission({sessionId:this.id,options:[...$.options.map((B,G)=>({optionId:Z[G],name:B.label,kind:"allow_once"})),{optionId:Y,name:"Cancel",kind:"reject_once"}],toolCall:{toolCallId:I(),status:"pending",title:$.header,kind:"think",content:[{type:"content",content:{type:"text",text:[$.question,...$.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[$.header]=$.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 $=await this.collectAcpElicitationField(X,J);if($.cancelled)return{approved:!1,reason:$.reason,elicitation:{action:"cancel"}};if($.value!==void 0)W[X.name]=$.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(($,Z)=>({id:`option:${Z}`,label:$.label,value:$.value})),W=await this.requestElicitationChoice(z.title,[z.description,z.required?"Required":"Optional"].filter(Boolean).join(`
|
|
22
|
+
`),[...H.map(($)=>({id:$.id,label:$.label})),...!z.required?[{id:"skip",label:"Skip"}]:[]],J);if(W==="skip")return{cancelled:!1};let X=H.find(($)=>$.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(($)=>({optionId:$.id,name:$.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),Y()},Z=()=>$(()=>H(void 0));if(J.addEventListener("abort",Z,{once:!0}),J.aborted)Z();z.then((Y)=>$(()=>H(Y)),(Y)=>$(()=>W(Y)))})}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 O=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 O.info("[BladeAgent] Initializing ACP connection"),O.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"],$=X==="local"||X==="worktree"?X:void 0,Z=z._meta?.["blade/taskPrompt"],Y;try{let F=$?await gz.createSessionTask({sessionId:J,prompt:typeof Z==="string"&&Z.trim()?Z:"ACP task session",sourceProjectPath:W,isolation:$}):void 0,L=F?.metadata.projectPath??W;return O.info(`[BladeAgent] Creating new session: ${J}`),O.debug(`[BladeAgent] Session cwd: ${L}`),Y=new b(J,L,this.connection,this.clientCapabilities,{mcpServers:z.mcpServers,...F?.taskWorktree?{taskWorktree:F.taskWorktree}:{},...F?.metadata.taskIsolation?{taskIsolation:F.metadata.taskIsolation}:{}}),await Y.initialize(),this.assertNotDestroyed(),this.commitSession(J,Y,H),O.info(`[BladeAgent] Session ${J} created, scheduling available commands update`),Y.sendAvailableCommandsDelayed(),this.buildChildSessionResponse(J,F?.metadata,Y.getModelConfiguration())}catch(F){throw H.cancel(),await Y?.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(),O.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 $=await this.runtimeResidency.forget(z,H);if(this.sessions.get(z)===H)this.sessions.delete(z);if(W&&!$&&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"}],$=[];if(H.length>0)$.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)$.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)$.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)$.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)$.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:$.length>0?$: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){O.info(`[BladeAgent] Cancel notification received for session: ${z.sessionId}`);let J=this.runtimeResidency.acquire(z.sessionId);if(J){O.info("[BladeAgent] Found session, calling session.cancel()");try{J.value.cancel()}finally{J.release()}}else O.warn(`[BladeAgent] Session not found for cancel: ${z.sessionId}`)}async setSessionMode(z){O.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")O.info(`[BladeAgent] Setting session model: ${z.value}`),await H.setModel(z.value);else if(z.configId==="reasoning_effort"&&"value"in z&&Cz(z.value))O.info(`[BladeAgent] Setting reasoning effort: ${z.value}`),await H.setReasoningEffort(z.value);else if(z.configId==="service_tier"&&"value"in z&&Sz(z.value))O.info(`[BladeAgent] Setting service tier: ${z.value}`),await H.setServiceTier(z.value);else if(z.configId==="response_verbosity"&&"value"in z&&hz(z.value))O.info(`[BladeAgent] Setting response verbosity: ${z.value}`),await H.setResponseVerbosity(z.value);else if(z.configId==="communication_style"&&"value"in z&&fz(z.value))O.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),$=mz(async()=>{await W?.destroy()});try{await X.closed}finally{$(),await W?.destroy()}}export{eH as runAcpIntegration};
|