blade-code 0.10.16 → 0.10.18

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.
Files changed (39) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-y61ne49f.js → chunk-0ke6fsmy.js} +1 -1
  3. package/dist/{chunk-y26ngyc2.js → chunk-19z401aq.js} +1 -1
  4. package/dist/{chunk-9m1ayjve.js → chunk-1gqmy8aq.js} +1 -1
  5. package/dist/{chunk-gc9wfvfd.js → chunk-1re8nwdc.js} +1 -1
  6. package/dist/{chunk-ynncadtz.js → chunk-2rkdyx6m.js} +1 -1
  7. package/dist/{chunk-qwpbwhmn.js → chunk-4g5wvaa9.js} +1 -1
  8. package/dist/{chunk-f2qj464t.js → chunk-88n14h5d.js} +1 -1
  9. package/dist/{chunk-0ndm72az.js → chunk-8rzwyknk.js} +15 -13
  10. package/dist/{chunk-vhxarqb0.js → chunk-9xpq3a19.js} +1 -1
  11. package/dist/{chunk-xzhk0smg.js → chunk-a43d70k9.js} +1 -1
  12. package/dist/{chunk-sxj3psy3.js → chunk-ae66ffh3.js} +2 -2
  13. package/dist/{chunk-mbrevmbp.js → chunk-agsvdf45.js} +1 -1
  14. package/dist/{chunk-3wbheq1y.js → chunk-awnrm721.js} +1 -1
  15. package/dist/{chunk-n6jjfyqn.js → chunk-c6t2nt3v.js} +1 -1
  16. package/dist/{chunk-y78smk7g.js → chunk-cx0yycfr.js} +1 -1
  17. package/dist/{chunk-djktk1az.js → chunk-dc094tzc.js} +1 -1
  18. package/dist/{chunk-ajy99edp.js → chunk-eb6d2sqj.js} +1 -1
  19. package/dist/chunk-h18y4067.js +200 -0
  20. package/dist/{chunk-s31msata.js → chunk-h7pregxp.js} +1 -1
  21. package/dist/{chunk-dskgbv7c.js → chunk-hatwwhm2.js} +1 -1
  22. package/dist/{chunk-8brheywa.js → chunk-j0wssvjp.js} +1 -1
  23. package/dist/{chunk-mcr47s40.js → chunk-jba4g4y1.js} +3 -3
  24. package/dist/{chunk-wxvkrxf4.js → chunk-jsey85bn.js} +1 -1
  25. package/dist/{chunk-4twtqram.js → chunk-n8egkfa0.js} +1 -1
  26. package/dist/{chunk-h1kgh7xz.js → chunk-nbx7kcwy.js} +1 -1
  27. package/dist/{chunk-as56atkw.js → chunk-nddkzabm.js} +1 -1
  28. package/dist/chunk-nke2117v.js +1 -0
  29. package/dist/{chunk-h37yw6g3.js → chunk-pq1p9jz6.js} +1 -1
  30. package/dist/{chunk-kn8xx8ng.js → chunk-qnnyasc0.js} +1 -1
  31. package/dist/{chunk-2e03enfb.js → chunk-s7cp67vw.js} +1 -1
  32. package/dist/{chunk-ky0v990x.js → chunk-wbxv9wcn.js} +1 -1
  33. package/dist/{chunk-2g41y2tz.js → chunk-xn02evty.js} +1 -1
  34. package/dist/{chunk-gwx7jz87.js → chunk-xyzhpd3j.js} +1 -1
  35. package/dist/{chunk-4k615fx6.js → chunk-y72p0x68.js} +1 -1
  36. package/dist/{chunk-334jhwxz.js → chunk-yn2fvjfm.js} +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunk-51hjqrt8.js +0 -1
  39. package/dist/chunk-n2hwfw7v.js +0 -200
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{Cc as W}from"./chunk-wxvkrxf4.js";import{Fc as F,Gc as M}from"./chunk-k3nkcaap.js";import"./chunk-y78smk7g.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-ky0v990x.js";import"./chunk-q3c07kb4.js";import{he as T}from"./chunk-6207mbmr.js";import"./chunk-h37yw6g3.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{lf as N,mf as B}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import{Qf as J}from"./chunk-6g5k5de1.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(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 c(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 m(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 t(){if(c(E)){let{getVersion:K}=await import("./chunk-ynncadtz.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-2g41y2tz.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-4svjvyyd.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-vhxarqb0.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-gc9wfvfd.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-4twtqram.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-51hjqrt8.js"),import("./chunk-djktk1az.js"),import("./chunk-sxj3psy3.js"),import("./chunk-entmz5b1.js"),import("./chunk-n6jjfyqn.js"),import("./chunk-t3b689pm.js"),import("./chunk-zt5wq0qj.js"),import("./chunk-y61ne49f.js"),import("./chunk-fvj1mzgs.js"),import("./chunk-h1kgh7xz.js")]),A=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(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).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),p&&Z.stack)console.error(`
2
+ import{Cc as W}from"./chunk-jsey85bn.js";import{Fc as F,Gc as M}from"./chunk-k3nkcaap.js";import"./chunk-cx0yycfr.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-wbxv9wcn.js";import"./chunk-q3c07kb4.js";import{he as T}from"./chunk-6207mbmr.js";import"./chunk-pq1p9jz6.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{lf as N,mf as B}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import{Qf as J}from"./chunk-6g5k5de1.js";import v from"node:path";var E=process.argv.slice(2),I=u(E),p=I!==null;if(I!==null)T.setGlobalDebug(I);function u(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 c(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 m(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 t(){if(c(E)){let{getVersion:K}=await import("./chunk-2rkdyx6m.js");console.log(K());return}let Q=process.cwd(),Y=F(Q);M(Y),N(B());let U=m(E,"--plugin-dir","--pluginDir");if(U.length>0){let{configureInvocationPluginDirs:K}=await import("./chunk-xn02evty.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-4svjvyyd.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-9xpq3a19.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-1re8nwdc.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-n8egkfa0.js");await K();return}let[{default:X},{hideBin:G},{cliConfig:z,globalOptions:$},{loadConfiguration:_,validateOutput:D,validatePermissions:R},{doctorCommands:S},{installCommands:k},{mcpCommands:O},{projectsCommands:y},{scheduleCommands:b},{serveCommand:V},{updateCommands:P},{webCommand:x}]=await Promise.all([import("yargs"),import("yargs/helpers"),import("./chunk-nke2117v.js"),import("./chunk-dc094tzc.js"),import("./chunk-ae66ffh3.js"),import("./chunk-entmz5b1.js"),import("./chunk-c6t2nt3v.js"),import("./chunk-t3b689pm.js"),import("./chunk-zt5wq0qj.js"),import("./chunk-0ke6fsmy.js"),import("./chunk-fvj1mzgs.js"),import("./chunk-nbx7kcwy.js")]),A=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(O).command(y).command(b).command(S).command(P).command(k).command(x).command(V).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),p&&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,h=import("./chunk-87vsgqvy.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-334jhwxz.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
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,h=import("./chunk-87vsgqvy.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-yn2fvjfm.js")]),H={...K,initialMessage:L,debug:K.debug,print:Boolean(K.print),versionCheckPromise:h};delete H._,delete H.$0,delete H.message,w(f(j,H),{patchConsole:!0,exitOnCtrlC:!1,alternateBuffer:!1})});try{await A.parse()}catch(K){console.error("Error: Parse error:",K),process.exit(1)}}if(J.main==J.module)t().catch(console.error);export{t as main};
@@ -1 +1 @@
1
- import{f as y,g as A,h as C,i as D}from"./chunk-gwx7jz87.js";import"./chunk-zdkc4kj1.js";import"./chunk-fa6313dv.js";import"./chunk-2e03enfb.js";import"./chunk-3wbheq1y.js";import"./chunk-mcr47s40.js";import"./chunk-9m1ayjve.js";import"./chunk-qt114yth.js";import"./chunk-n2hwfw7v.js";import"./chunk-095x2ykj.js";import"./chunk-ajy99edp.js";import"./chunk-0ndm72az.js";import"./chunk-k3nkcaap.js";import{Xc as q}from"./chunk-y78smk7g.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-kn8xx8ng.js";import"./chunk-as56atkw.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-ky0v990x.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-h37yw6g3.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
1
+ import{f as y,g as A,h as C,i as D}from"./chunk-xyzhpd3j.js";import"./chunk-zdkc4kj1.js";import"./chunk-fa6313dv.js";import"./chunk-s7cp67vw.js";import"./chunk-awnrm721.js";import"./chunk-jba4g4y1.js";import"./chunk-1gqmy8aq.js";import"./chunk-qt114yth.js";import"./chunk-h18y4067.js";import"./chunk-095x2ykj.js";import"./chunk-eb6d2sqj.js";import"./chunk-8rzwyknk.js";import"./chunk-k3nkcaap.js";import{Xc as q}from"./chunk-cx0yycfr.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-qnnyasc0.js";import"./chunk-nddkzabm.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-wbxv9wcn.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-pq1p9jz6.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import H from"chalk";var R={command:"serve",describe:"Start a headless Blade server (no browser)",builder:y,handler:async(E)=>{let f=A(E);if(await q(),!process.env.BLADE_SERVER_PASSWORD)console.log(H.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let b=await D.listenAsync(f);if(console.log(`Blade server listening on http://${b.hostname}:${b.port}`),f.hostname==="0.0.0.0"){let F=C();for(let G of F)console.log(` Network: http://${G}:${b.port}`)}await new Promise(()=>{}),await b.stop()}};export{R as serveCommand};
@@ -1 +1 @@
1
- import{$b as d,Yb as a,Zb as b,_b as c,ac as e,bc as f}from"./chunk-ajy99edp.js";import"./chunk-0ndm72az.js";import"./chunk-5chec8rs.js";import"./chunk-6sb7cg95.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
1
+ import{$b as d,Yb as a,Zb as b,_b as c,ac as e,bc as f}from"./chunk-eb6d2sqj.js";import"./chunk-8rzwyknk.js";import"./chunk-5chec8rs.js";import"./chunk-6sb7cg95.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as __setSessionSnapshotIOForTesting,b as __resetSessionSnapshotIOForTesting,f as SessionService,c as SessionMissingCreationError,d as SessionArchivedError,e as SessionArchiveConflictError};
@@ -1,4 +1,4 @@
1
- import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{de as Ut}from"./chunk-ky0v990x.js";import{Ae as un,Be as Mn,Ce as wn,Ee as S,He as yn,Ie as Ht,Je as Bt,Ke as R,Le as qt,ke as xt,le as tn,me as en,ne as zt,oe as B,pe as rn,qe as gt,re as mt,te as dn,ue as En,ve as U,we as on,xe as pn,ye as cn,ze as lt}from"./chunk-h37yw6g3.js";import{af as X,cf as x}from"./chunk-96h588rd.js";import{mf as vt}from"./chunk-prgh321y.js";import{Af as sn,zf as nn}from"./chunk-dskgbv7c.js";import{Qf as ss}from"./chunk-6g5k5de1.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
1
+ import{rb as jt,sb as Xt,tb as bn,ub as Tn,vb as fn}from"./chunk-095x2ykj.js";import{de as Ut}from"./chunk-wbxv9wcn.js";import{Ae as un,Be as Mn,Ce as wn,Ee as S,He as yn,Ie as Ht,Je as Bt,Ke as R,Le as qt,ke as xt,le as tn,me as en,ne as zt,oe as B,pe as rn,qe as gt,re as mt,te as dn,ue as En,ve as U,we as on,xe as pn,ye as cn,ze as lt}from"./chunk-pq1p9jz6.js";import{af as X,cf as x}from"./chunk-96h588rd.js";import{mf as vt}from"./chunk-prgh321y.js";import{Af as sn,zf as nn}from"./chunk-hatwwhm2.js";import{Qf as ss}from"./chunk-6g5k5de1.js";import{EventEmitter as hs}from"events";import Un from"node:path";function An(t){if(t===void 0)return"undefined";if(typeof t==="string")return t;try{let i=JSON.stringify(t);return i===void 0?String(t):i}catch{return String(t)}}function _n(t){let i=t;switch(t.code){case"type":return`类型错误:${t.message}`;case"required":return"缺少必需参数";case"minLength":return`字符串过短:${t.message}`;case"maxLength":return`字符串过长:${t.message}`;case"minimum":case"exclusiveMinimum":return`数值太小:${t.message}`;case"maximum":case"exclusiveMaximum":return`数值太大:${t.message}`;case"minItems":return`数组元素过少:${t.message}`;case"maxItems":return`数组元素过多:${t.message}`;case"format":return`格式错误:${t.message}`;case"enum":return`必须是枚举允许的值之一:${t.message}`;case"const":return`必须是指定的字面量值:${t.message}`;case"additionalProperties":case"unevaluatedProperties":return`包含未知参数:${t.message}`;case"anyOf":case"oneOf":return"不符合任何有效的类型定义";case"~refine":return t.message||"自定义验证失败";default:return t.message||`验证失败:${An(i)}`}}class Jt extends Error{issues;type;constructor(t,i,n="validation_error"){super(t);this.issues=i;this.type=n;this.name="ToolValidationError"}}function Vt(t,i){let n=X(t,i);if(n.success)return n.data;let s=n.error.issues.map((r)=>({field:r.path.length>0?r.path.join("."):"root",message:_n(r),value:r.value})),e=s.length===1?`参数验证失败 [${s[0].field}]: ${s[0].message}`:`参数验证失败 (${s.length} 个错误):
2
2
  ${s.map((r)=>` - ${r.field}: ${r.message}`).join(`
3
3
  `)}`;throw new Jt(e,s)}function st(t){if(!t||typeof t!=="object")return;let i=t;if(i.type==="object"&&i.properties)i.required??=[],i.additionalProperties??=!1;for(let n of Object.values(i))if(Array.isArray(n))for(let s of n)st(s);else st(n)}function et(t){let i=JSON.parse(JSON.stringify(t,(n,s)=>n.startsWith("~")?void 0:s));return st(i),i}class rt{toolName;params;executeFn;descriptionFn;affectedPathsFn;constructor(t,i,n,s,e){this.toolName=t;this.params=i;this.executeFn=n;this.descriptionFn=s;this.affectedPathsFn=e}getDescription(){if(this.descriptionFn)return this.descriptionFn(this.params);return`执行工具: ${this.toolName}`}getAffectedPaths(){if(this.affectedPathsFn)return this.affectedPathsFn(this.params);return[]}async execute(t,i,n){let s={signal:t,updateOutput:i,...n};return this.executeFn(this.params,s)}}function Gt(t){return{name:t.name,displayName:t.displayName,kind:t.kind,isReadOnly:t.isReadOnly??jt(t.kind),isConcurrencySafe:t.isConcurrencySafe??!1,parallelism:t.parallelism??(t.isConcurrencySafe?"shared":"exclusive"),strict:t.strict??!1,description:t.description,version:t.version||"1.0.0",category:t.category,tags:t.tags||[],getFunctionDeclaration(){let i=et(t.schema),n=t.description.short;if(t.description.long)n+=`
4
4
 
@@ -1,4 +1,4 @@
1
- import{m as R,n as I,o as C,p as v,q as S}from"./chunk-xzhk0smg.js";import{F as y,L as w}from"./chunk-mcr47s40.js";import"./chunk-9m1ayjve.js";import"./chunk-qt114yth.js";import{Va as x,hb as U}from"./chunk-n2hwfw7v.js";import"./chunk-095x2ykj.js";import{Qb as k,bc as b}from"./chunk-ajy99edp.js";import"./chunk-0ndm72az.js";import{uc as P}from"./chunk-mbrevmbp.js";import{wc as h,xc as O,yc as M}from"./chunk-s31msata.js";import{zc as z}from"./chunk-wt7gy9bm.js";import"./chunk-k3nkcaap.js";import{Wc as N}from"./chunk-y78smk7g.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-kn8xx8ng.js";import"./chunk-as56atkw.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-ky0v990x.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-h37yw6g3.js";import{Ye as D}from"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as E}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.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(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
1
+ import{m as R,n as I,o as C,p as v,q as S}from"./chunk-a43d70k9.js";import{F as y,L as w}from"./chunk-jba4g4y1.js";import"./chunk-1gqmy8aq.js";import"./chunk-qt114yth.js";import{Va as x,hb as U}from"./chunk-h18y4067.js";import"./chunk-095x2ykj.js";import{Qb as k,bc as b}from"./chunk-eb6d2sqj.js";import"./chunk-8rzwyknk.js";import{uc as P}from"./chunk-agsvdf45.js";import{wc as h,xc as O,yc as M}from"./chunk-h7pregxp.js";import{zc as z}from"./chunk-wt7gy9bm.js";import"./chunk-k3nkcaap.js";import{Wc as N}from"./chunk-cx0yycfr.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-qnnyasc0.js";import"./chunk-nddkzabm.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-wbxv9wcn.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-pq1p9jz6.js";import{Ye as D}from"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as E}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import g from"yargs";import{hideBin as c}from"yargs/helpers";var m=new Set(Object.values(D));function d(j){if(j&&m.has(j))return j;return}function l(j){return j.command("* [message]","Print response and exit (useful for pipes)",(q)=>q.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(q)=>{if(!q.p)return;let B=await u(q);process.exit(B)})}async function u(j,q=process){let B;try{await R();let T=await I({message:j.message,_:j._,defaultMessage:"Hello"}),J=await C(T);if(J.mode==="output"){if(J.content)q.stdout.write(`${J.content}
2
2
  `);return J.exitCode??0}let K=J.content,X=await v(j),Y=K.trimStart().startsWith("!")?K.trimStart().slice(1).trim():void 0;if(Y!==void 0&&X)throw Error("Output schemas cannot be combined with user shell commands");let{sessionId:G,messages:F,metadata:V}=await S({sessionId:j.sessionId,continue:j.continue,resume:j.resume,forkSession:j.forkSession,fallbackSessionPrefix:"print"}),W=V?.projectPath??E(),Z=d(j.permissionMode)??V?.permissionMode??N()?.permissionMode??"default";await b.setSessionPermissionMode(G,W,Z);let _=await U.cancelPendingNonInteractive(W,G)?await b.loadSessionModelContext(G,W):F;if(B=await y.create({sessionId:G,workspaceRoot:W,modelId:j.model,permissionMode:Z,mcpConfig:j.mcpConfig,strictMcpConfig:j.strictMcpConfig,agents:j.agents?z(j.agents):void 0,..._.length>0?{sessionStart:{isResume:!0,resumeSessionId:G}}:{}}),Y!==void 0){let H=await B.executeUserShellCommand(Y);if(j.outputFormat==="json")q.stdout.write(`${JSON.stringify(H,null,2)}
3
3
  `);else if(j.outputFormat==="stream-json")q.stdout.write(`${JSON.stringify({type:"user_shell_completed",executionId:H.executionId,record:H.record})}
4
4
  `);else q.stdout.write(`${k(H.record)}
@@ -1 +1 @@
1
- import{Af as c,Bf as d,Cf as e,Df as f,yf as a,zf as b}from"./chunk-dskgbv7c.js";import"./chunk-6g5k5de1.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
1
+ import{Af as c,Bf as d,Cf as e,Df as f,yf as a,zf as b}from"./chunk-hatwwhm2.js";import"./chunk-6g5k5de1.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +1 @@
1
- import{$c as k,Rc as a,Sc as b,Tc as c,Uc as d,Vc as e,Wc as f,Xc as g,Yc as h,Zc as i,_c as j,ad as l,bd as m,cd as n,dd as o,ed as p,fd as q}from"./chunk-y78smk7g.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-6207mbmr.js";import"./chunk-h37yw6g3.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
1
+ import{$c as k,Rc as a,Sc as b,Tc as c,Uc as d,Vc as e,Wc as f,Xc as g,Yc as h,Zc as i,_c as j,ad as l,bd as m,cd as n,dd as o,ed as p,fd as q}from"./chunk-cx0yycfr.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-6207mbmr.js";import"./chunk-pq1p9jz6.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1 +1 @@
1
- import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-n2hwfw7v.js";import"./chunk-095x2ykj.js";import"./chunk-ajy99edp.js";import"./chunk-0ndm72az.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-5chec8rs.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-ky0v990x.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.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
+ import{$a as i,Ma as a,Na as b,Pa as c,Ta as d,Ua as e,Va as f,Za as g,_a as h,ab as j,bb as k,ib as l,jb as m,kb as n,lb as o,mb as p,nb as q,ob as r}from"./chunk-h18y4067.js";import"./chunk-095x2ykj.js";import"./chunk-eb6d2sqj.js";import"./chunk-8rzwyknk.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-5chec8rs.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-wbxv9wcn.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.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,14 +1,16 @@
1
- import{ie as o}from"./chunk-6207mbmr.js";import{Gf as l,If as C,Kf as N,Of as L,Pf as n}from"./chunk-yvf4nmds.js";import{Qf as f}from"./chunk-6g5k5de1.js";import{stat as i}from"node:fs/promises";import B from"node:path";import*as K from"node:path";var a=50,s=100,t=/^[A-Za-z0-9_-]+$/,e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function __(_){return typeof _==="string"&&e.test(_)&&Number.isFinite(Date.parse(_))}function p(_){return typeof _==="string"&&K.isAbsolute(_)}function E_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function R_(_){try{if(!t.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||p(R.cwd))||!__(R.lastMessageTime)||!p(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:K.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:K.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function I(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function W_(_){if(!_.cursor)return;let E=R_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function w_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!K.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?a:W;if(!Number.isInteger(k)||k<1||k>s)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:K.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function $_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function x_(_,E){let R=[..._],W=W_(E);if(W)R=R.filter((k)=>$_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:E_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function k_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function q(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:P(_,E),createdAt:R.data.createdAt}}function P(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function S(_,E){q(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!k_(k)})}function z(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(q(E,R.data.targetMessageId),R.data.mode!=="code")E=S(E,R.data.targetMessageId)}return E}function u_(_){let E=z(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:P(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function I_(_,E){let R=z(_),W=q(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:S(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as x from"node:fs";import{createReadStream as H_}from"node:fs";import*as X from"node:fs/promises";import*as y from"node:path";import{createInterface as M_}from"node:readline";var c=65536;function Q_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function w(_,E="session transcript"){let R=_.split(`
1
+ import{ie as n}from"./chunk-6207mbmr.js";import{Gf as l,If as C,Kf as N,Of as L,Pf as o}from"./chunk-yvf4nmds.js";import{Qf as f}from"./chunk-6g5k5de1.js";import{stat as i}from"node:fs/promises";import B from"node:path";import*as U from"node:path";var a=50,s=100,t=/^[A-Za-z0-9_-]+$/,e=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})$/;function __(_){return typeof _==="string"&&e.test(_)&&Number.isFinite(Date.parse(_))}function p(_){return typeof _==="string"&&U.isAbsolute(_)}function E_(_){return Buffer.from(JSON.stringify(_),"utf8").toString("base64url")}function R_(_){try{if(!t.test(_))throw Error("invalid");let E=Buffer.from(_,"base64url").toString("utf8");if(Buffer.from(E,"utf8").toString("base64url")!==_)throw Error("invalid");let R=JSON.parse(E);if(R.version!==1||typeof R.includeSubagents!=="boolean"||R.archived!==void 0&&typeof R.archived!=="boolean"||!(R.cwd===null||p(R.cwd))||!__(R.lastMessageTime)||!p(R.projectPath)||!C(R.sessionId))throw Error("invalid");return{version:1,cwd:R.cwd===null?null:U.resolve(R.cwd),includeSubagents:R.includeSubagents,archived:R.archived??!1,lastMessageTime:R.lastMessageTime,projectPath:U.resolve(R.projectPath),sessionId:R.sessionId}}catch{throw Error("Invalid session cursor")}}function q(_){let E="";for(let R=0;R<_.length;R+=1)E+=_.charCodeAt(R).toString(16).padStart(4,"0");return E}function W_(_){if(!_.cursor)return;let E=R_(_.cursor);if(E.cwd!==_.cwd||E.includeSubagents!==_.includeSubagents||(E.archived??!1)!==_.archived)throw Error("Session cursor scope does not match this query");return E}function w_(_={}){let{cwd:E,cursor:R,limit:W,includeSubagents:$=!1,archived:H=!1}=_;if(E!==void 0&&!U.isAbsolute(E))throw Error("Session catalog cwd must be absolute");let k=W===void 0?a:W;if(!Number.isInteger(k)||k<1||k>s)throw Error("Session catalog limit must be an integer from 1 to 100");return{cwd:E===void 0?null:U.resolve(E),cursor:R??void 0,limit:k,includeSubagents:$,archived:H}}function $_(_,E){if(_.lastMessageTime>E.lastMessageTime)return-1;if(_.lastMessageTime<E.lastMessageTime)return 1;if(_.projectPath<E.projectPath)return-1;if(_.projectPath>E.projectPath)return 1;if(_.sessionId<E.sessionId)return-1;if(_.sessionId>E.sessionId)return 1;return 0}function x_(_,E){let R=[..._],W=W_(E);if(W)R=R.filter((k)=>$_(k,{sessionId:W.sessionId,projectPath:W.projectPath,lastMessageTime:W.lastMessageTime})>0);let $=R.slice(0,E.limit);if($.length===0||R.length<=$.length)return{sessions:$};let H=$[$.length-1];return{sessions:$,nextCursor:E_({version:1,cwd:E.cwd,includeSubagents:E.includeSubagents,archived:E.archived,lastMessageTime:H.lastMessageTime,projectPath:H.projectPath,sessionId:H.sessionId})}}function k_(_){return _.type==="message_created"||_.type==="part_created"||_.type==="part_updated"||_.type==="turn_started"||_.type==="turn_completed"||_.type==="turn_aborted"||_.type==="interaction_requested"||_.type==="interaction_responded"||_.type==="interaction_recovered"||_.type==="review_started"||_.type==="review_completed"}function J(_){return _.type==="message_created"&&_.data.role==="user"&&(_.data.inboxMessageId!==void 0||_.data.parentMessageId===void 0)}function u(_,E){let R=_.find((W)=>J(W)&&W.data.messageId===E);if(!R)throw Error(`Rewind checkpoint not found: ${E}`);return{messageId:E,preview:P(_,E),createdAt:R.data.createdAt}}function P(_,E){let R=_.flatMap((W)=>{if(W.type!=="part_created"||W.data.messageId!==E)return[];if(W.data.partType==="text"){let $=W.data.payload;return typeof $.text==="string"?[$.text]:[]}if(W.data.partType==="image")return["[Image]"];return[]}).join("").trim();if(R.length<=160)return R;return`${R.slice(0,160)}...`}function c(_,E){u(_,E);let R=_.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),W=_[R],$=W?.type==="message_created"?W.data.inboxMessageId:void 0,H=new Set(_.flatMap((k)=>k.type==="turn_started"&&$&&k.data.inputMessageIds?.includes($)?[k.data.turnId]:[]));return _.filter((k,M)=>{if((k.type==="turn_started"||k.type==="turn_completed"||k.type==="turn_aborted")&&H.has(k.data.turnId))return!1;return M<R||!k_(k)})}function z(_){let E=[];for(let R of _){if(R.type!=="session_rewound"){E.push(R);continue}if(u(E,R.data.targetMessageId),R.data.mode!=="code")E=c(E,R.data.targetMessageId)}return E}function I_(_){let E=z(_);return E.filter(J).map((R)=>({messageId:R.data.messageId,preview:P(E,R.data.messageId),createdAt:R.data.createdAt})).reverse()}function q_(_,E){let R=z(_),W=u(R,E),$=R.findIndex((k)=>k.type==="message_created"&&k.data.messageId===E),H=R.slice($);return{checkpoint:W,projectedEntries:c(R,E),removedTurns:H.filter(J).length,snapshotMessageIds:H.flatMap((k)=>k.type==="part_created"&&k.data.partType==="tool_call"?[k.data.partId]:[])}}import*as x from"node:fs";import{createReadStream as H_}from"node:fs";import*as X from"node:fs/promises";import*as y from"node:path";import{createInterface as M_}from"node:readline";var S=65536;function Q_(_,E,R){let W=_.trim();if(!W)return;try{return JSON.parse(W)}catch($){throw Error(`Invalid session JSONL in ${R} at line ${E}`,{cause:$})}}function w(_,E="session transcript"){let R=_.split(`
2
2
  `),W=!_.endsWith(`
3
- `),$=[];for(let[H,k]of R.entries())try{let M=Q_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class G{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return G.stampSeqFrom(_,G.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=G.stampSeqFrom(_,W),H=`${$.map((k)=>JSON.stringify(k)).join(`
3
+ `),$=[];for(let[H,k]of R.entries())try{let M=Q_(k,H+1,E);if(M){if(typeof M.seq!=="number")M.seq=$.length+1;$.push(M)}}catch(M){if(W&&H===R.length-1)break;throw M}return $}class Y{static appendQueues=new Map;filePath;constructor(_){this.filePath=_}static maxSeq(_){let E=0;for(let R of _)if(typeof R.seq==="number"&&R.seq>E)E=R.seq;return E}static stampSeqFrom(_,E){let R=E;return _.map((W)=>{if(typeof W.seq==="number"){if(W.seq>R)R=W.seq;return W}return R+=1,{...W,seq:R}})}static stampSeq(_,E){return Y.stampSeqFrom(_,Y.maxSeq(E))}async append(_){try{let[E]=await this.appendEntries([_]);return E}catch(E){throw console.error(`[JSONLStore] 追加写入失败: ${this.filePath}`,E),E}}async appendBatch(_){try{return await this.appendEntries(_)}catch(E){throw console.error(`[JSONLStore] 批量追加写入失败: ${this.filePath}`,E),E}}async appendEntries(_){if(_.length===0)return[];return this.enqueue(async()=>{await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E=await X.open(this.filePath,"a+",384);try{let R=await this.repairIncompleteTail(E),W=await this.readTailSeq(E),$=Y.stampSeqFrom(_,W),H=`${$.map((k)=>JSON.stringify(k)).join(`
4
4
  `)}
5
- `;return await E.appendFile(R+H,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await X.open(this.filePath,"wx",384);let W=`${G.stampSeq(_,[]).map(($)=>JSON.stringify($)).join(`
5
+ `;return await E.appendFile(R+H,"utf8"),await E.sync(),$}finally{await E.close()}})}async createExclusive(_){if(_.length===0)throw Error("Cannot create an empty session transcript");await X.mkdir(y.dirname(this.filePath),{recursive:!0,mode:493});let E;try{E=await X.open(this.filePath,"wx",384);let W=`${Y.stampSeq(_,[]).map(($)=>JSON.stringify($)).join(`
6
6
  `)}
7
7
  `;await E.writeFile(W,"utf-8"),await E.sync()}catch(R){if(E)await E.close(),E=void 0,await X.unlink(this.filePath).catch(()=>{return});throw R}finally{await E?.close()}}async readAll(){if(!x.existsSync(this.filePath))return[];let _=await X.readFile(this.filePath,"utf-8");return w(_,this.filePath)}async readStream(_){return new Promise((E,R)=>{if(!x.existsSync(this.filePath)){E();return}let W=H_(this.filePath,"utf-8"),$=M_({input:W,crlfDelay:Number.POSITIVE_INFINITY}),H=0;$.on("line",async(k)=>{let M=k.trim();if(M.length===0)return;try{let V=JSON.parse(M);if(H+=1,typeof V.seq!=="number")V.seq=H;await _(V)}catch(V){console.warn(`[JSONLStore] 解析 JSON 行失败: ${M}`,V)}}),$.on("close",()=>E()),$.on("error",R),W.on("error",R)})}async filter(_){let E=[];return await this.readStream((R)=>{if(_(R))E.push(R)}),E}async readLast(_){return(await this.readAll()).slice(-_)}async readFromSeq(_){return(await this.readAll()).filter((R)=>(R.seq??0)>=_)}async getStats(){try{if(!x.existsSync(this.filePath))return{exists:!1,size:0,lineCount:0};let _=await X.stat(this.filePath),R=(await X.readFile(this.filePath,"utf-8")).split(`
8
- `).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await X.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await X.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await X.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=w(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await X.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){return this.appendValidatedAsync(async(E)=>_(E))}async appendValidatedAsync(_){return this.enqueue(async()=>{let E=await X.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R),[k]=G.stampSeq([H],R),M=`${W}${JSON.stringify(k)}
9
- `;return await E.write(M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}getFilePath(){return this.filePath}async enqueue(_){let R=(G.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(_),W=R.then(()=>{return},()=>{return});G.appendQueues.set(this.filePath,W);try{return await R}finally{if(G.appendQueues.get(this.filePath)===W)G.appendQueues.delete(this.filePath)}}async readCommittedState(_,E=this.filePath){let R=await this.repairIncompleteTail(_),W=await _.readFile("utf8"),$=w(W,E),{size:H}=await _.stat();return{entries:$,separator:R,size:H}}async readTailSeq(_){let{size:E}=await _.stat();if(E===0)return 0;let R=Math.max(0,E-c),W=Buffer.allocUnsafe(E-R);await _.read(W,0,W.length,R);let $=W.toString("utf8").split(`
10
- `);for(let k=$.length-1;k>=0;k--){let M=$[k].trim();if(!M)continue;if(k===0&&R>0)break;try{let V=JSON.parse(M).seq;if(typeof V==="number")return V}catch{}break}let H=await _.readFile("utf8");return G.maxSeq(w(H,this.filePath))}async repairIncompleteTail(_){let{size:E}=await _.stat();if(E===0)return"";let R=Buffer.allocUnsafe(1);if(await _.read(R,0,1,E-1),R[0]===10)return"";let W=await this.findTailStart(_,E),$=Buffer.allocUnsafe(E-W);await _.read($,0,$.length,W);try{return JSON.parse($.toString("utf8").trim()),`
11
- `}catch{return await _.truncate(W),""}}async findTailStart(_,E){let R=E;while(R>0){let W=Math.max(0,R-c),$=Buffer.allocUnsafe(R-W);await _.read($,0,$.length,W);let H=$.lastIndexOf(10);if(H>=0)return W+H+1;R=W}return 0}}function V_(){return typeof globalThis.Bun<"u"}function X_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.prepare(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>_.pragma(E,{simple:!0}),close:()=>_.close()}}function Y_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.query(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>{let R=_.query(`PRAGMA ${E}`).get();if(!R)return;let W=Object.values(R);return W.length===1?W[0]:R},close:()=>_.close()}}var G_=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
8
+ `).filter((W)=>W.trim().length>0).length;return{exists:!0,size:_.size,lineCount:R}}catch(_){return console.error(`[JSONLStore] 获取统计信息失败: ${this.filePath}`,_),{exists:!1,size:0,lineCount:0}}}async exists(){try{return await X.access(this.filePath),!0}catch{return!1}}async delete(){try{return await this.enqueue(async()=>{try{return await X.unlink(this.filePath),!0}catch(_){if(_.code==="ENOENT")return!1;throw _}})}catch(_){throw console.error(`[JSONLStore] 删除文件失败: ${this.filePath}`,_),_}}async deleteValidated(_){return this.enqueue(async()=>{let E;try{E=await X.open(this.filePath,"r")}catch(W){if(W.code==="ENOENT")return!1;throw W}let R;try{R=w(await E.readFile("utf8"),"session transcript")}finally{await E.close()}if(!_(R))return!1;try{return await X.unlink(this.filePath),!0}catch(W){if(W.code==="ENOENT")return!1;throw W}})}async appendValidated(_){return this.appendValidatedAsync(async(E)=>_(E))}async appendValidatedBatch(_){return this.appendValidatedBatchAsync(async(E)=>_(E))}async appendValidatedBatchAsync(_){return this.enqueue(async()=>{let E=await X.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R);if(H.length===0)return[];let k=Y.stampSeq(H,R),M=`${k.map((V)=>JSON.stringify(V)).join(`
9
+ `)}
10
+ `;return await E.write(W+M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}async appendValidatedAsync(_){return this.enqueue(async()=>{let E=await X.open(this.filePath,"r+");try{let{entries:R,separator:W,size:$}=await this.readCommittedState(E,"session transcript"),H=await _(R),[k]=Y.stampSeq([H],R),M=`${W}${JSON.stringify(k)}
11
+ `;return await E.write(M,$,"utf8"),await E.sync(),k}finally{await E.close()}})}getFilePath(){return this.filePath}async enqueue(_){let R=(Y.appendQueues.get(this.filePath)??Promise.resolve()).catch(()=>{return}).then(_),W=R.then(()=>{return},()=>{return});Y.appendQueues.set(this.filePath,W);try{return await R}finally{if(Y.appendQueues.get(this.filePath)===W)Y.appendQueues.delete(this.filePath)}}async readCommittedState(_,E=this.filePath){let R=await this.repairIncompleteTail(_),W=await _.readFile("utf8"),$=w(W,E),{size:H}=await _.stat();return{entries:$,separator:R,size:H}}async readTailSeq(_){let{size:E}=await _.stat();if(E===0)return 0;let R=Math.max(0,E-S),W=Buffer.allocUnsafe(E-R);await _.read(W,0,W.length,R);let $=W.toString("utf8").split(`
12
+ `);for(let k=$.length-1;k>=0;k--){let M=$[k].trim();if(!M)continue;if(k===0&&R>0)break;try{let V=JSON.parse(M).seq;if(typeof V==="number")return V}catch{}break}let H=await _.readFile("utf8");return Y.maxSeq(w(H,this.filePath))}async repairIncompleteTail(_){let{size:E}=await _.stat();if(E===0)return"";let R=Buffer.allocUnsafe(1);if(await _.read(R,0,1,E-1),R[0]===10)return"";let W=await this.findTailStart(_,E),$=Buffer.allocUnsafe(E-W);await _.read($,0,$.length,W);try{return JSON.parse($.toString("utf8").trim()),`
13
+ `}catch{return await _.truncate(W),""}}async findTailStart(_,E){let R=E;while(R>0){let W=Math.max(0,R-S),$=Buffer.allocUnsafe(R-W);await _.read($,0,$.length,W);let H=$.lastIndexOf(10);if(H>=0)return W+H+1;R=W}return 0}}function V_(){return typeof globalThis.Bun<"u"}function X_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.prepare(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>_.pragma(E,{simple:!0}),close:()=>_.close()}}function Y_(_){return{exec:(E)=>_.exec(E),prepare:(E)=>{let R=_.query(E);return{run:(...W)=>{R.run(...W)},get:(...W)=>R.get(...W),all:(...W)=>R.all(...W)}},transaction:(E)=>_.transaction(E)(),pragma:(E)=>{let R=_.query(`PRAGMA ${E}`).get();if(!R)return;let W=Object.values(R);return W.length===1?W[0]:R},close:()=>_.close()}}var G_=["PRAGMA journal_mode=WAL;","PRAGMA busy_timeout=5000;","PRAGMA synchronous=NORMAL;","PRAGMA foreign_keys=ON;"].join(`
12
14
  `);async function m(_){try{let E;if(V_()){let{Database:W}=await import("bun:sqlite");E=Y_(new W(_))}else{let $=(await import("better-sqlite3")).default;E=X_(new $(_))}return E.exec(G_),E}catch{return null}}function h(_){let E=Number(_.pragma("user_version")??0);if(E===3)return;if(E>0&&E!==3)_.exec(`
13
15
  DROP TABLE IF EXISTS parts_fts;
14
16
  DROP TABLE IF EXISTS parts;
@@ -81,10 +83,10 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
81
83
  seq UNINDEXED,
82
84
  tokenize = 'unicode61'
83
85
  );
84
- `),_.exec("PRAGMA user_version=3;")}var g_=o("Service"),D;function d(){return B.join(L(),"index.db")}async function T_(){let _=d();if(D&&D.path===_)return D.db;let E=(async()=>{let R=await m(_);if(!R)return null;try{return h(R),R}catch{return null}})();return D={path:_,db:E},E}function Z_(){D=void 0}function K_(_){if(_&&typeof _==="object"){let E=_.text;if(typeof E==="string")return E}return null}function U_(_,E,R,W){_.prepare("DELETE FROM parts WHERE project_path=? AND session_id=?").run(E,R),_.prepare("DELETE FROM parts_fts WHERE project_path=? AND session_id=?").run(E,R);let $=new Map;for(let M of W)if(M.type==="message_created")$.set(M.data.messageId,M.data.role);let H=_.prepare(`INSERT OR REPLACE INTO parts
86
+ `),_.exec("PRAGMA user_version=3;")}var T_=n("Service"),D;function d(){return B.join(L(),"index.db")}async function Z_(){let _=d();if(D&&D.path===_)return D.db;let E=(async()=>{let R=await m(_);if(!R)return null;try{return h(R),R}catch{return null}})();return D={path:_,db:E},E}function K_(){D=void 0}function U_(_){if(_&&typeof _==="object"){let E=_.text;if(typeof E==="string")return E}return null}function g_(_,E,R,W){_.prepare("DELETE FROM parts WHERE project_path=? AND session_id=?").run(E,R),_.prepare("DELETE FROM parts_fts WHERE project_path=? AND session_id=?").run(E,R);let $=new Map;for(let M of W)if(M.type==="message_created")$.set(M.data.messageId,M.data.role);let H=_.prepare(`INSERT OR REPLACE INTO parts
85
87
  (project_path, session_id, part_id, message_id, part_type, role, seq, timestamp, text)
86
88
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`),k=_.prepare(`INSERT INTO parts_fts (text, project_path, session_id, part_id, role, timestamp, seq)
87
- VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let M of W){if(M.type!=="part_created"&&M.type!=="part_updated")continue;if(M.data.partType!=="text")continue;let V=K_(M.data.payload);if(V===null)continue;let Y=$.get(M.data.messageId)??"assistant",U=M.seq??0;if(H.run(E,R,M.data.partId,M.data.messageId,M.data.partType,Y,U,M.timestamp,V),Y==="user"||Y==="assistant")k.run(V,E,R,M.data.partId,Y,M.timestamp,U)}}function F_(_,E){_.prepare(`INSERT INTO sessions
89
+ VALUES (?, ?, ?, ?, ?, ?, ?)`);for(let M of W){if(M.type!=="part_created"&&M.type!=="part_updated")continue;if(M.data.partType!=="text")continue;let V=U_(M.data.payload);if(V===null)continue;let G=$.get(M.data.messageId)??"assistant",g=M.seq??0;if(H.run(E,R,M.data.partId,M.data.messageId,M.data.partType,G,g,M.timestamp,V),G==="user"||G==="assistant")k.run(V,E,R,M.data.partId,G,M.timestamp,g)}}function F_(_,E){_.prepare(`INSERT INTO sessions
88
90
  (project_path, session_id, root_id, parent_id, relation_type, title,
89
91
  agent_type, model, task_status, archived_at, last_message_time, project_sort_key,
90
92
  session_sort_key, first_message_time, message_count, has_errors,
@@ -100,15 +102,15 @@ CREATE VIRTUAL TABLE IF NOT EXISTS parts_fts USING fts5(
100
102
  session_sort_key=excluded.session_sort_key,
101
103
  first_message_time=excluded.first_message_time, message_count=excluded.message_count,
102
104
  has_errors=excluded.has_errors, is_subagent=excluded.is_subagent,
103
- metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,I(E.projectPath),I(E.sessionId),E.firstMessageTime,E.messageCount,E.hasErrors?1:0,E.relationType==="subagent"?1:0,JSON.stringify(E))}function r(_,E,R){for(let W of["sessions","parts","parts_fts"])_.prepare(`DELETE FROM ${W} WHERE project_path=? AND session_id=?`).run(E,R)}function j(_,E,R){r(_,E,R),_.prepare("DELETE FROM projection_state WHERE project_path=? AND session_id=?").run(E,R)}function O(_,E,R,W,$,H){_.prepare(`INSERT INTO projection_state
105
+ metadata_json=excluded.metadata_json`).run(E.projectPath,E.sessionId,E.rootId,E.parentId??null,E.relationType??null,E.title??null,E.agentType??null,E.model??null,E.taskStatus,E.archivedAt??null,E.lastMessageTime,q(E.projectPath),q(E.sessionId),E.firstMessageTime,E.messageCount,E.hasErrors?1:0,E.relationType==="subagent"?1:0,JSON.stringify(E))}function r(_,E,R){for(let W of["sessions","parts","parts_fts"])_.prepare(`DELETE FROM ${W} WHERE project_path=? AND session_id=?`).run(E,R)}function j(_,E,R){r(_,E,R),_.prepare("DELETE FROM projection_state WHERE project_path=? AND session_id=?").run(E,R)}function O(_,E,R,W,$,H){_.prepare(`INSERT INTO projection_state
104
106
  (project_path, session_id, last_seq, file_size, mtime_ms)
105
107
  VALUES (?, ?, ?, ?, ?)
106
108
  ON CONFLICT(project_path, session_id) DO UPDATE SET
107
109
  last_seq=excluded.last_seq, file_size=excluded.file_size,
108
- mtime_ms=excluded.mtime_ms`).run(E,R,W,$,H)}async function D_(_,E,R,W,$=N(R,E)){let H;try{let Q=await i($);H={size:Q.size,mtimeMs:Q.mtimeMs}}catch{return _.transaction(()=>j(_,R,E)),!0}let k=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(k&&k.file_size===H.size&&k.mtime_ms===Math.floor(H.mtimeMs))return!1;let V=await new G($).readAll(),Y=V.reduce((Q,T)=>typeof T.seq==="number"&&T.seq>Q?T.seq:Q,0),U=z(V),g=W(V,E,R);if(V.length===0||!g)return _.transaction(()=>{r(_,R,E),O(_,R,E,Y,H.size,Math.floor(H.mtimeMs))}),!0;let F=_.prepare("SELECT last_message_time FROM sessions WHERE project_path=? AND session_id=?").get(g.projectPath,g.sessionId),A=B.resolve($)===B.resolve(N(g.projectPath,g.sessionId));if(F&&!A&&typeof F.last_message_time==="string"&&F.last_message_time>g.lastMessageTime)return O(_,R,E,Y,H.size,Math.floor(H.mtimeMs)),!0;return _.transaction(()=>{F_(_,g),U_(_,g.projectPath,g.sessionId,U),O(_,R,E,Y,H.size,Math.floor(H.mtimeMs))}),!0}var b=new WeakMap;async function B_(_,E,R=0){let W=b.get(_)??{};if(b.set(_,W),W.inFlight)return W.inFlight;if(R>0&&W.lastCompletedAt!==void 0&&Date.now()-W.lastCompletedAt<=R)return;let $=A_(_,E);W.inFlight=$;try{await $,W.lastCompletedAt=Date.now()}finally{if(W.inFlight===$)W.inFlight=void 0}}async function A_(_,E){let{readdir:R}=await import("node:fs/promises"),W=await n(),$=new Set,k=(await Promise.all(W.map(async(Q)=>{let T=l(Q),Z=B.join(L(),"projects",Q);try{return(await R(Z)).flatMap((u)=>{if(!u.endsWith(".jsonl"))return[];let v=u.slice(0,-6);if(!C(v))return[];return[{filePath:B.join(Z,u),projectPath:T,sessionId:v}]})}catch{return[]}}))).flat();for(let Q of k)$.add(`${Q.projectPath}\x00${Q.sessionId}`);let M=_.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms
109
- FROM projection_state`).all(),V=new Map(M.map((Q)=>[`${Q.project_path}\x00${Q.session_id}`,Q])),Y=[],U=Math.min(128,k.length),g=0;await Promise.all(Array.from({length:U},async()=>{while(g<k.length){let Q=k[g++];if(!Q)continue;try{let T=await i(Q.filePath),Z=V.get(`${Q.projectPath}\x00${Q.sessionId}`);if(Z&&Z.file_size===T.size&&Z.mtime_ms===Math.floor(T.mtimeMs))continue}catch{}Y.push(Q)}}));let F=Math.min(32,Y.length),A=0;await Promise.all(Array.from({length:F},async()=>{while(A<Y.length){let Q=Y[A++];if(!Q)continue;try{await D_(_,Q.sessionId,Q.projectPath,E,Q.filePath)}catch(T){if(T.code!=="ENOENT")g_.warn(`[SessionService] Skipping invalid session transcript: ${Q.sessionId}`)}}}));for(let Q of M)if(!$.has(`${Q.project_path}\x00${Q.session_id}`))_.transaction(()=>j(_,Q.project_path,Q.session_id))}function n_(_,E,R){_.transaction(()=>j(_,R,E))}async function o_(_){let{rm:E}=await import("node:fs/promises");Z_();let R=d();for(let H of["","-wal","-shm"])await E(`${R}${H}`,{force:!0}).catch(()=>{return});let W=await T_();if(!W)return null;return await B_(W,_),W.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function i_(_,E,R,W){let $=E.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!$)return[];let H=`"${$}"*`,k=R?`SELECT session_id, role, timestamp, text FROM parts_fts
110
+ mtime_ms=excluded.mtime_ms`).run(E,R,W,$,H)}async function D_(_,E,R,W,$=N(R,E)){let H;try{let Q=await i($);H={size:Q.size,mtimeMs:Q.mtimeMs}}catch{return _.transaction(()=>j(_,R,E)),!0}let k=_.prepare("SELECT last_seq, file_size, mtime_ms FROM projection_state WHERE project_path=? AND session_id=?").get(R,E);if(k&&k.file_size===H.size&&k.mtime_ms===Math.floor(H.mtimeMs))return!1;let V=await new Y($).readAll(),G=V.reduce((Q,Z)=>typeof Z.seq==="number"&&Z.seq>Q?Z.seq:Q,0),g=z(V),T=W(V,E,R);if(V.length===0||!T)return _.transaction(()=>{r(_,R,E),O(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0;let F=_.prepare("SELECT last_message_time FROM sessions WHERE project_path=? AND session_id=?").get(T.projectPath,T.sessionId),A=B.resolve($)===B.resolve(N(T.projectPath,T.sessionId));if(F&&!A&&typeof F.last_message_time==="string"&&F.last_message_time>T.lastMessageTime)return O(_,R,E,G,H.size,Math.floor(H.mtimeMs)),!0;return _.transaction(()=>{F_(_,T),g_(_,T.projectPath,T.sessionId,g),O(_,R,E,G,H.size,Math.floor(H.mtimeMs))}),!0}var b=new WeakMap;async function B_(_,E,R=0){let W=b.get(_)??{};if(b.set(_,W),W.inFlight)return W.inFlight;if(R>0&&W.lastCompletedAt!==void 0&&Date.now()-W.lastCompletedAt<=R)return;let $=A_(_,E);W.inFlight=$;try{await $,W.lastCompletedAt=Date.now()}finally{if(W.inFlight===$)W.inFlight=void 0}}async function A_(_,E){let{readdir:R}=await import("node:fs/promises"),W=await o(),$=new Set,k=(await Promise.all(W.map(async(Q)=>{let Z=l(Q),K=B.join(L(),"projects",Q);try{return(await R(K)).flatMap((I)=>{if(!I.endsWith(".jsonl"))return[];let v=I.slice(0,-6);if(!C(v))return[];return[{filePath:B.join(K,I),projectPath:Z,sessionId:v}]})}catch{return[]}}))).flat();for(let Q of k)$.add(`${Q.projectPath}\x00${Q.sessionId}`);let M=_.prepare(`SELECT project_path, session_id, last_seq, file_size, mtime_ms
111
+ FROM projection_state`).all(),V=new Map(M.map((Q)=>[`${Q.project_path}\x00${Q.session_id}`,Q])),G=[],g=Math.min(128,k.length),T=0;await Promise.all(Array.from({length:g},async()=>{while(T<k.length){let Q=k[T++];if(!Q)continue;try{let Z=await i(Q.filePath),K=V.get(`${Q.projectPath}\x00${Q.sessionId}`);if(K&&K.file_size===Z.size&&K.mtime_ms===Math.floor(Z.mtimeMs))continue}catch{}G.push(Q)}}));let F=Math.min(32,G.length),A=0;await Promise.all(Array.from({length:F},async()=>{while(A<G.length){let Q=G[A++];if(!Q)continue;try{await D_(_,Q.sessionId,Q.projectPath,E,Q.filePath)}catch(Z){if(Z.code!=="ENOENT")T_.warn(`[SessionService] Skipping invalid session transcript: ${Q.sessionId}`)}}}));for(let Q of M)if(!$.has(`${Q.project_path}\x00${Q.session_id}`))_.transaction(()=>j(_,Q.project_path,Q.session_id))}function o_(_,E,R){_.transaction(()=>j(_,R,E))}async function n_(_){let{rm:E}=await import("node:fs/promises");K_();let R=d();for(let H of["","-wal","-shm"])await E(`${R}${H}`,{force:!0}).catch(()=>{return});let W=await Z_();if(!W)return null;return await B_(W,_),W.prepare("SELECT COUNT(*) c FROM sessions").get()?.c??0}function i_(_,E,R,W){let $=E.replace(/["*]/g," ").trim().split(/\s+/)[0];if(!$)return[];let H=`"${$}"*`,k=R?`SELECT session_id, role, timestamp, text FROM parts_fts
110
112
  WHERE parts_fts MATCH ? AND project_path = ?
111
113
  ORDER BY timestamp DESC LIMIT ?`:`SELECT session_id, role, timestamp, text FROM parts_fts
112
114
  WHERE parts_fts MATCH ?
113
115
  ORDER BY timestamp DESC LIMIT ?`,M=_.prepare(k);return R?M.all(H,R,W):M.all(H,W)}
114
- export{z as cc,u_ as dc,I_ as ec,w as fc,G as gc,I as hc,W_ as ic,w_ as jc,$_ as kc,x_ as lc,d as mc,T_ as nc,Z_ as oc,D_ as pc,B_ as qc,n_ as rc,o_ as sc,i_ as tc};
116
+ export{z as cc,I_ as dc,q_ as ec,w as fc,Y as gc,q as hc,W_ as ic,w_ as jc,$_ as kc,x_ as lc,d as mc,Z_ as nc,K_ as oc,D_ as pc,B_ as qc,o_ as rc,n_ as sc,i_ as tc};
@@ -1,4 +1,4 @@
1
- import{m as Gq,n as Vq,o as Xq,p as Bq,q as Kq}from"./chunk-xzhk0smg.js";import{s as $q}from"./chunk-3wbheq1y.js";import{F as a,H as o,I as n,K as y,L as t}from"./chunk-mcr47s40.js";import"./chunk-9m1ayjve.js";import"./chunk-qt114yth.js";import{Va as i,Ya as s,hb as r}from"./chunk-n2hwfw7v.js";import"./chunk-095x2ykj.js";import{Tb as S,bc as h}from"./chunk-ajy99edp.js";import"./chunk-0ndm72az.js";import{uc as qq}from"./chunk-mbrevmbp.js";import{wc as Qq,xc as Yq,yc as Zq}from"./chunk-s31msata.js";import{zc as e}from"./chunk-wt7gy9bm.js";import"./chunk-k3nkcaap.js";import{Zc as v}from"./chunk-y78smk7g.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-kn8xx8ng.js";import"./chunk-as56atkw.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-ky0v990x.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-h37yw6g3.js";import{Ye as m,Ze as l}from"./chunk-y2g5a5bp.js";import{af as u,cf as Q,df as w,ff as j}from"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as I}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Y){return Q.Object({event_version:Q.Literal(g),...Y})}var Uq=K({type:Q.Literal("content_delta"),delta:Q.String()}),Rq=K({type:Q.Literal("thinking_delta"),delta:Q.String()}),Mq=K({type:Q.Literal("thinking"),content:Q.String()}),Pq=K({type:Q.Literal("stream_end")}),fq=K({type:Q.Literal("content"),content:Q.String()}),Nq=K({type:Q.Literal("structured_output"),output:Q.Record(Q.String(),Q.Unknown()),schema_digest:Q.String({pattern:"^[a-f0-9]{64}$"})}),T=j(["readonly","write","execute"]),Eq=K({type:Q.Literal("tool_start"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T)}),xq=K({type:Q.Literal("tool_progress"),tool_name:Q.String(),message:Q.String(),progress:Q.Optional(Q.Number()),total:Q.Optional(Q.Number())}),Iq=K({type:Q.Literal("tool_result"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T),success:Q.Optional(Q.Boolean()),error_type:Q.Optional(Q.String()),error_message:Q.Optional(Q.String())}),Jq=K({type:Q.Literal("mcp_catalog_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Lq=K({type:Q.Literal("mcp_content_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),content_kind:j(["resources","resource_templates","prompts"]),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Wq=K({type:Q.Literal("mcp_resource_updated"),revision:Q.Integer({minimum:1}),server_name:Q.String(),uri:Q.String()}),Sq=K({type:Q.Literal("mcp_connection_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),phase:j(["reconnecting","recovered","failed"]),reason:Q.String(),attempt:Q.Integer({minimum:0}),max_attempts:Q.Integer({minimum:0}),next_retry_at:Q.Optional(Q.Integer({minimum:0})),error:Q.Optional(Q.String())}),Oq=K({type:Q.Literal("mcp_log"),revision:Q.Integer({minimum:1}),server_name:Q.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:Q.Optional(Q.String()),message:Q.String(),projected_bytes:Q.Integer({minimum:0}),data_sha256:Q.String(),truncated:Q.Boolean(),details_omitted:Q.Boolean(),timestamp:Q.Integer({minimum:0}),synthetic:Q.Optional(Q.Boolean())}),hq=K({type:Q.Literal("mcp_instructions_changed"),revision:Q.Integer({minimum:0}),server_name:Q.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:Q.Optional(Q.String()),source_bytes:Q.Optional(Q.Integer({minimum:0})),projected_bytes:Q.Optional(Q.Integer({minimum:0})),sha256:Q.Optional(Q.String()),truncated:Q.Optional(Q.Boolean()),details_omitted:Q.Optional(Q.Boolean())}),Cq=K({type:Q.Literal("mcp_task_changed"),revision:Q.Integer({minimum:0}),task_id:Q.String(),server_name:Q.String(),tool_name:Q.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:Q.Optional(Q.String()),created_at:Q.Integer({minimum:0}),updated_at:Q.Integer({minimum:0}),completed_at:Q.Optional(Q.Integer({minimum:0})),has_result:Q.Boolean(),error:Q.Optional(Q.String())}),kq=K({type:Q.Literal("project_rules_loaded"),files:Q.Array(Q.Object({id:Q.String(),relative_path:Q.String(),source:j(["project","local"]),conditional:Q.Boolean(),content_sha256:Q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:Q.Array(Q.String()),blocked_write:Q.Boolean()}),Fq=K({type:Q.Literal("user_shell_started"),execution_id:Q.String(),command:Q.String(),auxiliary:Q.Boolean()}),wq=K({type:Q.Literal("user_shell_output"),execution_id:Q.String(),stream:j(["stdout","stderr"]),chunk:Q.String(),stream_truncated:Q.Boolean()}),yq=K({type:Q.Literal("user_shell_completed"),execution_id:Q.String(),message_id:Q.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:Q.Union([Q.Integer(),Q.Null()]),duration_ms:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),truncated:Q.Boolean(),auxiliary:Q.Boolean()}),gq=K({type:Q.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:Q.String(),turn:Q.Optional(Q.Number()),tool_name:Q.Optional(Q.String()),target:Q.Optional(Q.String())}),Tq=K({type:Q.Literal("tool_detail"),tool_name:Q.String(),detail:Q.String()}),cq=K({type:Q.Literal("task_update"),tasks:Q.Array(y)}),dq=K({type:Q.Literal("goal"),state:j(["updated","cleared"]),goal_id:Q.Optional(Q.String()),status:Q.Optional(j(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:Q.Optional(Q.Integer({minimum:1})),verification_status:Q.Optional(j(["pending","pass","fail","partial"])),verifier_session_id:Q.Optional(Q.String()),verification_evidence_sha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))}),pq=K({type:Q.Literal("subagent"),state:j(["spawned","completed"]),session_id:Q.String(),subagent_type:Q.Optional(Q.String()),success:Q.Optional(Q.Boolean()),summary:Q.Optional(Q.String()),verification_verdict:Q.Optional(j(["pass","fail","partial"])),resumed_from:Q.Optional(Q.String()),root_agent_id:Q.Optional(Q.String()),resume_depth:Q.Optional(Q.Integer({minimum:0}))}),mq=K({type:Q.Literal("token_usage"),input_tokens:Q.Number(),output_tokens:Q.Number(),total_tokens:Q.Number(),max_context_tokens:Q.Number(),cache_read_tokens:Q.Optional(Q.Number()),cache_write_tokens:Q.Optional(Q.Number()),cost_usd:Q.Optional(Q.Number())}),uq=K({type:Q.Literal("compacting"),state:j(["started","completed"]),reason:Q.Optional(j(["threshold","context_limit","turn_limit","manual"])),strategy:Q.Optional(j(["llm","fallback","snip"])),outcome:Q.Optional(j(["completed","fallback","failed"])),pre_tokens:Q.Optional(Q.Number({minimum:0})),post_tokens:Q.Optional(Q.Number({minimum:0}))}),lq=K({type:Q.Literal("provider_retry"),phase:j(["scheduled","attempt","recovered","exhausted"]),attempt:Q.Integer({minimum:0}),max_retries:Q.Integer({minimum:0}),reason:j(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:Q.Optional(Q.Integer({minimum:100,maximum:599})),delay_ms:Q.Optional(Q.Integer({minimum:0})),next_retry_at:Q.Optional(Q.Integer({minimum:0}))}),vq=K({type:Q.Literal("provider_stall"),phase:j(["detected","recovered"]),stall_count:Q.Integer({minimum:1}),duration_ms:Q.Integer({minimum:0}),warning_after_ms:Q.Integer({minimum:1}),timeout_ms:Q.Integer({minimum:1}),output_started:Q.Boolean()}),iq=K({type:Q.Literal("turn_limit"),turns_count:Q.Number(),action:Q.Literal("continue")}),sq=K({type:Q.Literal("task_session"),session_id:Q.String(),project_path:Q.String(),source_project_path:Q.String(),isolation:j(["local","worktree"]),worktree_branch:Q.Optional(Q.String()),base_commit:Q.Optional(Q.String())}),rq=K({type:Q.Literal("task_admission"),state:j(["queued","running"]),queue_position:Q.Optional(Q.Integer({minimum:1})),queue_depth:Q.Integer({minimum:0}),in_flight:Q.Integer({minimum:0}),max_concurrent_tasks:Q.Integer({minimum:1})}),aq=K({type:Q.Literal("output"),content:Q.String(),exit_code:Q.Number()}),oq=K({type:Q.Literal("error"),message:Q.String()}),zQ=w(Q.Union([Uq,Rq,Mq,Pq,fq,Nq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Y,Z){return{event_version:g,type:Y,...Z}}function eq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let Z=new AbortController,H=()=>Z.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:Z.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qQ=j(["text","jsonl"]),QQ=Q.Object({headless:Q.Optional(Q.Boolean()),message:Q.Optional(Q.String()),_:Q.Optional(Q.Array(Q.Union([Q.String(),Q.Number()]))),model:Q.Optional(Q.String()),systemPrompt:Q.Optional(Q.String()),appendSystemPrompt:Q.Optional(Q.String()),maxTurns:Q.Optional(Q.Refine(Q.Integer({maximum:l}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:Q.Optional(Q.Enum(m)),mcpConfig:Q.Optional(Q.Array(Q.String())),strictMcpConfig:Q.Optional(Q.Boolean()),sessionId:Q.Optional(Q.String()),allowedTools:Q.Optional(Q.Array(Q.String())),disallowedTools:Q.Optional(Q.Array(Q.String())),agents:Q.Optional(Q.String()),continue:Q.Optional(Q.Boolean()),resume:Q.Optional(Q.Union([Q.String(),Q.Boolean()])),forkSession:Q.Optional(Q.Boolean()),taskIsolation:Q.Optional(j(["local","worktree"])),outputFormat:Q.Optional(qQ),jsonSchema:Q.Optional(Q.String()),outputSchema:Q.Optional(Q.String())});class Dq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function YQ(Y){return Y.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function ZQ(Y){let Z=u(QQ,Y);if(!Z.success)throw Error(`Invalid headless options: ${YQ(Z.error)}`);return Z.data}function $Q(Y){return Y.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("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 H=await DQ(Z);process.exit(H)})}function D(Y,Z=""){Y.write(`${Z}
1
+ import{m as Gq,n as Vq,o as Xq,p as Bq,q as Kq}from"./chunk-a43d70k9.js";import{s as $q}from"./chunk-awnrm721.js";import{F as a,H as o,I as n,K as y,L as t}from"./chunk-jba4g4y1.js";import"./chunk-1gqmy8aq.js";import"./chunk-qt114yth.js";import{Va as i,Ya as s,hb as r}from"./chunk-h18y4067.js";import"./chunk-095x2ykj.js";import{Tb as S,bc as h}from"./chunk-eb6d2sqj.js";import"./chunk-8rzwyknk.js";import{uc as qq}from"./chunk-agsvdf45.js";import{wc as Qq,xc as Yq,yc as Zq}from"./chunk-h7pregxp.js";import{zc as e}from"./chunk-wt7gy9bm.js";import"./chunk-k3nkcaap.js";import{Zc as v}from"./chunk-cx0yycfr.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-xet98pc1.js";import"./chunk-kbpc97n3.js";import"./chunk-5chec8rs.js";import"./chunk-qnnyasc0.js";import"./chunk-nddkzabm.js";import"./chunk-r1jxbx1h.js";import"./chunk-6sb7cg95.js";import"./chunk-2c3zavy2.js";import"./chunk-wbxv9wcn.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-pq1p9jz6.js";import{Ye as m,Ze as l}from"./chunk-y2g5a5bp.js";import{af as u,cf as Q,df as w,ff as j}from"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as I}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import nq from"yargs";import{hideBin as tq}from"yargs/helpers";var g=1;function K(Y){return Q.Object({event_version:Q.Literal(g),...Y})}var Uq=K({type:Q.Literal("content_delta"),delta:Q.String()}),Rq=K({type:Q.Literal("thinking_delta"),delta:Q.String()}),Mq=K({type:Q.Literal("thinking"),content:Q.String()}),Pq=K({type:Q.Literal("stream_end")}),fq=K({type:Q.Literal("content"),content:Q.String()}),Nq=K({type:Q.Literal("structured_output"),output:Q.Record(Q.String(),Q.Unknown()),schema_digest:Q.String({pattern:"^[a-f0-9]{64}$"})}),T=j(["readonly","write","execute"]),Eq=K({type:Q.Literal("tool_start"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T)}),xq=K({type:Q.Literal("tool_progress"),tool_name:Q.String(),message:Q.String(),progress:Q.Optional(Q.Number()),total:Q.Optional(Q.Number())}),Iq=K({type:Q.Literal("tool_result"),tool_name:Q.String(),summary:Q.String(),target:Q.Optional(Q.String()),tool_kind:Q.Optional(T),success:Q.Optional(Q.Boolean()),error_type:Q.Optional(Q.String()),error_message:Q.Optional(Q.String())}),Jq=K({type:Q.Literal("mcp_catalog_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Lq=K({type:Q.Literal("mcp_content_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),content_kind:j(["resources","resource_templates","prompts"]),added:Q.Array(Q.String()),removed:Q.Array(Q.String()),updated:Q.Array(Q.String())}),Wq=K({type:Q.Literal("mcp_resource_updated"),revision:Q.Integer({minimum:1}),server_name:Q.String(),uri:Q.String()}),Sq=K({type:Q.Literal("mcp_connection_changed"),revision:Q.Integer({minimum:1}),server_name:Q.String(),phase:j(["reconnecting","recovered","failed"]),reason:Q.String(),attempt:Q.Integer({minimum:0}),max_attempts:Q.Integer({minimum:0}),next_retry_at:Q.Optional(Q.Integer({minimum:0})),error:Q.Optional(Q.String())}),Oq=K({type:Q.Literal("mcp_log"),revision:Q.Integer({minimum:1}),server_name:Q.String(),level:j(["debug","info","notice","warning","error","critical","alert","emergency"]),logger:Q.Optional(Q.String()),message:Q.String(),projected_bytes:Q.Integer({minimum:0}),data_sha256:Q.String(),truncated:Q.Boolean(),details_omitted:Q.Boolean(),timestamp:Q.Integer({minimum:0}),synthetic:Q.Optional(Q.Boolean())}),hq=K({type:Q.Literal("mcp_instructions_changed"),revision:Q.Integer({minimum:0}),server_name:Q.String(),action:j(["added","removed"]),reason:j(["snapshot","connection","disconnection"]),text:Q.Optional(Q.String()),source_bytes:Q.Optional(Q.Integer({minimum:0})),projected_bytes:Q.Optional(Q.Integer({minimum:0})),sha256:Q.Optional(Q.String()),truncated:Q.Optional(Q.Boolean()),details_omitted:Q.Optional(Q.Boolean())}),Cq=K({type:Q.Literal("mcp_task_changed"),revision:Q.Integer({minimum:0}),task_id:Q.String(),server_name:Q.String(),tool_name:Q.String(),status:j(["working","input_required","interrupted","completed","failed","cancelled"]),status_message:Q.Optional(Q.String()),created_at:Q.Integer({minimum:0}),updated_at:Q.Integer({minimum:0}),completed_at:Q.Optional(Q.Integer({minimum:0})),has_result:Q.Boolean(),error:Q.Optional(Q.String())}),kq=K({type:Q.Literal("project_rules_loaded"),files:Q.Array(Q.Object({id:Q.String(),relative_path:Q.String(),source:j(["project","local"]),conditional:Q.Boolean(),content_sha256:Q.String({pattern:"^[a-f0-9]{64}$"})})),trigger_paths:Q.Array(Q.String()),blocked_write:Q.Boolean()}),Fq=K({type:Q.Literal("user_shell_started"),execution_id:Q.String(),command:Q.String(),auxiliary:Q.Boolean()}),wq=K({type:Q.Literal("user_shell_output"),execution_id:Q.String(),stream:j(["stdout","stderr"]),chunk:Q.String(),stream_truncated:Q.Boolean()}),yq=K({type:Q.Literal("user_shell_completed"),execution_id:Q.String(),message_id:Q.String(),status:j(["completed","failed","aborted","timed_out","spawn_error"]),exit_code:Q.Union([Q.Integer(),Q.Null()]),duration_ms:Q.Number({minimum:0}),stdout:Q.String(),stderr:Q.String(),truncated:Q.Boolean(),auxiliary:Q.Boolean()}),gq=K({type:Q.Literal("phase"),phase:j(["turn","searching","inspecting","target_hit","executing","completed"]),status:j(["ongoing","hit","done"]),message:Q.String(),turn:Q.Optional(Q.Number()),tool_name:Q.Optional(Q.String()),target:Q.Optional(Q.String())}),Tq=K({type:Q.Literal("tool_detail"),tool_name:Q.String(),detail:Q.String()}),cq=K({type:Q.Literal("task_update"),tasks:Q.Array(y)}),dq=K({type:Q.Literal("goal"),state:j(["updated","cleared"]),goal_id:Q.Optional(Q.String()),status:Q.Optional(j(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"])),verification_attempt:Q.Optional(Q.Integer({minimum:1})),verification_status:Q.Optional(j(["pending","pass","fail","partial"])),verifier_session_id:Q.Optional(Q.String()),verification_evidence_sha256:Q.Optional(Q.String({pattern:"^[a-f0-9]{64}$"}))}),pq=K({type:Q.Literal("subagent"),state:j(["spawned","completed"]),session_id:Q.String(),subagent_type:Q.Optional(Q.String()),success:Q.Optional(Q.Boolean()),summary:Q.Optional(Q.String()),verification_verdict:Q.Optional(j(["pass","fail","partial"])),resumed_from:Q.Optional(Q.String()),root_agent_id:Q.Optional(Q.String()),resume_depth:Q.Optional(Q.Integer({minimum:0}))}),mq=K({type:Q.Literal("token_usage"),input_tokens:Q.Number(),output_tokens:Q.Number(),total_tokens:Q.Number(),max_context_tokens:Q.Number(),cache_read_tokens:Q.Optional(Q.Number()),cache_write_tokens:Q.Optional(Q.Number()),cost_usd:Q.Optional(Q.Number())}),uq=K({type:Q.Literal("compacting"),state:j(["started","completed"]),reason:Q.Optional(j(["threshold","context_limit","turn_limit","manual"])),strategy:Q.Optional(j(["llm","fallback","snip"])),outcome:Q.Optional(j(["completed","fallback","failed"])),pre_tokens:Q.Optional(Q.Number({minimum:0})),post_tokens:Q.Optional(Q.Number({minimum:0}))}),lq=K({type:Q.Literal("provider_retry"),phase:j(["scheduled","attempt","recovered","exhausted"]),attempt:Q.Integer({minimum:0}),max_retries:Q.Integer({minimum:0}),reason:j(["rate_limit","server_error","timeout","transport","stream_closed"]),status_code:Q.Optional(Q.Integer({minimum:100,maximum:599})),delay_ms:Q.Optional(Q.Integer({minimum:0})),next_retry_at:Q.Optional(Q.Integer({minimum:0}))}),vq=K({type:Q.Literal("provider_stall"),phase:j(["detected","recovered"]),stall_count:Q.Integer({minimum:1}),duration_ms:Q.Integer({minimum:0}),warning_after_ms:Q.Integer({minimum:1}),timeout_ms:Q.Integer({minimum:1}),output_started:Q.Boolean()}),iq=K({type:Q.Literal("turn_limit"),turns_count:Q.Number(),action:Q.Literal("continue")}),sq=K({type:Q.Literal("task_session"),session_id:Q.String(),project_path:Q.String(),source_project_path:Q.String(),isolation:j(["local","worktree"]),worktree_branch:Q.Optional(Q.String()),base_commit:Q.Optional(Q.String())}),rq=K({type:Q.Literal("task_admission"),state:j(["queued","running"]),queue_position:Q.Optional(Q.Integer({minimum:1})),queue_depth:Q.Integer({minimum:0}),in_flight:Q.Integer({minimum:0}),max_concurrent_tasks:Q.Integer({minimum:1})}),aq=K({type:Q.Literal("output"),content:Q.String(),exit_code:Q.Number()}),oq=K({type:Q.Literal("error"),message:Q.String()}),zQ=w(Q.Union([Uq,Rq,Mq,Pq,fq,Nq,Eq,xq,Iq,Jq,Lq,Wq,Sq,Oq,hq,Cq,kq,Fq,wq,yq,gq,Tq,cq,dq,pq,mq,uq,lq,vq,iq,sq,rq,aq,oq]));function c(Y,Z){return{event_version:g,type:Y,...Z}}function eq(Y){if(Y?.signal)return{signal:Y.signal,dispose:()=>{return}};let Z=new AbortController,H=()=>Z.abort("interrupt");return process.once("SIGINT",H),process.once("SIGTERM",H),{signal:Z.signal,dispose:()=>{process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H)}}}var qQ=j(["text","jsonl"]),QQ=Q.Object({headless:Q.Optional(Q.Boolean()),message:Q.Optional(Q.String()),_:Q.Optional(Q.Array(Q.Union([Q.String(),Q.Number()]))),model:Q.Optional(Q.String()),systemPrompt:Q.Optional(Q.String()),appendSystemPrompt:Q.Optional(Q.String()),maxTurns:Q.Optional(Q.Refine(Q.Integer({maximum:l}),(Y)=>Y===-1||Y>0,()=>"must be -1 or a positive integer")),permissionMode:Q.Optional(Q.Enum(m)),mcpConfig:Q.Optional(Q.Array(Q.String())),strictMcpConfig:Q.Optional(Q.Boolean()),sessionId:Q.Optional(Q.String()),allowedTools:Q.Optional(Q.Array(Q.String())),disallowedTools:Q.Optional(Q.Array(Q.String())),agents:Q.Optional(Q.String()),continue:Q.Optional(Q.Boolean()),resume:Q.Optional(Q.Union([Q.String(),Q.Boolean()])),forkSession:Q.Optional(Q.Boolean()),taskIsolation:Q.Optional(j(["local","worktree"])),outputFormat:Q.Optional(qQ),jsonSchema:Q.Optional(Q.String()),outputSchema:Q.Optional(Q.String())});class Dq{openedThinking=!1;wroteAssistantContent=!1;markAssistantContent(){this.wroteAssistantContent=!0}setThinkingOpened(Y){this.openedThinking=Y}hasOpenThinking(){return this.openedThinking}completeStream(){let Y={openedThinking:this.openedThinking,wroteAssistantContent:this.wroteAssistantContent};return this.openedThinking=!1,this.wroteAssistantContent=!1,Y}}function YQ(Y){return Y.issues.map((Z)=>`${Z.path.join(".")||"options"}: ${Z.message}`).join("; ")}function ZQ(Y){let Z=u(QQ,Y);if(!Z.success)throw Error(`Invalid headless options: ${YQ(Z.error)}`);return Z.data}function $Q(Y){return Y.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("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 H=await DQ(Z);process.exit(H)})}function D(Y,Z=""){Y.write(`${Z}
2
2
  `)}function GQ(Y){return`[task] [${Y.status}] ${Y.subject}`}function VQ(){return{requestConfirmation:async(Y)=>Y.type==="mcpElicitation"?{approved:!1,reason:"headless-mcp-elicitation-unavailable",elicitation:{action:"cancel"}}:Y.type==="mcpSampling"?{approved:!1,reason:"headless-mcp-sampling-unavailable"}:{approved:!0,reason:"headless-auto-approved",scope:"session"}}}function XQ(Y){if(!(Y instanceof Error))return"Unknown error";let V=Y.lastError??Y;if(V.responseBody)try{let b=JSON.parse(V.responseBody)?.error?.message;if(b)return V.statusCode?`${b} (HTTP ${V.statusCode})`:b}catch{}let q=Y.message.match(/Last error:\s*(.+)$/);if(q)return q[1];return Y.message}function BQ(Y){return Y==="jsonl"?"jsonl":"text"}function d(Y,Z){let H=(...V)=>{for(let q of V){let $=Z[q];if(typeof $==="string"&&$.trim()!=="")return $}return};switch(Y){case"Read":case"Edit":case"Write":case"UndoEdit":return H("file_path");case"ApplyPatch":return"multi-file patch";case"NotebookEdit":return H("notebook_path");case"Grep":return H("path","pattern");case"Glob":return H("pattern");case"WebFetch":return H("url");case"WebSearch":return H("query");case"Bash":return H("command","description");case"Task":return H("description");case"LSP":return H("filePath","operation");case"EnterWorktree":return H("name");case"ExitWorktree":return H("action");default:return}}function KQ(Y,Z,H,V){let q=new Set(["Glob","Grep","WebSearch","LS"]),$=new Set(["Read","WebFetch"]);if(new Set(["Edit","Write","ApplyPatch","NotebookEdit","Bash","LSP","UndoEdit","EnterWorktree","ExitWorktree"]).has(Y)&&!V.targetLocked)return{phase:"target_hit",status:"hit",message:`Target locked: ${Z}`,shouldLockTarget:!0};if(V.targetLocked)return{phase:"executing",status:"hit",message:H?`Working within target: ${Z}`:`Executing: ${Z}`,shouldLockTarget:!1};if(q.has(Y))return{phase:"searching",status:"ongoing",message:`Still searching: ${Z}`,shouldLockTarget:!1};if($.has(Y))return{phase:"inspecting",status:"ongoing",message:`Inspecting candidate: ${Z}`,shouldLockTarget:!1};return{phase:"executing",status:V.targetLocked?"hit":"ongoing",message:`Executing: ${Z}`,shouldLockTarget:!1}}function p(Y,Z,H=!1){let V=(q,$)=>{Y.stdout.write(`${JSON.stringify(c(q,$))}
3
3
  `)};return{contentDelta(q){if(Z==="jsonl"){V("content_delta",{delta:q});return}if(H)return;Y.stdout.write(q)},thinkingDelta(q,$){if(Z==="jsonl")return V("thinking_delta",{delta:q}),$;if(!$)Y.stderr.write("[thinking] ");return Y.stderr.write(q),!0},thinking(q){if(Z==="jsonl"){V("thinking",{content:q});return}D(Y.stderr,`[thinking] ${q}`)},streamEnd(q,$){if(Z==="jsonl"){V("stream_end",{});return}if($)Y.stderr.write(`
4
4
  `);if(q)Y.stdout.write(`
@@ -1,4 +1,4 @@
1
- import{$ as F,Z as y}from"./chunk-mcr47s40.js";import{Ub as Z,Wb as x,bc as K}from"./chunk-ajy99edp.js";import{Pd as $}from"./chunk-as56atkw.js";import{mf as V}from"./chunk-prgh321y.js";async function O(){await $(V())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let Q of z)G.push(Q);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:Q}=z;return{mode:"agent",content:Q?`Please use the "${G}" skill to help me with: ${Q}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
1
+ import{$ as F,Z as y}from"./chunk-jba4g4y1.js";import{Ub as Z,Wb as x,bc as K}from"./chunk-eb6d2sqj.js";import{Pd as $}from"./chunk-nddkzabm.js";import{mf as V}from"./chunk-prgh321y.js";async function O(){await $(V())}async function j(b){let q=b.message||b._?.[0];if(typeof q==="string"&&q.trim())return q;let z=b.stdin??process.stdin;if(!z.isTTY){let G=[];for await(let Q of z)G.push(Q);return Buffer.concat(G).toString("utf-8").trim()}if(b.defaultMessage!==void 0)return b.defaultMessage;throw Error("No input provided")}async function I(b){if(!y(b))return{mode:"agent",content:b};let q=await F(b,{cwd:V(),surface:"headless",workspaceRoot:V()});if(!q.success)return{mode:"output",content:`Error: ${q.error||"未知错误"}`,exitCode:1};let z=q.data;if(z?.action==="invoke_skill"){let{skillName:G,skillArgs:Q}=z;return{mode:"agent",content:Q?`Please use the "${G}" skill to help me with: ${Q}`:`Please use the "${G}" skill.`}}if(z?.action==="invoke_custom_command"||z?.action==="invoke_plugin_command"){let G=z.processedContent;return{mode:"agent",content:`# Custom Command: /${z.commandName}
2
2
 
3
3
  ${G}`}}return{mode:"output",content:q.content||q.message||"",exitCode:0}}import{readFile as B,stat as D}from"node:fs/promises";import H from"node:path";function L(b,q){let z;try{z=JSON.parse(b)}catch(G){throw Error(`Invalid JSON output schema from ${q}`,{cause:G})}return x(z).schema}async function A(b){if(b.jsonSchema!==void 0&&b.outputSchema!==void 0)throw Error("--json-schema cannot be combined with --output-schema");if(b.jsonSchema!==void 0)return L(b.jsonSchema,"--json-schema");if(b.outputSchema===void 0)return;let q=H.resolve(b.outputSchema),z=await D(q);if(!z.isFile())throw Error(`Output schema path is not a regular file: ${q}`);if(z.size>Z)throw Error(`Output schema exceeds ${Z} bytes: ${q}`);return L(await B(q,"utf8"),q)}function J(b){if(!(b instanceof Error))return!1;return b.message.includes("未找到会话")||b.message.includes("ENOENT")||b.message.includes("no such file")}async function N(b){try{return await K.loadSessionModelContext(b,V())}catch(q){if(J(q))return null;throw q}}async function f(b){if(b.resume===!0||b.resume==="true")throw Error("--resume without a session ID is only supported in interactive UI mode");if(typeof b.resume==="string"&&b.resume.length>0){if(b.forkSession){let G=V(),Q=await K.forkSession(b.resume,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...Q,messages:await K.loadSessionModelContext(Q.sessionId,G)}}let[q,z]=await Promise.all([K.loadSessionModelContext(b.resume),K.findSessionMetadata(b.resume)]);return{sessionId:b.resume,messages:q,metadata:z}}if(b.continue){let q=b.forkSession?await K.listSessions({cwd:V()}):await K.listSessions();if(q.length>0){let z=q[0].sessionId;if(b.forkSession){let G=V(),Q=await K.forkSession(z,{newSessionId:b.sessionId,sourceProjectPath:G,targetProjectPath:G});return{...Q,messages:await K.loadSessionModelContext(Q.sessionId,G)}}return{sessionId:z,messages:await K.loadSessionModelContext(z),metadata:q[0]}}if(b.forkSession)throw Error("Cannot fork: no sessions are available to continue")}if(b.sessionId){let q=await N(b.sessionId);return{sessionId:b.sessionId,messages:q??[],...q?{metadata:await K.findSessionMetadata(b.sessionId,V())}:{}}}return{sessionId:`${b.fallbackSessionPrefix}-${Date.now()}`,messages:[]}}
4
4
  export{O as m,j as n,I as o,A as p,f as q};
@@ -1,4 +1,4 @@
1
- import"./chunk-6pa6c2n0.js";import"./chunk-6207mbmr.js";import{We as Q}from"./chunk-h37yw6g3.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as L}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import{Qf as F}from"./chunk-6g5k5de1.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
- `);try{let{rebuildProjectionIndex:z}=await import("./chunk-4k615fx6.js"),{SessionService:B}=await import("./chunk-y26ngyc2.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
1
+ import"./chunk-6pa6c2n0.js";import"./chunk-6207mbmr.js";import{We as Q}from"./chunk-pq1p9jz6.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as L}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import{Qf as F}from"./chunk-6g5k5de1.js";var K=[22,19,0];function T(G){let A=/^v?(\d+)\.(\d+)\.(\d+)/.exec(G);if(!A)return!1;let H=A.slice(1).map(Number);for(let z=0;z<K.length;z++){let B=H[z]??0,J=K[z];if(B!==J)return B>J}return!0}var X={command:"doctor",describe:"Check the health of your Blade installation",builder:(G)=>G.option("rebuild-index",{type:"boolean",default:!1,describe:"Rebuild the SQLite session index from JSONL transcripts"}),handler:async(G)=>{if(G.rebuildIndex){console.log(`Rebuilding session index from JSONL transcripts...
2
+ `);try{let{rebuildProjectionIndex:z}=await import("./chunk-y72p0x68.js"),{SessionService:B}=await import("./chunk-19z401aq.js"),J=await z(B.projectionDeriverForSearch());if(J===null)console.log("[WARN] Session index unavailable (SQLite driver missing); reads fall back to JSONL scan.");else console.log(`[OK] Session index rebuilt: ${J} session(s) indexed.`)}catch(z){console.log("[FAIL] Session index rebuild failed"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),process.exit(1)}return}console.log(`Running Blade health check...
3
3
  `);let A=0;try{await Q.getInstance().initialize(),console.log("[OK] Configuration: OK")}catch(z){console.log("[FAIL] Configuration: FAILED"),console.log(` Error: ${z instanceof Error?z.message:"未知错误"}`),A++}let H=process.version;if(T(H))console.log(`[OK] Node.js version: ${H}`);else console.log(`[WARN] Node.js version: ${H} (required: >=22.19.0)`),A++;try{let z=await import("fs/promises"),B=L();await z.access(B,(await import("fs")).constants.R_OK|(await import("fs")).constants.W_OK),console.log("[OK] File system permissions: OK")}catch(z){console.log("[FAIL] File system permissions: FAILED"),console.log(" Error: Cannot read/write in current directory"),A++}try{await import("ink"),console.log("[OK] Dependencies: OK")}catch(z){console.log("[FAIL] Dependencies: FAILED"),console.log(" Error: Missing required dependencies"),A++}if(console.log(`
4
4
  Health Check Summary:`),A===0)console.log("All checks passed! Blade is ready to use.");else console.log(`Warning: Found ${A} issue(s). Please resolve them for optimal performance.`),process.exit(1)}};export{T as isSupportedNodeVersion,X as doctorCommands};
@@ -1,2 +1,2 @@
1
- import{Bf as h,zf as d}from"./chunk-dskgbv7c.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},"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};
1
+ import{Bf as h,zf as d}from"./chunk-hatwwhm2.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},"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 uc,w as vc};
@@ -1,2 +1,2 @@
1
- import{C as o}from"./chunk-mcr47s40.js";import{bc as i}from"./chunk-ajy99edp.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
1
+ import{C as o}from"./chunk-jba4g4y1.js";import{bc as i}from"./chunk-eb6d2sqj.js";import a from"node:path";function n(e){let s=e.replace(/\s+/g," ").trim();return s.length<=72?s:`${s.slice(0,69)}...`}function c(e){let s=e.replace(/\s+/g," ").trim();return s.length<=500?s:`${s.slice(0,497)}...`}function d(e){return`task/${e.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class m{static async createSessionTask(e){if(!e.prompt.trim())throw Error("Task prompt must not be blank");if(!a.isAbsolute(e.sourceProjectPath))throw Error("Task source project path must be absolute");let s=a.resolve(e.sourceProjectPath),t;try{return t=e.isolation==="worktree"?await o.enter({sessionId:e.sessionId,workspaceRoot:s,name:d(e.sessionId)}):void 0,{metadata:await i.createSessionMetadata(e.sessionId,t?.workspaceRoot??s,{title:e.title?.trim()||n(e.prompt),taskPromptSummary:c(e.prompt),taskDispatch:e.dispatch,taskModelId:e.dispatch?.modelId,selectedModelId:e.dispatch?.modelId,permissionMode:e.dispatch?.permissionMode,reasoningEffort:e.dispatch?.reasoningEffort,serviceTier:e.dispatch?.serviceTier,responseVerbosity:e.dispatch?.responseVerbosity,communicationStyle:e.dispatch?.communicationStyle,communicationStyleDigest:e.dispatch?.communicationStyleDigest,projectInstructionsDigest:e.dispatch?.projectInstructionsDigest,taskRetriedFrom:e.retriedFrom,taskIsolation:e.isolation,taskSourceProjectPath:s,taskWorktree:t}),taskWorktree:t}}catch(r){if(t)await o.exit({sessionId:e.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw r}}}
2
2
  export{m as s};
@@ -1,4 +1,4 @@
1
- import{ka as H}from"./chunk-9m1ayjve.js";import"./chunk-095x2ykj.js";import{$c as $,fd as T}from"./chunk-y78smk7g.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-ky0v990x.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-h37yw6g3.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as k}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-dskgbv7c.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
1
+ import{ka as H}from"./chunk-1gqmy8aq.js";import"./chunk-095x2ykj.js";import{$c as $,fd as T}from"./chunk-cx0yycfr.js";import"./chunk-6pa6c2n0.js";import"./chunk-yz2bsntj.js";import"./chunk-wbxv9wcn.js";import"./chunk-q3c07kb4.js";import"./chunk-6207mbmr.js";import"./chunk-pq1p9jz6.js";import"./chunk-y2g5a5bp.js";import"./chunk-96h588rd.js";import"./chunk-3qhqbj09.js";import{mf as k}from"./chunk-prgh321y.js";import"./chunk-jpwfq49n.js";import"./chunk-yqfqj7mh.js";import"./chunk-hatwwhm2.js";import"./chunk-1n60pgsq.js";import"./chunk-qkrssft1.js";import"./chunk-yvf4nmds.js";import"./chunk-6g5k5de1.js";import U from"os";import J from"path";function X(z){return typeof z==="string"?z:void 0}function N(z){if(!Array.isArray(z))return;let q=[];for(let K of z)if(typeof K==="string")q.push(K);else if(K!=null)q.push(String(K));return q}function b(){console.log(`
2
2
  blade mcp
3
3
  `),console.log(`管理 MCP 服务器
4
4
  `),console.log("Commands:"),console.log(" blade mcp add <name> <commandOrUrl> [args...] 添加 MCP 服务器"),console.log(" blade mcp remove <name> 删除 MCP 服务器 [aliases: rm]"),console.log(" blade mcp list 列出所有 MCP 服务器并检查健康状态 [aliases: ls]"),console.log(" blade mcp get <name> 获取服务器详情"),console.log(" blade mcp login <name> 登录远程 MCP OAuth"),console.log(" blade mcp logout <name> 清除远程 MCP OAuth 凭证"),console.log(` blade mcp add-json <name> <json> 从 JSON 字符串添加服务器