blade-code 0.10.162 → 0.10.163
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-j9fdpvq0.js → chunk-158zwy3s.js} +1 -1
- package/dist/{chunk-hjrc4jdm.js → chunk-1ak6q7tt.js} +1 -1
- package/dist/chunk-1vxc7qxm.js +1 -0
- package/dist/{chunk-n7kwrvvw.js → chunk-1zgqrzfv.js} +1 -1
- package/dist/{chunk-f194ct93.js → chunk-2b1f5rwp.js} +1 -1
- package/dist/{chunk-yk62xvqm.js → chunk-2w6hbep9.js} +1 -1
- package/dist/{chunk-psm2d7pr.js → chunk-30tn6r05.js} +1 -1
- package/dist/{chunk-qq8h5eag.js → chunk-4t5hhrwt.js} +1 -1
- package/dist/{chunk-4k7gvnth.js → chunk-60ggtcfe.js} +1 -1
- package/dist/{chunk-hs0fatm3.js → chunk-682e101s.js} +1 -1
- package/dist/{chunk-92ck72sg.js → chunk-73gr1w7q.js} +1 -1
- package/dist/{chunk-56ma2n3p.js → chunk-76vtq1we.js} +1 -1
- package/dist/{chunk-y54mge74.js → chunk-7eexcvd6.js} +1 -1
- package/dist/{chunk-3aavhxe8.js → chunk-8bb421cb.js} +1 -1
- package/dist/chunk-93b8x5s0.js +1 -0
- package/dist/{chunk-ajtwwg2b.js → chunk-bztcgtpv.js} +1 -1
- package/dist/{chunk-6c5z2b5s.js → chunk-dj17zw92.js} +1 -1
- package/dist/{chunk-3xffezpc.js → chunk-f3n2hyxk.js} +1 -1
- package/dist/{chunk-wbr9fc4k.js → chunk-gsrx4w3v.js} +1 -1
- package/dist/{chunk-nj2bggcj.js → chunk-h0d4154v.js} +1 -1
- package/dist/{chunk-9f6nyfcs.js → chunk-hm1tp7jr.js} +1 -1
- package/dist/{chunk-9cb1hv2z.js → chunk-jaxpzavy.js} +1 -1
- package/dist/{chunk-msx7ecb2.js → chunk-jzvnjrj9.js} +2 -2
- package/dist/{chunk-t89f4way.js → chunk-mgw83hkv.js} +1 -1
- package/dist/{chunk-0aya8d61.js → chunk-qfpgms8w.js} +1 -1
- package/dist/{chunk-sspk1ah8.js → chunk-qskr05jh.js} +1 -1
- package/dist/{chunk-mg03ydep.js → chunk-qyj9khsj.js} +1 -1
- package/dist/{chunk-cvwcrr4h.js → chunk-tmxh9cds.js} +3 -3
- package/dist/{chunk-vh5hxd2w.js → chunk-wwsax8zw.js} +1 -1
- package/dist/{chunk-46t79ek8.js → chunk-wysmzs8h.js} +1 -1
- package/dist/{chunk-zb6mn0dz.js → chunk-wysx2q8e.js} +1 -1
- package/dist/{chunk-sz1jw89z.js → chunk-xabj78vm.js} +1 -1
- package/dist/{chunk-syq7j5b0.js → chunk-xeyhp68m.js} +1 -1
- package/dist/{chunk-rjbneaq0.js → chunk-xhg70jby.js} +1 -1
- package/dist/{chunk-abc5bzqn.js → chunk-xp4zfqxh.js} +1 -1
- package/dist/{chunk-6sedqj8r.js → chunk-ydfqzfy5.js} +1 -1
- package/dist/{chunk-za0frk62.js → chunk-zew66zhx.js} +1 -1
- package/dist/{chunk-qjbn97e2.js → chunk-zgtned44.js} +1 -1
- package/package.json +1 -1
- package/dist/chunk-azn3qphf.js +0 -1
- package/dist/chunk-e6tz8qrg.js +0 -1
package/dist/blade.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{zf as W}from"./chunk-
|
|
2
|
+
import{zf as W}from"./chunk-zgtned44.js";import{Cf as F,Df as M}from"./chunk-jj4ggb04.js";import"./chunk-xeyhp68m.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import"./chunk-2b1f5rwp.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{aj as N,bj as B}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Cj as T}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import{Mk as J}from"./chunk-eg3ms291.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-wysx2q8e.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-76vtq1we.js");K(U.map((Z)=>p.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-66wk3exc.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-682e101s.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-30tn6r05.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-73gr1w7q.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-93b8x5s0.js"),import("./chunk-dj17zw92.js"),import("./chunk-kvp523gt.js"),import("./chunk-jzvnjrj9.js"),import("./chunk-xmymx75h.js"),import("./chunk-ydfqzfy5.js"),import("./chunk-0tzecdv3.js"),import("./chunk-a6wkam4s.js"),import("./chunk-xp4zfqxh.js"),import("./chunk-xabj78vm.js"),import("./chunk-1zgqrzfv.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-1vxc7qxm.js").then(({checkVersionOnStartup:v})=>v()),[{render:w},{createElement:j},{AppWrapper:C}]=await Promise.all([import("ink"),import("react"),import("./chunk-4t5hhrwt.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 +1 @@
|
|
|
1
|
-
import{$b as h,Qb as a,Rb as b,Tb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,kc as l,lc as m,mc as n,nc as o,pc as p,qc as q,rc as r}from"./chunk-
|
|
1
|
+
import{$b as h,Qb as a,Rb as b,Tb as c,Xb as d,Yb as e,Zb as f,_b as g,ac as i,bc as j,cc as k,kc as l,lc as m,mc as n,nc as o,pc as p,qc as q,rc as r}from"./chunk-7eexcvd6.js";import"./chunk-zzvs471p.js";import"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-50vwafn5.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Ai as H,Bi as I}from"./chunk-
|
|
1
|
+
import{Ai as H,Bi as I}from"./chunk-2b1f5rwp.js";import{Mutex as J}from"async-mutex";class B extends Error{limit;resource="resident_runtimes";retryable=!0;constructor(b){super("Session runtime capacity is full");this.limit=b;this.name="SessionRuntimeCapacityError"}}class D extends Error{constructor(){super("Session runtime residency is closed");this.name="SessionRuntimeResidencyClosedError"}}class A extends Error{constructor(b){super(`Session runtime residency already owns key: ${b}`);this.name="SessionRuntimeResidencyConflictError"}}class K{maxResident;idleMs;now;residents=new Map;reservations=new Map;operations=new J;nextGeneration=1;closed=!1;constructor(b){if(!H(b.maxResident))throw Error("Invalid max resident Session Runtime limit");if(!I(b.idleMs))throw Error("Invalid Session Runtime idle timeout");this.maxResident=b.maxResident,this.idleMs=b.idleMs,this.now=b.now??Date.now}acquire(b){let j=this.residents.get(b);if(!j||j.poisoned)return;return j.pins++,j.lastUsedAt=this.now(),this.createLease(j)}owns(b,j){let q=this.residents.get(b);return Boolean(q&&(j===void 0||q.value===j))}async reserve(b,j){if(!b.trim())throw Error("Session runtime residency key must not be blank");return this.operations.runExclusive(async()=>{if(this.closed)throw new D;if(this.residents.has(b)||this.reservations.has(b))throw new A(b);while(this.retainedCount()>=this.maxResident){if(!j.allowEviction)throw new B(this.maxResident);let z=this.oldestEvictableWebResident();if(!z)throw new B(this.maxResident);await this.disposeResident(z,!0)}let q={generation:this.allocateGeneration(),surface:j.surface};return this.reservations.set(b,q),this.createReservation(b,q)})}async remove(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j)return!1;if(q.pins>0)return!1;return await this.disposeResident(q,!0),!0})}async forget(b,j){return this.operations.runExclusive(async()=>{let q=this.residents.get(b);if(!q||j!==void 0&&q.value!==j||q.pins>0)return!1;return this.residents.delete(b),!0})}async sweepIdle(){return this.operations.runExclusive(async()=>{if(this.closed)return 0;let b=0;while(!0){let j=this.oldestIdleWebResident();if(!j)return b;await this.disposeResident(j,!0),b++}})}async disposeAll(){await this.operations.runExclusive(async()=>{this.closed=!0,this.reservations.clear();let b;for(let j of[...this.residents.values()])try{await this.disposeResident(j,!1)}catch(q){b??=q}if(this.residents.clear(),b!==void 0)throw b})}getStats(){let b=0;for(let j of this.residents.values())if(j.pins>0)b++;return{resident:this.residents.size,reserved:this.reservations.size,pinned:b,maxResident:this.maxResident}}retainedCount(){return this.residents.size+this.reservations.size}allocateGeneration(){let b=this.nextGeneration;return this.nextGeneration=this.nextGeneration===Number.MAX_SAFE_INTEGER?1:this.nextGeneration+1,b}createReservation(b,j){let q=!1;return{commit:(z)=>{if(q)throw new A(b);if(z.key!==b||z.surface!==j.surface||this.reservations.get(b)!==j||this.closed)throw this.reservations.delete(b),q=!0,this.closed?new D:new A(b);this.reservations.delete(b);let G={...z,generation:j.generation,pins:1,lastUsedAt:this.now(),poisoned:!1};return this.residents.set(b,G),q=!0,this.createLease(G)},cancel:()=>{if(q)return;if(this.reservations.get(b)===j)this.reservations.delete(b);q=!0}}}createLease(b){let j=!1;return{value:b.value,release:()=>{if(j)return;j=!0;let q=this.residents.get(b.key);if(q!==b||q.generation!==b.generation)return;q.pins=Math.max(0,q.pins-1),q.lastUsedAt=this.now()}}}oldestEvictableWebResident(){return this.sortedWebResidents().find((b)=>this.canEvict(b))}oldestIdleWebResident(){let b=this.now();return this.sortedWebResidents().find((j)=>b-j.lastUsedAt>=this.idleMs&&this.canEvict(j))}sortedWebResidents(){return[...this.residents.values()].filter((b)=>b.surface==="web").sort((b,j)=>b.lastUsedAt-j.lastUsedAt||b.generation-j.generation)}canEvict(b){if(b.pins>0||b.poisoned)return!1;try{return b.canEvict()}catch{return!1}}async disposeResident(b,j){if(this.residents.get(b.key)!==b)return;this.residents.delete(b.key);try{await b.dispose()}catch(q){if(j&&!this.closed&&!this.residents.has(b.key))b.lastUsedAt=this.now(),b.poisoned=!0,this.residents.set(b.key,b);throw q}}}
|
|
2
2
|
export{B as v,K as w};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{k as a,l as b,m as c,n as d,o as e}from"./chunk-wwsax8zw.js";import"./chunk-xhg70jby.js";import"./chunk-eg3ms291.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{a as T,b as W,c as X,d as Y}from"./chunk-
|
|
1
|
+
import{a as T,b as W,c as X,d as Y}from"./chunk-qfpgms8w.js";import"./chunk-gsrx4w3v.js";import"./chunk-zj1g4nbq.js";import"./chunk-1ak6q7tt.js";import"./chunk-jaxpzavy.js";import"./chunk-bztcgtpv.js";import"./chunk-tmxh9cds.js";import"./chunk-g01mth5d.js";import"./chunk-h0d4154v.js";import"./chunk-30x3mcsb.js";import"./chunk-7eexcvd6.js";import"./chunk-zzvs471p.js";import"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as R}from"./chunk-zgtned44.js";import"./chunk-jj4ggb04.js";import{Uf as Q}from"./chunk-xeyhp68m.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-mgw83hkv.js";import"./chunk-qyj9khsj.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import"./chunk-2b1f5rwp.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{Xj as M}from"./chunk-xhg70jby.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import m from"chalk";import K from"open";var A=`
|
|
2
2
|
____ _ _
|
|
3
3
|
| __ )| | __ _ __| | ___
|
|
4
4
|
| _ \\| |/ _\` |/ _\` |/ _ \\
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{Ui as K}from"./chunk-kv458q06.js";import{Vi as wt,Wi as ft}from"./chunk-5v0jcyea.js";import{bj as I}from"./chunk-2f8d0km4.js";import{cj as tt,dj as Dt,ej as Bt,ij as Gt,jj as et,kj as Kt,lj as Ht,mj as Yt,nj as cn,oj as Ft,pj as qt,qj as Mt,rj as Vt,sj as Jt,tj as _t,uj as Qt,vj as jt,wj as Wt,xj as Zt,yj as kt,zj as yt}from"./chunk-ddvdc2p0.js";import{Dj as Un,Fj as bn,Gj as _n,Hj as T}from"./chunk-2mk914vk.js";import{Mj as zt,Pj as v}from"./chunk-j8hbddjp.js";import{Xj as xn,Yj as Cn}from"./chunk-
|
|
1
|
+
import{Ui as K}from"./chunk-kv458q06.js";import{Vi as wt,Wi as ft}from"./chunk-5v0jcyea.js";import{bj as I}from"./chunk-2f8d0km4.js";import{cj as tt,dj as Dt,ej as Bt,ij as Gt,jj as et,kj as Kt,lj as Ht,mj as Yt,nj as cn,oj as Ft,pj as qt,qj as Mt,rj as Vt,sj as Jt,tj as _t,uj as Qt,vj as jt,wj as Wt,xj as Zt,yj as kt,zj as yt}from"./chunk-ddvdc2p0.js";import{Dj as Un,Fj as bn,Gj as _n,Hj as T}from"./chunk-2mk914vk.js";import{Mj as zt,Pj as v}from"./chunk-j8hbddjp.js";import{Xj as xn,Yj as Cn}from"./chunk-xhg70jby.js";import{ck as a}from"./chunk-rvs364rz.js";import{fk as Ln}from"./chunk-4wx5sya5.js";var lt=/^[\x21\x23-\x5b\x5d-\x7e]+$/;function vt(n){return n==="127.0.0.1"||n==="[::1]"||n.toLowerCase()==="localhost"}function p(n,t="MCP OAuth URL"){let e=new URL(n);if(e.username||e.password)throw Error(`${t} must not contain credentials`);if(e.protocol!=="https:"&&!(e.protocol==="http:"&&vt(e.hostname)))throw Error(`${t} requires HTTPS; HTTP is allowed only for loopback servers`);return e}var B=async(n,t)=>{p(n,"MCP OAuth request URL");let e=await fetch(n,{...t,redirect:"manual"});if(e.status>=300&&e.status<400)throw await e.body?.cancel(),Error("MCP OAuth network requests must not follow redirects");return e};function nn(n){let t=n.oauth;if(!t)return;let e=t;for(let E of["clientSecret","authorizationUrl","tokenUrl","redirectUri"])if(e[E]!==void 0)throw Error(`MCP OAuth "${E}" 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(p(n.url,"MCP OAuth server URL"),Object.keys(n.headers??{}).find((E)=>E.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((E)=>E.trim());if(S){if(S.length>32)throw Error("MCP OAuth supports at most 32 scopes");if(S.some((E)=>!E||E.length>128||!lt.test(E)))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 Sn}from"node:crypto";import Te from"node:http";import{auth as dn}from"@modelcontextprotocol/sdk/client/auth.js";import se from"open";import{createHash as ne,randomUUID as te}from"node:crypto";import{constants as tn,promises as b}from"node:fs";import en from"node:path";import ee from"write-file-atomic";var Nn=1,Me=1048576,_e=5000,re=50,Se=/^[a-f0-9]{64}$/,Ee=T.Object({client_id:T.String({minLength:1,maxLength:4096})},{additionalProperties:!0}),ue=T.Object({access_token:T.String({minLength:1,maxLength:65536}),token_type:T.String({minLength:1,maxLength:64}),expires_in:T.Optional(T.Number({minimum:0})),refresh_token:T.Optional(T.String({minLength:1,maxLength:65536})),scope:T.Optional(T.String({maxLength:16384})),id_token:T.Optional(T.String({minLength:1,maxLength:262144}))},{additionalProperties:!1}),oe=T.Unsafe({type:"object",properties:{authorizationServerUrl:T.String({format:"uri"}),resourceMetadataUrl:T.Optional(T.String({format:"uri"})),resourceMetadata:T.Optional(T.Unknown()),authorizationServerMetadata:T.Optional(T.Unknown())},required:["authorizationServerUrl"],additionalProperties:!1}),an=T.Object({serverUrl:T.String({format:"uri"}),clientId:T.Optional(T.String({minLength:1,maxLength:4096})),clientInformation:T.Optional(Ee),tokens:T.Optional(ue),tokenExpiresAt:T.Optional(T.Number({minimum:0})),discoveryState:T.Optional(oe),updatedAt:T.String({format:"date-time"})},{additionalProperties:!1}),gn=T.Object({version:T.Literal(Nn),credentials:T.Record(T.String(),an)},{additionalProperties:!1});function G(n,t){return n instanceof Error&&"code"in n&&n.code===t}function me(n){if(!Number.isInteger(n)||n<=0)return!1;try{return process.kill(n,0),!0}catch(t){return G(t,"EPERM")}}function Mn(n){return structuredClone(n)}function In(n){if(Object.keys(n.credentials).some((t)=>!Se.test(t)))throw Error("MCP OAuth credential store contains an invalid identity")}function H(n){let t=new URL(n);return t.hash="",t.toString()}function rn(n,t,e=[]){return ne("sha256").update(JSON.stringify({serverUrl:H(n),clientId:t?.trim()||null,scopes:[...e].sort()})).digest("hex")}class f{static locks=new K;stateRoot;tokenFilePath;constructor(n=Ln()){this.stateRoot=en.join(n,"mcp"),this.tokenFilePath=en.join(this.stateRoot,"oauth-credentials.json")}static coordinationStatsForTests(){return this.locks.getStats()}async getCredential(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let e=(await this.readStore()).credentials[n];return e?Mn(e):null})}async updateCredential(n,t){return this.runMutation(async(e)=>{let M=e.credentials[n],_=await t(M?Mn(M):null);if(_)e.credentials[n]=_n(an,_);else delete e.credentials[n];return _?Mn(e.credentials[n]):null})}async deleteCredential(n){await this.updateCredential(n,()=>null)}async listCredentialIds(){return f.locks.runExclusive(this.tokenFilePath,async()=>Object.keys((await this.readStore()).credentials).sort())}async runMutation(n){return f.locks.runExclusive(this.tokenFilePath,async()=>{let t=await this.acquireStoreLock();try{let e=await this.readStore(),M=await n(e);return await this.writeStore(e),M}finally{await t()}})}async ensureStateRoot(){await b.mkdir(this.stateRoot,{recursive:!0,mode:448});let n=await b.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 b.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>Me)throw Error("MCP OAuth credential store exceeds the 1 MiB limit");let t=JSON.parse(await b.readFile(this.tokenFilePath,"utf8")),e=bn(gn,t);if(!e.success)throw Error("MCP OAuth credential store has an invalid schema");return In(e.data),e.data}catch(n){if(G(n,"ENOENT"))return{version:Nn,credentials:{}};throw n}}async writeStore(n){await this.ensureStateRoot();let t=_n(gn,n);In(t),await ee(this.tokenFilePath,`${JSON.stringify(t,null,2)}
|
|
2
2
|
`,{mode:384,encoding:"utf8"}),await b.chmod(this.tokenFilePath,384)}async acquireStoreLock(){await this.ensureStateRoot();let n=en.join(this.stateRoot,".oauth-credentials.lock"),t=te(),e=Date.now()+_e;while(Date.now()<e)try{let M=await b.open(n,tn.O_CREAT|tn.O_EXCL|tn.O_WRONLY,384);return await M.writeFile(`${JSON.stringify({version:1,pid:process.pid,token:t,createdAt:new Date().toISOString()})}
|
|
3
3
|
`,"utf8"),await M.close(),async()=>{try{if(JSON.parse(await b.readFile(n,"utf8")).token===t)await b.unlink(n)}catch(_){if(!G(_,"ENOENT"))throw _}}}catch(M){if(!G(M,"EEXIST"))throw M;await this.removeDeadLock(n),await new Promise((_)=>setTimeout(_,re))}throw Error("MCP OAuth credential store is busy; retry the operation")}async removeDeadLock(n){let t=await b.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 e=JSON.parse(await b.readFile(n,"utf8"));if(typeof e.pid!=="number"||!Number.isInteger(e.pid)||e.pid<=0)throw Error("MCP OAuth credential lock owner is invalid");if(!me(e.pid))await b.unlink(n)}}var wn="127.0.0.1",fn=7777,Pn="/oauth/callback",Ae=300000;class En 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 hn extends Error{constructor(n){super(`MCP OAuth credentials are unavailable in this runtime for server "${n}"`);this.name="McpOAuthUnavailableError"}}function ce(n){let t=n?"Authentication complete":"Authentication failed";return`<!doctype html>
|
|
4
4
|
<html lang="en">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{Xj as d,Zj as h}from"./chunk-
|
|
1
|
+
import{Xj as d,Zj as h}from"./chunk-xhg70jby.js";var q={debug:{alias:"d",type:"string",describe:'Enable debug mode with optional category filtering (e.g., "agent,ui" or "!chat,!loop")',group:"Debug Options:"},model:{type:"string",describe:"Override the current run model using a model config ID (TUI / print / headless)",group:"AI Options:"},print:{alias:"p",type:"boolean",describe:"Print response and exit (useful for pipes)",group:"Output Options:"},headless:{type:"boolean",describe:"Run full agent loop without Ink UI and print all events to the terminal",group:"Output Options:"},"output-format":{alias:["outputFormat"],type:"string",choices:["text","json","stream-json","jsonl"],default:"text",describe:"Output format: --print supports text|json|stream-json; --headless supports text|jsonl",group:"Output Options:"},"json-schema":{alias:["jsonSchema"],type:"string",describe:"Inline JSON Schema for the turn-scoped structured final response",group:"Output Options:"},"output-schema":{alias:["outputSchema"],type:"string",describe:"Path to a JSON Schema file for the structured final response",group:"Output Options:"},"include-partial-messages":{alias:["includePartialMessages"],type:"boolean",describe:"Include partial message chunks as they arrive",group:"Output Options:"},"input-format":{alias:["inputFormat"],type:"string",choices:["text","stream-json"],default:"text",describe:"Input format",group:"Input Options:"},"replay-user-messages":{alias:["replayUserMessages"],type:"boolean",describe:"Re-emit user messages from stdin",group:"Input Options:"},"allowed-tools":{alias:["allowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to allow",group:"Security Options:"},"disallowed-tools":{alias:["disallowedTools"],type:"array",string:!0,describe:"Comma or space-separated list of tool names to deny",group:"Security Options:"},"mcp-config":{alias:["mcpConfig"],type:"array",string:!0,describe:"Load MCP servers from JSON files or strings",group:"MCP Options:"},"system-prompt":{alias:["systemPrompt"],type:"string",describe:"System prompt to use for the session (replaces default)",group:"AI Options:"},"append-system-prompt":{alias:["appendSystemPrompt"],type:"string",describe:"Append a system prompt to the default system prompt",group:"AI Options:"},"max-turns":{alias:["maxTurns"],type:"number",describe:"Maximum conversation turns (-1: unlimited, 0: disable chat, N>0: limit to N turns)",group:"AI Options:",default:void 0},"max-concurrent-tasks":{alias:["maxConcurrentTasks"],type:"number",describe:"Maximum top-level tasks running concurrently in this process",group:"AI Options:",default:void 0},"max-queued-tasks":{alias:["maxQueuedTasks"],type:"number",describe:"Maximum top-level tasks waiting for an admission slot",group:"AI Options:",default:void 0},"max-queued-task-bytes":{alias:["maxQueuedTaskBytes"],type:"number",describe:"Maximum retained bytes across queued top-level tasks",group:"AI Options:",default:void 0},"max-resident-session-runtimes":{alias:["maxResidentSessionRuntimes"],type:"number",describe:"Maximum initialized Session runtimes resident in this process",group:"AI Options:",default:void 0},"session-runtime-idle-ms":{alias:["sessionRuntimeIdleMs"],type:"number",describe:"Idle time before an evictable Web Session runtime is evicted",group:"AI Options:",default:void 0},"max-resident-session-projections":{alias:["maxResidentSessionProjections"],type:"number",describe:"Maximum resident Session projections retained in this process",group:"AI Options:",default:void 0},"session-projection-idle-ms":{alias:["sessionProjectionIdleMs"],type:"number",describe:"Idle time before an evictable Session projection is evicted",group:"AI Options:",default:void 0},"permission-mode":{alias:["permissionMode"],type:"string",choices:["default","autoEdit","yolo","plan"],describe:"Permission mode (default: ask for non-read tools, autoEdit: auto-approve edits, yolo: auto-approve all, plan: reserved)",group:"Security Options:"},yolo:{type:"boolean",describe:"Auto-approve all tools (shortcut for --permission-mode=yolo)",group:"Security Options:"},"trust-workspace":{alias:["trustWorkspace"],type:"boolean",describe:"Trust the current workspace before loading project models, MCP, LSP, permissions, or plugins",group:"Security Options:"},continue:{alias:"c",type:"boolean",describe:"Continue the most recent conversation",group:"Session Options:"},resume:{alias:"r",describe:"Resume a conversation - provide a session ID or interactively select a conversation to resume",group:"Session Options:",coerce:(b)=>{if(b===void 0||b===!0||b==="")return"true";return String(b)}},"fork-session":{alias:["forkSession"],type:"boolean",describe:"Create a new session ID when resuming",group:"Session Options:"},settings:{type:"string",describe:"Path to a settings JSON file or JSON string",group:"Configuration:"},"add-dir":{alias:["addDir"],type:"array",string:!0,describe:"Additional directories to allow tool access to",group:"Security Options:"},ide:{type:"boolean",describe:"Automatically connect to IDE on startup",group:"Integration:"},acp:{type:"boolean",describe:"Run in ACP (Agent Client Protocol) mode for IDE integration",group:"Integration:"},"strict-mcp-config":{alias:["strictMcpConfig"],type:"boolean",describe:"Only use MCP servers from --mcp-config",group:"MCP Options:"},"session-id":{alias:["sessionId"],type:"string",describe:"Use a specific session ID for the conversation",group:"Session Options:"},agents:{type:"string",describe:"JSON object defining custom agents",group:"AI Options:"},"setting-sources":{alias:["settingSources"],type:"string",describe:"Comma-separated list of setting sources to load",group:"Configuration:"},"plugin-dir":{alias:["pluginDir"],type:"array",string:!0,describe:"Load plugins from specified directories",group:"Plugin Options:"}},w={scriptName:"blade",usage:"$0 [command] [options]",description:h(),version:d(),locale:"en",showHelpOnFail:!0,demandCommand:!1,recommendCommands:!0,strict:!1};
|
|
2
2
|
export{q as rf,w as sf};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-
|
|
1
|
+
import{p as c,q as v,r as d,s as m,t as l,u as a}from"./chunk-8bb421cb.js";import{da as O,ka as S}from"./chunk-tmxh9cds.js";import"./chunk-g01mth5d.js";import"./chunk-h0d4154v.js";import"./chunk-30x3mcsb.js";import{Zb as M,hc as E}from"./chunk-7eexcvd6.js";import"./chunk-zzvs471p.js";import{he as f}from"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import{Me as h}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as I}from"./chunk-2w6hbep9.js";import{tf as y,uf as R,vf as g}from"./chunk-wysmzs8h.js";import{wf as C}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Tf as w}from"./chunk-xeyhp68m.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-mgw83hkv.js";import"./chunk-qyj9khsj.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import"./chunk-2b1f5rwp.js";import{Ti as A}from"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import{bj as P}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import s from"yargs";import{hideBin as e}from"yargs/helpers";var i=new Set(Object.values(A));function t(j){if(j&&i.has(j))return j;return}function z(j){if(j.options.outputFormat==="json")j.io.stdout.write(`${JSON.stringify({response:j.response,...j.structuredOutput?{structured_output:j.structuredOutput,output_schema_digest:j.structuredOutputSchemaDigest}:{},input:j.requestInput,model:j.options.model,timestamp:new Date().toISOString()},null,2)}
|
|
2
2
|
`);else if(j.options.outputFormat==="stream-json")j.io.stdout.write(`${JSON.stringify(j.structuredOutput?{type:"structured_output",output:j.structuredOutput,schema_digest:j.structuredOutputSchemaDigest}:{type:"response",content:j.response})}
|
|
3
3
|
`);else j.io.stdout.write(`${j.response}
|
|
4
4
|
`)}function n(j){return j.command("* [message]","Print response and exit (useful for pipes)",(B)=>B.positional("message",{describe:"Message to process",type:"string"}).option("p",{alias:"print",describe:"Print response and exit (useful for pipes)",type:"boolean"}).option("output-format",{describe:'Output format: "text", "json", "stream-json"',type:"string",default:"text"}).option("include-partial-messages",{describe:"Include partial message chunks as they arrive",type:"boolean"}).option("input-format",{describe:'Input format: "text", "stream-json"',type:"string",default:"text"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("model",{describe:"Model for the current session",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}),async(B)=>{if(!B.p)return;let q=await o(B);process.exit(q)})}async function o(j,B=process){let q;try{await c();let D=j.forkSession!==!0&&(j.continue===!0||typeof j.resume==="string"&&j.resume.length>0)?await d({message:j.message,_:j._}):await v({message:j.message,_:j._,defaultMessage:"Hello"}),K=D===void 0,T=K?{mode:"agent",content:""}:await m(D);if(T.mode==="output"){if(T.content)B.stdout.write(`${T.content}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{e as $X,f as JX,h as S$,i as M4}from"./chunk-wbr9fc4k.js";import{l as eX,m as $Z,n as JZ}from"./chunk-vh5hxd2w.js";import{A as q4,y as A9,z as b9}from"./chunk-9cb1hv2z.js";import{Aa as XY,Ca as ZY,Ea as uY,I as cY,M as WZ,O as h6,P as C6,Q as vY,W as wY,X as PY,_ as AY,da as r$,fa as y9,ga as I9,ia as bY,ka as U8,la as LX,ma as BX,pa as wX,qa as PX,ua as lJ,va as B3,xa as H3,ya as F3,za as HZ}from"./chunk-cvwcrr4h.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-nj2bggcj.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-y54mge74.js";import{sc as _8}from"./chunk-zzvs471p.js";import{Cd as zY,Md as P9,Nd as E2,Rd as C9,Wd as R9,Yd as t8,ee as G8,he as a0}from"./chunk-za0frk62.js";import"./chunk-53fc0yrq.js";import{Le as D9,Me as w6,Ne as f9}from"./chunk-y5wngtz0.js";import{if as e9,jf as G4}from"./chunk-w33zjw8m.js";import{wf as tX}from"./chunk-nheny8xp.js";import{Af as J1,xf as O8,yf as _4}from"./chunk-qjbn97e2.js";import"./chunk-jj4ggb04.js";import{Ef as C2,Ff as L$,Gf as r1,Hf as UJ,If as o8,Jf as M9,Kf as t3,Lf as RJ,Mf as r5,Nf as s3,Of as f2,Pf as m0,Qf as _Z,Rf as B$,Sf as nX,Tf as a4,Uf as z8,Xf as s9,cg as z$}from"./chunk-syq7j5b0.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import{ug as yJ}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-t89f4way.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-mg03ydep.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as qJ,zh as E$}from"./chunk-sspk1ah8.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-f194ct93.js";import{Ui as h9}from"./chunk-kv458q06.js";import{Vi as h2,Wi as e8,Yi as _J}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as KZ,Dj as O1}from"./chunk-2mk914vk.js";import{Lj as t5,Mj as s5,Pj as T1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as x5}from"./chunk-rjbneaq0.js";import{ck as uJ}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as Q8,zk as t9}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Gz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import iX from"ansi-escapes";import{Box as h1,useStdout as eK}from"ink";import{useEffect as $1,useMemo as $z,useRef as y2,useState as oX}from"react";import{useShallow as BZ}from"zustand/react/shallow";import{useStore as LZ}from"zustand";function q0($){return LZ(f2,$)}var wZ=[],v2=()=>q0(($)=>$.session.sessionId),_1=()=>q0(($)=>$.session.workspaceRoot),f8=()=>q0(($)=>$.session.messages),rJ=()=>q0(($)=>$.session.clearCount),aJ=()=>q0(($)=>$.session.isCompacting),iJ=()=>q0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>q0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var v8=()=>q0(($)=>$.session.providerRecovery),nJ=()=>q0(($)=>$.session.turnActivity),tJ=()=>q0(($)=>$.session.actionStationarity),c1=()=>q0(($)=>$.session.actions),sJ=()=>q0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),eJ=()=>q0(($)=>$.app.initializationStatus),$9=()=>q0(($)=>$.app.initializationError),V8=()=>q0(($)=>$.app.activeModal),J9=()=>q0(($)=>$.app.tasks),Y9=()=>q0(($)=>$.app.modelEditorTarget),X9=()=>q0(($)=>$.app.sessionSelectorData),Z9=()=>q0(($)=>$.app.sessionHistoryViewerData),Q9=()=>q0(($)=>$.app.taskAttentionStatus),j8=()=>q0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>q0(($)=>$.app.awaitingSecondCtrlC),u1=()=>q0(($)=>$.app.actions),E8=()=>q0(($)=>$.app.sideConversation),U9=()=>q0(($)=>$.app.teams),h8=()=>q0(($)=>$.app.initializationStatus==="ready"),K9=()=>q0(($)=>$.app.tasks.length>0),V2=()=>q0(($)=>$.config.config?.permissionMode||"default"),z9=()=>q0(($)=>$.config.config?.models??wZ),g8=()=>q0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>q0(($)=>$.config.config?.currentModelId),q9=()=>q0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>q0(($)=>{return L$.getTheme()}),_9=()=>q0(($)=>$.config.config?.codeTheme??"default"),Z$=()=>q0(($)=>$.focus.currentFocus),O9=()=>q0(($)=>$.focus.actions),j2=()=>q0(($)=>$.command.isProcessing),N9=()=>q0(($)=>$.command.actions),p8=()=>q0(($)=>$.app.followUpQueue),W9=()=>q0(($)=>$.app.followUpQueueMutation),H9=()=>q0(($)=>$.command.recoveredSteeringCount),x8=()=>q0(($)=>$.app.reasoningEffort!=="off"),c8=()=>q0(($)=>$.app.reasoningEffort),u8=()=>q0(($)=>$.app.serviceTier),d8=()=>q0(($)=>$.app.responseVerbosity),l8=()=>q0(($)=>$.app.communicationStyle),r8=()=>q0(($)=>$.session.currentThinkingContent),F9=()=>q0(($)=>$.session.thinkingExpanded),a8=()=>q0(($)=>$.session.currentStreamingMessageId),i8=()=>q0(BZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>q0(($)=>$.session.finalizingStreamingMessageId),B9=()=>q0(($)=>$.session.historyExpanded),w9=()=>q0(($)=>$.session.expandedMessageCount);import{randomUUID as _7}from"node:crypto";import{useMemoizedFn as Y1}from"ahooks";import{useEffect as d1,useMemo as WY,useRef as N4}from"react";function PZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q=await this.options.run(Y.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let G=this.wakeEpoch!==Z;if(this.clearEpisode(),G)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=E2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!PZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=b9({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),E2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class X8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function AZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let G=JSON.parse(Z.responseBody)?.error?.message;if(G){let U=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${G}${U}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function bZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function MZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=bZ($),Y=MZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=AZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as TZ,mkdirSync as CZ,writeFileSync as RZ}from"node:fs";import yZ from"node:os";import z6 from"node:path";var T9=null;function IZ(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(yZ.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function SZ($){if(T9===$)return;let J=z6.dirname($);CZ(J,{recursive:!0,mode:493}),RZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
1
|
+
import{e as $X,f as JX,h as S$,i as M4}from"./chunk-gsrx4w3v.js";import{l as eX,m as $Z,n as JZ}from"./chunk-wwsax8zw.js";import{A as q4,y as A9,z as b9}from"./chunk-jaxpzavy.js";import{Aa as XY,Ca as ZY,Ea as uY,I as cY,M as WZ,O as h6,P as C6,Q as vY,W as wY,X as PY,_ as AY,da as r$,fa as y9,ga as I9,ia as bY,ka as U8,la as LX,ma as BX,pa as wX,qa as PX,ua as lJ,va as B3,xa as H3,ya as F3,za as HZ}from"./chunk-tmxh9cds.js";import"./chunk-g01mth5d.js";import{Ma as E5,Na as h5,Oa as g5,Ra as NZ}from"./chunk-h0d4154v.js";import{Ta as BY}from"./chunk-30x3mcsb.js";import{Mb as FY,Nb as F4,Zb as LY,hc as P6}from"./chunk-7eexcvd6.js";import{sc as _8}from"./chunk-zzvs471p.js";import{Cd as zY,Md as P9,Nd as E2,Rd as C9,Wd as R9,Yd as t8,ee as G8,he as a0}from"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import{Le as D9,Me as w6,Ne as f9}from"./chunk-y5wngtz0.js";import{if as e9,jf as G4}from"./chunk-w33zjw8m.js";import{wf as tX}from"./chunk-nheny8xp.js";import{Af as J1,xf as O8,yf as _4}from"./chunk-zgtned44.js";import"./chunk-jj4ggb04.js";import{Ef as C2,Ff as L$,Gf as r1,Hf as UJ,If as o8,Jf as M9,Kf as t3,Lf as RJ,Mf as r5,Nf as s3,Of as f2,Pf as m0,Qf as _Z,Rf as B$,Sf as nX,Tf as a4,Uf as z8,Xf as s9,cg as z$}from"./chunk-xeyhp68m.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import{ug as yJ}from"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-mgw83hkv.js";import{Hg as H4,Jg as hX,Og as FX,Xg as OZ}from"./chunk-qyj9khsj.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import{xh as qJ,zh as E$}from"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import{Mi as zZ,Ri as HX,Si as qZ}from"./chunk-2b1f5rwp.js";import{Ui as h9}from"./chunk-kv458q06.js";import{Vi as h2,Wi as e8,Yi as _J}from"./chunk-5v0jcyea.js";import{bj as K$}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Aj as KZ,Dj as O1}from"./chunk-2mk914vk.js";import{Lj as t5,Mj as s5,Pj as T1}from"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import{$j as x5}from"./chunk-xhg70jby.js";import{ck as uJ}from"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as Q8,zk as t9}from"./chunk-4wx5sya5.js";import{Mk as Y4}from"./chunk-eg3ms291.js";import{useMemoizedFn as Q6}from"ahooks";import{useEffect as Gz,useState as G6}from"react";import{useMemoizedFn as i0}from"ahooks";import iX from"ansi-escapes";import{Box as h1,useStdout as eK}from"ink";import{useEffect as $1,useMemo as $z,useRef as y2,useState as oX}from"react";import{useShallow as BZ}from"zustand/react/shallow";import{useStore as LZ}from"zustand";function q0($){return LZ(f2,$)}var wZ=[],v2=()=>q0(($)=>$.session.sessionId),_1=()=>q0(($)=>$.session.workspaceRoot),f8=()=>q0(($)=>$.session.messages),rJ=()=>q0(($)=>$.session.clearCount),aJ=()=>q0(($)=>$.session.isCompacting),iJ=()=>q0(($)=>$.session.tokenUsage.estimatedCostUsd),oJ=()=>q0(($)=>{let{totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}=$.session.tokenUsage;return lJ({totalInputTokens:J,cacheReadTokens:Y,cacheWriteTokens:Z}).hitRate});var v8=()=>q0(($)=>$.session.providerRecovery),nJ=()=>q0(($)=>$.session.turnActivity),tJ=()=>q0(($)=>$.session.actionStationarity),c1=()=>q0(($)=>$.session.actions),sJ=()=>q0(($)=>{let{totalTokens:J,maxContextTokens:Y}=$.session.tokenUsage;if(Y<=0)return 100;let Z=Math.max(0,100-J/Y*100);return Math.round(Z)}),eJ=()=>q0(($)=>$.app.initializationStatus),$9=()=>q0(($)=>$.app.initializationError),V8=()=>q0(($)=>$.app.activeModal),J9=()=>q0(($)=>$.app.tasks),Y9=()=>q0(($)=>$.app.modelEditorTarget),X9=()=>q0(($)=>$.app.sessionSelectorData),Z9=()=>q0(($)=>$.app.sessionHistoryViewerData),Q9=()=>q0(($)=>$.app.taskAttentionStatus),j8=()=>q0(($)=>$.app.taskAttentionUnreadKeys),G9=()=>q0(($)=>$.app.awaitingSecondCtrlC),u1=()=>q0(($)=>$.app.actions),E8=()=>q0(($)=>$.app.sideConversation),U9=()=>q0(($)=>$.app.teams),h8=()=>q0(($)=>$.app.initializationStatus==="ready"),K9=()=>q0(($)=>$.app.tasks.length>0),V2=()=>q0(($)=>$.config.config?.permissionMode||"default"),z9=()=>q0(($)=>$.config.config?.models??wZ),g8=()=>q0(($)=>{let J=$.config.config;if(!J)return;let Y=J.currentModelId;return J.models.find((X)=>X.id===Y)??J.models[0]}),m8=()=>q0(($)=>$.config.config?.currentModelId),q9=()=>q0(($)=>$.config.config?.agentTeamsEnabled===!0),D0=()=>q0(($)=>{return L$.getTheme()}),_9=()=>q0(($)=>$.config.config?.codeTheme??"default"),Z$=()=>q0(($)=>$.focus.currentFocus),O9=()=>q0(($)=>$.focus.actions),j2=()=>q0(($)=>$.command.isProcessing),N9=()=>q0(($)=>$.command.actions),p8=()=>q0(($)=>$.app.followUpQueue),W9=()=>q0(($)=>$.app.followUpQueueMutation),H9=()=>q0(($)=>$.command.recoveredSteeringCount),x8=()=>q0(($)=>$.app.reasoningEffort!=="off"),c8=()=>q0(($)=>$.app.reasoningEffort),u8=()=>q0(($)=>$.app.serviceTier),d8=()=>q0(($)=>$.app.responseVerbosity),l8=()=>q0(($)=>$.app.communicationStyle),r8=()=>q0(($)=>$.session.currentThinkingContent),F9=()=>q0(($)=>$.session.thinkingExpanded),a8=()=>q0(($)=>$.session.currentStreamingMessageId),i8=()=>q0(BZ(($)=>({lines:$.session.currentStreamingLines,tail:$.session.currentStreamingTail,lineCount:$.session.currentStreamingLineCount,version:$.session.currentStreamingVersion}))),L9=()=>q0(($)=>$.session.finalizingStreamingMessageId),B9=()=>q0(($)=>$.session.historyExpanded),w9=()=>q0(($)=>$.session.expandedMessageCount);import{randomUUID as _7}from"node:crypto";import{useMemoizedFn as Y1}from"ahooks";import{useEffect as d1,useMemo as WY,useRef as N4}from"react";function PZ($,J){try{return $.code===J.code&&$.message===J.message&&$.retryable===J.retryable&&$.resource===J.resource}catch{return!1}}class K6{options;requested=!1;waitingForIdle=!1;disposed=!1;generation=0;wakeEpoch=0;idleEpoch=0;attempt=0;recoveryStartedAt=null;scheduledToken=null;activeAttemptToken=null;activeRunController=null;retryTimer=null;deadlineTimer=null;now;scheduleCallback;setTimerCallback;clearTimerCallback;constructor($){this.options=$;this.now=$.now??Date.now,this.scheduleCallback=$.scheduleMicrotask??queueMicrotask,this.setTimerCallback=$.setTimer??setTimeout,this.clearTimerCallback=$.clearTimer??clearTimeout}request(){if(this.disposed)return;if(this.wakeEpoch++,this.requested=!0,this.waitingForIdle||this.retryTimer)return;this.scheduleIfRunnable()}notifyIdle(){if(this.disposed)return;if(this.idleEpoch++,this.retryTimer)return;this.waitingForIdle=!1,this.scheduleIfRunnable()}dispose(){if(this.disposed)return;this.disposed=!0,this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.activeAttemptToken=null;let $=this.activeRunController;this.activeRunController=null,$?.abort("pending-resume-coordinator-disposed"),this.resetEpisodeBudget()}scheduleIfRunnable(){if(this.disposed||!this.requested||this.scheduledToken||this.activeAttemptToken||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let $=this.generation,J={};this.scheduledToken=J;try{this.scheduleCallback(()=>{if(this.disposed||$!==this.generation||this.scheduledToken!==J)return;this.scheduledToken=null,this.flush($).catch((Y)=>{this.handleUnexpectedFailure(Y,$)})})}catch(Y){this.handleUnexpectedFailure(Y,$)}}async flush($){if(this.disposed||$!==this.generation||this.activeAttemptToken||!this.requested||this.retryTimer||this.waitingForIdle)return;if(!this.options.canRun()){this.waitingForIdle=!0;return}let J={},Y=new AbortController,Z=this.wakeEpoch,X=this.idleEpoch;if(this.attempt++,this.recoveryStartedAt===null)this.recoveryStartedAt=this.now(),this.installDeadlineTimer($);this.activeAttemptToken=J,this.activeRunController=Y;let Q=await this.options.run(Y.signal);if(this.disposed||$!==this.generation||this.activeAttemptToken!==J)return;if(this.activeAttemptToken=null,this.activeRunController=null,Q.status==="completed"){let G=this.wakeEpoch!==Z;if(this.clearEpisode(),G)this.requested=!0,this.scheduleIfRunnable();return}if(Q.status==="deferred"){if(this.attempt--,this.attempt===0)this.clearOwnedTimer("deadline"),this.resetEpisodeBudget();if(this.requested=!0,this.idleEpoch!==X)this.waitingForIdle=!1,this.scheduleIfRunnable();else this.waitingForIdle=!0;return}this.handleFailure(Q,$)}handleFailure($,J){let Y=E2($.taskFailure),Z=this.options.sessionIdentity;if($.workKind!=="pending_input"||!$.evidence||!Z||!PZ($.taskFailure,$.evidence.taskFailure)){this.terminate("failed",this.attempt,Y);return}let X=b9({sessionIdentity:Z,failedAttempt:this.attempt,recoveryStartedAt:this.recoveryStartedAt??this.now(),now:this.now(),workStillPending:$.workStillPending,evidence:$.evidence});if(X.phase!=="retry_scheduled"){this.terminate(X.phase,this.attempt,Y);return}this.requested=!0,this.waitingForIdle=!1;let Q={},G=this.setTimerCallback(()=>{if(this.disposed||J!==this.generation||this.retryTimer?.token!==Q)return;this.retryTimer=null,this.scheduleIfRunnable()},X.delayMs);this.retryTimer={handle:G,token:Q},G.unref?.()}handleUnexpectedFailure($,J){if(this.disposed||J!==this.generation)return;this.terminate("failed",Math.max(1,this.attempt),E2($),"pending-resume-coordinator-failed")}installDeadlineTimer($){let J={},Y=this.setTimerCallback(()=>{if(this.disposed||$!==this.generation||this.deadlineTimer?.token!==J)return;this.deadlineTimer=null,this.terminate("exhausted",Math.max(1,this.attempt),P9("timeout"),"pending-resume-recovery-deadline-exceeded")},A9);this.deadlineTimer={handle:Y,token:J},Y.unref?.()}terminate($,J,Y,Z){let X=this.activeRunController;if(this.generation++,this.requested=!1,this.waitingForIdle=!1,this.scheduledToken=null,this.activeAttemptToken=null,this.activeRunController=null,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget(),Z)X?.abort(Z);try{this.options.onTerminalFailure?.({phase:$,attempt:J,taskFailure:Y})}catch{}}clearEpisode(){this.requested=!1,this.waitingForIdle=!1,this.clearOwnedTimer("retry"),this.clearOwnedTimer("deadline"),this.resetEpisodeBudget()}resetEpisodeBudget(){this.attempt=0,this.recoveryStartedAt=null}clearOwnedTimer($){let J=$==="retry"?this.retryTimer:this.deadlineTimer;if(!J)return;if($==="retry")this.retryTimer=null;else this.deadlineTimer=null;this.clearTimerCallback(J.handle)}}class X8{options;finalized=!1;constructor($){this.options=$}get isFinalized(){return this.finalized}acceptsDeltas(){return!this.finalized&&!this.options.signal.aborted}startTurn(){this.finalized=!1}finalize(){if(!this.acceptsDeltas())return!1;return this.finalized=!0,this.commit(this.options.streamingBuffer.drainPendingBuffers()),!0}abortAndFinalize($){if(this.finalized)return $(),!1;this.finalized=!0;let J=this.options.streamingBuffer.drainPendingBuffers();return $(),this.commit(J),!0}discard(){this.finalized=!0,this.options.streamingBuffer.resetStreamingBuffers(),this.options.discardStreamingMessage(),this.options.clearThinking()}commit($){let J=this.options.getStreamingMessageId();if(J){if($.extraContent)o8(J,$.extraContent);M9(J)}this.options.finalizeStreamingMessage($.extraContent,$.extraThinking)}}function AZ($){if(!($ instanceof Error))return"未知错误";let Z=$.lastError??$;if(Z.responseBody)try{let G=JSON.parse(Z.responseBody)?.error?.message;if(G){let U=Z.statusCode?` (HTTP ${Z.statusCode})`:"";return`${G}${U}`}}catch{}let X=$.message.match(/Last error:\s*(.+)$/);if(X)return X[1];return $.message}function bZ($){if(!($ instanceof Error))return!1;return $.name==="AbortError"||$.message.includes("aborted")}function MZ($){if(!($ instanceof Error))return!1;let J=$.message;return J.includes("can only concatenate str")||J.includes("image_url")||J.includes("multimodal")||J.includes("vision")||J.includes("does not support images")}function n8($){let J=bZ($),Y=MZ($),Z;if(Y)Z="当前模型不支持图片理解功能。请切换到支持视觉能力的模型(如 Claude 4.5、GPT-5.2、Gemini 3 Pro、Qwen3-VL-Plus 等)后重试。";else Z=AZ($);return{displayMessage:Z,isAbort:J,isVisionNotSupported:Y}}import{appendFileSync as TZ,mkdirSync as CZ,writeFileSync as RZ}from"node:fs";import yZ from"node:os";import z6 from"node:path";var T9=null;function IZ(){let $=process.env.BLADE_STORAGE_ROOT||z6.join(yZ.homedir(),".blade");return z6.join($,"logs","stream-debug.log")}function SZ($){if(T9===$)return;let J=z6.dirname($);CZ(J,{recursive:!0,mode:493}),RZ($,`=== Stream Debug Log Started: ${new Date().toISOString()} ===
|
|
2
2
|
`),T9=$}function q6($,J,Y){try{let Z=IZ();SZ(Z);let X=new Date().toISOString(),Q=Y?` | ${JSON.stringify(Y)}`:"",G=`[${X}] [${$}] ${J}${Q}
|
|
3
3
|
`;TZ(Z,G)}catch{}}var Z8=O1("UI");function _6($,J){if(J.state==="requires_attention"){let Y=J.reason==="interrupted_tool_call";$.addToolMessage("Turn recovery requires attention",{toolName:"Runtime Recovery",phase:"complete",summary:Y?"An interrupted tool may have partially completed":"A completed tool may already have changed external state",detail:`${J.turnId} · inspect workspace, processes, and external state before retrying`});return}$.addToolMessage(J.state==="completed"?"Recovered completed turn":"Resuming interrupted turn",{toolName:"Runtime Recovery",phase:"complete",summary:J.state==="completed"?"The durable final response was recovered":"No tool execution was recorded before interruption",detail:J.turnId})}function S9($,J){let Y=$.streamSession??new X8({signal:$.signal,streamingBuffer:$.streamingBuffer,getStreamingMessageId:$.getStreamingMessageId,finalizeStreamingMessage:$.sessionActions.finalizeStreamingMessage,discardStreamingMessage:$.sessionActions.discardStreamingMessage,clearThinking:()=>$.sessionActions.setCurrentThinkingContent(null)}),Z=(X)=>{for(let Q of X){if((Q.origin??"user")!=="user")continue;let G=$.commandActions.takeFollowUpPresentation(Q.id);if(G){$.sessionActions.addUserMessage(G.displayText);continue}if(!Q.recovered||Q.persisted)continue;let U=typeof Q.content==="string"?Q.content:Q.content.map((z)=>z.type==="text"?z.text:"[Image]").join(`
|
|
4
4
|
`);$.sessionActions.addUserMessage(U)}};return(X)=>{switch(X.kind){case"content_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;J.contentDeltaCount++,J.contentDeltaTotalLen+=X.delta.length,q6("loopEventHandler","onContentDelta",{callCount:J.contentDeltaCount,deltaLen:X.delta.length,totalLen:J.contentDeltaTotalLen}),$.streamingBuffer.batchAppendContent(X.delta);break;case"thinking_delta":if(X.delta.length>0)J.outputStarted=!0;if(!Y.acceptsDeltas())break;if($.thinkingModeEnabled)$.streamingBuffer.batchAppendThinking(X.delta);break;case"stream_end":{$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Z8.debug("[loopEventHandler] stream_end",{contentDeltaCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),q6("loopEventHandler","onStreamEnd",{contentDeltaCallCount:J.contentDeltaCount,contentDeltaTotalLen:J.contentDeltaTotalLen,streamFinalized:Y.isFinalized,signalAborted:$.signal.aborted}),Y.finalize();break}case"model_fallback":$.sessionActions.setProviderAdmission(null),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.discard();break;case"provider_admission":{let{kind:Q,...G}=X;$.sessionActions.setProviderAdmission(X.phase==="queued"?G:null);break}case"provider_circuit":{let{kind:Q,...G}=X;$.sessionActions.setProviderCircuit(X.phase==="closed"?null:G);break}case"provider_retry":{let{kind:Q,...G}=X;$.sessionActions.setProviderRetry(X.phase==="recovered"?null:G);break}case"provider_stall":{let{kind:Q,...G}=X;$.sessionActions.setProviderStall(X.phase==="detected"?G:null);break}case"provider_recovery":$.sessionActions.setProviderRecovery(X.recovery);break;case"action_stationarity":{let{kind:Q,...G}=X;$.sessionActions.setActionStationarity(X.phase==="recovered"?null:G);break}case"turn_recovery":{_6($.sessionActions,X.assessment);break}case"tool_start":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;if(Z8.debug("[loopEventHandler] tool_start",{toolName:Q.function.name,toolKind:X.toolKind}),["TaskCreate","TaskUpdate","TaskList"].includes(Q.function.name))break;try{let G=JSON.parse(Q.function.arguments),U=y9(Q.function.name,G);$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"start",summary:U,params:G})}catch(G){Z8.error("[loopEventHandler] onToolStart error:",G)}break}case"tool_progress":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;let G=X.update.total!==void 0?` ${Math.max(0,Math.min(100,Math.round((X.update.progress??0)/X.update.total*100)))}%`:"",U=`${Q.function.name}${G}: ${X.update.message}`;$.sessionActions.addToolMessage(U,{toolCallId:Q.id,toolName:Q.function.name,phase:"progress",summary:U,...X.update.admission?{admission:X.update.admission}:{}});break}case"tool_result":{J.toolExecutionStarted=!0;let Q=X.toolCall;if(!("function"in Q))break;if(Q.function.name===t8)break;Z8.debug("[loopEventHandler] tool_result",{toolName:Q.function.name,success:X.result.success});let G=R9(I9(Q.function.name,X.result),C9);$.sessionActions.addToolMessage(G.summary,{toolCallId:Q.id,toolName:Q.function.name,phase:"complete",summary:G.summary,detail:G.detail});break}case"structured_output":J.outputStarted=!0,$.sessionActions.replaceLastAssistantMessage(JSON.stringify(X.output,null,2));break;case"token_usage":$.sessionActions.updateTokenUsage(X.usage);break;case"compaction":if($.sessionActions.setCompacting(X.phase==="start"),X.phase==="end"){if($.sessionActions.resetContextUsage(),X.outcome!=="failed")J.compactionCount=(J.compactionCount??0)+1;if(X.memory?.outcome==="written"){let Q=`Saved ${X.memory.entries} project memories`;$.sessionActions.addToolMessage(Q,{toolName:"Project Memory",phase:"complete",summary:Q})}}break;case"turn_start":Z8.debug("[loopEventHandler] turn_start",{turn:X.turn,maxTurns:X.maxTurns}),$.sessionActions.updateTokenUsage({turnCount:X.turn}),$.sessionActions.setProviderCircuit(null),$.sessionActions.setProviderRetry(null),$.sessionActions.setProviderStall(null),Y.startTurn();break;case"task_update":$.appActions.setTasks(X.tasks);break;case"goal_frontier_updated":$.appActions.setTasks(X.tasks);break;case"mcp_catalog_changed":{let Q=`MCP catalog r${X.revision}: +${X.added.length} -${X.removed.length} ~${X.updated.length}`;$.sessionActions.addToolMessage(Q,{toolName:"MCP Catalog",phase:"complete",summary:Q,detail:[X.added.length>0?`Added: ${X.added.join(", ")}`:"",X.removed.length>0?`Removed: ${X.removed.join(", ")}`:"",X.updated.length>0?`Updated: ${X.updated.join(", ")}`:""].filter(Boolean).join(`
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{be as a,ce as b,de as c,ee as d,fe as e,ge as f,he as g}from"./chunk-
|
|
1
|
+
import{be as a,ce as b,de as c,ee as d,fe as e,ge as f,he as g}from"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import"./chunk-50vwafn5.js";import"./chunk-vbjgcn49.js";import"./chunk-3y2x6fb6.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-2mk914vk.js";import"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.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,4 +1,4 @@
|
|
|
1
|
-
import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-3aavhxe8.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-ajtwwg2b.js";import{H as NH,da as MH,fa as zH,ga as fH,ka as AH}from"./chunk-cvwcrr4h.js";import"./chunk-g01mth5d.js";import"./chunk-nj2bggcj.js";import{ab as QH}from"./chunk-30x3mcsb.js";import{Nb as e,Zb as FH,hc as EH}from"./chunk-y54mge74.js";import"./chunk-zzvs471p.js";import{Sd as GH,Wd as PH,Yd as d,he as t}from"./chunk-za0frk62.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as TH}from"./chunk-yk62xvqm.js";import{tf as yH,uf as bH,vf as IH}from"./chunk-46t79ek8.js";import{wf as SH}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Wf as _H}from"./chunk-syq7j5b0.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-t89f4way.js";import"./chunk-mg03ydep.js";import"./chunk-3kszepm6.js";import{hh as c,lh as BH}from"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-sspk1ah8.js";import"./chunk-3y2x6fb6.js";import"./chunk-f194ct93.js";import{Ti as xH}from"./chunk-kv458q06.js";import{Yi as r,Zi as n}from"./chunk-5v0jcyea.js";import{bj as C}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Fj as UH,Hj as H,Ij as YH,Kj as Y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-rjbneaq0.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(HJ)}),VJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),QJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
|
|
1
|
+
import{p as gH,q as kH,r as CH,s as hH,t as OH,u as wH}from"./chunk-8bb421cb.js";import{B as RH,C as ZH,D as $H,E as qH,F as a,G as XH}from"./chunk-bztcgtpv.js";import{H as NH,da as MH,fa as zH,ga as fH,ka as AH}from"./chunk-tmxh9cds.js";import"./chunk-g01mth5d.js";import"./chunk-h0d4154v.js";import{ab as QH}from"./chunk-30x3mcsb.js";import{Nb as e,Zb as FH,hc as EH}from"./chunk-7eexcvd6.js";import"./chunk-zzvs471p.js";import{Sd as GH,Wd as PH,Yd as d,he as t}from"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{rf as TH}from"./chunk-2w6hbep9.js";import{tf as yH,uf as bH,vf as IH}from"./chunk-wysmzs8h.js";import{wf as SH}from"./chunk-nheny8xp.js";import"./chunk-jj4ggb04.js";import{Wf as _H}from"./chunk-xeyhp68m.js";import"./chunk-v508x7cg.js";import"./chunk-t0gm0pn1.js";import"./chunk-1yq72zb7.js";import"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import"./chunk-50vwafn5.js";import"./chunk-mgw83hkv.js";import"./chunk-qyj9khsj.js";import"./chunk-3kszepm6.js";import{hh as c,lh as BH}from"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import"./chunk-2b1f5rwp.js";import{Ti as xH}from"./chunk-kv458q06.js";import{Yi as r,Zi as n}from"./chunk-5v0jcyea.js";import{bj as C}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Fj as UH,Hj as H,Ij as YH,Kj as Y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import uJ from"yargs";import{hideBin as dJ}from"yargs/helpers";function i(V,Z,Q){if(V.off){V.off(Z,Q);return}V.removeListener?.(Z,Q)}function aH(V,Z){if(!V.once&&!V.on||!V.off&&!V.removeListener)throw Error("Writable returned false without an observable drain contract");return new Promise((Q,q)=>{let J=!1,K=()=>{i(V,"drain",x),i(V,"error",j),Z.removeEventListener("abort",P)},D=(F)=>{if(J)return;J=!0,K(),F()},x=()=>D(Q),j=(F)=>D(()=>q(F??Error("Writable emitted an error"))),P=()=>D(()=>q(Z.reason??Error("Writable drain aborted")));if(Z.aborted){P();return}let T=V.once?.bind(V)??V.on?.bind(V);T?.("drain",x),T?.("error",j),Z.addEventListener("abort",P,{once:!0})})}async function iH(V,Z,Q){if(V.destroyed||V.writableEnded)throw Error("Writable is already closed");if(V.write(Z)===!1)await aH(V,Q)}class o{options;queues;sinkErrorListeners=[];failed=!1;closing=!1;handleAbort=()=>{this.fail(new a("aborted","Headless output was aborted",{cause:this.options.signal?.reason}))};constructor(V,Z={}){this.options=Z;let Q=(q)=>new XH({maxPendingItems:Z.maxPendingItems??ZH,maxPendingBytes:Z.maxPendingBytes??$H,writeTimeoutMs:Z.writeTimeoutMs??qH,sizeOf:(J)=>Buffer.byteLength(J),write:(J,K)=>iH(V[q],J,K),onFailure:(J)=>this.fail(J)});if(this.queues={stdout:Q("stdout"),stderr:Q("stderr")},this.observeSinkErrors(V.stdout),V.stderr!==V.stdout)this.observeSinkErrors(V.stderr);if(Z.signal?.addEventListener("abort",this.handleAbort,{once:!0}),Z.signal?.aborted)this.handleAbort()}write(V,Z){return this.queues[V].offer(Z).accepted}async flush(){await Promise.all([this.queues.stdout.flush(),this.queues.stderr.flush()])}close(V){if(this.closing||this.failed)return;this.closing=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V)}stats(){return{stdout:this.queues.stdout.stats(),stderr:this.queues.stderr.stats()}}observeSinkErrors(V){if(!V.on||!V.off&&!V.removeListener)return;let Z=(Q)=>{this.fail(new a("write_failed","Headless writable failed",{cause:Q??Error("Writable emitted an error")}))};V.on("error",Z),this.sinkErrorListeners.push({writer:V,listener:Z})}fail(V){if(this.closing||this.failed)return;this.failed=!0,this.options.signal?.removeEventListener("abort",this.handleAbort),this.removeSinkErrorListeners(),this.queues.stdout.close(V),this.queues.stderr.close(V),this.options.onFailure?.(V)}removeSinkErrorListeners(){for(let{writer:V,listener:Z}of this.sinkErrorListeners.splice(0))i(V,"error",Z)}}var k=1;function L(V){return H.Object({event_version:H.Literal(k),...V})}var oH=L({type:H.Literal("content_delta"),delta:H.String()}),sH=L({type:H.Literal("thinking_delta"),delta:H.String()}),rH=L({type:H.Literal("thinking"),content:H.String()}),nH=L({type:H.Literal("stream_end")}),tH=L({type:H.Literal("content"),content:H.String()}),eH=L({type:H.Literal("structured_output"),output:H.Record(H.String(),H.Unknown()),schema_digest:H.String({pattern:"^[a-f0-9]{64}$"})}),s=Y(["readonly","write","execute"]),HJ=H.Object({kind:s,scope:Y(["global","session"]),queue_position:H.Integer({minimum:1}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:1})}),JJ=L({type:H.Literal("tool_start"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s)}),KJ=L({type:H.Literal("tool_progress"),tool_name:H.String(),message:H.String(),progress:H.Optional(H.Number()),total:H.Optional(H.Number()),admission:H.Optional(HJ)}),VJ=H.Object({auto_backgrounded:H.Literal(!0),background_reason:H.Literal("foreground_budget"),foreground_budget_ms:H.Integer({minimum:1}),shell_id:H.String({minLength:1,maxLength:128,pattern:"^bash_[A-Za-z0-9-]+$"}),pid:H.Optional(H.Integer({minimum:1})),terminal_transport:Y(["local","acp"])}),ZJ=L({type:H.Literal("tool_result"),tool_name:H.String(),summary:H.String(),target:H.Optional(H.String()),tool_kind:H.Optional(s),success:H.Optional(H.Boolean()),error_type:H.Optional(H.String()),error_message:H.Optional(H.String()),background:H.Optional(VJ)}),$J=L({type:H.Literal("mcp_catalog_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),qJ=L({type:H.Literal("mcp_content_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),content_kind:Y(["resources","resource_templates","prompts"]),added:H.Array(H.String()),removed:H.Array(H.String()),updated:H.Array(H.String())}),XJ=L({type:H.Literal("mcp_resource_updated"),revision:H.Integer({minimum:1}),server_name:H.String(),uri:H.String()}),YJ=L({type:H.Literal("mcp_connection_changed"),revision:H.Integer({minimum:1}),server_name:H.String(),phase:Y(["reconnecting","recovered","failed"]),reason:H.String(),attempt:H.Integer({minimum:0}),max_attempts:H.Integer({minimum:0}),next_retry_at:H.Optional(H.Integer({minimum:0})),error:H.Optional(H.String())}),BJ=L({type:H.Literal("mcp_log"),revision:H.Integer({minimum:1}),server_name:H.String(),level:Y(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:H.Optional(H.String()),message:H.String(),projected_bytes:H.Integer({minimum:0}),data_sha256:H.String(),truncated:H.Boolean(),details_omitted:H.Boolean(),timestamp:H.Integer({minimum:0}),synthetic:H.Optional(H.Boolean())}),NJ=L({type:H.Literal("mcp_instructions_changed"),revision:H.Integer({minimum:0}),server_name:H.String(),action:Y(["added","removed"]),reason:Y(["snapshot","connection","disconnection"]),text:H.Optional(H.String()),source_bytes:H.Optional(H.Integer({minimum:0})),projected_bytes:H.Optional(H.Integer({minimum:0})),sha256:H.Optional(H.String()),truncated:H.Optional(H.Boolean()),details_omitted:H.Optional(H.Boolean())}),QJ=L({type:H.Literal("mcp_task_changed"),revision:H.Integer({minimum:0}),task_id:H.String(),server_name:H.String(),tool_name:H.String(),status:Y(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:H.Optional(H.String()),created_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),completed_at:H.Optional(H.Integer({minimum:0})),has_result:H.Boolean(),error:H.Optional(H.String())}),DJ=L({type:H.Literal("project_rules_loaded"),files:H.Array(H.Object({id:H.String(),relative_path:H.String(),source:Y(["project","local"]),conditional:H.Boolean(),content_sha256:H.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:H.Array(H.String()),blocked_write:H.Boolean()}),LJ=L({type:H.Literal("user_shell_started"),execution_id:H.String(),command:H.String(),auxiliary:H.Boolean()}),WJ=L({type:H.Literal("user_shell_output"),execution_id:H.String(),stream:Y(["stdout","stderr"]),chunk:H.String(),stream_truncated:H.Boolean()}),jJ=L({type:H.Literal("user_shell_completed"),execution_id:H.String(),message_id:H.String(),status:Y(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:H.Union([H.Integer(),H.Null()]),duration_ms:H.Number({minimum:0}),stdout:H.String(),stderr:H.String(),truncated:H.Boolean(),auxiliary:H.Boolean()}),xJ=L({type:H.Literal("phase"),phase:Y(["turn","searching","inspecting","target_hit","executing","completed"]),status:Y(["ongoing","hit","done"]),message:H.String(),turn:H.Optional(H.Number()),tool_name:H.Optional(H.String()),target:H.Optional(H.String())}),UJ=L({type:H.Literal("tool_detail"),tool_name:H.String(),detail:H.String()}),_J=L({type:H.Literal("task_update"),tasks:H.Array(NH)}),GJ=L({type:H.Literal("goal_frontier"),goal_id:H.String({minLength:1}),status:Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),task_list_id:H.String({minLength:1,maxLength:256}),total:H.Integer({minimum:0}),completed:H.Integer({minimum:0}),in_progress:H.Integer({minimum:0}),pending:H.Integer({minimum:0}),blocked:H.Integer({minimum:0}),next_task:H.Optional(H.Object({id:H.String({minLength:1}),subject:H.String({minLength:1,maxLength:512}),priority:Y(["high","medium","low"])})),digest_sha256:H.String({pattern:"^[a-f0-9]{64}$"}),observed_at:H.String(),stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),stall_count:H.Optional(H.Integer({minimum:1,maximum:3}))}),PJ=L({type:H.Literal("goal"),state:Y(["updated","cleared"]),goal_id:H.Optional(H.String()),status:H.Optional(Y(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:H.Optional(H.Integer({minimum:1})),verification_status:H.Optional(Y(["pending","pass","fail","partial"])),verifier_session_id:H.Optional(H.String()),verification_evidence_sha256:H.Optional(H.String({pattern:"^[a-f0-9]{64}$"})),verification_summary:H.Optional(H.String()),verification_stall_count:H.Optional(H.Integer({minimum:1})),premature_stop_pattern:H.Optional(Y(BH)),premature_stop_count:H.Optional(H.Integer({minimum:1})),execution_host_failure_category:H.Optional(Y(["timeout","admission","spawn","finalization","sandbox_start","terminal"])),execution_host_failure_count:H.Optional(H.Integer({minimum:1,maximum:3})),frontier_stall_category:H.Optional(Y(["waiting_dependency","same_task_no_effect","repeated_deferral"])),frontier_stall_count:H.Optional(H.Integer({minimum:1,maximum:3})),root_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),current_turn_id:H.Optional(H.String({minLength:1,maxLength:c})),parent_turn_id:H.Optional(H.String({minLength:1,maxLength:c}))}),FJ=L({type:H.Literal("subagent"),state:Y(["spawned","completed"]),session_id:H.String(),subagent_type:H.Optional(H.String()),success:H.Optional(H.Boolean()),summary:H.Optional(H.String()),verification_verdict:H.Optional(Y(["pass","fail","partial"])),resumed_from:H.Optional(H.String()),root_agent_id:H.Optional(H.String()),resume_depth:H.Optional(H.Integer({minimum:0}))}),EJ=L({type:H.Literal("token_usage"),input_tokens:H.Number(),output_tokens:H.Number(),total_tokens:H.Number(),max_context_tokens:H.Number(),cache_read_tokens:H.Optional(H.Number()),cache_write_tokens:H.Optional(H.Number()),prompt_cache_break:H.Optional(H.Object({reason:Y(["model_changed","system_prompt_changed","tools_changed","request_policy_changed","ttl_expired","server_side"]),previous_cache_read_tokens:H.Number(),cache_read_tokens:H.Number(),cache_write_tokens:H.Number(),token_drop:H.Number(),elapsed_ms:H.Number(),call_number:H.Number(),system_prompt_changed:H.Boolean(),system_char_delta:H.Number(),tools_changed:H.Boolean(),added_tool_count:H.Number(),removed_tool_count:H.Number(),changed_tool_count:H.Number(),model_changed:H.Boolean(),request_policy_changed:H.Boolean()})),cost_usd:H.Optional(H.Number())}),MJ=L({type:H.Literal("compacting"),state:Y(["started","completed"]),reason:H.Optional(Y(["threshold","context_limit","turn_limit","manual"])),strategy:H.Optional(Y(["llm","fallback","snip"])),outcome:H.Optional(Y(["completed","fallback","failed"])),pre_tokens:H.Optional(H.Number({minimum:0})),pre_token_source:H.Optional(Y(["provider","provider_plus_estimate","local_estimate"])),estimated_pending_tokens:H.Optional(H.Number({minimum:0})),post_tokens:H.Optional(H.Number({minimum:0})),sample_attempts:H.Optional(H.Integer({minimum:0})),input_reductions:H.Optional(H.Integer({minimum:0})),messages_omitted:H.Optional(H.Integer({minimum:0})),files_omitted:H.Optional(H.Integer({minimum:0})),images_omitted:H.Optional(H.Integer({minimum:0})),fallback_target_tokens:H.Optional(H.Integer({minimum:0})),fallback_messages_omitted:H.Optional(H.Integer({minimum:0})),fallback_messages_truncated:H.Optional(H.Integer({minimum:0})),failure_reason:H.Optional(Y(["circuit_open","context_exhausted","deterministic","empty_exhausted","insufficient_reduction","transient_exhausted"])),memory:H.Optional(QH)}),zJ=L({type:H.Literal("provider_retry"),phase:Y(["scheduled","waiting","attempt","recovered","exhausted"]),attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),delay_ms:H.Optional(H.Integer({minimum:0})),next_retry_at:H.Optional(H.Integer({minimum:0})),mode:H.Optional(Y(["standard","bounded_foreground"])),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0})),exhausted_by:H.Optional(Y(["attempt_limit","recovery_budget"]))}),fJ=L({type:H.Literal("provider_admission"),phase:Y(["queued","admitted","rejected"]),request_class:Y(["foreground","background","internal"]),resource:Y(["stream","pending_count","pending_bytes"]),scope:Y(["global","domain","owner","class"]),reason:H.Optional(Y(["capacity","queue_full","wait_timeout","closed"])),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),AJ=L({type:H.Literal("provider_circuit"),phase:Y(["opened","waiting","probe","closed","reopened","rejected"]),reason:Y(["rate_limit","server_error","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:599})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))}),SJ=L({type:H.Literal("provider_stall"),phase:Y(["detected","recovered"]),stall_count:H.Integer({minimum:1}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:1}),timeout_ms:H.Integer({minimum:1}),output_started:H.Boolean()}),u=H.Object({provider:H.String({minLength:1,maxLength:256}),model:H.String({minLength:1,maxLength:256})},{additionalProperties:!1}),DH=H.Union([H.Object({source:Y(["retry","circuit"]),reason:Y(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999}))},{additionalProperties:!1}),H.Object({source:H.Literal("admission"),reason:Y(["queue_full","wait_timeout","closed"])},{additionalProperties:!1}),H.Object({source:H.Literal("stall"),reason:H.Literal("timeout")},{additionalProperties:!1})]),TJ=H.Object({activity:Y(["admission_wait","retry_wait","retry_attempt","circuit_open","circuit_probe","stream_stall","fallback"]),reason:Y(["capacity","queue_full","wait_timeout","admission_closed","rate_limit","server_error","timeout","transport","stream_closed","circuit_open","stream_stall"]),updated_at:H.Integer({minimum:0}),next_action_at:H.Optional(H.Integer({minimum:0})),retry:H.Optional(H.Object({attempt:H.Integer({minimum:0}),max_retries:H.Integer({minimum:0}),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),delay_ms:H.Optional(H.Integer({minimum:0})),recovery_budget_ms:H.Optional(H.Integer({minimum:0})),recovery_elapsed_ms:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),admission:H.Optional(H.Object({request_class:Y(["foreground","background","internal"]),scope:Y(["global","domain","owner","class"]),resource:Y(["stream","pending_count","pending_bytes"]),queue_position:H.Integer({minimum:0}),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),limit:H.Integer({minimum:0}),wait_ms:H.Integer({minimum:0}),max_wait_ms:H.Integer({minimum:0}),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),circuit:H.Optional(H.Object({phase:Y(["opened","reopened","waiting","probe","rejected"]),status_code:H.Optional(H.Integer({minimum:100,maximum:999})),retry_after_ms:H.Optional(H.Integer({minimum:0})),next_probe_at:H.Optional(H.Integer({minimum:0})),open_duration_ms:H.Integer({minimum:0}),sample_count:H.Optional(H.Integer({minimum:0})),failure_count:H.Optional(H.Integer({minimum:0})),recovery_remaining_ms:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1})),stall:H.Optional(H.Object({stall_count:H.Integer({minimum:0}),duration_ms:H.Integer({minimum:0}),warning_after_ms:H.Integer({minimum:0}),timeout_ms:H.Integer({minimum:0}),output_started:H.Boolean()},{additionalProperties:!1})),fallback:H.Optional(H.Object({from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}))},{additionalProperties:!1}),yJ=H.Object({event_version:H.Literal(k),type:H.Literal("provider_recovery"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([TJ,H.Null()])},{additionalProperties:!1}),bJ=H.Object({name:H.String({minLength:1,maxLength:128}),kind:H.Optional(Y(["readonly","write","execute"])),started_at:H.Integer({minimum:0}),progress:H.Optional(H.Integer({minimum:0})),total:H.Optional(H.Integer({minimum:0}))},{additionalProperties:!1}),IJ=H.Object({phase:Y(["starting","thinking","responding","executing_tools","compacting","continuing"]),started_at:H.Integer({minimum:0}),updated_at:H.Integer({minimum:0}),turn:H.Integer({minimum:0}),max_turns:H.Union([H.Integer({minimum:0}),H.Null()]),output_started:H.Boolean(),tool_calls_started:H.Integer({minimum:0}),tool_calls_completed:H.Integer({minimum:0}),active_tools:H.Array(bJ,{maxItems:8}),active_tool_overflow:H.Integer({minimum:0})},{additionalProperties:!1}),RJ=H.Object({event_version:H.Literal(k),type:H.Literal("turn_activity"),generation:H.String({minLength:1,maxLength:128}),revision:H.Integer({minimum:0}),snapshot:H.Union([IJ,H.Null()])},{additionalProperties:!1}),gJ=H.Object({event_version:H.Literal(k),type:H.Literal("model_fallback"),from:u,to:u,candidate:H.Integer({minimum:1}),candidate_count:H.Integer({minimum:1}),trigger:DH},{additionalProperties:!1}),kJ=L({type:H.Literal("action_stationarity"),phase:Y(["detected","recovered","halted"]),tool_name:H.String(),run_length:H.Integer({minimum:1}),nudge_threshold:H.Integer({minimum:1}),halt_threshold:H.Integer({minimum:1}),progress_aware:H.Boolean()}),CJ=L({type:H.Literal("turn_recovery"),state:Y(["completed","resumable","requires_attention"]),turn_id:H.String({minLength:1}),input_message_count:H.Integer({minimum:0}),reason:H.Optional(Y(["successful_tool_result","interrupted_tool_call"]))}),hJ=L({type:H.Literal("turn_limit"),turns_count:H.Number(),action:H.Literal("continue")}),OJ=L({type:H.Literal("task_session"),session_id:H.String(),project_path:H.String(),source_project_path:H.String(),isolation:Y(["local","worktree"]),worktree_branch:H.Optional(H.String()),base_commit:H.Optional(H.String())}),wJ=L({type:H.Literal("task_admission"),state:Y(["queued","running"]),queue_position:H.Optional(H.Integer({minimum:1})),queue_depth:H.Integer({minimum:0}),in_flight:H.Integer({minimum:0}),max_concurrent_tasks:H.Integer({minimum:1})}),mJ=L({type:H.Literal("output"),content:H.String(),exit_code:H.Number()}),cJ=L({type:H.Literal("error"),message:H.String()}),NK=YH(H.Union([oH,sH,rH,nH,tH,eH,JJ,KJ,ZJ,$J,qJ,XJ,YJ,BJ,NJ,QJ,DJ,LJ,WJ,jJ,xJ,UJ,_J,GJ,PJ,FJ,EJ,MJ,fJ,AJ,zJ,SJ,yJ,RJ,gJ,kJ,CJ,hJ,OJ,wJ,mJ,cJ]));function LH(V,Z){return{event_version:k,type:V,...Z}}function pJ(V){if(!V||typeof V!=="object"||Array.isArray(V))return;let Z=V;if(Z.auto_backgrounded!==!0||Z.background_reason!=="foreground_budget"||!Number.isSafeInteger(Z.foreground_budget_ms)||Z.foreground_budget_ms<=0||typeof Z.shell_id!=="string"||!/^bash_[A-Za-z0-9-]+$/.test(Z.shell_id)||Z.shell_id.length>128||Z.terminal_transport!=="local"&&Z.terminal_transport!=="acp"||Z.pid!==void 0&&(!Number.isSafeInteger(Z.pid)||Z.pid<=0))return;return{auto_backgrounded:!0,background_reason:"foreground_budget",foreground_budget_ms:Z.foreground_budget_ms,shell_id:Z.shell_id,...Z.pid===void 0?{}:{pid:Z.pid},terminal_transport:Z.terminal_transport}}function vJ(V){let Z=new AbortController,Q=(K)=>{if(!Z.signal.aborted)Z.abort(K)},q=()=>Q("interrupt"),J=()=>Q(V?.signal?.reason);if(V?.signal){if(V.signal.addEventListener("abort",J,{once:!0}),V.signal.aborted)J()}else process.once("SIGINT",q),process.once("SIGTERM",q);return{signal:Z.signal,abort:Q,dispose:()=>{V?.signal?.removeEventListener("abort",J),process.removeListener("SIGINT",q),process.removeListener("SIGTERM",q)}}}var lJ=Y(["text","jsonl"]),aJ=H.Object({headless:H.Optional(H.Boolean()),message:H.Optional(H.String()),_:H.Optional(H.Array(H.Union([H.String(),H.Number()]))),model:H.Optional(H.String()),systemPrompt:H.Optional(H.String()),appendSystemPrompt:H.Optional(H.String()),verificationAgent:H.Optional(H.Boolean()),maxTurns:H.Optional(H.Refine(H.Integer(),(V)=>V===-1||V>0,()=>"must be -1 (unlimited) or a positive integer")),permissionMode:H.Optional(H.Enum(xH)),mcpConfig:H.Optional(H.Array(H.String())),strictMcpConfig:H.Optional(H.Boolean()),sessionId:H.Optional(H.String()),allowedTools:H.Optional(H.Array(H.String())),disallowedTools:H.Optional(H.Array(H.String())),agents:H.Optional(H.String()),continue:H.Optional(H.Boolean()),resume:H.Optional(H.Union([H.String(),H.Boolean()])),forkSession:H.Optional(H.Boolean()),taskIsolation:H.Optional(Y(["local","worktree"])),outputFormat:H.Optional(lJ),jsonSchema:H.Optional(H.String()),outputSchema:H.Optional(H.String())});class mH{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(V){this.openedThinking=V}hasOpenThinking(){return this.openedThinking}completeStream(){let V={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,V}}function iJ(V){return V.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function oJ(V){let Z=UH(aJ,V);if(!Z.success)throw Error(`Invalid headless options: ${iJ(Z.error)}`);return Z.data}function sJ(V){return V.command("* [message]","Run full agent loop without Ink UI and print events to the terminal",(Z)=>Z.positional("message",{describe:"Message to process",type:"string"}).option("headless",{type:"boolean",describe:"Run full agent loop without Ink UI and print events to the terminal"}).option("model",{describe:"Model ID for this run",type:"string"}).option("system-prompt",{describe:"Replace the default system prompt",type:"string"}).option("append-system-prompt",{describe:"Append a system prompt to the default system prompt",type:"string"}).option("verification-agent",{describe:"Run the built-in independent verification agent after non-trivial changes",type:"boolean",default:!0}).option("max-turns",{alias:["maxTurns"],describe:"Maximum conversation turns (-1: unlimited, N>0: limit to N turns)",type:"number"}).option("output-format",{alias:["outputFormat"],choices:["text","jsonl"],describe:"Headless output format",type:"string"}).option("json-schema",{alias:["jsonSchema"],describe:"Inline JSON Schema for the structured final response",type:"string"}).option("output-schema",{alias:["outputSchema"],describe:"Path to a JSON Schema file for the structured final response",type:"string"}).option("task-isolation",{alias:["taskIsolation"],choices:["local","worktree"],describe:"Dispatch a new durable task in the selected workspace mode",type:"string"}),async(Z)=>{if(!Z.headless)return;let Q=await JK(Z);process.exit(Q)})}function W(V,Z=""){V.write(`${Z}
|
|
2
2
|
`)}function rJ(V){return`[task] [${V.status}] ${V.subject}`}function nJ(){return{requestConfirmation:async(V)=>V.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:V.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function tJ(V){if(!(V instanceof Error))return"Unknown error";let q=V.lastError??V;if(q.responseBody)try{let D=JSON.parse(q.responseBody)?.error?.message;if(D)return q.statusCode?`${D} (HTTP ${q.statusCode})`:D}catch{}let J=V.message.match(/Last error:\s*(.+)$/);if(J)return J[1];return V.message}function eJ(V){return V==="jsonl"?"jsonl":"text"}function WH(V,Z){let Q=(...q)=>{for(let J of q){let K=Z[J];if(typeof K==="string"&&K.trim()!=="")return K}return};switch(V){case"Read":case"Edit":case"Write":case"UndoEdit":return Q("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return Q("notebook_path");case"Grep":return Q("path","pattern");case"Glob":return Q("pattern");case"WebFetch":return Q("url");case"WebSearch":return Q("query");case"Bash":return Q("command","description");case"Task":return Q("description");case"LSP":return Q("filePath","operation");case"EnterWorktree":return Q("name");case"ExitWorktree":return Q("action");default:return}}function HK(V,Z,Q,q){let J=new Set(["Glob","Grep","WebSearch","LS"]),K=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(V)&&!q.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(q.targetLocked)return{phase:"executing",status:"hit",message:Q?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(J.has(V))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if(K.has(V))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:q.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function jH(V,Z,Q=!1){let q=(J,K)=>{V.stdout.write(`${JSON.stringify(LH(J,K))}
|
|
3
3
|
`)};return{contentDelta(J){if(Z==="jsonl"){q("content_delta",{delta:J});return}if(Q)return;V.stdout.write(J)},thinkingDelta(J,K){if(Z==="jsonl")return q("thinking_delta",{delta:J}),K;if(!K)V.stderr.write("[thinking] ");return V.stderr.write(J),!0},thinking(J){if(Z==="jsonl"){q("thinking",{content:J});return}W(V.stderr,`[thinking] ${J}`)},streamEnd(J,K){if(Z==="jsonl"){q("stream_end",{});return}if(K)V.stderr.write(`
|
|
4
4
|
`);if(J)V.stdout.write(`
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{v as HH,w as JH}from"./chunk-
|
|
1
|
+
import{v as HH,w as JH}from"./chunk-1ak6q7tt.js";import{A as S,x as Cz,y as fz,z as uz}from"./chunk-jaxpzavy.js";import{B as zH,C as xz,D as bz,E as Rz,F as Sz,G as Mz}from"./chunk-bztcgtpv.js";import{Aa as Iz,Ba as yz,Ca as hz,Da as kz,N as R,W as Az,X as Oz,da as Ez,ga as qz,ha as Tz,ka as Pz}from"./chunk-tmxh9cds.js";import"./chunk-g01mth5d.js";import{Ra as ez}from"./chunk-h0d4154v.js";import{Ta as Nz,Xa as i,_a as a}from"./chunk-30x3mcsb.js";import{Nb as Kz,Zb as wz,hc as l}from"./chunk-7eexcvd6.js";import{sc as d}from"./chunk-zzvs471p.js";import{$d as Dz,Cd as Bz,Md as I,Nd as v,Od as Gz,Td as Vz,Wd as jz,Yd as M,ee as Fz,he as F}from"./chunk-zew66zhx.js";import"./chunk-53fc0yrq.js";import{Fe as _z,Me as r,Ne as Uz}from"./chunk-y5wngtz0.js";import"./chunk-w33zjw8m.js";import{yf as LH}from"./chunk-zgtned44.js";import"./chunk-jj4ggb04.js";import{Tf as oz,Uf as nz}from"./chunk-xeyhp68m.js";import"./chunk-v508x7cg.js";import{dg as e}from"./chunk-t0gm0pn1.js";import{ig as Wz}from"./chunk-1yq72zb7.js";import{qg as m}from"./chunk-kqvzmnja.js";import"./chunk-0mr8nexh.js";import{vg as sz}from"./chunk-50vwafn5.js";import"./chunk-mgw83hkv.js";import"./chunk-qyj9khsj.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import{rh as tz}from"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import{ui as az,xi as rz}from"./chunk-2b1f5rwp.js";import"./chunk-kv458q06.js";import{Vi as g,Wi as Xz,Yi as c,Zi as p}from"./chunk-5v0jcyea.js";import{bj as t}from"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import{Dj as y}from"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import{Qj as lz,Tj as iz}from"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import{fk as $z,gk as dz,kk as zz,ok as Hz,pk as vz,qk as Jz}from"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";import{Readable as KH,Writable as wH}from"node:stream";import*as f from"@agentclientprotocol/sdk";import o from"node:path";import{PROTOCOL_VERSION as GH,RequestError as C}from"@agentclientprotocol/sdk";import{RequestError as gz}from"@agentclientprotocol/sdk";import{nanoid as u}from"nanoid";var G=y("Agent");function P(z){return Object.freeze({kind:"local",hostStateRoot:z,executionRoot:z,hostResourceRoot:z})}function Zz(z){if(!z)return{};return Object.fromEntries(z.map((H)=>[H.name,H.value]))}function ZH(z){if("command"in z)return{type:"stdio",command:z.command,args:z.args,env:Zz(z.env)};if("url"in z)return{type:z.type,url:z.url,headers:Zz("headers"in z?z.headers:void 0)};return null}function $H(z){let H={};for(let L of z){let Y=ZH(L);if(Y)H[L.name]=Y}return H}function cz(z){if(typeof z==="string")return z?[{type:"text",text:z}]:[];return z.flatMap((H)=>{if(H.type==="text")return H.text?[{type:"text",text:H.text}]:[];let L=H.image_url.url,Y=/^data:([^;,]+);base64,(.+)$/s.exec(L);if(!Y)return[{type:"text",text:"[Image]"}];return[{type:"image",mimeType:Y[1]??"image/png",data:Y[2]??""}]})}function XH(z){let H=Uz(z.metadata);return H?[{type:"text",text:r(H)}]:cz(z.content)}function WH(z){return[`Status: ${z.status}`,`Exit code: ${z.exitCode??"null"}`,`Duration: ${(z.durationMs/1000).toFixed(3)} seconds`].join(`
|
|
2
2
|
`)}function BH(z){if(!Wz(z)||z.reason!=="queue_full"||z.resource!=="pending_count"&&z.resource!=="pending_bytes")return;return{...I("capacity"),resource:z.resource}}function _H(z){if(!(z instanceof gz)||!z.data||typeof z.data!=="object")return;let H=z.data;if(!Gz(H.taskFailure)||H.toolExecutionStarted!==!1||!Number.isInteger(H.toolCallsCount)||H.toolCallsCount<0||H.outputStarted!==!1)return;return{taskFailure:H.taskFailure,toolExecutionStarted:H.toolExecutionStarted,toolCallsCount:H.toolCallsCount,outputStarted:H.outputStarted}}function UH(z){return{version:z.version,pending:z.pending,mutable:z.mutable,locked:z.locked,internal:z.internal}}class x{id;roots;connection;clientCapabilities;options;agent=null;runtime=null;pendingPrompt=null;pendingPromptCompletion=null;pendingUserShell=null;pendingUserShellCompletion=null;pendingSideConversation=null;pendingSideConversationCompletion=null;pendingResumeRequested=!1;pendingResumeAttempt=0;projectedPendingResumeInputIds=new Set;pendingResumeRecoveryStartedAt=0;pendingResumeInFlight=!1;pendingResumeScheduled=!1;pendingResumeGeneration=0;pendingResumeTimer=null;pendingResumeCompletion=null;pendingResumeNextDelayMs=null;availableCommandsTimer=null;taskStatusUnsubscribe;lastTurnActivityGeneration;lastTurnActivityRevision=-1;destroyed=!1;destroyFinished=!1;destroyPromise;serviceRegistration;messages;contextMessages;mode;updateEgress;constructor(z,H,L,Y,$={}){this.id=z;this.roots=H;this.connection=L;this.clientCapabilities=Y;this.options=$;this.messages=[...$.initialMessages??[]],this.contextMessages=[...this.messages],this.mode=this.mapPermissionModeToMode($.permissionMode),this.updateEgress=new Mz({maxPendingItems:xz,maxPendingBytes:bz,writeTimeoutMs:Rz,signal:L.signal,sizeOf:(X)=>Buffer.byteLength(JSON.stringify(X)),write:async(X)=>{await L.sessionUpdate(X)},onFailure:(X)=>this.handleUpdateEgressFailure(X)})}async refreshPersistedMessages(){let[z,H]=await Promise.all([this.loadPersistedMessages(),this.loadPersistedModelContext()]);if(z.length>0)this.messages=z;if(H.length>0)this.contextMessages=H}async loadModelContextOr(z){let H=await this.loadPersistedModelContext();return H.length>0?H:[...z]}loadPersistedMessages(){return this.roots.kind==="acp-remote"?F.loadRemoteSession(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSession(this.id,this.roots.hostStateRoot)}loadPersistedModelContext(){return this.roots.kind==="acp-remote"?F.loadRemoteSessionModelContext(this.id,this.roots.hostStateRoot,this.roots.descriptor):F.loadSessionModelContext(this.id,this.roots.hostStateRoot)}async persistMetadataUpdate(z,H=z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,z);return}try{await F.updateSessionMetadata(this.id,this.roots.hostStateRoot,z)}catch(L){if(!(L instanceof Fz)&&L.code!=="ENOENT")throw L;await F.createSessionMetadata(this.id,this.roots.hostStateRoot,{taskStatus:"completed",...H})}}async persistPermissionMode(z){if(this.roots.kind==="acp-remote"){await F.updateRemoteSessionMetadata(this.id,this.roots.hostStateRoot,this.roots.descriptor,{permissionMode:z});return}await F.setSessionPermissionMode(this.id,this.roots.hostStateRoot,z)}mapPermissionModeToMode(z){switch(z){case"yolo":return"yolo";case"autoEdit":return"auto-edit";case"plan":return"plan";case"default":default:return"default"}}createAgent(){if(!this.runtime)throw Error("Session runtime is unavailable");return Pz.createWithRuntime(this.runtime,{sessionId:this.id,...this.options.taskWorktree?{toolBlacklist:["EnterWorktree","ExitWorktree"]}:{}})}async initialize(){G.debug(`[AcpSession ${this.id}] Initializing...`),await this.persistPermissionMode(this.mapModeToPermissionMode()??"default");let z=R.initializeSession(this.connection,this.id,this.clientCapabilities,this.roots.executionRoot,async(Z)=>{await this.sendUpdateAndWait(Z)},this.roots.kind==="acp-remote"?this.roots.profile:void 0);if(z)this.serviceRegistration=z;if(G.debug(`[AcpSession ${this.id}] ACP service context initialized`),this.roots.kind==="local"?await l.resolvePendingWithHandler(this.roots.hostStateRoot,this.id,{requestConfirmation:(Z)=>this.requestPermission(Z)}):!1)await this.refreshPersistedMessages();else if((this.options.initialMessages?.length??0)>0)this.contextMessages=await this.loadModelContextOr(this.options.initialMessages??[]);let L=this.options.mcpServers?$H(this.options.mcpServers):void 0,Y=R.getInstance().getTerminalService(this.id),$=this.roots.kind==="acp-remote"?{kind:"acp-remote",executionRoot:this.roots.executionRoot,resourceRoot:this.roots.hostResourceRoot,readTextFile:this.clientCapabilities?.fs?.readTextFile===!0,writeTextFile:this.clientCapabilities?.fs?.writeTextFile===!0,terminal:this.clientCapabilities?.terminal===!0,descriptor:this.roots.descriptor}:void 0;if(this.runtime=await Ez.create({sessionId:this.id,workspaceRoot:this.roots.hostStateRoot,...$?{workspace:$}:{},permissionMode:this.mapModeToPermissionMode(),...L?{mcpServers:L}:{},...this.options.taskWorktree?{taskWorktree:this.options.taskWorktree}:{},...this.options.taskIsolation?{taskIsolation:this.options.taskIsolation}:{},userShellExecutor:{execute:async(Z,_)=>{let U=await Y.execute(Z,{cwd:_.cwd,env:_.env,timeout:_.timeoutMs,signal:_.signal,allowLocalFallback:!1,onOutput:(V)=>_.onOutput?.("stdout",V)});return{exitCode:U.exitCode,stdout:U.stdout,stderr:U.stderr,...U.error?{error:U.error}:{},timedOut:U.failureKind==="timeout",aborted:U.failureKind==="aborted"}}},...(this.options.initialMessages?.length??0)>0?{sessionStart:{isResume:!0,resumeSessionId:this.id}}:{}}),this.roots.kind==="local"?await S.recoverInterrupted(this.roots.hostStateRoot,this.id,this.runtime):!1)await this.refreshPersistedMessages();if(this.agent=await this.createAgent(),this.roots.kind==="local")await yz(this.roots.hostStateRoot);G.debug(`[AcpSession ${this.id}] Agent created successfully`),this.taskStatusUnsubscribe?.(),this.taskStatusUnsubscribe=Kz.subscribe((Z)=>{if(Z.sessionId!==this.id||Z.projectPath!==this.roots.hostStateRoot)return;if(Z.type==="subagent.completion.queued"){this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/backgroundSubagentCompletion":Z.properties}}),this.requestPendingResume();return}if(Z.type==="follow_up.queue.changed"){let _=i.safeParse(Z.properties.queue);if(_.success)this.sendFollowUpQueueSnapshot(_.data);return}if(Z.type==="provider.recovery"){let _=m.safeParse(Z.properties.recovery);if(!_.success)return;this.sendProviderRecoveryProjection(_.data);return}if(Z.type==="turn.activity"){let _=a.safeParse(Z.properties.activity);if(!_.success)return;this.sendTurnActivityProjection(_.data);return}if(Z.type==="task.delivery"){if(!Z.properties.taskDelivery||typeof Z.properties.taskDelivery!=="object")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskDelivery":Z.properties.taskDelivery,...Z.properties.taskWorktreeRemoved===!0?{"blade/taskWorktreeRemoved":!0}:{}}});return}if(Z.type.startsWith("team.")){let{teamName:_,messageId:U,content:V}=Z.properties,T=Z.properties.metadata;if(Z.type==="team.message.received"&&typeof _==="string"&&typeof U==="string"&&typeof V==="string"&&Oz(T,{messageId:U,teamName:_}))(async()=>{let E=await this.runtime?.enqueueSteering(V,{allowBeforeTurn:!0,messageId:U,origin:"team_message",metadata:T});if(!E?.accepted)return;if(E.queue)this.sendFollowUpQueueSnapshot(E.queue);if(await new Az(_,$z()).markDelivered([U]),E.delivery==="next_turn")this.requestPendingResume()})().catch((E)=>{G.warn(`[AcpSession ${this.id}] Failed to deliver teammate message`,E)});this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/teamEvent":{type:Z.type,...Z.properties}}});return}if(Z.type!=="task.status")return;this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:typeof Z.properties.updatedAt==="string"?Z.properties.updatedAt:new Date().toISOString(),_meta:{"blade/taskStatus":Z.properties.taskStatus,...typeof Z.properties.taskStatusReason==="string"?{"blade/taskStatusReason":Z.properties.taskStatusReason}:{},...Z.properties.taskFailure&&typeof Z.properties.taskFailure==="object"?{"blade/taskFailure":Z.properties.taskFailure}:{},...typeof Z.properties.taskStartedAt==="string"?{"blade/taskStartedAt":Z.properties.taskStartedAt}:{},...typeof Z.properties.taskCompletedAt==="string"?{"blade/taskCompletedAt":Z.properties.taskCompletedAt}:{},...Z.properties.taskDiffStat&&typeof Z.properties.taskDiffStat==="object"?{"blade/taskDiffStat":Z.properties.taskDiffStat}:{},...typeof Z.properties.taskQueuePosition==="number"?{"blade/taskQueuePosition":Z.properties.taskQueuePosition}:{},...typeof Z.properties.taskQueueDepth==="number"?{"blade/taskQueueDepth":Z.properties.taskQueueDepth}:{},...typeof Z.properties.taskConcurrencyLimit==="number"?{"blade/taskConcurrencyLimit":Z.properties.taskConcurrencyLimit}:{},...typeof Z.properties.taskInFlight==="number"?{"blade/taskInFlight":Z.properties.taskInFlight}:{}}})});let Q=await this.runtime.getGoal(),W=this.runtime.getPendingSteeringCount()>0,B=Q?.status==="active"||Q?.status==="verifying";if(W||B)this.requestPendingResume({defer:this.options.initialMessages!==void 0});else{let Z=this.runtime.getTurnRecoveryAssessment();if(Z.state!=="none")this.sendUpdate({sessionUpdate:"session_info_update",updatedAt:new Date().toISOString(),_meta:{"blade/turnRecovery":Z}})}}async replayHistory(){for(let H of this.messages){if(!this.canSendUpdates())return;if(!_z(H))continue;let L=H.role==="user"?"user_message_chunk":H.role==="assistant"?"agent_message_chunk":void 0;if(!L)continue;for(let Y of XH(H)){if(!this.canSendUpdates())return;if(!await this.sendUpdateAndWait({sessionUpdate:L,content:Y}))return}}let z=await this.runtime?.getGoal();if(z&&!await this.sendUpdateAndWait(this.goalSessionUpdate(z)))return;if(this.pendingResumeRequested)this.ensurePendingResumeScheduled()}sendAvailableCommandsDelayed(){if(this.destroyed||this.connection.signal.aborted)return;if(this.availableCommandsTimer!==null)clearTimeout(this.availableCommandsTimer);G.debug(`[AcpSession ${this.id}] Scheduling available commands update (500ms delay)`),this.availableCommandsTimer=setTimeout(()=>{if(this.availableCommandsTimer=null,this.destroyed||this.connection.signal.aborted)return;this.sendInitialSessionUpdates()},500)}async sendInitialSessionUpdates(){try{let z=this.runtime;if(z)this.sendFollowUpQueueSnapshot(await z.getFollowUpQueueSnapshot()),this.sendProviderRecoveryProjection(z.getProviderRecoveryProjection()),this.sendTurnActivityProjection(z.getTurnActivityProjection())}catch{G.warn("[AcpSession "+this.id+"] Initial follow-up queue unavailable")}await this.sendAvailableCommands()}async handleSlashCommand(z,H){try{G.debug(`[AcpSession ${this.id}] Executing slash command: ${z}`);let L={cwd:this.roots.hostStateRoot,workspaceKind:this.roots.kind,surface:"acp",workspaceRoot:this.roots.hostStateRoot,sessionId:this.id,messages:[...this.contextMessages],rewind:{listCheckpoints:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listRewindCheckpoints()},execute:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let W=await this.runtime.rewindSession(Q);return this.messages=[...W.messages],this.contextMessages=await this.loadModelContextOr(W.messages),await this.agent?.destroy(),this.agent=await this.createAgent(),W}},reasoning:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()},set:async(Q)=>{if(await this.setReasoningEffort(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getReasoningConfiguration()}},serviceTier:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()},set:async(Q)=>{if(await this.setServiceTier(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getServiceTierConfiguration()}},responseVerbosity:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()},set:async(Q)=>{if(await this.setResponseVerbosity(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getResponseVerbosityConfiguration()}},communicationStyle:{get:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()},set:async(Q)=>{if(await this.setCommunicationStyle(Q),!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getCommunicationStyleConfiguration()}},...this.roots.kind==="local"?{subagents:{list:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listSubagents()},resume:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=!1,Z,_=(V)=>{this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:V.id,status:V.status==="completed"?"completed":"failed",content:[{type:"content",content:{type:"text",text:V.result?.message||V.result?.error||`Subagent ${V.status}`}}]})},U=this.runtime.resumeSubagent({agentId:Q,prompt:W,onCompleted:(V)=>{if(B)_(V);else Z=V}});if(this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.session.id,status:"in_progress",title:`Resuming ${U.session.subagentType} subagent`,content:[{type:"content",content:{type:"text",text:`Resumed from ${U.source.id} at depth ${U.session.resumeDepth}`}}],kind:this.mapToolKind("readonly")}),B=!0,Z)_(Z);return U}}}:{},...this.roots.kind==="local"?{mcp:{getCatalog:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpContentCatalog()},refresh:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.refreshMcpContentCatalogs(Q)},getPrompt:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpPrompt(Q,W,B)},complete:async(Q,W,B)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.completeMcpArgument(Q,W,B)},listTasks:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.listMcpTasks(Q)},getTask:async(Q)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpTask(Q)},cancelTask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.cancelMcpTask(Q,W)},getLogs:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpLogs(Q,W)},setLoggingLevel:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");await this.runtime.setMcpLoggingLevel(Q,W)},getInstructions:async()=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.getMcpInstructions()}}}:{},sideConversation:{ask:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");return this.runtime.askSideQuestion(Q,{signal:W})}},...this.roots.kind==="local"?{codeReview:{run:async(Q,W)=>{if(!this.runtime)throw Error("Session runtime is unavailable");let B=await S.start({sessionId:this.id,projectPath:this.roots.hostStateRoot,runtime:this.runtime,request:Q,signal:W,onEvent:(U)=>{if(U.kind==="tool_start")this.sendUpdate({sessionUpdate:"tool_call",toolCallId:U.toolCall.id,status:"in_progress",title:`Review: ${U.toolCall.function.name}`,content:[],kind:this.mapToolKind(U.toolKind)});else if(U.kind==="tool_result")this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:U.toolCall.id,status:U.result.success?"completed":"failed",content:[]})}}),Z=await B.completion,_=(await S.list(this.roots.hostStateRoot,this.id)).find((U)=>U.start.reviewId===B.reviewId);if(!_)throw Error(`Review not found: ${B.reviewId}`);return await this.refreshPersistedMessages(),{reviewId:B.reviewId,status:Z.status,findings:Z.findings.length,content:Bz(_.start,Z)}}}}:{},signal:H,acp:{sendMessage:(Q)=>{this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:Q}})},sendToolStart:(Q,W,B)=>{let Z=`tool_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,_=this.mapToolKind(B);this.sendUpdate({sessionUpdate:"tool_call",toolCallId:Z,status:"in_progress",title:`${Q}`,content:[{type:"content",content:{type:"text",text:JSON.stringify(W,null,2)}}],kind:_})},sendToolResult:(Q,W)=>{if(W.summary)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:W.summary}})}}},Y=await hz(z,L),$=Y.data?.action;if($==="start_goal"||$==="resume_goal")this.requestPendingResume();if($==="rewind_session"&&Array.isArray(Y.data?.messages))this.messages=[...Y.data.messages],this.contextMessages=await this.loadModelContextOr(Y.data.messages);if((Y.message==="compact_completed"||Y.message==="compact_fallback")&&Y.data?.compactedMessages){this.contextMessages=[...Y.data.compactedMessages];let Q=await this.loadPersistedMessages();if(Q.length>0)this.messages=Q}let X=Y.content||Y.message;if(X)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:X}});if(Y.error)this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] ${Y.error}`}});return await this.flushUpdates(),{stopReason:Y.success?"end_turn":"cancelled"}}catch(L){if(H.aborted||L instanceof Error&&L.name==="AbortError")return{stopReason:"cancelled"};return G.error(`[AcpSession ${this.id}] Slash command error:`,L),this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`[FAIL] 命令执行失败: ${L instanceof Error?L.message:"未知错误"}`}}),{stopReason:"cancelled"}}}async handleSideConversationCommand(z){if(this.pendingSideConversation)throw Error("A side conversation is already running");let H=new AbortController,L,Y=new Promise(($)=>{L=$});this.pendingSideConversation=H,this.pendingSideConversationCompletion=Y;try{return await this.handleSlashCommand(z,H.signal)}catch($){if(H.signal.aborted||$ instanceof Error&&$.name==="AbortError")return{stopReason:"cancelled"};throw $}finally{if(L(),this.pendingSideConversationCompletion===Y)this.pendingSideConversationCompletion=null;if(this.pendingSideConversation===H){if(this.pendingSideConversation=null,!this.destroyed&&this.pendingResumeRequested)this.ensurePendingResumeScheduled()}}}async sendAvailableCommands(){try{let z=kz(this.roots.hostStateRoot,this.runtime?.getAgentResources(),this.roots.kind),H=["model","permissions","theme","config","exit","ide"],Y=z.filter(($)=>!H.includes($.name)&&($.name!=="team"||this.runtime?.getConfig().agentTeamsEnabled===!0)).map(($)=>{let X;if($.usage){let Q=$.usage.replace(/^\/\w+\s*/,"").trim();if(Q)X=Q}if($.aliases?.length){let Q=`Aliases: ${$.aliases.join(", ")}`;X=X?`${X} | ${Q}`:Q}return{name:$.name,description:$.description,input:X?{hint:X}:void 0}});G.info(`[AcpSession ${this.id}] Sending available commands: ${JSON.stringify(Y.map(($)=>$.name))}`),this.sendUpdate({sessionUpdate:"available_commands_update",availableCommands:Y}),G.info(`[AcpSession ${this.id}] Sent ${Y.length} available commands`)}catch(z){G.error(`[AcpSession ${this.id}] Failed to send available commands:`,z)}}async prompt(z,H={}){if(R.setCurrentSession(this.id),!this.agent||!this.runtime)throw Error("Session not initialized");let L=this.resolvePrompt(z.prompt),Y=L.content,$=L.displayText,X=z._meta?.outputSchema??(H.pendingInputOnly?this.runtime.getPendingSteeringMessages().find((j)=>j.outputSchema)?.outputSchema:void 0),Q;if(X!==void 0)Q=Dz(X).schema;if($.trimStart().startsWith("!")){if(Q)throw Error("Output schemas cannot be combined with user shell commands");return this.handleUserShellCommand($)}let W=Nz($);if(W){if(Q)throw Error("Output schemas cannot be combined with slash commands");if(Array.isArray(Y)&&Y.some((j)=>j.type==="image_url"))throw Error("Side conversations do not accept image attachments");return this.handleSideConversationCommand(W.question?`/btw ${W.question}`:"/btw")}if(this.pendingPrompt){if(Q)throw Error("Wait for the active turn to finish before setting an output schema");if(/^\/goal(?:\s|$)/i.test($.trim()))return this.handleSlashCommand($,this.pendingPrompt.signal);let j=await this.runtime.enqueueSteering(Y,{allowBeforeTurn:!0});if(!j.accepted)throw Error(j.reason==="queue_full"?"Active turn steering queue is full":"Active turn is no longer steerable");if(G.debug(`[AcpSession ${this.id}] Queued steering for active turn (${j.queued})`),this.sendFollowUpQueueSnapshot(j.queue??await this.runtime.getFollowUpQueueSnapshot()),j.delivery==="next_turn")this.requestPendingResume();return{stopReason:"end_turn"}}let B=new AbortController,Z=()=>{B.abort(H.abortSignal?.reason)};if(H.abortSignal?.aborted)Z();else H.abortSignal?.addEventListener("abort",Z,{once:!0});let _=!1,U=!1,V=!1,T,E=new Promise((j)=>{T=j});this.pendingPrompt=B,this.pendingPromptCompletion=E;try{if(G.debug(`[AcpSession ${this.id}] Received prompt: ${$.slice(0,100)}...`),Iz($)){if(Q)throw Error("Output schemas cannot be combined with slash commands");return await this.handleSlashCommand($,B.signal)}let j={sessionId:this.id,userId:"acp-user",workspaceRoot:this.roots.hostStateRoot,executionRoot:this.roots.executionRoot,workspaceKind:this.roots.kind,messages:[...this.contextMessages],signal:B.signal,permissionMode:this.mapModeToPermissionMode(),onPermissionModeChange:async(J)=>{this.mode=this.mapPermissionModeToMode(J),this.sendUpdate({sessionUpdate:"current_mode_update",currentModeId:this.mode})},...this.options.taskWorktree?{worktreeActive:!0}:{},confirmationHandler:{requestConfirmation:async(J)=>{return this.requestPermission(J)}}},N=await wz(this.agent.chatStream(Y,j,{pendingInputOnly:H.pendingInputOnly,goalContinuationOnly:H.goalContinuationOnly,outputSchema:Q}),async(J)=>{switch(J.kind){case"content_delta":if(Q)break;if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:J.delta}});break;case"thinking_delta":if(J.delta.length>0)U=!0;this.sendUpdate({sessionUpdate:"agent_thought_chunk",content:{type:"text",text:J.delta}});break;case"tool_start":{V=!0;let D=J.toolCall,A=D.function.name;if(A===M)break;let q=this.mapToolKind(J.toolKind),K=`Executing ${A}`;if(A==="Task"&&"function"in D)try{let b=JSON.parse(D.function.arguments),w=b.resume_from??b.resume;if(typeof w==="string")K=`Resuming ${String(b.subagent_type||"subagent")} from ${w}`}catch{}this.sendUpdate({sessionUpdate:"tool_call",toolCallId:D.id,status:"in_progress",title:K,content:[],kind:q});break}case"tool_progress":{V=!0;let D=J.toolCall;if(D.function.name===M)break;this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:"in_progress",content:[{type:"content",content:{type:"text",text:J.update.message}}]});break}case"tool_result":{V=!0;let D=J.toolCall;if(D.function.name===M)break;let A=J.result,q=[],K=A.metadata;if(K?.kind==="patch"&&Array.isArray(K.changes))for(let w of K.changes){if(!w||typeof w!=="object"||!("path"in w)||typeof w.path!=="string")continue;q.push({type:"diff",path:w.path,oldText:"oldContent"in w&&typeof w.oldContent==="string"?w.oldContent:null,newText:"newContent"in w&&typeof w.newContent==="string"?w.newContent:null})}else if(K?.kind==="edit"&&typeof K.file_path==="string"&&typeof K.oldContent==="string"&&(typeof K.newContent==="string"||K.newContent===void 0))q.push({type:"diff",path:K.file_path,oldText:K.oldContent,newText:K.newContent??null});else{let w=D.function.name,QH=Tz(jz(qz(w,A),Vz));q.push({type:"content",content:{type:"text",text:QH}})}if(D.function.name==="Task"&&(K?.verificationVerdict==="pass"||K?.verificationVerdict==="fail"||K?.verificationVerdict==="partial"))q.unshift({type:"content",content:{type:"text",text:`Verification result: ${K.verificationVerdict.toUpperCase()}`}});let b=A.success?"completed":"failed";this.sendUpdate({sessionUpdate:"tool_call_update",toolCallId:D.id,status:b,content:q});break}case"structured_output":U=!0,this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:JSON.stringify(J.output)}});break;case"mcp_catalog_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP catalog r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
3
3
|
`}});break;case"mcp_content_changed":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP ${J.contentKind} r${J.revision} (${J.serverName}): +${J.added.length} -${J.removed.length} ~${J.updated.length}
|
|
4
4
|
`}});break;case"mcp_resource_updated":this.sendUpdate({sessionUpdate:"agent_message_chunk",content:{type:"text",text:`MCP resource updated r${J.revision} (${J.serverName}): ${J.uri}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-
|
|
1
|
+
import{$g as j,Sg as a,Tg as b,Ug as c,Vg as d,Wg as e,Xg as f,Yg as g,Zg as h,_g as i,ah as k}from"./chunk-qyj9khsj.js";import"./chunk-3kszepm6.js";import"./chunk-wcps5gjm.js";import"./chunk-vbjgcn49.js";import"./chunk-06hkf59s.js";import"./chunk-qskr05jh.js";import"./chunk-3y2x6fb6.js";import"./chunk-2b1f5rwp.js";import"./chunk-kv458q06.js";import"./chunk-5v0jcyea.js";import"./chunk-2f8d0km4.js";import"./chunk-ddvdc2p0.js";import"./chunk-2mk914vk.js";import"./chunk-j8hbddjp.js";import"./chunk-4cdk4mds.js";import"./chunk-xhg70jby.js";import"./chunk-rvs364rz.js";import"./chunk-vw9paban.js";import"./chunk-4wx5sya5.js";import"./chunk-eg3ms291.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,k as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,j as createEmptySessionAgentResources,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
|