blade-code 0.10.81 → 0.10.83

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 (103) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-shq0pkxq.js → chunk-01zar8q6.js} +1 -1
  3. package/dist/{chunk-33bpwkyk.js → chunk-0q5bz3nm.js} +2 -2
  4. package/dist/{chunk-0b9jdzbq.js → chunk-1htd858b.js} +2 -2
  5. package/dist/{chunk-zkhb55jz.js → chunk-272swnyr.js} +1 -1
  6. package/dist/chunk-2b7zryg3.js +118 -0
  7. package/dist/chunk-3p808rrt.js +1 -0
  8. package/dist/{chunk-mygw13zd.js → chunk-44dzrn0p.js} +1 -1
  9. package/dist/chunk-4pksah0q.js +1 -0
  10. package/dist/{chunk-60esv83q.js → chunk-4rq0jhf4.js} +3 -3
  11. package/dist/{chunk-wra4tbhz.js → chunk-69rpb78b.js} +1 -1
  12. package/dist/{chunk-h0fh3j9w.js → chunk-6jsmac0q.js} +1 -1
  13. package/dist/{chunk-42p755yz.js → chunk-73j10ezs.js} +2 -2
  14. package/dist/chunk-7jp7e0zj.js +1 -0
  15. package/dist/{chunk-pfvgkexe.js → chunk-7m5q8vxf.js} +1 -1
  16. package/dist/{chunk-b9nhnzaj.js → chunk-7rfhmbqw.js} +1 -1
  17. package/dist/{chunk-c22vqgah.js → chunk-8215sm79.js} +12 -11
  18. package/dist/{chunk-sj0k8cdf.js → chunk-83caxxbt.js} +1 -1
  19. package/dist/{chunk-5gqqenv1.js → chunk-a14vnxrf.js} +1 -1
  20. package/dist/{chunk-kkzynnnn.js → chunk-aqkexfag.js} +1 -1
  21. package/dist/{chunk-seamt0j3.js → chunk-b2p9qm6j.js} +2 -2
  22. package/dist/chunk-bd5e1n5z.js +1 -0
  23. package/dist/{chunk-gbjtfgck.js → chunk-cchk5xrs.js} +1 -1
  24. package/dist/{chunk-skw3b17a.js → chunk-d2pwwdab.js} +1 -1
  25. package/dist/chunk-d4k4v959.js +1 -0
  26. package/dist/{chunk-091qx62q.js → chunk-e1ry8aj5.js} +1 -1
  27. package/dist/{chunk-b9vm7gns.js → chunk-ffa6hhee.js} +2 -2
  28. package/dist/{chunk-yyt14et5.js → chunk-fkwfymb6.js} +4 -4
  29. package/dist/{chunk-n2hqr6st.js → chunk-fs9j9gas.js} +2 -2
  30. package/dist/{chunk-jdb2mwbn.js → chunk-fv8b98tz.js} +2 -2
  31. package/dist/{chunk-7wf1gb3e.js → chunk-g832dwdm.js} +2 -2
  32. package/dist/{chunk-c9e0fbyh.js → chunk-g9xjcfrf.js} +1 -1
  33. package/dist/{chunk-1mc7nfb4.js → chunk-gd2sw9zm.js} +1 -1
  34. package/dist/chunk-hg8d4vhj.js +2 -0
  35. package/dist/{chunk-eeb2945p.js → chunk-hjr9r44k.js} +1 -1
  36. package/dist/chunk-hqsqk5dp.js +1 -0
  37. package/dist/{chunk-fsm3fb2m.js → chunk-jf4bxxyf.js} +1 -1
  38. package/dist/{chunk-gre57x9m.js → chunk-jndq361v.js} +1 -1
  39. package/dist/chunk-js3j00ka.js +1 -0
  40. package/dist/{chunk-aa4n9nbw.js → chunk-k50z8903.js} +1 -1
  41. package/dist/{chunk-90057qj6.js → chunk-m0a75642.js} +1 -1
  42. package/dist/{chunk-h6a0nct6.js → chunk-m5f934fh.js} +1 -1
  43. package/dist/chunk-mbt25rs5.js +1 -0
  44. package/dist/{chunk-xjr6y8s4.js → chunk-mgtcjwhy.js} +2 -2
  45. package/dist/{chunk-99hhpms5.js → chunk-mq2nx77s.js} +2 -2
  46. package/dist/{chunk-xyncta62.js → chunk-p9a3d507.js} +1 -1
  47. package/dist/{chunk-wjjapjhe.js → chunk-q14mgye7.js} +2 -2
  48. package/dist/chunk-qb242y47.js +1 -0
  49. package/dist/{chunk-pt97sfr3.js → chunk-r4mjdkzv.js} +1 -1
  50. package/dist/{chunk-b9bk43pk.js → chunk-r51ds5qw.js} +2 -2
  51. package/dist/{chunk-jwx10h5z.js → chunk-r77pcb0f.js} +2 -2
  52. package/dist/chunk-rmqksw1e.js +1 -0
  53. package/dist/{chunk-0a0sj79a.js → chunk-rwvaapta.js} +2 -2
  54. package/dist/{chunk-0141jad7.js → chunk-sb84vdcf.js} +1 -1
  55. package/dist/{chunk-0ra945vt.js → chunk-shr5cg46.js} +2 -2
  56. package/dist/{chunk-qxn5bg5k.js → chunk-sk8h4m9m.js} +1 -1
  57. package/dist/{chunk-h3w814js.js → chunk-skg520wq.js} +2 -2
  58. package/dist/{chunk-jzvbjn6e.js → chunk-sr4zv59p.js} +1 -1
  59. package/dist/{chunk-5nezhmnq.js → chunk-t1633e8m.js} +2 -2
  60. package/dist/{chunk-2vyfsby0.js → chunk-t5ysd5z8.js} +1 -1
  61. package/dist/{chunk-3cd753fb.js → chunk-t6phsb5h.js} +2 -2
  62. package/dist/{chunk-ky9q53m7.js → chunk-tpxs85cg.js} +1 -1
  63. package/dist/chunk-w2sb1hy9.js +1 -0
  64. package/dist/{chunk-7nx0pzfk.js → chunk-ww51801m.js} +1 -1
  65. package/dist/chunk-x2rraka3.js +1 -0
  66. package/dist/{chunk-30y6med4.js → chunk-xepdd9yj.js} +1 -1
  67. package/dist/chunk-xj65p2sn.js +1 -0
  68. package/dist/chunk-xp3ad15c.js +10 -0
  69. package/dist/{chunk-m1xmc7kh.js → chunk-xy67pj74.js} +325 -320
  70. package/dist/chunk-xzgqyzmy.js +171 -0
  71. package/dist/chunk-znhjr51w.js +1 -0
  72. package/dist/chunk-zp27f256.js +6 -0
  73. package/dist/web/assets/{ChatView-tu6nu0Yw.js → ChatView-DRn47Y3l.js} +3 -3
  74. package/dist/web/assets/{CodeBlockHighlighter-DFj0ZWq6.js → CodeBlockHighlighter-DxATdO6i.js} +1 -1
  75. package/dist/web/assets/{FilePreview-CLJNHlXO.js → FilePreview-D21mo4fn.js} +1 -1
  76. package/dist/web/assets/{KanbanBoard-B63UlcNr.js → KanbanBoard-DEUuLh0H.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-D7ap0LLK.js → MarkdownRenderer-BA9VgOyM.js} +3 -3
  78. package/dist/web/assets/{SettingsModal-B8Gp0bXw.js → SettingsModal-CXq3qDgQ.js} +1 -1
  79. package/dist/web/assets/{TaskSwitcher-gxALR-zu.js → TaskSwitcher-CUcZEUQH.js} +1 -1
  80. package/dist/web/assets/{TerminalPanel-dnC4oh4w.js → TerminalPanel-CcC6f3H_.js} +1 -1
  81. package/dist/web/assets/{index-Dn4vZglG.js → index-CfVQVVVI.js} +3 -3
  82. package/dist/web/assets/{teamService-CoJLtqAq.js → teamService-BX1zdQBb.js} +1 -1
  83. package/dist/web/index.html +1 -1
  84. package/package.json +1 -1
  85. package/dist/chunk-523kette.js +0 -1
  86. package/dist/chunk-6adxyred.js +0 -1
  87. package/dist/chunk-8g00qcv6.js +0 -171
  88. package/dist/chunk-bhwxskbf.js +0 -1
  89. package/dist/chunk-cwhxx0kj.js +0 -112
  90. package/dist/chunk-daca5tet.js +0 -1
  91. package/dist/chunk-etjw6np8.js +0 -1
  92. package/dist/chunk-ex3zfc8d.js +0 -1
  93. package/dist/chunk-g1e92rmg.js +0 -10
  94. package/dist/chunk-gn6ftvjy.js +0 -1
  95. package/dist/chunk-h9xayrwp.js +0 -1
  96. package/dist/chunk-reakyamv.js +0 -2
  97. package/dist/chunk-rpbyc2k4.js +0 -1
  98. package/dist/chunk-tkhbf34n.js +0 -1
  99. package/dist/chunk-twdw0c2p.js +0 -1
  100. package/dist/chunk-w7a801g0.js +0 -1
  101. package/dist/chunk-x5cya3gg.js +0 -6
  102. package/dist/chunk-zb79xdyv.js +0 -1
  103. package/dist/chunk-zd2zhy2t.js +0 -1
package/dist/blade.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{zd as W}from"./chunk-b9bk43pk.js";import{Cd as F,Dd as M}from"./chunk-h3w814js.js";import"./chunk-wjjapjhe.js";import"./chunk-v508x7cg.js";import"./chunk-c9e0fbyh.js";import"./chunk-60esv83q.js";import"./chunk-zkhb55jz.js";import"./chunk-3cd753fb.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Ng as N,Og as B}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import{nh as T}from"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-n2hqr6st.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as J}from"./chunk-h0fh3j9w.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-w7a801g0.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-daca5tet.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-6adxyred.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-x5cya3gg.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-pt97sfr3.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-c22vqgah.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-bhwxskbf.js"),import("./chunk-523kette.js"),import("./chunk-0b9jdzbq.js"),import("./chunk-fsm3fb2m.js"),import("./chunk-gbjtfgck.js"),import("./chunk-gre57x9m.js"),import("./chunk-091qx62q.js"),import("./chunk-zb79xdyv.js"),import("./chunk-30y6med4.js"),import("./chunk-g1e92rmg.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{Cd as W}from"./chunk-r51ds5qw.js";import{Fd as F,Gd as M}from"./chunk-skg520wq.js";import"./chunk-q14mgye7.js";import"./chunk-v508x7cg.js";import"./chunk-g9xjcfrf.js";import"./chunk-4rq0jhf4.js";import"./chunk-272swnyr.js";import"./chunk-t6phsb5h.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import{Sg as N,Tg as B}from"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import{sh as T}from"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-fs9j9gas.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import{$h as J}from"./chunk-6jsmac0q.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-3p808rrt.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-d4k4v959.js");K(U.map((Z)=>v.resolve(Q,Z)))}if(q(E,"--trust-workspace","--trustWorkspace")){let{WorkspaceTrustService:K}=await import("./chunk-7jp7e0zj.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-zp27f256.js");if(await K())return}if(W(),q(E,"--print","-p")){let{handlePrintMode:K}=await import("./chunk-r4mjdkzv.js");if(await K())return}if(E.includes("--acp")){let{runAcpIntegration:K}=await import("./chunk-8215sm79.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-znhjr51w.js"),import("./chunk-4pksah0q.js"),import("./chunk-1htd858b.js"),import("./chunk-jf4bxxyf.js"),import("./chunk-cchk5xrs.js"),import("./chunk-jndq361v.js"),import("./chunk-e1ry8aj5.js"),import("./chunk-bd5e1n5z.js"),import("./chunk-xepdd9yj.js"),import("./chunk-xp3ad15c.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-etjw6np8.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-aa4n9nbw.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-mbt25rs5.js").then(({checkVersionOnStartup:C})=>C()),[{render:w},{createElement:f},{AppWrapper:j}]=await Promise.all([import("ink"),import("react"),import("./chunk-k50z8903.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,3 +1,3 @@
1
- import{Th as $,Uh as F}from"./chunk-0ra945vt.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
1
+ import{Yh as $,Zh as F}from"./chunk-shr5cg46.js";import{promises as J}from"node:fs";import Q from"node:path";import{Mutex as U}from"async-mutex";import w from"write-file-atomic";var X=1;function D(k){if(!k||typeof k!=="object"||Array.isArray(k))return!1;let q=k;return typeof q.path==="string"&&Q.isAbsolute(q.path)&&typeof q.boundAt==="string"}async function Z(k){if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k);if(!(await J.stat(q)).isDirectory())throw Error("Project path must be a directory");return q}class K{filePath;mutex=new U;constructor(k=Q.join(F(),"bound-projects.json")){this.filePath=k}async list(k){let q=await this.read(),z=await Z(k),H=new Map;for(let C of q.projects)H.set(C.path,C);if(!H.has(z))H.set(z,{path:z,boundAt:new Date(0).toISOString()});return(await Promise.all([...H.values()].map(async(C)=>{let L=!1;try{L=(await J.stat(C.path)).isDirectory()}catch{}return{path:C.path,name:Q.basename(C.path)||C.path,...L?{gitBranch:$(C.path)}:{},available:L,isCurrent:C.path===z,boundAt:C.boundAt}}))).sort((C,L)=>{if(C.isCurrent!==L.isCurrent)return C.isCurrent?-1:1;return C.name.localeCompare(L.name)})}async bind(k,q){return this.mutex.runExclusive(async()=>{let z=await Z(k),H=await this.read(),W=H.projects.find((M)=>M.path===z),C=W??{path:z,boundAt:new Date().toISOString()};if(!W)H.projects.push(C),await this.write(H);let L=await Z(q),A=$(z);return{path:z,name:Q.basename(z)||z,...A?{gitBranch:A}:{},available:!0,isCurrent:z===L,boundAt:C.boundAt}})}async unbind(k){return this.mutex.runExclusive(async()=>{if(!Q.isAbsolute(k))throw Error("Project path must be absolute");let q=await J.realpath(k).catch(()=>Q.resolve(k)),z=await this.read(),H=z.projects.filter((W)=>W.path!==q);if(H.length===z.projects.length)return!1;return z.projects=H,await this.write(z),!0})}async read(){try{let k=await J.readFile(this.filePath,"utf8"),q=JSON.parse(k);if(q.version!==X||!Array.isArray(q.projects))return{version:X,projects:[]};return{version:X,projects:q.projects.filter(D)}}catch(k){if(k.code==="ENOENT"||k instanceof SyntaxError)return{version:X,projects:[]};throw k}}async write(k){let q=Q.dirname(this.filePath);await J.mkdir(q,{recursive:!0,mode:448}),await J.chmod(q,448),await w(this.filePath,`${JSON.stringify(k,null,2)}
2
2
  `,{mode:384}),await J.chmod(this.filePath,384)}}var _=new K;
3
3
  export{_ as l};
@@ -1,2 +1,2 @@
1
- import{ue as B}from"./chunk-mygw13zd.js";import{uh as Y}from"./chunk-5nezhmnq.js";import{Ah as $,xh as Z}from"./chunk-h6a0nct6.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
- export{D as qe,h as re,j as se};
1
+ import{xe as B}from"./chunk-44dzrn0p.js";import{zh as Y}from"./chunk-t1633e8m.js";import{Ch as Z,Fh as $}from"./chunk-m5f934fh.js";import{createHash as H}from"node:crypto";var N="fast-mode-2026-02-01";function R(q,x,z){if(x.api!=="anthropic-messages"||z.providerValue!=="fast")return q;let J={...q},w=Object.keys(J).find((G)=>G.toLowerCase()==="anthropic-beta")??"anthropic-beta",Q=new Set((J[w]??"").split(",").map((G)=>G.trim()).filter(Boolean));return Q.add(N),J[w]=[...Q].join(","),J}function D(q){return`BLADE_MODEL_API_KEY_${H("sha256").update(q).digest("hex").slice(0,32).toUpperCase()}`}function F(q,x){if(!q.fallbackModels?.length)return;return q.fallbackModels.map((z)=>{let J=(x.models??[]).filter((G)=>G.provider===z.provider&&G.model===z.model),w=z.configId?(x.models??[]).find((G)=>G.id===z.configId):J.length===1?J[0]:void 0;if(z.configId&&!w)throw Error(`Unknown fallback model config ID: ${z.configId}`);if(w&&(w.provider!==z.provider||w.model!==z.model))throw Error(`Fallback model config ${w.id} does not match ${z.provider}/${z.model}`);if(!z.configId&&J.length>1)throw Error(`Fallback model ${z.provider}/${z.model} is ambiguous; set configId`);if(!w)return z;let Q=w.provider===q.provider;return{...z,configId:w.id,channel:{apiKey:process.env[D(w.id)]??(Q?process.env.BLADE_API_KEY:void 0),baseUrl:w.overrides?.baseUrl??(Q?process.env.BLADE_BASE_URL:void 0),temperature:w.overrides?.temperature??x.temperature,maxOutputTokens:w.overrides?.maxOutputTokens,timeout:w.overrides?.timeout??x.timeout,streamIdleTimeout:w.overrides?.streamIdleTimeout,apiVersion:w.overrides?.apiVersion,customHeaders:w.overrides?.customHeaders,enablePromptCaching:w.overrides?.enablePromptCaching}}})}function h(q,x,z,J=Y(),w="auto",Q="auto"){let G=J.resolveConfig(q),U=B(G,z),W=$(G,w),X=Z(G,Q),L=q.overrides;return{config:q,model:G,displayName:q.displayName??G.name,chat:{provider:q.provider,model:q.model,apiKey:process.env[D(q.id)]??process.env.BLADE_API_KEY,baseUrl:process.env.BLADE_BASE_URL??L?.baseUrl,temperature:L?.temperature??x.temperature,maxContextTokens:G.contextWindow,maxOutputTokens:L?.maxOutputTokens,timeout:L?.timeout??x.timeout,streamIdleTimeout:L?.streamIdleTimeout,reasoningEnabled:U.effective!=="off",...U.effective==="off"?{}:{reasoningEffort:U.effective},...W.providerValue?{serviceTier:W.providerValue}:{},...X.providerValue?{responseVerbosity:X.providerValue}:{},fallbackModels:F(q,x),enablePromptCaching:L?.enablePromptCaching,customHeaders:R(L?.customHeaders,G,W),apiVersion:L?.apiVersion,maxRetries:L?.maxRetries,providerCircuitBreakerOpenMs:x.providerCircuitBreakerOpenMs,providerRequestConcurrency:x.providerRequestConcurrency,providerGlobalConcurrency:x.providerGlobalConcurrency,providerOwnerConcurrency:x.providerOwnerConcurrency,providerRequestAdmissionMs:x.providerRequestAdmissionMs,providerRequestPendingBytes:x.providerRequestPendingBytes,modelCatalog:J},reasoning:U,serviceTier:W,responseVerbosity:X}}function j(q,x=Y()){try{return q.displayName??x.getModel(q.provider,q.model).name}catch{return q.displayName??q.model}}
2
+ export{D as te,h as ue,j as ve};
@@ -1,4 +1,4 @@
1
- import"./chunk-v508x7cg.js";import{yg as Q}from"./chunk-3cd753fb.js";import"./chunk-pfvgkexe.js";import"./chunk-qxn5bg5k.js";import"./chunk-reakyamv.js";import{Og as L}from"./chunk-0141jad7.js";import"./chunk-eeb2945p.js";import"./chunk-b9vm7gns.js";import"./chunk-5nezhmnq.js";import"./chunk-h6a0nct6.js";import"./chunk-n2hqr6st.js";import"./chunk-0a0sj79a.js";import"./chunk-sj0k8cdf.js";import"./chunk-0ra945vt.js";import{Wh as F}from"./chunk-h0fh3j9w.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-h9xayrwp.js"),{SessionService:B}=await import("./chunk-twdw0c2p.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-v508x7cg.js";import{Bg as Q}from"./chunk-t6phsb5h.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import{Tg as L}from"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-fs9j9gas.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import{$h as F}from"./chunk-6jsmac0q.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-w2sb1hy9.js"),{SessionService:B}=await import("./chunk-qb242y47.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
1
  import{spawn as I}from"node:child_process";var X=500;function x(j){return new Promise((q)=>setTimeout(q,j))}function Z(j){return j&&typeof j==="object"&&"code"in j?String(j.code):void 0}function L(j){return j()||j()}function G(j,q=process.platform,y=process.kill.bind(process)){if(q==="win32"||!Number.isInteger(j)||j<=1||j===process.pid)return!1;try{return y(-j,0),!0}catch(z){let B=Z(z);if(B==="ESRCH")return!1;if(B==="EPERM")return!0;throw z}}function N(j,q){return new Promise((y)=>{let z=["/PID",String(j),"/T"];if(q)z.push("/F");let B=I("taskkill",z,{stdio:"ignore",windowsHide:!0}),K=!1,J=(H)=>{if(K)return;K=!0,y(H)};B.once("error",()=>J(!1)),B.once("close",(H)=>J(H===0))})}async function F(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};let y=q.platform??process.platform,z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.taskkill??N,J=q.wait??x,H=q.validatePidOwnership??(()=>!0);if(!L(H))return{success:!1,alreadyExited:!1,forced:!1};if(y==="win32"){let V=await K(j,!1);if(await J(z),!H())return{success:V,alreadyExited:!1,forced:!1};let Y=await K(j,!0);return{success:V||Y,alreadyExited:!V&&!Y,forced:Y}}let Q=(V,Y)=>{try{return B(V,Y)}catch(D){return Z(D)==="ESRCH"}},W=Q(-j,"SIGTERM")||Q(j,"SIGTERM");if(await J(z),!H())return{success:W,alreadyExited:!1,forced:!1};let $=Q(-j,"SIGKILL")||Q(j,"SIGKILL");return{success:W||$,alreadyExited:!1,forced:$}}async function R(j,q={}){if(!Number.isInteger(j)||j<=1||j===process.pid)return{success:!1,alreadyExited:!1,forced:!1};if((q.platform??process.platform)==="win32")return{success:!1,alreadyExited:!1,forced:!1};let z=q.gracePeriodMs??X,B=q.killProcess??process.kill.bind(process),K=q.wait??x,J=q.validatePidOwnership??(()=>!0);if(!J())return{success:!1,alreadyExited:!1,forced:!1};let H=($)=>{try{return B(-j,$),"sent"}catch(V){return Z(V)==="ESRCH"?"missing":"failed"}},Q=H("SIGTERM");if(Q==="missing")return{success:!0,alreadyExited:!0,forced:!1};if(Q==="failed")return{success:!1,alreadyExited:!1,forced:!1};if(await K(z),!J())return{success:!1,alreadyExited:!1,forced:!1};let W=H("SIGKILL");return{success:W!=="failed",alreadyExited:W==="missing",forced:W==="sent"}}class b{child;state="owned";terminationPromise;terminationResult;platform;gracePeriodMs;killProcess;taskkill;wait;constructor(j,q={}){this.child=j;if(this.platform=q.platform??process.platform,this.gracePeriodMs=q.gracePeriodMs??X,this.killProcess=q.killProcess??process.kill.bind(process),this.taskkill=q.taskkill??N,this.wait=q.wait??x,q.releaseOnExit!==!1){let y=()=>{if(this.state==="owned")this.state="released"};j.once("close",y),j.once("error",y)}}release(){if(this.state==="owned")this.state="released"}terminate(){if(this.terminationPromise)return this.terminationPromise;if(this.terminationResult)return Promise.resolve(this.terminationResult);if(this.state==="released")return this.terminationResult={success:!0,alreadyExited:!0,forced:!1},Promise.resolve(this.terminationResult);return this.state="terminating",this.terminationPromise=this.terminateOwnedTree().then((j)=>{return this.state="released",this.terminationResult=j,j}),this.terminationPromise}async terminateOwnedTree(){let j=this.child.pid;if(!j)return{success:!1,alreadyExited:!0,forced:!1};if(this.platform==="win32"){let z=await this.taskkill(j,!1);await this.wait(this.gracePeriodMs);let B=await this.taskkill(j,!0);if(!z&&!B)return{success:this.signalDirectChild("SIGKILL"),alreadyExited:!1,forced:!0};return{success:!0,alreadyExited:!1,forced:!0}}let q=this.signalPosixTree(j,"SIGTERM");await this.wait(this.gracePeriodMs);let y=this.signalPosixTree(j,"SIGKILL");return{success:q||y,alreadyExited:!1,forced:y}}signalPosixTree(j,q){if(j<=1||j===process.pid)return this.signalDirectChild(q);try{return this.killProcess(-j,q)}catch(y){if(Z(y)==="ESRCH")return!0;return this.signalDirectChild(q)}}signalDirectChild(j){try{return this.child.kill(j)}catch(q){return Z(q)==="ESRCH"}}}function v(j,q,y={},z={}){let B=I(j,q,{...y,detached:process.platform==="win32"?y.detached:!0,windowsHide:y.windowsHide??!0});return{child:B,processTree:new b(B,z)}}
2
- export{G as sf,F as tf,R as uf,v as vf};
2
+ export{G as vf,F as wf,R as xf,v as yf};
@@ -0,0 +1,118 @@
1
+ import{bd as h,cd as Cq,dd as g$,ed as Yq,fd as S,gd as S$,hd as Wq,id as y$,jd as Hq,kd as j$,ld as m$,nd as l0,qd as I$,rd as Bq}from"./chunk-r77pcb0f.js";import{we as D0}from"./chunk-44dzrn0p.js";import{mf as z0}from"./chunk-ww51801m.js";import{yf as m1}from"./chunk-272swnyr.js";import{Lg as Vq,Mg as Xq,Ng as V0,Og as k0,Pg as Q0}from"./chunk-hg8d4vhj.js";import{Tg as e$}from"./chunk-sb84vdcf.js";import{th as I0}from"./chunk-ffa6hhee.js";import{Ah as f0,Dh as T0}from"./chunk-m5f934fh.js";import{Hh as t}from"./chunk-fs9j9gas.js";import{Rh as Gq,Sh as B0,Th as Qq,Uh as x,Vh as v,Xh as U0,Yh as r,Zh as l}from"./chunk-shr5cg46.js";import{readdir as E$,readFile as L0,rm as X0,stat as n0}from"node:fs/promises";import*as K from"node:path";import{nanoid as I}from"nanoid";import{createHash as Mq,randomUUID as Aq}from"node:crypto";import*as P from"node:fs/promises";import*as x0 from"node:path";import{execFileSync as Uq}from"node:child_process";import{createHash as Rq}from"node:crypto";import{readFileSync as fq}from"node:fs";var Tq=/^[a-f0-9]{64}$/;function o$($){if(!$||typeof $!=="object")return!1;let q=$;return(q.platform==="linux"||q.platform==="darwin"||q.platform==="win32")&&typeof q.fingerprint==="string"&&Tq.test(q.fingerprint)}var r$={readFile:($)=>fq($,"utf8"),execFile:($,q)=>Uq($,q,{encoding:"utf8",timeout:$==="powershell.exe"?3000:2000,windowsHide:!0})},Dq=($)=>{try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}};function q$($,q){return{platform:$,fingerprint:Rq("sha256").update(`${$}\x00${q}`).digest("hex")}}function zq($,q){let J=q.readFile(`/proc/${$}/stat`).trim(),L=J.lastIndexOf(")");if(L<0)throw Error("Invalid /proc process stat");let Z=J.slice(L+2).split(/\s+/)[19];if(!Z||!/^\d+$/.test(Z))throw Error("Missing process start ticks");return Z}function A0($,q=process.platform,J=r$){if(!Number.isInteger($)||$<=1)return;try{if(q==="linux")return q$(q,zq($,J));if(q==="darwin"){let L=J.execFile("ps",["-o","lstart=","-p",String($)]).trim();return L?q$(q,L):void 0}if(q==="win32"){let L=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${$}").CreationDate.ToUniversalTime().ToString('O')`,G=J.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",L]).trim();return G?q$(q,G):void 0}}catch{return}return}function t$($,q){return A0($,q.platform)?.fingerprint===q.fingerprint}function W4($,q,J=r$,L=Dq){if(!Number.isInteger($)||$<=1)return!1;let G=A0($,q.platform,J);if(G)return G.fingerprint===q.fingerprint;return!L($)}var $1=1;function wq($,q){let J=Mq("sha256").update(q).digest("hex");return x0.join(B0($),".locks",`${J}.lock`)}function w0($,q){return $ instanceof Error&&"code"in $&&$.code===q}async function J$($){try{let q=JSON.parse(await P.readFile($,"utf8"));if(q.version!==$1||typeof q.sessionId!=="string"||typeof q.ownerId!=="string"||!Number.isInteger(q.pid)||(q.pid??0)<=0||q.processIdentity!==void 0&&!o$(q.processIdentity)||typeof q.acquiredAt!=="string")return;return q}catch{return}}async function a$($){let q=await J$($);if(q)return q;return await new Promise((J)=>setTimeout(J,10)),J$($)}function xq($){try{return process.kill($,0),!0}catch(q){return w0(q,"EPERM")}}async function s$($,q){let J;try{return J=await P.open($,"wx",384),await J.writeFile(`${JSON.stringify(q)}
2
+ `,"utf8"),!0}catch(L){if(w0(L,"EEXIST"))return!1;if(J)await P.unlink($).catch(()=>{return});throw L}finally{await J?.close().catch(()=>{return})}}class i extends Error{code="BLADE_SESSION_IN_USE";constructor($){super($?`Session is already active in another Blade process (PID ${$}). Stop that process or choose a different session.`:"Session is already active in another Blade process. Stop that process or choose a different session.");this.name="SessionInUseError"}}class d{filePath;record;released=!1;constructor($,q){this.filePath=$;this.record=q}static async acquire($,q=e$()){let J=wq(q,$),L={version:$1,sessionId:$,ownerId:Aq(),pid:process.pid,processIdentity:A0(process.pid),acquiredAt:new Date().toISOString()};if(await P.mkdir(x0.dirname(J),{recursive:!0,mode:448}),await s$(J,L))return new d(J,L);let G=await a$(J);if(G&&xq(G.pid)&&(!G.processIdentity||t$(G.pid,G.processIdentity)))throw new i(G.pid);if(await P.unlink(J).catch((Z)=>{if(!w0(Z,"ENOENT"))throw Z}),await s$(J,L))return new d(J,L);throw new i((await a$(J))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await J$(this.filePath))?.ownerId!==this.record.ownerId)return;await P.unlink(this.filePath).catch((q)=>{if(!w0(q,"ENOENT"))throw q})}}import{createHash as E0}from"node:crypto";import{constants as a,promises as u}from"node:fs";import p from"node:path";import{Mutex as Eq}from"async-mutex";var q1=128,J1=67108864,bq=24576,L1=65536,Z$=1,C1=/^[a-f0-9]{64}$/,kq=/^[a-f0-9]{64}\.txt$/,Y1=64,g0=`
3
+
4
+ ...[middle omitted; read the private prompt artifact for the complete request]...
5
+
6
+ `;function Z1($,q){return $ instanceof Error&&"code"in $&&$.code===q}function K0($,q){if($ instanceof Error&&($.message.startsWith("Prompt artifact")||$.message.startsWith("User prompt")))return $;return Error(q)}function G1($){return(!process.getuid||$.uid===process.getuid())&&(process.platform==="win32"||($.mode&511)===384)}async function L$($){if(await u.mkdir($,{recursive:!0,mode:448}),process.platform!=="win32")await u.chmod($,448);let q=await u.lstat($);if(!q.isDirectory()||q.isSymbolicLink()||process.getuid&&q.uid!==process.getuid()||process.platform!=="win32"&&(q.mode&511)!==448)throw Error("Prompt artifact directory ownership or permissions are invalid")}async function gq($){if(process.platform==="win32")return;let q=await u.open($,a.O_RDONLY);try{await q.sync()}finally{await q.close()}}function Q1($){if(!C1.test($))throw Error("Prompt artifact ID is invalid");return`${$}.txt`}function Sq($){if(typeof $==="string")return{text:$};let q="",J=[];for(let L of $){if(L.type==="image_url"){J.push({type:"image_url"});continue}if(!L.text)continue;q+=L.text;let G=J.at(-1);if(G?.type==="text")G.chars+=L.text.length;else J.push({type:"text",chars:L.text.length})}return{text:q,contentLayout:J}}function V1($){if(typeof $==="string")return[];return $.filter((q)=>q.type==="image_url").map((q)=>({type:"image_url",image_url:{...q.image_url}}))}function b0($,q){if(!q)return;let J=$.at(-1);if(J?.type==="text")J.text+=q;else $.push({type:"text",text:q})}function X1($,q){let J=Buffer.from($,"utf8");if(J.length<=q)return $;let L=q;while(L>0&&(J[L]&192)===128)L--;return J.subarray(0,L).toString("utf8")}function yq($,q){let J=Buffer.from($,"utf8");if(J.length<=q)return $;let L=J.length-q;while(L<J.length&&(J[L]&192)===128)L++;return J.subarray(L).toString("utf8")}function jq($,q){if(Buffer.from($,"utf8").length<=q)return{head:$,tail:"",elided:!1};if(q<=Buffer.byteLength(g0))return{head:X1($,q),tail:"",elided:!1};let L=q-Buffer.byteLength(g0),G=Math.min(4096,Math.floor(L/2)),Z=L-G;return{head:X1($,Z),tail:yq($,G),elided:!0}}function mq($,q,J,L,G){let Z=jq($,L);if(!J||q.length===0)return`${Z.head}${Z.elided?g0:""}${Z.tail}${G}`;let Q=[],V=Z.head.length,C=$.length-Z.tail.length,Y=0,H=0,X=!1;for(let W of J){if(W.type==="image_url"){let T=q[H++];if(!T)throw Error("Prompt artifact image layout does not match its content");Q.push(T);continue}let B=Y,_=Y+W.chars;if(B<V)b0(Q,$.slice(B,Math.min(_,V)));let f=Math.max(B,V),b=Math.min(_,C);if(Z.elided&&f<b&&!X)b0(Q,g0),X=!0;if(_>C)b0(Q,$.slice(Math.max(B,C),_));Y=_}if(H!==q.length||Y!==$.length)throw Error("Prompt artifact content layout does not match its content");return b0(Q,G),Q}function Iq($,q){if($===void 0)return;if(!Array.isArray($)||$.length===0||$.length>Y1)return;let J=[],L=0;for(let G of $){if(!G||typeof G!=="object"||Array.isArray(G))return;let Z=G;if(Z.type==="image_url"){J.push({type:"image_url"});continue}if(Z.type!=="text"||typeof Z.chars!=="number"||!Number.isSafeInteger(Z.chars)||Z.chars<=0||Z.chars>q)return;L+=Z.chars,J.push({type:"text",chars:Z.chars})}return L===q?J:void 0}function G$($){return $!==null&&typeof $==="object"&&!Array.isArray($)&&Object.hasOwn($,"userPromptArtifact")}function Q$($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$.userPromptArtifact;if(!q||typeof q!=="object"||Array.isArray(q))return;let J=q;if(J.version!==Z$||typeof J.id!=="string"||!C1.test(J.id)||typeof J.sha256!=="string"||J.sha256!==J.id||typeof J.sizeBytes!=="number"||!Number.isSafeInteger(J.sizeBytes)||J.sizeBytes<=V0||J.sizeBytes>Q0||typeof J.textChars!=="number"||!Number.isSafeInteger(J.textChars)||J.textChars<=0||J.textChars>k0||typeof J.inlineBytes!=="number"||!Number.isSafeInteger(J.inlineBytes)||J.inlineBytes<=0||J.inlineBytes>V0)return;let L=Iq(J.contentLayout,J.textChars);if(J.contentLayout!==void 0&&!L)return;return{version:Z$,id:J.id,sha256:J.sha256,sizeBytes:J.sizeBytes,textChars:J.textChars,inlineBytes:J.inlineBytes,...L?{contentLayout:L}:{}}}function W1($){return[...new Set($.flatMap((q)=>{let J=Q$(q);if(!J&&G$(q))throw Error("Prompt artifact reference is invalid");return J?[J.id]:[]}))]}class s{root;writeMutex=new Eq;initializePromise;artifactCount=0;storedBytes=0;constructor($,q,J){if(!p.isAbsolute($))throw Error("Prompt artifact project root must be absolute");if(!q||Buffer.byteLength(q)>256)throw Error("Prompt artifact Session identity is invalid");let L=E0("sha256").update(p.resolve($)).digest("hex"),G=E0("sha256").update(q).digest("hex");this.root=p.join(J.storageRoot,"prompt-artifacts",L,G)}async materialize($,q){let J=Q$(q);if(!J&&G$(q))throw Error("Prompt artifact reference is invalid");if(J){try{await this.verify(J.id,J.sizeBytes)}catch(H){throw K0(H,"Prompt artifact is unavailable or invalid")}return{content:$,metadata:q,offloaded:!0}}let L=Sq($),G=L.text,Z=Buffer.from(G,"utf8");if(Z.length<=V0)return{content:$,metadata:q,offloaded:!1};if(L.contentLayout&&L.contentLayout.length>Y1)throw Error("User prompt contains too many text and image segments");if(G.length>k0)throw Error(`User prompt exceeds the ${k0}-character durable input limit`);if(Z.length>Q0)throw Error(`User prompt exceeds the ${Q0}-byte durable input limit`);let Q;try{Q=await this.write(Z,G.length,L.contentLayout)}catch(H){throw K0(H,"Prompt artifact could not be stored")}let V=["","","[Full user request stored as a private prompt artifact]",`artifact_id=${Q.id}`,`size_bytes=${Q.sizeBytes}`,"Call ReadPromptArtifact with this artifact_id before acting. The complete","request may contain required instructions omitted from the bounded excerpt."].join(`
7
+ `),C=V1($);return{content:mq(G,C,L.contentLayout,V0-Buffer.byteLength(V),V),metadata:{...q,userPromptArtifact:Q},offloaded:!0}}async restore($,q){let J=Q$(q);if(!J&&G$(q))throw Error("Prompt artifact reference is invalid");if(!J)return $;let L;try{L=await this.readVerified(J.id,J.sizeBytes)}catch(Y){throw K0(Y,"Prompt artifact is unavailable or invalid")}let G=L.toString("utf8");if(G.length!==J.textChars)throw Error("Prompt artifact character count does not match its reference");let Z=V1($);if(!J.contentLayout){if(Z.length>0)throw Error("Prompt artifact content layout is missing");return G}let Q=[],V=0,C=0;for(let Y of J.contentLayout){if(Y.type==="image_url"){let H=Z[C++];if(!H)throw Error("Prompt artifact image layout does not match its content");Q.push(H);continue}Q.push({type:"text",text:G.slice(V,V+Y.chars)}),V+=Y.chars}if(V!==G.length||C!==Z.length)throw Error("Prompt artifact content layout does not match its content");return Q}async read($,q=0,J=bq){if(!Number.isSafeInteger(q)||q<0)throw Error("Prompt artifact offset must be a non-negative integer");if(!Number.isSafeInteger(J)||J<4||J>L1)throw Error(`Prompt artifact limit must be between 4 and ${L1}`);let L;try{L=await this.readVerified($)}catch(Q){throw K0(Q,"Prompt artifact is unavailable or invalid")}if(q>L.length)throw Error("Prompt artifact offset exceeds its size");let G=q;while(G>0&&G<L.length&&(L[G]&192)===128)G--;let Z=Math.min(L.length,G+J);while(Z>G&&Z<L.length&&(L[Z]&192)===128)Z--;return{id:$,sha256:$,sizeBytes:L.length,offset:G,...Z<L.length?{nextOffset:Z}:{},returnedBytes:Z-G,content:L.subarray(G,Z).toString("utf8")}}async copyReferencedTo($,q){try{for(let J of new Set($)){let L=await this.readVerified(J);if((await q.write(L,L.toString("utf8").length)).id!==J)throw Error("Prompt artifact identity changed during copy")}}catch(J){throw K0(J,"Prompt artifact copy failed")}}async removeAll(){try{await u.rm(this.root,{recursive:!0,force:!0})}catch{throw Error("Prompt artifact cleanup failed")}}async initialize(){return this.initializePromise??=this.scan(),this.initializePromise}async scan(){await L$(p.dirname(p.dirname(this.root))),await L$(p.dirname(this.root)),await L$(this.root);let $=await u.readdir(this.root,{withFileTypes:!0}),q=0,J=0;for(let L of $){if(!kq.test(L.name))throw Error("Prompt artifact store contains an unsafe entry");let G=p.join(this.root,L.name),Z=await u.lstat(G);if(!L.isFile()||Z.isSymbolicLink()||!G1(Z)||Z.size>Q0)throw Error("Prompt artifact store contains an unsafe entry");q++,J+=Z.size}if(q>q1||J>J1)throw Error("Prompt artifact Session quota exceeded");this.artifactCount=q,this.storedBytes=J}async write($,q,J){return this.writeMutex.runExclusive(()=>this.writeExclusive($,q,J))}async writeExclusive($,q,J){await this.initialize();let L=E0("sha256").update($).digest("hex"),G=p.join(this.root,Q1(L));try{await this.verify(L,$.length)}catch(Q){if(!Z1(Q,"ENOENT"))throw Q;if(this.artifactCount>=q1||this.storedBytes+$.length>J1)throw Error("Prompt artifact Session quota exceeded");let V;try{if(V=await u.open(G,a.O_CREAT|a.O_EXCL|a.O_WRONLY|(a.O_NOFOLLOW??0),384),await V.writeFile($),process.platform!=="win32")await V.chmod(384);await V.sync(),await V.close(),V=void 0,await gq(this.root),this.artifactCount++,this.storedBytes+=$.length}catch(C){if(await V?.close().catch(()=>{return}),!Z1(C,"EEXIST"))throw await u.rm(G,{force:!0}).catch(()=>{return}),C;await this.verify(L,$.length)}}let Z=Buffer.byteLength(["","","[Full user request stored as a private prompt artifact]",`artifact_id=${L}`,`size_bytes=${$.length}`,"Call ReadPromptArtifact with this artifact_id before acting. The complete","request may contain required instructions omitted from the bounded excerpt."].join(`
8
+ `));return{version:Z$,id:L,sha256:L,sizeBytes:$.length,textChars:q,inlineBytes:V0-Z,...J?{contentLayout:J}:{}}}async verify($,q){await this.readVerified($,q)}async readVerified($,q){await this.initialize();let J=p.join(this.root,Q1($)),L=await u.open(J,a.O_RDONLY|(a.O_NOFOLLOW??0));try{let G=await L.stat();if(!G.isFile()||!G1(G)||G.size>Q0||q!==void 0&&G.size!==q)throw Error("Prompt artifact ownership, permissions, or size are invalid");let Z=await L.readFile();if(E0("sha256").update(Z).digest("hex")!==$)throw Error("Prompt artifact content hash does not match its identity");return Z}finally{await L.close()}}}var z4=1;function V$($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function vq($){if(!V$($)||typeof $.type!=="string")return!1;if($.type==="text")return typeof $.text==="string";return $.type==="image_url"&&V$($.image_url)&&typeof $.image_url.url==="string"}function Pq($){if(!V$($))return!1;if(!["system","user","assistant","tool"].includes(String($.role)))return!1;return typeof $.content==="string"||Array.isArray($.content)&&$.content.every(vq)}function H1($){if(!Array.isArray($)||$.length===0||$.length>4096)return;let q=JSON.stringify($);if(Buffer.byteLength(q)>16777216)return;let J=JSON.parse(q);if(!Array.isArray(J)||!J.every(Pq))return;return J}function M4($){let q=H1($);if(!q)throw Error("Compaction replacement context is invalid or exceeds limits");return q}function S0($){return H1($)}function uq($,q){for(let J of $){if(J.type!=="part_created"||J.data.partType!=="tool_result")continue;let L=J.data.payload;if(!L||typeof L!=="object"||Array.isArray(L))continue;let G=L;if(G.toolCallId===q||J.data.partId===q||J.data.messageId===q)return G}return}function B1($){let q=h($),J=new Map;for(let L of q){if(L.type==="interaction_requested"){J.set(L.data.requestId,{request:L.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(L.type==="interaction_responded"){let G=J.get(L.data.requestId);if(G)G.response=L.data;continue}if(L.type==="interaction_recovered"){let G=J.get(L.data.requestId);if(G)G.recovery=L.data}}for(let L of J.values()){let G=uq(q,L.request.toolCallId);L.hasToolResult=G!==void 0;let Z=G?.metadata&&typeof G.metadata==="object"?G.metadata:void 0;L.hasRecoveryToolResult=Z?.interactionRecovery===!0&&Z.requestId===L.request.requestId}return[...J.values()]}function K1($){return B1($).reverse().find((q)=>!q.response&&!q.recovery)}function x4($){let q=new Map;for(let J of B1($))q.set(J.request.toolCallId,J);return[...q.values()].filter((J)=>J.response&&!J.recovery&&(!J.hasToolResult||J.hasRecoveryToolResult))}function _1($){if(!$)return;return{type:$.request.interactionType,requestId:$.request.requestId}}function y0($){let q=new Map,J=[];for(let L of $){if(L.type==="review_started"){if(!q.has(L.data.reviewId))J.push(L.data.reviewId),q.set(L.data.reviewId,{start:L.data});continue}if(L.type!=="review_completed")continue;let G=q.get(L.data.reviewId);if(G&&G.completion===void 0)G.completion=L.data}return J.map((L)=>q.get(L)).filter((L)=>L!==void 0)}function b4($){return y0($).reverse().find((q)=>q.completion===void 0)}function X$($){switch($){case"completed":return"completed";case"stale":return"stale: the review target changed while the reviewer was running";case"aborted":return"aborted";case"interrupted":return"interrupted by process restart";case"failed":return"failed"}}function O1($,q){let J=["## Code Review","",`Target: ${$.target.label}`,`Status: ${X$(q.status)}`,"",q.overallExplanation||"No overall explanation was provided."];if(q.findings.length===0)J.push("","No actionable findings.");else{J.push("","### Findings");for(let[L,G]of q.findings.entries()){let Z=G.codeLocation.lineStart===G.codeLocation.lineEnd?`${G.codeLocation.lineStart}`:`${G.codeLocation.lineStart}-${G.codeLocation.lineEnd}`;J.push("",`${L+1}. ${G.title}`,` ${G.codeLocation.path}:L${Z} · confidence ${G.confidenceScore.toFixed(2)}`,` ${G.body}`)}}if(q.error)J.push("",`Error: ${q.error}`);return J.join(`
9
+ `)}function F1($,q){return{reviewId:$.reviewId,phase:"completed",status:q.status,target:{kind:$.target.kind,label:$.target.label,...$.target.baseSha?{reference:$.target.baseSha}:{},...$.target.commitSha?{reference:$.target.commitSha}:{}},overallExplanation:q.overallExplanation,findings:q.findings.map((J)=>({title:J.title,body:J.body,priority:J.priority,confidenceScore:J.confidenceScore,codeLocation:{...J.codeLocation}})),...q.error?{error:q.error}:{}}}var H$=1;var C$=2000,hq='<token-budget-handoff version="1">',S4="handoff-message-",cq=128,lq=["version","messageId","observedPromptTokens","availableForInput","handoffThreshold","compactionThreshold","createdAt"],nq=/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/,pq=/(?:^|\n)Remaining prompt-token headroom before compaction: (\d+)\.$/;function c($){return typeof $==="number"&&Number.isSafeInteger($)&&$>=0}function B$($){return c($)&&$>0}function iq($){for(let q=0;q<$.length;q+=1){let J=$.charCodeAt(q);if(J<=31||J===127)return!0}return!1}function N1($){return typeof $==="string"&&$.length>=1&&$.length<=cq&&!iq($)}function Y$($){if(!$||typeof $!=="object"||Array.isArray($))return!1;let q=Object.getPrototypeOf($);return q===Object.prototype||q===null}function j0($,q){let J=Math.floor($/10),L=$%10;return J*q+Math.floor(L*q/10)}function dq($){if(typeof $!=="string"||!nq.test($))return!1;try{let q=new Date($);return Number.isFinite(q.getTime())&&q.toISOString()===$}catch{return!1}}function U1($){if(!c($))throw Error("Token budget handoff headroom must be a safe nonnegative integer");return[hq,"Context rollover is approaching. Continue the user task from this state only.","Make objective, decisions, mutations, verification, background work, blockers, and the exact next action explicit.","For pending work, preserve exact commands, tool arguments, and required final-response constraints when they are known.","Do not claim success or completion unless it is already proven in the transcript.","Do not create bookkeeping files the user did not request.",`Remaining prompt-token headroom before compaction: ${$}.`].join(`
10
+ `)}function oq($){let q=U1($);if(new TextEncoder().encode(q).length>C$)throw Error(`Token budget handoff reminder exceeds ${C$} bytes`);return q}function W$($,q){let J=Object.keys($).sort(),L=[...q].sort();return J.length===L.length&&J.every((G,Z)=>G===L[Z])}function y4($){let{maxContextTokens:q,maxOutputTokens:J,configuredMaxOutputTokens:L}=$,G=J??L??void 0;if(G!==void 0)return G;if(!B$(q))return;return Math.min(Math.max(Math.floor(q*0.1),8192),32768)}function j4($){let{contextTokens:q,tokenSource:J,estimatedPendingTokens:L,maxContextTokens:G,maxOutputTokens:Z}=$;if(!B$(G)||!c(Z)||Z>=G)return{phase:"unknown"};let Q=G-Z;if(Q<=0)return{phase:"unknown"};let V=j0(Q,7),C=j0(Q,8);if(!c(q))return{phase:"unknown",...J?{tokenSource:J}:{},...c(L)?{estimatedPendingTokens:L}:{},maxContextTokens:G,maxOutputTokens:Z,availableForInput:Q,handoffThreshold:V,compactionThreshold:C};let Y={contextTokens:q,...J?{tokenSource:J}:{},...c(L)?{estimatedPendingTokens:L}:{},maxContextTokens:G,maxOutputTokens:Z,availableForInput:Q,handoffThreshold:V,compactionThreshold:C};if(q<V)return{phase:"below_handoff",...Y};if(q<C)return{phase:"handoff_band",...Y};return{phase:"compaction_due",...Y}}function R1($){if($.type!=="token_budget_handoff_recorded"||!Y$($.data))return;let q=$.data;if(!W$(q,lq)||q.version!==H$||!N1(q.messageId)||!c(q.observedPromptTokens)||!B$(q.availableForInput)||!c(q.handoffThreshold)||!c(q.compactionThreshold)||!dq(q.createdAt))return;let J=j0(q.availableForInput,7),L=j0(q.availableForInput,8);if(q.handoffThreshold!==J||q.compactionThreshold!==L||q.observedPromptTokens<q.handoffThreshold||q.observedPromptTokens>=q.compactionThreshold)return;return $}function rq($){return $.type==="token_budget_handoff_recorded"}function f1($){let q=$.findLastIndex((Z)=>{if(Z.type!=="part_created"||Z.data.partType!=="summary")return!1;let Q=Z.data.payload;return Q!==null&&typeof Q==="object"&&!Array.isArray(Q)&&S0(Q.replacementMessages)!==void 0}),J=$.slice(q+1).filter(rq);if(J.length===0)return{kind:"none"};let L=J.at(-1);if(!L)return{kind:"none"};if(J.length!==1)return{kind:"suppressed",recordId:L.id};let G=R1(L);return G?{kind:"valid",event:G}:{kind:"suppressed",recordId:L.id}}function T1($){let q=R1($);if(!q)return;let J={clientVisible:!1,tokenBudgetHandoff:{version:H$,messageId:q.data.messageId}};return{id:q.data.messageId,role:"user",content:oq(Math.max(0,q.data.compactionThreshold-q.data.observedPromptTokens)),metadata:J}}function tq($){if(typeof $.id!=="string"||$.role!=="user"||typeof $.content!=="string"||!Y$($.metadata)||$.metadata.clientVisible!==!1)return!1;let q=$.metadata;if(!W$(q,["clientVisible","tokenBudgetHandoff"]))return!1;let J=q.tokenBudgetHandoff;if(!Y$(J))return!1;if(!W$(J,["messageId","version"]))return!1;if(J.version!==H$||!N1(J.messageId)||J.messageId!==$.id)return!1;if(new TextEncoder().encode($.content).length>C$)return!1;let G=pq.exec($.content);if(!G)return!1;let Z=Number(G[1]);return c(Z)&&$.content===U1(Z)}function m4($){return $.filter((q)=>!tq(q))}var K$={authentication:{message:"Provider authentication failed. Check model credentials.",retryable:!1},permission:{message:"Provider rejected this request. Check account and model permissions.",retryable:!1},rate_limit:{message:"Provider rate limit or quota exceeded.",retryable:!0},timeout:{message:"Provider request timed out.",retryable:!0},network:{message:"Provider connection failed.",retryable:!0},model_unavailable:{message:"The selected model is unavailable.",retryable:!0},context_limit:{message:"The request exceeded the model context limit.",retryable:!1},unsupported_input:{message:"The selected model does not support this input.",retryable:!1},capacity:{message:"Task admission capacity is full. Retry after running tasks complete.",retryable:!0},runtime:{message:"Agent execution failed.",retryable:!0}};function aq($){try{if($ instanceof Error)return $.message;if($!==null&&typeof $==="object"&&"message"in $&&typeof $.message==="string")return $.message;return String($)}catch{return"Unknown error"}}function sq($){let q=$.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test(q))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test(q))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test(q))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test(q))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test(q))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test(q))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test(q))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test(q))return"unsupported_input";if(/\btask admission\b.*\b(capacity|queue)\b/.test(q))return"capacity";return"runtime"}function eq($){try{if(!$||typeof $!=="object"||!("name"in $)||$.name!=="TaskAdmissionQueueFullError"&&$.name!=="SessionRuntimeCapacityError"||!("resource"in $))return;return $.resource==="pending_count"||$.resource==="pending_bytes"||$.resource==="resident_runtimes"?$.resource:void 0}catch{return}}function D1($){return{code:$,...K$[$]}}function _$($){let q=eq($);if(q)return{...D1("capacity"),resource:q};return D1(sq(aq($)))}function O$($){if(!$||typeof $!=="object")return!1;let q=$;if(typeof q.code!=="string"||!(q.code in K$))return!1;let J=K$[q.code],L=q.resource===void 0||q.resource==="pending_count"||q.resource==="pending_bytes"||q.resource==="resident_runtimes";return q.message===J.message&&q.retryable===J.retryable&&L&&(q.code==="capacity"||q.resource===void 0)}import{promises as _0,realpathSync as q2}from"node:fs";import m0 from"node:path";import*as $0 from"fs/promises";import*as D from"path";var z1=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class e extends Error{code;constructor($,q){super($);this.code=q;this.name="PathSecurityError"}}class F${static normalize($,q){let J=D.isAbsolute($)?$:D.resolve(q,$),L=D.normalize(J),G=D.normalize(q);if(!this.isWithinWorkspace(L,G))throw new e(`Path outside workspace: ${$} (resolved to ${L}, workspace: ${G})`,"PATH_OUTSIDE_WORKSPACE");return L}static checkRestricted($){let q=$.split(D.sep);for(let J of z1)if(q.includes(J))throw new e(`Access denied: "${J}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal($){if($.includes(".."))throw new e(`Path traversal not allowed: ${$}`,"PATH_TRAVERSAL")}static async validatePath($,q){this.checkTraversal($);let J=this.normalize($,q);this.checkRestricted(J);try{await $0.access(J)}catch(L){throw new e(`Path not found: ${$}`,"PATH_NOT_FOUND")}return J}static async resolveSymlink($,q){try{let J=await $0.realpath($),L=await $0.realpath(q);if(!this.isWithinWorkspace(J,L))throw new e(`Symlink points outside workspace: ${$} -> ${J}`,"SYMLINK_OUTSIDE_WORKSPACE");return J}catch(J){if(J instanceof e)throw J;return $}}static getRelativePath($,q){return D.relative(q,$)}static isWithinWorkspace($,q){let J=D.resolve($),L=D.resolve(q),G=D.relative(L,J);return G===""||G!==".."&&!G.startsWith(`..${D.sep}`)&&!D.isAbsolute(G)}static async isWithinWorkspaceResolved($,q){let J=D.resolve(q),L=D.isAbsolute($)?D.resolve($):D.resolve(J,$);if(!this.isWithinWorkspace(L,J))return!1;let G;try{G=await $0.realpath(J)}catch{return!1}let Z=L;while(!0){try{let V=await $0.realpath(Z);return this.isWithinWorkspace(V,G)}catch(V){let C=V.code;if(C!=="ENOENT"&&C!=="ENOTDIR")return!1}let Q=D.dirname(Z);if(Q===Z)return!1;Z=Q}}static isRestricted($){let q=$.split(D.sep);return z1.some((J)=>q.includes(J))}}var O0=I0("Tool");class o{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!o.instance)o.instance=new o;return o.instance}async recordFileRead($,q){try{let J=await _0.stat($),L={filePath:m0.resolve($),accessTime:Date.now(),mtime:J.mtimeMs,sessionId:q,lastOperation:"read"};this.setRecord(L),await this.recordAliases($,L.filePath),O0.debug(`记录文件读取: ${$}`)}catch(J){O0.warn(`记录文件读取失败: ${$}`,J)}}async recordFileEdit($,q,J="edit"){try{let L=await _0.stat($),G={filePath:m0.resolve($),accessTime:Date.now(),mtime:L.mtimeMs,sessionId:q,lastOperation:J};this.setRecord(G),await this.recordAliases($,G.filePath),O0.debug(`记录文件${J==="edit"?"编辑":"写入"}: ${$}`)}catch(L){O0.warn(`记录文件${J==="edit"?"编辑":"写入"}失败: ${$}`,L)}}hasFileBeenRead($,q){let J=this.accessedFiles.get(this.resolveTrackedPath($));if(!J)return!1;return q?J.has(q):J.size>0}async checkFileModification($,q){let J=this.getFileRecord($,q);if(!J)return{modified:!1,message:"文件未被跟踪"};try{let L=await _0.stat($);if(Math.abs(L.mtimeMs-J.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(J.accessTime).toISOString()}, 当前修改时间: ${L.mtime.toISOString()})`};return{modified:!1}}catch(L){let G=L;if(G.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${G.message}`}}}async checkExternalModification($,q){let J=this.getFileRecord($,q);if(!J)return{isExternal:!1,message:"文件未被跟踪"};try{let L=await _0.stat($);if(L.mtimeMs-J.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(J.accessTime).toISOString()} (${J.lastOperation}) 之后被外部程序修改(当前修改时间: ${L.mtime.toISOString()})`};return{isExternal:!1}}catch(L){let G=L;if(G.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return O0.warn(`检查文件外部修改失败: ${$}`,L),{isExternal:!1,message:`无法检查文件状态: ${G.message}`}}}getFileRecord($,q){let J=this.accessedFiles.get(this.resolveTrackedPath($));if(!J)return;if(q)return J.get(q);return[...J.values()].sort((L,G)=>G.accessTime-L.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap(($)=>[...$.values()])}clearFileRecord($,q){let J=this.resolveTrackedPath($);if(!q){this.accessedFiles.delete(J),this.removeAliases(J);return}let L=this.accessedFiles.get(J);if(L?.delete(q),L?.size===0)this.accessedFiles.delete(J),this.removeAliases(J)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession($,q){for(let[J,L]of this.accessedFiles.entries()){if(q&&!F$.isWithinWorkspace(J,q))continue;if(L.delete($),L.size===0)this.accessedFiles.delete(J),this.removeAliases(J)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){o.instance=null}setRecord($){let q=this.accessedFiles.get($.filePath);if(!q)q=new Map,this.accessedFiles.set($.filePath,q);q.set($.sessionId,$)}async recordAliases($,q){this.pathAliases.set(m0.resolve($),q);let J=await _0.realpath($).catch(()=>{return});if(J)this.pathAliases.set(J,q)}resolveTrackedPath($){let q=m0.resolve($);if(this.accessedFiles.has(q))return q;let J=this.pathAliases.get(q);if(J)return J;try{let L=q2.native(q);return this.pathAliases.get(L)??L}catch{return q}}removeAliases($){for(let[q,J]of this.pathAliases)if(J===$)this.pathAliases.delete(q)}}import*as F0 from"node:crypto";import{promises as O}from"node:fs";import*as N from"node:path";import N$ from"write-file-atomic";var M1="missing";class v0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor($){if(x($.sessionId),this.sessionId=$.sessionId,$.workspaceRoot&&!N.isAbsolute($.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=$.workspaceRoot?N.resolve($.workspaceRoot):void 0,this.enableCheckpoints=$.enableCheckpoints??!0,this.maxSnapshots=$.maxSnapshots??10;let q=l();this.snapshotDir=N.join(q,"file-history",this.sessionId),this.manifestPath=N.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await O.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let $=l(),q=await O.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),J=F0.createHash("sha256").update(q).digest("hex").slice(0,24),L=N.join($,"file-history",this.sessionId),G=N.join($,"file-history","workspaces",J,this.sessionId),Z=N.join(G,"manifest.json");try{await O.access(Z)}catch{await this.migrateLegacySnapshotDir(L,G,q)}this.snapshotDir=G,this.manifestPath=Z}async migrateLegacySnapshotDir($,q,J){let L;try{L=JSON.parse(await O.readFile(N.join($,"manifest.json"),"utf8"))}catch{return}if(L.schemaVersion!==1||!Array.isArray(L.snapshots)||!L.snapshots.every((G)=>this.isWithinWorkspace(G.filePath,J)))return;await O.mkdir(N.dirname(q),{recursive:!0,mode:493});try{await O.rename($,q)}catch(G){let Z=G.code;if(Z!=="ENOENT"&&Z!=="EEXIST"&&Z!=="ENOTEMPTY")throw G}}isWithinWorkspace($,q){if(!N.isAbsolute($))return!1;let J=N.relative(q,N.resolve($));return J===""||J!==".."&&!J.startsWith(`..${N.sep}`)&&!N.isAbsolute(J)}async createSnapshot($,q){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let J=await this.resolveFileIdentity($),L=!0;try{await O.access(J)}catch{L=!1}let G=this.trackedFileBackups.get(J),Z=G?G.version+1:1,Q=this.generateFileHash(J,Z),V=this.getSnapshotPath(Q,Z),C=new Date;if(L){let H=await O.readFile(J);await O.writeFile(V,H)}let Y={backupFileName:Q,version:Z,backupTime:C};return this.trackedFileBackups.set(J,Y),this.snapshots.push({messageId:q,backupFileName:Q,timestamp:C,filePath:J,version:Z,existedBefore:L}),await this.cleanupOldSnapshots(J),await this.persistManifest(),Y}async recordPostEditState($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let J=await this.resolveFileIdentity($),L=this.snapshots.find((G)=>G.filePath===J&&G.backupFileName===q.backupFileName&&G.version===q.version);if(!L)throw Error(`未找到待完成的快照: ${J}`);L.postEditHash=await this.hashFile(J),await this.persistManifest()}async discardSnapshot($,q){if(!this.enableCheckpoints||!q.backupFileName)return;let J=await this.resolveFileIdentity($),L=this.snapshots.find((G)=>G.filePath===J&&G.backupFileName===q.backupFileName&&G.version===q.version);if(!L)return;this.removeSnapshot(L),await O.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),await this.persistManifest()}async rewindLatest($){let q=await this.resolveFileIdentity($),J=this.snapshots.slice().reverse().find((Z)=>Z.filePath===q&&Z.postEditHash!==void 0);if(!J?.postEditHash)throw Error(`未找到可回退快照: ${q}`);if(await this.hashFile(q)!==J.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${q}`);let G=this.getSnapshotPath(J.backupFileName,J.version);if(J.existedBefore){let Z=await O.readFile(G);await O.mkdir(N.dirname(q),{recursive:!0}),await O.writeFile(q,Z)}else await O.rm(q,{force:!0});return this.removeSnapshot(J),await O.rm(G,{force:!0}),await this.persistManifest(),J}async restoreSnapshot($,q){let J=await this.resolveFileIdentity($),L=this.snapshots.slice().reverse().find((Z)=>Z.messageId===q&&Z.filePath===J);if(!L)throw Error(`未找到快照: messageId=${q}, filePath=${J}`);let G=this.getSnapshotPath(L.backupFileName,L.version);if(L.existedBefore){let Z=await O.readFile(G);await O.mkdir(N.dirname(J),{recursive:!0}),await O.writeFile(J,Z)}else await O.rm(J,{force:!0})}async listSnapshots($){let q=await this.resolveFileIdentity($);return this.snapshots.filter((J)=>J.filePath===q)}async listAllSnapshots(){return this.snapshots.filter(($)=>$.postEditHash!==void 0)}async previewRewind($){let q=this.buildRewindPlan($);return{files:q.map((J)=>J.filePath),snapshotCount:q.reduce((J,L)=>J+L.selected.length,0)}}async rewindSnapshots($){let q=this.buildRewindPlan($);if(q.length===0)return{files:[],snapshotCount:0};let J=new Map;for(let G of q){let Z,Q=!0;try{Z=await O.readFile(G.filePath)}catch(C){if(C.code!=="ENOENT")throw C;Q=!1}if((Z?F0.createHash("sha256").update(Z).digest("hex"):M1)!==G.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${G.filePath}`);if(J.set(G.filePath,{existed:Q,content:Z}),G.target.existedBefore)await O.access(this.getSnapshotPath(G.target.backupFileName,G.target.version))}let L=[...this.snapshots];try{for(let Z of q)if(Z.target.existedBefore){let Q=await O.readFile(this.getSnapshotPath(Z.target.backupFileName,Z.target.version));await O.mkdir(N.dirname(Z.filePath),{recursive:!0}),await N$(Z.filePath,Q)}else await O.rm(Z.filePath,{force:!0});let G=new Set(q.flatMap((Z)=>Z.selected));this.snapshots=this.snapshots.filter((Z)=>!G.has(Z)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...G].map((Z)=>O.rm(this.getSnapshotPath(Z.backupFileName,Z.version),{force:!0}).catch(()=>{return})))}catch(G){this.snapshots=L,this.rebuildTrackedFileBackups();let Z=[];for(let[Q,V]of J)try{if(V.existed&&V.content)await N$(Q,V.content);else await O.rm(Q,{force:!0})}catch(C){Z.push(C)}if(Z.length>0)throw AggregateError([G,...Z],"快照回退失败且无法完整恢复回退前状态");throw G}return{files:q.map((G)=>G.filePath),snapshotCount:q.reduce((G,Z)=>G+Z.selected.length,0)}}async commitSnapshots($){let q=this.buildRewindPlan($),J=new Set(q.flatMap((G)=>G.selected));if(J.size===0)return{files:[],snapshotCount:0};let L=[...this.snapshots];this.snapshots=this.snapshots.filter((G)=>!J.has(G)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(G){throw this.snapshots=L,this.rebuildTrackedFileBackups(),G}return await Promise.all([...J].map((G)=>O.rm(this.getSnapshotPath(G.backupFileName,G.version),{force:!0}).catch(()=>{return}))),{files:q.map((G)=>G.filePath),snapshotCount:J.size}}buildRewindPlan($){let q=new Set($),J=this.snapshots.filter((Z)=>Z.postEditHash!==void 0),L=J.filter((Z)=>q.has(Z.messageId));return[...new Set(L.map((Z)=>Z.filePath))].sort().map((Z)=>{let Q=J.filter((H)=>H.filePath===Z),V=Q.filter((H)=>q.has(H.messageId)),C=Q.indexOf(V[0]),Y=Q.slice(C);if(Y.length!==V.length||Y.some((H)=>!q.has(H.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${Z}`);return{filePath:Z,selected:V,target:V[0],latest:V.at(-1)}})}async loadManifest(){try{let $=await O.readFile(this.manifestPath,"utf-8"),q=JSON.parse($);if(q.schemaVersion!==1||!Array.isArray(q.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all(q.snapshots.map(async(J)=>({...J,filePath:await this.resolveFileIdentity(J.filePath),timestamp:new Date(J.timestamp)}))),this.rebuildTrackedFileBackups()}catch($){if($.code!=="ENOENT")throw $;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await O.rm(this.manifestPath,{force:!0});return}let $={schemaVersion:1,snapshots:this.snapshots.map((q)=>({...q,timestamp:q.timestamp.toISOString()}))};await N$(this.manifestPath,JSON.stringify($,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots($){let J=this.snapshots.filter((L)=>L.filePath===$).slice(0,-this.maxSnapshots);for(let L of J)await O.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}),this.removeSnapshot(L)}async cleanup($=0){let q=this.snapshots.slice().sort((L,G)=>G.timestamp.getTime()-L.timestamp.getTime()),J=new Set(q.slice(0,$));for(let L of this.snapshots)if(!J.has(L))await O.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0});this.snapshots=q.slice(0,$).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath($,q){return N.join(this.snapshotDir,`${$}@v${q}`)}async resolveFileIdentity($){let q=N.resolve($),J=[],L=q;while(!0){try{let Z=await O.realpath(L);return N.join(Z,...J.reverse())}catch(Z){let Q=Z.code;if(Q!=="ENOENT"&&Q!=="ENOTDIR")throw Z}let G=N.dirname(L);if(G===L)return q;J.push(N.basename(L)),L=G}}async hashFile($){try{let q=await O.readFile($);return F0.createHash("sha256").update(q).digest("hex")}catch(q){if(q.code==="ENOENT")return M1;throw q}}removeSnapshot($){let q=this.snapshots.indexOf($);if(q>=0)this.snapshots.splice(q,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let $ of this.snapshots){let q=this.trackedFileBackups.get($.filePath);if(!q||q.version<$.version)this.trackedFileBackups.set($.filePath,{backupFileName:$.backupFileName,version:$.version,backupTime:$.timestamp})}}generateFileHash($,q){let J=F0.createHash("md5");return J.update(`${$}:${q}`),J.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var a4=1200,s4=2000,e4=2000,$8=2000;function w1($){return typeof $==="object"&&$!==null&&!Array.isArray($)}function J2($){if(typeof $==="string"&&$.length>0)return $;if(w1($)&&typeof $.message==="string")return $.message;return}function L2($,q){if($===null||$===void 0)return q??"";if(typeof $==="string")return $;if(typeof $==="object")return $;return String($)}function x1($){let q=$.error!==null&&$.error!==void 0,J=q?J2($.error)??"Tool execution failed":void 0,L=w1($.metadata)?$.metadata:void 0;return{success:!q,llmContent:L2($.output,J),...J?{error:{type:"execution_error",message:J}}:{},...L?{metadata:L}:{}}}function R$($,q){if($.length<=q)return $;let J=Math.max(0,q);if(J>0&&J<$.length&&/[\uD800-\uDBFF]/.test($.charAt(J-1)))J-=1;return $.slice(0,J)}function A1($,q){if($.length<=q)return $;let J=Math.max(0,$.length-q);if(J<$.length&&/[\uDC00-\uDFFF]/.test($.charAt(J)))J+=1;return $.slice(J)}function U$($,q){if($.length<=q)return $;if(q<=0)return"";let J=`
11
+ ... (display clipped) ...
12
+ `,L=$.indexOf(`
13
+ `),G=L>=0&&/^(?:stdout|stderr):$/.test($.slice(0,L))?`${$.slice(0,L)}
14
+ `:"",Z=G?$.slice(G.length):$,Q=q-G.length-J.length;if(Q<=0)return A1($,q);let V=Math.min(Math.floor(Q/3),Z.length),C=Math.max(0,Q-V);return G+R$(Z,V)+J+A1(Z,C)}function Z2($){let q=$.split(`
15
+ `),J=q.at(-1);if(!J?.startsWith("Output truncated"))return{body:$};return{body:q.slice(0,-1).join(`
16
+ `),suffix:J}}function G2($){let J=$.indexOf(`
17
+ stderr:
18
+ `);if(!$.startsWith(`stdout:
19
+ `)||J<0)return[$];return[$.slice(0,J),$.slice(J+1)]}function q8($,q){if(!Number.isSafeInteger(q)||q<=0)throw Error("maxChars must be a positive safe integer");if(!$.detail||$.detail.length<=q)return $;let{body:J,suffix:L}=Z2($.detail),G=L?`
20
+ ${R$(L,q)}`:"",Z=Math.max(0,q-G.length),Q=G2(J),V;if(Q.length===2){let H=Math.max(0,Z-1),X=Math.floor(H/2),W=H-X;V=`${U$(Q[0],X)}
21
+ ${U$(Q[1],W)}`}else V=U$(J,Z);let C=R$(`${V}${G}`,q);return{...$,detail:C}}var L8={clientVisible:!1};function E1($){if($.metadata&&typeof $.metadata==="object"&&!Array.isArray($.metadata)&&$.metadata.clientVisible===!1)return!1;return!($.role==="user"&&typeof $.content==="string"&&$.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&$.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{createHash as F2}from"node:crypto";import P1 from"node:path";import{StringDecoder as X2}from"node:string_decoder";var G8=1048576;function f$($,q){let J=q;while(J<$.length&&($[J]&192)===128)J+=1;return J}class T${maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor($=1048576){this.maxBytes=$;if(!Number.isSafeInteger($)||$<=0)throw Error("maxBytes must be a positive safe integer")}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,q.length>this.maxBytes){this.retainOversizedChunkTail(q);return}this.chunks.push(q),this.retainedBytes+=q.length,this.trimToLimit(),this.compactChunks()}peek(){return{content:Buffer.concat(this.chunks,this.retainedBytes).toString("utf8"),retainedBytes:this.retainedBytes,omittedBytes:this.omittedBytes,totalBytes:this.totalBytes}}consume(){let $=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,$}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail($){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let q=f$($,$.length-this.maxBytes);if(this.omittedBytes+=q,q===$.length)return;let J=Buffer.from($.subarray(q));this.chunks.push(J),this.retainedBytes=J.length}trimToLimit(){let $=!1;while(this.retainedBytes>this.maxBytes){let q=this.chunks[0];if(!q)return;let J=this.retainedBytes-this.maxBytes;if(q.length<=J){this.chunks.shift(),this.retainedBytes-=q.length,this.omittedBytes+=q.length,$=!0;continue}let L=f$(q,J);this.chunks[0]=q.subarray(L),this.retainedBytes-=L,this.omittedBytes+=L,$=!0}if($)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let $=this.chunks[0];if($.length===0){this.chunks.shift();continue}let q=f$($,0);if(q===0)return;if(this.retainedBytes-=q,this.omittedBytes+=q,q===$.length)this.chunks.shift();else{this.chunks[0]=$.subarray(q);return}}}compactChunks(){if(this.chunks.length<=32)return;let $=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,$.length>0)this.chunks.push($)}}var P0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},q0={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},b1={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},Q2={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},V2=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:P0,summaryTemplate:($)=>`Successfully processed ${$} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:P0,summaryTemplate:($)=>`Package operation completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:q0,summaryTemplate:($)=>`Build completed (${$} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:b1},{pattern:/^git\s+(status|branch|remote)/i,config:q0},{pattern:/^git\s+(log|diff|show)/i,config:b1},{pattern:/^(ls|dir|tree)\s+/i,config:q0,summaryTemplate:($)=>`Listed ${$} items`},{pattern:/^find\s+/i,config:q0,summaryTemplate:($)=>`Found ${$} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:q0,summaryTemplate:($)=>`Found ${$} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:P0,summaryTemplate:($)=>`Docker operation completed (${$} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:P0,summaryTemplate:($)=>`Python package operation completed (${$} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:q0,summaryTemplate:($)=>`Rust operation completed (${$} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:q0,summaryTemplate:($)=>`Go operation completed (${$} lines)`}];function k1($,q,J){let L=q,G=J??$.length;if(L>0){let Z=$.charCodeAt(L);if(Z>=56320&&Z<=57343)L+=1}if(G<$.length){let Z=$.charCodeAt(G-1);if(Z>=55296&&Z<=56319)G-=1}return $.slice(L,G)}class D${static getConfigForCommand($){for(let{pattern:q,config:J,summaryTemplate:L}of V2)if(q.test($))return{config:J,summaryTemplate:L};return{config:Q2}}static truncate($,q){let{config:J,summaryTemplate:L}=this.getConfigForCommand(q);return this.truncateWithConfig($,J,L)}static truncateWithConfig($,q,J){let L=$.length,G=$.split(`
22
+ `),Z=G.length;if(Z<=q.maxLines&&L<=q.maxChars)return{content:$,truncated:!1,originalLines:Z,originalChars:L};let Q=G.slice(0,q.keepHead),V=G.slice(-q.keepTail),C=Z-q.keepHead-q.keepTail,Y=Q.join(`
23
+ `);if(Y+=`
24
+
25
+ ... (${C} lines truncated, showing first ${q.keepHead} and last ${q.keepTail} of ${Z} total) ...
26
+
27
+ `,Y+=V.join(`
28
+ `),Y.length>q.maxChars){let X=Math.floor(q.maxChars/2)-50,W=k1(Y,0,X),B=k1(Y,Y.length-X);Y=`${W}
29
+
30
+ ... (content truncated to ${q.maxChars} chars) ...
31
+
32
+ ${B}`}let H=q.summarize&&J?J(Z,L):void 0;if(H)Y+=`
33
+
34
+ [Summary: ${H}]`;return{content:Y,truncated:!0,originalLines:Z,originalChars:L,summary:H}}static truncateForLLM($,q,J){let L=this.truncate($,J),G=this.truncate(q,J),Z;if(L.truncated||G.truncated){let Q=[];if(L.truncated)Q.push(`stdout: ${L.originalLines} lines -> ${L.content.split(`
35
+ `).length} lines`);if(G.truncated)Q.push(`stderr: ${G.originalLines} lines -> ${G.content.split(`
36
+ `).length} lines`);Z=`Output truncated: ${Q.join(", ")}`}return{stdout:L.content,stderr:G.content,truncationInfo:Z}}static shouldTruncate($,q){let{config:J}=this.getConfigForCommand(q);return $.split(`
37
+ `).length>J.maxLines||$.length>J.maxChars}static getStats($){return{lines:$.split(`
38
+ `).length,chars:$.length,words:$.split(/\s+/).filter(Boolean).length}}}var g1=32768,C2=1048576,Y2=65536,W2=3600000,S1=4096,H2=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class z${stream;executionId;onEvent;output=new T$(C2/2);decoder=new X2("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor($,q,J){this.stream=$;this.executionId=q;this.onEvent=J}append($){let q=Buffer.isBuffer($)?$:Buffer.from($);if(q.length===0)return;if(this.totalBytes+=q.length,this.sniffBytes<S1){let L=q.subarray(0,Math.min(q.length,S1-this.sniffBytes));this.sniffChunks.push(L),this.sniffBytes+=L.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let J=y1(this.decoder.write(q));this.output.append(J),this.emit(J)}finish(){if(this.binary)return;let $=y1(this.decoder.end());this.output.append($),this.emit($)}snapshot(){let $=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:$.content,omittedBytes:$.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit($){if(!$||!this.onEvent||this.streamTruncated)return;let q=Y2-this.streamedBytes;if(q<=0){this.streamTruncated=!0;return}let J=B2($,q);if(this.streamedBytes+=Buffer.byteLength(J),J.length<$.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:J,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function y1($){return $.replace(H2,"")}function B2($,q){let J=Buffer.from($);if(J.length<=q)return $;let L=q;while(L>0&&(J[L]&192)===128)L-=1;return J.subarray(0,L).toString("utf8")}function j1($){return $.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function K2($){let q=$.trim();if(!q)throw Error("User shell command cannot be empty");if(q.length>g1)throw Error(`User shell command exceeds ${g1} characters`);if(q.includes("\x00"))throw Error("User shell command contains a null byte");return q}function _2(){return{execute($,q){return new Promise((J)=>{let L=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",G=process.platform==="win32"?["/d","/s","/c",$]:["-l","-c",$],{child:Z,processTree:Q}=m1(L,G,{cwd:q.cwd,env:q.env,stdio:["ignore","pipe","pipe"]}),V="",C="",Y=!1,H=!1,X=!1,W,B=()=>{return W??=Q.terminate(),W},_=setTimeout(()=>{Y=!0,B()},q.timeoutMs),f=()=>{H=!0,B()};if(q.signal.addEventListener("abort",f,{once:!0}),q.signal.aborted)f();Z.stdout?.on("data",(T)=>{q.onOutput?.("stdout",T)}),Z.stderr?.on("data",(T)=>{q.onOutput?.("stderr",T)});let b=async(T)=>{if(X)return;if(X=!0,clearTimeout(_),q.signal.removeEventListener("abort",f),Y||H)await B();J({...T,stdout:"",stderr:"",timedOut:Y,aborted:H})};Z.once("error",(T)=>{b({exitCode:null,error:T.message})}),Z.once("close",(T)=>{b({exitCode:T})})})}}}async function H8($,q){let J=K2($),L=q.timeoutMs??W2,G=new z$("stdout",q.executionId,q.onEvent),Z=new z$("stderr",q.executionId,q.onEvent),Q=Date.now();await q.onEvent?.({type:"started",executionId:q.executionId,command:J});let V,C=!1,Y=!1;try{V=await(q.executor??_2()).execute(J,{cwd:q.cwd,env:q.env,timeoutMs:L,signal:q.signal,onOutput:(f,b)=>{if(f==="stdout")C=!0;else Y=!0;(f==="stdout"?G:Z).append(b)}})}catch(f){V={exitCode:null,stdout:"",stderr:"",error:f instanceof Error?f.message:String(f)}}if(!C)G.append(V.stdout);if(!Y)Z.append(V.stderr);G.finish(),Z.finish(),await Promise.all([G.flushEvents(),Z.flushEvents()]);let H=G.snapshot(),X=Z.snapshot(),W=D$.truncateForLLM(H.content.trim(),X.content.trim(),J),B=V.aborted||q.signal.aborted?"aborted":V.timedOut?"timed_out":V.error?"spawn_error":V.exitCode===0?"completed":"failed",_={version:1,command:J,status:B,exitCode:V.exitCode,durationMs:Math.max(0,Date.now()-Q),stdout:W.stdout,stderr:V.error?[W.stderr,V.error].filter(Boolean).join(`
39
+ `):W.stderr,stdoutOmittedBytes:H.omittedBytes,stderrOmittedBytes:X.omittedBytes,binaryOutput:H.binary||X.binary,truncated:Boolean(W.truncationInfo)||H.omittedBytes>0||X.omittedBytes>0};return await q.onEvent?.({type:"completed",executionId:q.executionId,record:_}),_}function B8($){let q=[$.stdout?`stdout:
40
+ ${$.stdout}`:"",$.stderr?`stderr:
41
+ ${$.stderr}`:""].filter(Boolean).join(`
42
+ `);return["<user_shell_command>",`<command>${j1($.command)}</command>`,"<result>",`Status: ${$.status}`,`Exit code: ${$.exitCode??"null"}`,`Duration: ${($.durationMs/1000).toFixed(3)} seconds`,`Output:
43
+ ${j1(q||"(no output)")}`,"</result>","</user_shell_command>"].join(`
44
+ `)}function I1($){let q=[$.stdout,$.stderr?`stderr:
45
+ ${$.stderr}`:""].filter(Boolean).join(`
46
+ `);return[`! ${$.command}`,q||"(no output)"].join(`
47
+ `)}function O2($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(q.version!==1||typeof q.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String(q.status))||q.exitCode!==null&&typeof q.exitCode!=="number"||typeof q.durationMs!=="number"||typeof q.stdout!=="string"||typeof q.stderr!=="string"||typeof q.stdoutOmittedBytes!=="number"||typeof q.stderrOmittedBytes!=="number"||typeof q.binaryOutput!=="boolean"||typeof q.truncated!=="boolean")return;return q}function u0($){if(!$||typeof $!=="object"||Array.isArray($))return;return O2($.userShellCommand)}var h0=16777216,v1=65536,U8=1048576,N2=8,c0=200,U2=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,R2=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,f2=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,T2=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),D2=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function g($,q){return $.count+=1,q}function z2($){return U2.test($.replace(/[A-Z]/g,(q)=>`_${q.toLowerCase()}`))}function M2($){return[...$].filter((q)=>{if(q===`
48
+ `||q==="\r"||q==="\t")return!0;let J=q.codePointAt(0)??0;if(J<32||J===127)return!1;if(J>=57344&&J<=63743)return!1;if(J>=983040&&J<=1048573)return!1;if(J>=1048576&&J<=1114109)return!1;if(J>=917504&&J<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test(q)}).join("")}function k($,q){let J=$.normalize("NFKC"),L=J.replace(T2,"");if(L!==J)q.count+=1;J=L,J=J.replace(D2,()=>g(q,"[redacted-private-key]")),J=J.replace(/\bBearer\s+[^\s"'`]+/gi,()=>g(q,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>g(q,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>g(q,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(Z,Q,V)=>`${Q}${V}${g(q,"[redacted]")}`);let G=M2(J);if(G!==J)q.count+=1;return G.replace(/\r\n?/g,`
49
+ `)}function u1($,q,J){if(/^data:[^;,]+;base64,/i.test($))return g(J,"[binary omitted]");let L=k($,J),G=P1.resolve(q);for(let Z of[G,G.startsWith("/private/")?G.slice(8):`/private${G}`])L=L.replaceAll(Z,".");return L=L.replace(R2,(Z)=>Z.startsWith("./")?Z:g(J,"[host-path]")),L=L.replace(f2,()=>g(J,"[host-path]")),L=L.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(Z)=>{try{let Q=new URL(Z);if(Q.username||Q.password||Q.search||Q.hash)J.count+=1;return Q.username="",Q.password="",Q.search="",Q.hash="",Q.toString()}catch{return g(J,"[redacted-url]")}}),L}function w$($,q,J,L=0,G){if(G&&z2(G))return g(J,"[redacted]");if(L>=N2)return g(J,"[depth limit]");if(typeof $==="string")return u1($,q,J);if($===null||typeof $==="boolean"||typeof $==="number"&&Number.isFinite($))return $;if(Array.isArray($)){let Z=$.slice(0,c0).map((Q)=>w$(Q,q,J,L+1));if($.length>Z.length)Z.push(g(J,`[${$.length-Z.length} items omitted]`));return Z}if($&&typeof $==="object"){let Z={},Q=Object.entries($);for(let[V,C]of Q.slice(0,c0))Z[k(V,J)]=w$(C,q,J,L+1,V);if(Q.length>c0)Z["[entries omitted]"]=Q.length-c0;return Z}return String($)}function A2($,q){let J=Buffer.from($,"utf8");if(J.length<=q)return $;let L=J.subarray(0,q).toString("utf8");while(Buffer.byteLength(L,"utf8")>q)L=L.slice(0,-1);return L}function w2($,q,J){let L=JSON.stringify(w$($,q,J),null,2);if(Buffer.byteLength(L,"utf8")<=v1)return L;J.count+=1;let G=`
50
+ ... [activity truncated]`;return A2(L,v1-Buffer.byteLength(G))+G}function x$($,q=""){let J=Math.max(2,...[...$.matchAll(/`+/g)].map((G)=>G[0].length)),L="`".repeat(J+1);return`${L}${q}
51
+ ${$}
52
+ ${L}`}function M$($){return $.replace(/\s+/g," ").trim()}function x2($){let q=new Map,J=new Map,L=new Map,G=0;for(let Z of h($)){if(Z.type==="message_created"){let H=J.get(Z.data.messageId);if(H)H.role=Z.data.role,H.metadata=Z.data.metadata,q.set(Z.data.messageId,H),J.delete(Z.data.messageId);else if(!q.has(Z.data.messageId))q.set(Z.data.messageId,{order:G++,role:Z.data.role,parts:[],metadata:Z.data.metadata});continue}if(Z.type!=="part_created"&&Z.type!=="part_updated")continue;let Q=q.get(Z.data.messageId)??J.get(Z.data.messageId);if(!Q)Q={order:G++,role:"activity",parts:[]},J.set(Z.data.messageId,Q);let V=`${Z.data.messageId}\x00${Z.data.partType}\x00${Z.data.partId}`,C=L.get(V);if(C){C.event=Z;continue}let Y={order:G++,event:Z};L.set(V,Y),Q.parts.push(Y)}return[...q.values(),...J.values()].sort((Z,Q)=>Z.order-Q.order)}function A$($,q,J,L){return`## Activity: ${$}
53
+
54
+ ${x$(w2(q,J.projectPath,L),"json")}`}function h1($,q,J={}){let L={count:0},G=J.includeReasoning===!0,Z=[],Q=0,V=0,C=0;for(let b of x2($)){let T=u0(b.metadata);if(T){let A=k(T.command,L),M=k([T.stdout,T.stderr?`stderr:
55
+ ${T.stderr}`:""].filter(Boolean).join(`
56
+ `)||"(no output)",L);Z.push(`## User shell command
57
+
58
+ ${x$(`$ ${A}
59
+ ${M}`,"console")}`),Q+=1;continue}let Z0=[],G0=[],y=[],j=Number.POSITIVE_INFINITY;for(let A of b.parts.sort((M,E)=>M.order-E.order)){let{partType:M,payload:E}=A.event.data;if(M==="text"){let F=E.text;if(typeof F==="string"&&F.trim())Z0.push(k(F,L)),j=Math.min(j,A.order)}else if(M==="image"){let F=E.mimeType;G0.push(typeof F==="string"?`[Image: ${k(F,L)}]`:"[Image]"),j=Math.min(j,A.order)}else if(M==="reasoning"&&G){let F=E.text;if(typeof F==="string"&&F.trim())y.push({order:A.order,markdown:`## Reasoning
60
+
61
+ ${k(F,L).trim()}`}),C+=1}else if(M==="tool_call"){let F=E,w=typeof F.toolName==="string"?k(F.toolName,L):"unknown";y.push({order:A.order,markdown:A$(`${w} call`,F.input??{},q,L)}),V+=1}else if(M==="tool_result"){let F=E,w=typeof F.toolName==="string"?k(F.toolName,L):"unknown";y.push({order:A.order,markdown:A$(`${w} result`,typeof F.error==="string"?{error:F.error}:{output:F.output??null},q,L)}),V+=1}else if(M==="summary"){let F=E.text;if(typeof F==="string"&&F.trim())y.push({order:A.order,markdown:`## Summary
62
+
63
+ ${k(F,L).trim()}`})}else if(M==="subtask_ref")y.push({order:A.order,markdown:A$("Subagent",E,q,L)}),V+=1;else if(M==="diff"||M==="patch"){let F=typeof E==="string"?E:JSON.stringify(E,null,2);y.push({order:A.order,markdown:`## File changes
64
+
65
+ ${x$(u1(F,q.projectPath,L),"diff")}`}),V+=1}}if((b.role==="user"||b.role==="assistant")&&(Z0.length>0||G0.length>0))y.push({order:j,markdown:`## ${b.role==="user"?"User":"Assistant"}
66
+
67
+ ${[...Z0,...G0].join(`
68
+
69
+ `).trim()}`}),Q+=1;Z.push(...y.sort((A,M)=>A.order-M.order).map((A)=>A.markdown))}if(Z.length===0)throw Error("No conversation content to export");let Y=`${Z.join(`
70
+
71
+ `)}
72
+ `,H=Buffer.byteLength(Y,"utf8");if(H>h0)throw Error(`Session export exceeds ${h0} bytes`);let X=F2("sha256").update(Y).digest("hex"),W=P1.basename(q.taskSourceProjectPath??q.projectPath),B=q.selectedModelId??q.taskModelId,f=["# Blade conversation","",`- Session: \`${q.sessionId}\``,...q.title?[`- Title: ${M$(k(q.title,L))}`]:[],`- Project: \`${M$(k(W,L))}\``,...B?[`- Model: \`${M$(k(B,L))}\``]:[],...q.permissionMode?[`- Permission mode: ${q.permissionMode}`]:[],`- Created: ${q.firstMessageTime}`,`- Updated: ${q.lastMessageTime}`,`- State: ${q.archivedAt?"archived":"active"}`,`- Reasoning: ${G?"included":"omitted"}`,...q.reasoningEffort?[`- Reasoning effort: ${q.reasoningEffort}`]:[],...q.serviceTier?[`- Service tier: ${q.serviceTier}`]:[],...q.responseVerbosity?[`- Response verbosity: ${q.responseVerbosity}`]:[],...q.communicationStyle?[`- Communication style: ${q.communicationStyle}`]:[],...q.communicationStyleDigest?[`- Communication style SHA-256: \`${q.communicationStyleDigest}\``]:[],...q.projectInstructionsDigest?[`- Project instructions SHA-256: \`${q.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${X}\``,`- Content bytes: ${H}`,`- Redactions: ${L.count}`,"","---",""].join(`
73
+ `)+`
74
+ `+Y;if(Buffer.byteLength(f,"utf8")>h0)throw Error(`Session export exceeds ${h0} bytes`);return{filename:`blade-session-${q.sessionId.slice(0,12)}.md`,markdown:f,contentSha256:X,contentBytes:H,messageCount:Q,activityCount:V,reasoningIncluded:G,reasoningCount:C,redactionCount:L.count}}import{createHash as E2}from"node:crypto";import b2 from"ajv";var r1="StructuredOutput",c1=65536,l1=131072,D8=2,n1=20,p1=1000,i1=200;function J0($){return $!==null&&typeof $==="object"&&!Array.isArray($)}function d1($,q){if(!J0($))throw Error(`${q} must be a JSON object`);let J;try{J=JSON.stringify($)}catch(G){throw Error(`${q} must be JSON-serializable`,{cause:G})}if(J===void 0)throw Error(`${q} must be JSON-serializable`);let L=JSON.parse(J);if(!J0(L))throw Error(`${q} must be a JSON object`);return L}function k2($){let q=0,J=0,L=(G,Z)=>{if(q++,q>p1)throw Error(`Output schema exceeds the ${p1} node complexity limit`);if(Z>n1)throw Error(`Output schema exceeds the ${n1} level depth limit`);if(Array.isArray(G)){for(let Q of G)L(Q,Z+1);return}if(!J0(G))return;if("$ref"in G){let Q=G.$ref;if(typeof Q!=="string"||!(Q==="#"||Q.startsWith("#/$defs/")||Q.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in G&&J0(G.properties)){if(J+=Object.keys(G.properties).length,J>i1)throw Error(`Output schema exceeds the ${i1} property limit`)}for(let Q of Object.values(G))L(Q,Z+1)};L($,0)}function g2($){if(!$||$.length===0)return"Structured output does not match the requested schema";return $.slice(0,8).map((q)=>{return`${q.instancePath||"root"}: ${q.message??q.keyword}`}).join("; ")}function S2($){let q=new b2({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return q.compile($)}catch(J){throw Error(`Invalid output schema: ${J instanceof Error?J.message:String(J)}`)}}function t1($){let q=d1($,"Output schema"),J=JSON.stringify(q);if(Buffer.byteLength(J)>c1)throw Error(`Output schema exceeds ${c1} bytes`);if(q.type!=="object")throw Error('Output schema root type must be "object"');k2(q);let G=S2(q),Z=E2("sha256").update(J).digest("hex");return{schema:q,schemaDigest:Z,declaration:{name:r1,description:"Submit the final response as an object matching the requested JSON Schema. Call this exactly once after all requested work and verification are complete.",parameters:q,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(Q){let V;try{V=d1(Q,"Structured output")}catch(Y){return{success:!1,message:Y instanceof Error?Y.message:String(Y)}}let C=JSON.stringify(V);if(Buffer.byteLength(C)>l1)return{success:!1,message:`Structured output exceeds ${l1} bytes`};if(!G(V))return{success:!1,message:g2(G.errors)};return{success:!0,output:V}}}}function o1($,q){if(!J0($))return;let J=J0($.structuredOutput)?$.structuredOutput:$;if(J.schemaDigest!==q.schemaDigest||!("output"in J))return;let L=q.validate(J.output);return L.success?L.output:void 0}function z8($,q){for(let J=$.length-1;J>=0;J--){let L=$[J];if(!L)continue;if(L.role==="user")return;if(L.role==="assistant"){let Q=o1(L.metadata,q);if(Q)return{output:Q,completed:!0};continue}if(L.role!=="tool"||L.name!==r1)continue;let G=J0(L.metadata)?L.metadata:void 0,Z=o1(G?.metadata,q);if(Z)return{output:Z,completed:!1}}return}var N0=I0("Service"),a1=new Set(["queued","running","completed","failed","cancelled","interrupted"]),v$=new Set(["local","worktree"]),i0=new Set(["high","medium","low"]),d0=new Set(["feature","bug","maintenance","research"]);function y2($,q,J,L){if($.taskStatuses){let G=$.taskStatuses.includes("interrupted")?[...new Set([...$.taskStatuses,"running"])]:$.taskStatuses;J.push(`${q}task_status IN (${G.map(()=>"?").join(", ")})`),L.push(...G)}if($.taskPriorities)J.push(`${q}task_priority IN (${$.taskPriorities.map(()=>"?").join(", ")})`),L.push(...$.taskPriorities);if($.taskDueAfter)J.push(`${q}task_due_at >= ?`),L.push($.taskDueAfter);if($.taskDueBefore)J.push(`${q}task_due_at <= ?`),L.push($.taskDueBefore)}function j2($,q){if(!Kq($,q))return!1;if(q.taskPriorities&&($.taskPriority===void 0||!q.taskPriorities.includes($.taskPriority)))return!1;if(q.taskDueAfter&&($.taskDueAt===void 0||$.taskDueAt<q.taskDueAfter))return!1;if(q.taskDueBefore&&($.taskDueAt===void 0||$.taskDueAt>q.taskDueBefore))return!1;return!0}function Kq($,q){return q.taskStatuses===void 0||q.taskStatuses.includes($.taskStatus)}var m2=new Set(["default","autoEdit","yolo","plan"]),I2=new Set(["applied","discarded","conflicted"]),v2=86400000;class P$ extends Error{}function s1($){try{return process.kill($,0),!0}catch(q){return q instanceof Error&&"code"in q&&q.code==="EPERM"}}function e1($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((L)=>typeof q[L]!=="string"||!q[L])||typeof q.sourceHadChanges!=="boolean"||q.sourceStateFingerprint!==void 0&&(typeof q.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test(q.sourceStateFingerprint)))return;return q}function $q($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(!I2.has(String(q.status))||typeof q.updatedAt!=="string"||!Number.isFinite(Date.parse(q.updatedAt))||q.sourceCommit!==void 0&&(typeof q.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test(q.sourceCommit))||q.changedFiles!==void 0&&(typeof q.changedFiles!=="number"||!Number.isInteger(q.changedFiles)||q.changedFiles<0)||q.message!==void 0&&(typeof q.message!=="string"||!q.message.trim()||q.message.length>500))return;return{status:q.status,updatedAt:q.updatedAt,...typeof q.sourceCommit==="string"?{sourceCommit:q.sourceCommit}:{},...typeof q.changedFiles==="number"?{changedFiles:q.changedFiles}:{},...typeof q.message==="string"?{message:q.message}:{}}}function qq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(["changedFiles","additions","deletions","commits"].some((L)=>typeof q[L]!=="number"||!Number.isInteger(q[L])||q[L]<0))return;return q}function Jq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$,J;if(q.outputSchema!==void 0)try{J=t1(q.outputSchema).schema}catch{return}if(q.version!==1||typeof q.prompt!=="string"||!q.prompt.trim()||q.prompt.length>32000||typeof q.sourceProjectPath!=="string"||!K.isAbsolute(q.sourceProjectPath)||!v$.has(q.isolation)||!p0(q.permissionMode)||q.title!==void 0&&(typeof q.title!=="string"||!q.title.trim()||q.title.length>200)||q.taskPriority!==void 0&&!i0.has(q.taskPriority)||q.taskKind!==void 0&&!d0.has(q.taskKind)||q.taskDueAt!==void 0&&(typeof q.taskDueAt!=="string"||!Number.isFinite(Date.parse(q.taskDueAt)))||q.modelId!==void 0&&(typeof q.modelId!=="string"||!q.modelId.trim()||q.modelId.length>500)||q.reasoningEffort!==void 0&&!D0(q.reasoningEffort)||q.serviceTier!==void 0&&!T0(q.serviceTier)||q.responseVerbosity!==void 0&&!f0(q.responseVerbosity)||q.communicationStyle!==void 0&&!z0(q.communicationStyle)||q.communicationStyleDigest!==void 0&&(typeof q.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.communicationStyleDigest))||q.projectInstructionsDigest!==void 0&&(typeof q.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test(q.projectInstructionsDigest)))return;let L;if(q.attachments!==void 0){if(!Array.isArray(q.attachments)||q.attachments.length>Vq)return;let G=0;for(let Z of q.attachments){if(!Z||typeof Z!=="object"||Array.isArray(Z))return;let Q=Z;if(!["file","image","url"].includes(String(Q.type)))return;for(let V of["path","url","content","mimeType","name"])if(Q[V]!==void 0&&typeof Q[V]!=="string")return;G+=typeof Q.content==="string"?Buffer.byteLength(Q.content):0}if(G>Xq)return;L=q.attachments.map((Z)=>{let Q=Z;return{type:Q.type,...Q.path!==void 0?{path:Q.path}:{},...Q.url!==void 0?{url:Q.url}:{},...Q.content!==void 0?{content:Q.content}:{},...Q.mimeType!==void 0?{mimeType:Q.mimeType}:{},...Q.name!==void 0?{name:Q.name}:{}}})}return{version:1,prompt:q.prompt,...typeof q.title==="string"?{title:q.title}:{},...i0.has(q.taskPriority)?{taskPriority:q.taskPriority}:{},...d0.has(q.taskKind)?{taskKind:q.taskKind}:{},...typeof q.taskDueAt==="string"?{taskDueAt:new Date(q.taskDueAt).toISOString()}:{},sourceProjectPath:K.resolve(q.sourceProjectPath),isolation:q.isolation,permissionMode:q.permissionMode,...typeof q.modelId==="string"?{modelId:q.modelId}:{},...D0(q.reasoningEffort)?{reasoningEffort:q.reasoningEffort}:{},...T0(q.serviceTier)?{serviceTier:q.serviceTier}:{},...f0(q.responseVerbosity)?{responseVerbosity:q.responseVerbosity}:{},...z0(q.communicationStyle)?{communicationStyle:q.communicationStyle}:{},...typeof q.communicationStyleDigest==="string"?{communicationStyleDigest:q.communicationStyleDigest}:{},...typeof q.projectInstructionsDigest==="string"?{projectInstructionsDigest:q.projectInstructionsDigest}:{},...L?{attachments:L}:{},...J?{outputSchema:J}:{}}}function p0($){return typeof $==="string"&&m2.has($)}function Lq($){if(!$||typeof $!=="object"||Array.isArray($))return;let q=$;if(typeof q.sessionId!=="string"||!q.sessionId||typeof q.projectPath!=="string"||!K.isAbsolute(q.projectPath))return;return{sessionId:q.sessionId,projectPath:K.resolve(q.projectPath)}}var _q={stat($){return n0($,{bigint:!0})},readFile($){return L0($,"utf-8")}},R0=_q;function $5($){R0=$}function q5(){R0=_q}class Oq extends Error{constructor($){super(`Session has no durable creation record: ${$}`);this.name="SessionMissingCreationError"}}class C0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor($,q){super($===q?`Session is archived: ${$}`:`Session is archived by ancestor ${q}: ${$}`);this.sessionId=$;this.archivedBySessionId=q;this.name="SessionArchivedError"}}class n extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor($){super($);this.name="SessionArchiveConflictError"}}function b$($,q){return`${$}\x00${q}`}function P2($){if($.kind==="base")return`/review base ${$.baseSha??$.label}`;if($.kind==="commit")return`/review commit ${$.commitSha??$.label}`;return"/review uncommitted"}function Fq($){return typeof $==="string"&&$.length<=64&&Number.isFinite(Date.parse($))}function u2($){let q=new Map($.map((J)=>[b$(J.projectPath,J.sessionId),J]));return $.map((J)=>{let L=J,G=new Set;while(L){let C=b$(L.projectPath,L.sessionId);if(G.has(C))break;if(G.add(C),Fq(L.archivedAt))return{...J,archivedAt:L.archivedAt,archivedBySessionId:L.sessionId};L=L.parentId?q.get(b$(L.projectPath,L.parentId)):void 0}let{archivedAt:Z,archivedBySessionId:Q,...V}=J;return V})}function k$($,q){let J=u2($);if(q===null)return J;return J.filter((L)=>Boolean(L.archivedAt)===q)}class R{static toUISafeMessages($){let q=Date.now(),J=$.length,L=[];return $.forEach((G,Z)=>{if(G.role!=="user"&&G.role!=="assistant"||!E1(G))return;let Q;if(typeof G.content==="string")Q=G.content;else if(Array.isArray(G.content))Q=G.content.map((X)=>X.type==="text"?X.text:"[Image]").join("");else Q="";let V=Q.trim();if(!V)return;let C=u0(G.metadata),Y=C?I1(C):V,H=L[L.length-1];if(H&&H.role===G.role&&H.content===Y)return;L.push({id:`restored-${q}-${Z}`,role:G.role,content:Y,timestamp:q-(J-Z)*1000,metadata:G.metadata&&typeof G.metadata==="object"?G.metadata:void 0})}),L}static async listSessionPage($={}){let q=y$($),J=await this.listSessionPageFromProjection(q);if(J)return J;let G=(await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,q.cursor?5000:0,q.archived)).sort(j$),Z=m$(G,q);return{sessions:Z.sessions.map((Q)=>this.toPublicMetadata(Q)),nextCursor:Z.nextCursor}}static async listSessionPageFromProjection($){let q=Wq($);try{let J=await l0();if(!J)return null;await I$(J,this.projectionDeriver(),$.cursor?5000:0);let L=[],G=[];if($.cwd)L.push("s.project_path = ?"),G.push($.cwd);if(!$.includeSubagents)L.push("s.is_subagent = 0");if(L.push($.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),q){L.push(`(
75
+ s.last_message_time < ?
76
+ OR (
77
+ s.last_message_time = ?
78
+ AND (
79
+ s.project_sort_key > ?
80
+ OR (s.project_sort_key = ? AND s.session_sort_key > ?)
81
+ )
82
+ )
83
+ )`);let C=S$(q.projectPath);G.push(q.lastMessageTime,q.lastMessageTime,C,C,S$(q.sessionId))}let Z=J.prepare(`WITH RECURSIVE archive_members(
84
+ project_path, session_id, archive_root_id, effective_archived_at, depth
85
+ ) AS (
86
+ SELECT project_path, session_id, session_id, archived_at, 0
87
+ FROM sessions
88
+ WHERE archived_at IS NOT NULL
89
+ UNION ALL
90
+ SELECT child.project_path, child.session_id, parent.archive_root_id,
91
+ parent.effective_archived_at, parent.depth + 1
92
+ FROM sessions child
93
+ JOIN archive_members parent
94
+ ON child.project_path = parent.project_path
95
+ AND child.parent_id = parent.session_id
96
+ WHERE parent.depth < 128
97
+ ),
98
+ ranked_archive AS (
99
+ SELECT project_path, session_id, archive_root_id,
100
+ effective_archived_at,
101
+ ROW_NUMBER() OVER (
102
+ PARTITION BY project_path, session_id
103
+ ORDER BY depth ASC, archive_root_id ASC
104
+ ) AS rank
105
+ FROM archive_members
106
+ )
107
+ SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
108
+ FROM sessions s
109
+ LEFT JOIN ranked_archive a
110
+ ON a.project_path = s.project_path
111
+ AND a.session_id = s.session_id
112
+ AND a.rank = 1
113
+ ${L.length>0?`WHERE ${L.join(" AND ")}`:""}
114
+ ORDER BY s.last_message_time DESC,
115
+ s.project_sort_key ASC,
116
+ s.session_sort_key ASC
117
+ LIMIT ?`).all(...G,$.limit+1),Q=await Promise.all(Z.map(async(C)=>{let Y=JSON.parse(C.metadata_json);if(C.archive_root_id&&C.effective_archived_at)return this.reconcileInterruptedTask({...Y,archivedAt:C.effective_archived_at,archivedBySessionId:C.archive_root_id});let{archivedAt:H,archivedBySessionId:X,...W}=Y;return this.reconcileInterruptedTask(W)})),V=m$(Q,$);return{sessions:V.sessions.map((C)=>this.toPublicMetadata(C)),nextCursor:V.nextCursor}}catch{return null}}static async listSessions($={}){let q=y$($),J=Hq($),L=await this.scanStoredSessions(q.cwd??void 0,q.includeSubagents,0,q.archived,J),G=new Set;return L.sort(j$).flatMap((Z)=>{let Q=`${Z.projectPath}\x00${Z.sessionId}`;if(G.has(Q))return[];return G.add(Q),[this.toPublicMetadata(Z)]})}static async collectStaleEmptySessions($={}){let q=$.now??Date.now(),J=$.olderThanMs??v2;if(!Number.isFinite(J)||J<0)throw Error("Stale empty session age must be a non-negative number");let L=$.projectPath?[{storagePath:B0(this.resolveCatalogWorkspace($.projectPath)),projectPath:this.resolveCatalogWorkspace($.projectPath)}]:await this.listAllProjectStorageDirectories(),G=0;for(let Z of L){let Q;try{Q=await E$(Z.storagePath)}catch(V){if(V.code==="ENOENT")continue;throw V}for(let V of Q){if(!V.endsWith(".jsonl"))continue;let C=V.slice(0,-6);if(!Qq(C))continue;let Y=K.join(Z.storagePath,V);try{let X=await n0(Y);if(q-X.mtimeMs<J)continue;if(await Promise.all([n0(K.join(Z.storagePath,`${C}.inbox.json`)).then(()=>!0).catch(()=>!1),n0(U0(Z.projectPath,C)).then(()=>!0).catch(()=>!1)]).then((B)=>B.some(Boolean)))continue}catch(X){if(X.code==="ENOENT")continue;throw X}let H;try{H=await d.acquire(C,Z.projectPath)}catch(X){if(X instanceof i)continue;throw X}try{if(!await new S(Y).deleteValidated((W)=>W.length===1&&W[0]?.type==="session_created"&&W[0].data.relationType!=="subagent"))continue;G++,await X0(K.join(Z.storagePath,`${C}.inbox.json`),{force:!0}),await X0(U0(Z.projectPath,C),{force:!0}),await this.removeFromProjection(C,Z.projectPath)}catch(X){N0.warn(`[SessionService] Skipping stale empty session cleanup: ${C}`,X)}finally{await H.release()}}}return G}static async findSessionMetadata($,q){if(x($),q!==void 0){if(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=K.resolve(q),G=this.getSessionFilePath(L,$);try{let Z=await this.readStoredSessionMetadata(G,$,L);if(Z.projectPath!==L)return;if(!Z.parentId||Z.archivedAt)return this.toPublicMetadata(k$([Z],null)[0]??Z);let Q=await this.scanStoredSessions(L,!0,0,null);return this.toPublicMetadata(Q.find((V)=>V.sessionId===$)??Z)}catch(Z){if(Z.code==="ENOENT")return;throw Z}}let J=(await this.scanStoredSessions(void 0,!0,0,null)).filter((L)=>L.sessionId===$);if(J.length===0)return;if(J.length>1)throw Error(`Ambiguous session ID: ${$}`);return this.toPublicMetadata(J[0])}static async loadSession($,q){try{if(q){if(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=K.resolve(q),G=this.getSessionFilePath(L,$);try{return await this.loadSessionFromFile(G,$,L)}catch(Z){if(Z.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw Z}}let J=(await this.scanStoredSessions(void 0,!0,0,null)).find((L)=>L.sessionId===$);if(!J)throw Error(`未找到会话: ${$}`);return await this.loadSessionFromFile(J.filePath,$)}catch(J){throw N0.error(`[SessionService] 加载会话失败 (${$}):`,J),J}}static async loadSessionModelContext($,q){try{if(q){if(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=K.resolve(q),G=this.getSessionFilePath(L,$);try{return await this.loadSessionModelContextFromFile(G,$,L)}catch(Z){if(Z.code==="ENOENT")throw Error(`未找到会话: ${$}`);throw Z}}let J=(await this.scanStoredSessions(void 0,!0,0,null)).find((L)=>L.sessionId===$);if(!J)throw Error(`未找到会话: ${$}`);return await this.loadSessionModelContextFromFile(J.filePath,$)}catch(J){throw N0.error(`[SessionService] 加载模型上下文失败 (${$}):`,J),J}}static async exportSessionMarkdown($,q,J={}){x($);let L=this.resolveCatalogWorkspace(q),G=v(L,$),Z;try{Z=await this.readStableSessionSnapshot(G,$)}catch(C){throw this.sanitizeStoredSessionError(C,$)}let Q=this.projectMetadataFromEntries(Z,$,L,G);if(Q.projectPath!==L)throw Error(`Session export workspace mismatch: ${$}`);let V=Q.archivedAt;if(!V&&Q.parentId)V=(await this.findArchivedAncestor(Q.parentId,L))?.archivedAt;return h1(Z,{...Q,archivedAt:V},J)}static async listRewindCheckpoints($,q){x($);let J=this.resolveCatalogWorkspace(q),L=v(J,$),G=await this.readStableSessionSnapshot(L,$);this.validateSessionWorkspace(G,$,J);let Z=new v0({sessionId:$,workspaceRoot:J});await Z.initialize();let Q=Cq(G),V=[];for(let C of Q){let Y=g$(G,C.messageId),H=await Z.previewRewind(Y.snapshotMessageIds);V.push({...C,fileCount:H.files.length})}return V}static async rewindSession($,q,J){x($);let L=this.resolveCatalogWorkspace(q);await this.assertSessionWritable($,L);let G=v(L,$),Z=new S(G),Q;try{await Z.appendValidatedAsync(async(V)=>{this.validateSessionWorkspace(V,$,L);let C=g$(V,J.targetMessageId),Y=new v0({sessionId:$,workspaceRoot:L});await Y.initialize();let H=await Y.previewRewind(C.snapshotMessageIds),X=J.mode==="conversation"?await Y.commitSnapshots(C.snapshotMessageIds):await Y.rewindSnapshots(C.snapshotMessageIds),W=new Date().toISOString(),B={id:I(),sessionId:$,timestamp:W,type:"session_rewound",cwd:L,gitBranch:r(L),version:t(),data:{rewindId:I(),targetMessageId:J.targetMessageId,mode:J.mode,restoredFiles:J.mode==="conversation"?[]:X.files,createdAt:W}},_=h([...V,B]);return Q={checkpoint:{...C.checkpoint,fileCount:H.files.length},mode:J.mode,removedTurns:C.removedTurns,restoredFiles:B.data.restoredFiles,messages:this.convertJSONLToMessages(_)},B})}catch(V){throw this.sanitizeStoredSessionError(V,$)}if(!Q)throw Error(`Session rewind did not produce a result: ${$}`);for(let V of Q.restoredFiles)o.getInstance().clearFileRecord(V);return Q}static async forkSession($,q){x($);let J=q.newSessionId??`fork-${Date.now()}-${I(8)}`;x(J);let L=this.resolveForkWorkspace(q.sourceProjectPath),G=this.resolveForkWorkspace(q.targetProjectPath);if(L!==G)throw Error("Session forks must stay in the source workspace");let Z=v(L,$),Q=await this.readStableSessionSnapshot(Z,$),V=this.getSessionCreatedEntry(Q,$);if(V.data.sessionId!==$)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!K.isAbsolute(V.cwd)||K.resolve(V.cwd)!==L)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let C=this.projectMetadataFromEntries(Q,$,L,Z);if(C.archivedAt)throw new C0($,$);if(C.parentId){let U=await this.findArchivedAncestor(C.parentId,L);if(U)throw new C0($,U.sessionId)}let Y=h(Q),H=new Date().toISOString(),X=V.data.rootId||$,W=r(G),B=t(),{status:_,taskStatus:f,taskStatusReason:b,taskFailure:T,taskStartedAt:Z0,taskCompletedAt:G0,taskOwnerPid:y,taskPromptSummary:j,taskPriority:A,taskKind:M,taskDueAt:E,taskDispatch:F,taskModelId:w,taskRetriedFrom:u$,taskDelivery:h$,taskIsolation:c$,taskSourceProjectPath:o0,taskWorktree:l$,taskDiffStat:n$,taskQueuePosition:p$,taskQueueDepth:i$,taskConcurrencyLimit:d$,pendingInteraction:r0,...t0}=V.data,a0={id:I(),sessionId:J,timestamp:H,type:"session_created",cwd:G,gitBranch:W,version:B,data:{...t0,sessionId:J,rootId:X,parentId:$,relationType:"fork",taskStatus:"completed",taskCompletedAt:H,taskIsolation:"local",taskSourceProjectPath:G,createdAt:H,updatedAt:H}},s0=Y.filter((U)=>U.type!=="session_created"&&U.type!=="token_budget_handoff_recorded"&&U.type!=="inbox_acknowledged"&&U.type!=="interaction_requested"&&U.type!=="interaction_responded"&&U.type!=="interaction_recovered"&&U.type!=="review_started"&&U.type!=="review_completed").map((U)=>{let m={...U,id:I(),sessionId:J,cwd:G,gitBranch:W,version:B};if(U.type==="session_updated"){let{status:z,taskStatus:H0,taskStatusReason:h2,taskFailure:c2,taskStartedAt:l2,taskCompletedAt:n2,taskOwnerPid:p2,taskPromptSummary:i2,taskPriority:d2,taskKind:o2,taskDueAt:r2,taskDispatch:t2,taskModelId:a2,taskRetriedFrom:s2,taskDelivery:e2,taskIsolation:$4,taskSourceProjectPath:q4,taskWorktree:J4,taskDiffStat:L4,taskQueuePosition:Z4,taskQueueDepth:G4,taskConcurrencyLimit:Q4,pendingInteraction:V4,...Nq}=U.data;return{...m,type:"session_updated",data:{...Nq,sessionId:J,rootId:X,parentId:$,relationType:"fork"}}}if(U.type==="message_created"){let{inboxMessageId:z,...H0}=U.data;return{...m,type:"message_created",data:H0}}return m}),e0={id:I(),sessionId:J,timestamp:H,type:"session_updated",cwd:G,gitBranch:W,version:B,data:{sessionId:J,rootId:X,parentId:$,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:H,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:G,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:H}},Y0=[a0,...s0,e0],W0=v(G,J),M0=!1;try{await new S(W0).createExclusive(Y0),M0=!0;let U=W1(Y.flatMap((m)=>m.type==="message_created"?[m.data.metadata]:[]));if(U.length>0){let m=new s(L,$,{storageRoot:l()}),z=new s(G,J,{storageRoot:l()});await m.copyReferencedTo(U,z)}}catch(U){if(M0)await new S(W0).delete().catch(()=>{return}),await new s(G,J,{storageRoot:l()}).removeAll().catch(()=>{return});if(U.code==="EEXIST")throw Error(`Fork session already exists: ${J}`,{cause:U});throw U}let $$=this.projectMetadataFromEntries(Y0,J,G,W0);return{sessionId:J,parentSessionId:$,projectPath:G,messages:this.convertJSONLToMessages(Y0),metadata:this.toPublicMetadata($$)}}static async deleteSession($,q){if(x($),q){if(!K.isAbsolute(q))throw Error("Session catalog cwd must be absolute");let L=K.resolve(q),G=this.getSessionFilePath(L,$),Z=new S(G),Q;try{Q=await Z.deleteValidated((V)=>{return this.projectMetadataFromEntries(V,$,L,G).projectPath===L})}catch(V){if(!this.isCorruptSessionJSONLError(V))throw V;Q=await Z.delete()}if(!Q)return 0;return await X0(K.join(K.dirname(G),`${$}.inbox.json`),{force:!0}),await X0(U0(L,$),{force:!0}),await new s(L,$,{storageRoot:l()}).removeAll(),await this.removeFromProjection($,L),1}let J=(await this.scanStoredSessions(void 0,!0)).filter((L)=>L.sessionId===$);if(J.length===0)return 0;return await Promise.all(J.map(async(L)=>{await new S(L.filePath).delete(),await X0(K.join(K.dirname(L.filePath),`${L.sessionId}.inbox.json`),{force:!0}),await X0(U0(L.projectPath,L.sessionId),{force:!0}),await new s(L.projectPath,L.sessionId,{storageRoot:l()}).removeAll(),await this.removeFromProjection(L.sessionId,L.projectPath)})),J.length}static async removeFromProjection($,q){try{let J=await l0();if(J)Bq(J,$,q)}catch{}}static validateTaskMetadataUpdate($,q){if($.taskPromptSummary!==void 0&&$.taskPromptSummary!==null&&(!$.taskPromptSummary.trim()||$.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if($.taskPriority!==void 0&&$.taskPriority!==null&&!i0.has($.taskPriority))throw Error("Invalid session task priority");if($.taskKind!==void 0&&$.taskKind!==null&&!d0.has($.taskKind))throw Error("Invalid session task kind");if($.taskDueAt!==void 0&&$.taskDueAt!==null&&!Number.isFinite(Date.parse($.taskDueAt)))throw Error("Invalid session task due date");if($.taskFailure!==void 0&&$.taskFailure!==null&&!O$($.taskFailure))throw Error("Invalid session task failure");if($.taskDispatch!==void 0&&$.taskDispatch!==null&&!Jq($.taskDispatch))throw Error("Invalid durable task dispatch");if($.taskModelId!==void 0&&$.taskModelId!==null&&(!$.taskModelId.trim()||$.taskModelId.length>500))throw Error("Invalid session task model ID");if($.selectedModelId!==void 0&&$.selectedModelId!==null&&(!$.selectedModelId.trim()||$.selectedModelId.length>500))throw Error("Invalid selected session model ID");if($.permissionMode!==void 0&&$.permissionMode!==null&&!p0($.permissionMode))throw Error("Invalid session permission mode");if($.reasoningEffort!==void 0&&$.reasoningEffort!==null&&!D0($.reasoningEffort))throw Error("Invalid session reasoning effort");if($.serviceTier!==void 0&&$.serviceTier!==null&&!T0($.serviceTier))throw Error("Invalid session service tier");if($.responseVerbosity!==void 0&&$.responseVerbosity!==null&&!f0($.responseVerbosity))throw Error("Invalid session response verbosity");if($.communicationStyle!==void 0&&$.communicationStyle!==null&&!z0($.communicationStyle))throw Error("Invalid session communication style");if($.communicationStyleDigest!==void 0&&$.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))throw Error("Invalid session communication style digest");if($.projectInstructionsDigest!==void 0&&$.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if($.taskRetriedFrom!==void 0&&$.taskRetriedFrom!==null&&!Lq($.taskRetriedFrom))throw Error("Invalid session task retry source");if($.taskDelivery!==void 0&&$.taskDelivery!==null&&!$q($.taskDelivery))throw Error("Invalid session task delivery");if($.taskIsolation!==void 0&&$.taskIsolation!==null&&!v$.has($.taskIsolation))throw Error(`Invalid session task isolation: ${String($.taskIsolation)}`);if($.taskSourceProjectPath!==void 0&&$.taskSourceProjectPath!==null&&!K.isAbsolute($.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if($.taskWorktree!==void 0&&$.taskWorktree!==null){let J=e1($.taskWorktree);if(!J||J.sessionId!==q||![J.repositoryRoot,J.originalWorkspaceRoot,J.worktreeRoot,J.workspaceRoot].every((L)=>K.isAbsolute(L)))throw Error("Invalid session task worktree metadata")}if($.taskDiffStat!==void 0&&$.taskDiffStat!==null&&!qq($.taskDiffStat))throw Error("Invalid session task diff stat");if($.taskQueuePosition!==void 0&&$.taskQueuePosition!==null&&(!Number.isInteger($.taskQueuePosition)||$.taskQueuePosition<1))throw Error("Invalid session task queue position");if($.taskQueueDepth!==void 0&&$.taskQueueDepth!==null&&(!Number.isInteger($.taskQueueDepth)||$.taskQueueDepth<0))throw Error("Invalid session task queue depth");if($.taskConcurrencyLimit!==void 0&&$.taskConcurrencyLimit!==null&&(!Number.isInteger($.taskConcurrencyLimit)||$.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof $.taskQueuePosition==="number"&&typeof $.taskQueueDepth==="number"&&$.taskQueuePosition>$.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata($,q,J={}){x($),R.validateTaskMetadataUpdate(J,$);let L=R.resolveCatalogWorkspace(q);if(J.taskWorktree&&K.resolve(J.taskWorktree.workspaceRoot)!==L)throw Error("Session task worktree must match the catalog workspace");let G=new Date().toISOString(),Z={id:I(),sessionId:$,timestamp:G,type:"session_created",cwd:L,gitBranch:r(L),version:t(),data:{sessionId:$,rootId:$,...J.title!==void 0?{title:J.title}:{},taskStatus:J.taskStatus??"queued",...J.taskPromptSummary!==void 0?{taskPromptSummary:J.taskPromptSummary}:{},...J.taskPriority!==void 0?{taskPriority:J.taskPriority}:{},...J.taskKind!==void 0?{taskKind:J.taskKind}:{},...typeof J.taskDueAt==="string"?{taskDueAt:new Date(J.taskDueAt).toISOString()}:{},...J.taskDispatch!==void 0?{taskDispatch:J.taskDispatch}:{},...J.taskModelId!==void 0?{taskModelId:J.taskModelId}:{},...J.taskRetriedFrom!==void 0?{taskRetriedFrom:J.taskRetriedFrom}:{},...J.taskIsolation!==void 0?{taskIsolation:J.taskIsolation}:{},...J.taskSourceProjectPath!==void 0?{taskSourceProjectPath:J.taskSourceProjectPath}:{},...J.taskWorktree!==void 0?{taskWorktree:J.taskWorktree}:{},...J.selectedModelId!==void 0?{selectedModelId:J.selectedModelId}:{},...J.permissionMode!==void 0?{permissionMode:J.permissionMode}:{},...J.reasoningEffort!==void 0?{reasoningEffort:J.reasoningEffort}:{},...J.serviceTier!==void 0?{serviceTier:J.serviceTier}:{},...J.responseVerbosity!==void 0?{responseVerbosity:J.responseVerbosity}:{},...J.communicationStyle!==void 0?{communicationStyle:J.communicationStyle}:{},...J.communicationStyleDigest!==void 0?{communicationStyleDigest:J.communicationStyleDigest}:{},...J.projectInstructionsDigest!==void 0?{projectInstructionsDigest:J.projectInstructionsDigest}:{},createdAt:G,updatedAt:G}},Q=R.getSessionFilePath(L,$);return await new S(Q).createExclusive([Z]),R.toPublicMetadata(R.projectMetadataFromEntries([Z],$,L,Q))}static async assertSessionWritable($,q){let J=await this.findSessionMetadata($,q);if(!J)throw Error(`Session not found: ${$}`);if(J.archivedAt)throw new C0($,J.archivedBySessionId??$);return J}static async findArchivedAncestor($,q){let J=new Set,L=$;while(L){if(J.has(L))throw Error("Session lineage contains a cycle");J.add(L),x(L);let G=v(q,L),Z;try{Z=await L0(G,"utf8")}catch(V){if(V.code==="ENOENT")return;throw V}let Q=this.projectMetadataFromEntries(this.parseStoredSession(Z,L),L,q,G);if(Q.projectPath!==q)throw Error("Session lineage escapes the requested workspace");if(Q.archivedAt)return{sessionId:Q.sessionId,archivedAt:Q.archivedAt};L=Q.parentId}return}static async listSessionArchiveMembers($,q){x($);let J=this.resolveCatalogWorkspace(q),L=await this.scanStoredSessions(J,!0,0,null);if(!L.some((Q)=>Q.sessionId===$))throw Error(`Session not found: ${$}`);let G=new Set([$]),Z=!0;while(Z){Z=!1;for(let Q of L)if(Q.parentId&&G.has(Q.parentId)&&!G.has(Q.sessionId))G.add(Q.sessionId),Z=!0}return L.filter((Q)=>G.has(Q.sessionId)).sort((Q,V)=>Q.sessionId.localeCompare(V.sessionId)).map((Q)=>this.toPublicMetadata(Q))}static async archiveSession($,q){x($);let J=this.resolveCatalogWorkspace(q),L=await this.findSessionMetadata($,J);if(!L)throw Error(`Session not found: ${$}`);if(L.archivedAt)return L;let G=await this.listSessionArchiveMembers($,J),Z=G.find((V)=>V.taskStatus==="queued"||V.taskStatus==="running");if(Z)throw new n(`Stop session ${Z.sessionId} before archiving this session tree`);let Q=[];try{for(let H of G)Q.push(await d.acquire(H.sessionId,J));let V=v(J,$),C=new S(V),Y=[];return await C.appendValidated((H)=>{let X=this.projectMetadataFromEntries(H,$,J,V);if(X.archivedAt)throw new n(`Session archive state changed concurrently: ${$}`);if(X.taskStatus==="queued"||X.taskStatus==="running")throw new n(`Stop session ${$} before archiving it`);let W=new Date().toISOString(),B={id:I(),sessionId:$,timestamp:W,type:"session_updated",cwd:J,gitBranch:r(J),version:t(),data:{sessionId:$,archivedAt:W,updatedAt:W}};return Y=[...H,B],B}),this.toPublicMetadata({...this.projectMetadataFromEntries(Y,$,J,V),archivedBySessionId:$})}catch(V){if(V instanceof n)throw V;if(V instanceof i)throw new n(V.message);throw this.sanitizeStoredSessionError(V,$)}finally{for(let V of Q.reverse())await V.release()}}static async unarchiveSession($,q){x($);let J=this.resolveCatalogWorkspace(q),L=await this.findSessionMetadata($,J);if(!L)throw Error(`Session not found: ${$}`);if(!L.archivedAt)return L;if(L.archivedBySessionId&&L.archivedBySessionId!==$)throw new n(`Unarchive ancestor ${L.archivedBySessionId} to restore session ${$}`);let G;try{G=await d.acquire($,J);let Z=v(J,$),Q=new S(Z),V=[];return await Q.appendValidated((C)=>{if(!this.projectMetadataFromEntries(C,$,J,Z).archivedAt)throw new n(`Session archive state changed concurrently: ${$}`);let H=new Date().toISOString(),X={id:I(),sessionId:$,timestamp:H,type:"session_updated",cwd:J,gitBranch:r(J),version:t(),data:{sessionId:$,archivedAt:null,updatedAt:H}};return V=[...C,X],X}),this.toPublicMetadata(this.projectMetadataFromEntries(V,$,J,Z))}catch(Z){if(Z instanceof n)throw Z;if(Z instanceof i)throw new n(Z.message);throw this.sanitizeStoredSessionError(Z,$)}finally{await G?.release()}}static async updateSessionMetadata($,q,J){if(x($),R.validateTaskMetadataUpdate(J,$),J.taskStatus!==void 0&&!a1.has(J.taskStatus))throw Error(`Invalid session task status: ${String(J.taskStatus)}`);if(J.taskOwnerPid!==void 0&&J.taskOwnerPid!==null&&(!Number.isInteger(J.taskOwnerPid)||J.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let L=R.resolveCatalogWorkspace(q);if(J.taskWorktree&&K.resolve(J.taskWorktree.workspaceRoot)!==L)throw Error("Session task worktree must match the catalog workspace");let G=R.getSessionFilePath(L,$),Z=new S(G),Q=[];try{await Z.appendValidatedAsync(async(V)=>{let C=R.getSessionCreatedEntry(V,$);if(C.data.sessionId!==$)throw Error(`Session metadata creation record sessionId mismatch: ${$}`);if(!K.isAbsolute(C.cwd)||K.resolve(C.cwd)!==L)throw Error(`Session metadata creation record cwd mismatch: ${$}`);let Y=R.projectMetadataFromEntries(V,$,L,G);if(Y.archivedAt)throw new C0($,$);if(Y.parentId){let W=await R.findArchivedAncestor(Y.parentId,L);if(W)throw new C0($,W.sessionId)}let H=new Date().toISOString(),X={id:I(),sessionId:$,timestamp:H,type:"session_updated",cwd:L,gitBranch:r(L),version:t(),data:{sessionId:$,...J.title!==void 0?{title:J.title}:{},...J.taskStatus!==void 0?{taskStatus:J.taskStatus}:{},...J.taskStatusReason!==void 0?{taskStatusReason:J.taskStatusReason}:{},...J.taskFailure!==void 0?{taskFailure:J.taskFailure}:{},...J.taskStartedAt!==void 0?{taskStartedAt:J.taskStartedAt}:{},...J.taskCompletedAt!==void 0?{taskCompletedAt:J.taskCompletedAt}:{},...J.taskOwnerPid!==void 0?{taskOwnerPid:J.taskOwnerPid}:{},...J.taskPromptSummary!==void 0?{taskPromptSummary:J.taskPromptSummary}:{},...J.taskPriority!==void 0?{taskPriority:J.taskPriority}:{},...J.taskKind!==void 0?{taskKind:J.taskKind}:{},...J.taskDueAt!==void 0?{taskDueAt:J.taskDueAt===null?null:new Date(J.taskDueAt).toISOString()}:{},...J.taskDispatch!==void 0?{taskDispatch:J.taskDispatch}:{},...J.taskModelId!==void 0?{taskModelId:J.taskModelId}:{},...J.taskRetriedFrom!==void 0?{taskRetriedFrom:J.taskRetriedFrom}:{},...J.taskDelivery!==void 0?{taskDelivery:J.taskDelivery}:{},...J.taskIsolation!==void 0?{taskIsolation:J.taskIsolation}:{},...J.taskSourceProjectPath!==void 0?{taskSourceProjectPath:J.taskSourceProjectPath}:{},...J.taskWorktree!==void 0?{taskWorktree:J.taskWorktree}:{},...J.taskDiffStat!==void 0?{taskDiffStat:J.taskDiffStat}:{},...J.taskQueuePosition!==void 0?{taskQueuePosition:J.taskQueuePosition}:{},...J.taskQueueDepth!==void 0?{taskQueueDepth:J.taskQueueDepth}:{},...J.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:J.taskConcurrencyLimit}:{},...J.selectedModelId!==void 0?{selectedModelId:J.selectedModelId}:{},...J.permissionMode!==void 0?{permissionMode:J.permissionMode}:{},...J.reasoningEffort!==void 0?{reasoningEffort:J.reasoningEffort}:{},...J.serviceTier!==void 0?{serviceTier:J.serviceTier}:{},...J.responseVerbosity!==void 0?{responseVerbosity:J.responseVerbosity}:{},...J.communicationStyle!==void 0?{communicationStyle:J.communicationStyle}:{},...J.communicationStyleDigest!==void 0?{communicationStyleDigest:J.communicationStyleDigest}:{},...J.projectInstructionsDigest!==void 0?{projectInstructionsDigest:J.projectInstructionsDigest}:{},updatedAt:H}};return Q=[...V,X],X})}catch(V){throw R.sanitizeStoredSessionError(V,$)}return R.toPublicMetadata(R.projectMetadataFromEntries(Q,$,L,G))}static async setSessionPermissionMode($,q,J){if(x($),!p0(J))throw Error("Invalid session permission mode");let L=R.resolveCatalogWorkspace(q),G=await R.findSessionMetadata($,L);if(G?.permissionMode===J)return G;if(G)return R.updateSessionMetadata($,L,{permissionMode:J});try{return await R.createSessionMetadata($,L,{taskStatus:"completed",permissionMode:J})}catch(Z){if(Z.code!=="EEXIST")throw Z;return R.updateSessionMetadata($,L,{permissionMode:J})}}static async findSessionTaskWorktree($,q){x($);let J=R.resolveCatalogWorkspace(q),L=R.getSessionFilePath(J,$);try{return(await R.readStoredSessionMetadata(L,$,J)).taskWorktree}catch(G){if(G.code==="ENOENT")return;throw R.sanitizeStoredSessionError(G,$)}}static async findSessionTaskDispatch($,q){x($);let J=R.resolveCatalogWorkspace(q),L=R.getSessionFilePath(J,$);try{return(await R.readStoredSessionMetadata(L,$,J)).taskDispatch}catch(G){if(G.code==="ENOENT")return;throw R.sanitizeStoredSessionError(G,$)}}static async loadSessionFromFile($,q,J){let L=await L0($,"utf-8"),G=this.parseStoredSession(L,q);if(J!==void 0){if(this.projectMetadataFromEntries(G,q,J,$).projectPath!==J)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToMessages(G)}static async loadSessionModelContextFromFile($,q,J){let L=await L0($,"utf-8"),G=this.parseStoredSession(L,q);if(J!==void 0){if(this.projectMetadataFromEntries(G,q,J,$).projectPath!==J)throw Error(`未找到会话: ${q}`)}return this.convertJSONLToModelContext(G)}static convertJSONLToModelContext($){let q=h($),J=-1,L;for(let Z=0;Z<q.length;Z++){let Q=q[Z];if(Q?.type!=="part_created"||Q.data.partType!=="summary")continue;let V=Q.data.payload;if(J=Z,L=S0(V.replacementMessages),!L)L=[{role:"user",content:V.text??"",metadata:Q.data.payload}]}if(J<0||!L)return this.convertJSONLToMessages(q,{includeTokenBudgetHandoffs:!0});let G=this.convertJSONLToMessages(q.slice(J+1),{includeTokenBudgetHandoffs:!0});return[...L,...G]}static convertJSONLToMessages($,q={}){let J=[],L=new Map,G=new Map,Z=new Map,Q=new Map,V=new Map,C=h($),Y=q.includeTokenBudgetHandoffs?f1(C):{kind:"none"},H=new Set;for(let X of C){if(X.type==="token_budget_handoff_recorded"){if(Y.kind==="valid"&&Y.event.id===X.id){let W=T1(X);if(W)J.push(W)}continue}if(X.type==="message_created"){let W=X.data.metadata&&typeof X.data.metadata==="object"&&!Array.isArray(X.data.metadata)?X.data.metadata:void 0,B=W?.codeReview&&typeof W.codeReview==="object"&&!Array.isArray(W.codeReview)?W.codeReview:void 0;if(B?.phase==="completed"&&typeof B.reviewId==="string")H.add(B.reviewId);let _=X.data.role==="assistant"&&X.data.parentMessageId?Z.get(X.data.parentMessageId):void 0,f=_??{role:X.data.role,content:"",...X.data.metadata||X.data.inboxMessageId?{metadata:{...X.data.metadata&&typeof X.data.metadata==="object"&&!Array.isArray(X.data.metadata)?X.data.metadata:{},...X.data.inboxMessageId?{inboxMessageId:X.data.inboxMessageId}:{}}}:{}};if(L.set(X.data.messageId,f),G.set(X.data.messageId,[]),!_)J.push(f)}if(X.type==="part_created"){if(X.data.partType==="reasoning"){let W=L.get(X.data.messageId);if(W){let B=X.data.payload;W.reasoningContent=(W.reasoningContent??"")+(B.text??"")}}if(X.data.partType==="text"){let W=L.get(X.data.messageId);if(W){let B=X.data.payload,_=G.get(X.data.messageId);if(_)_.push({type:"text",text:B.text??""}),W.content=Zq(_);else W.content=B.text??""}}if(X.data.partType==="image"){let W=L.get(X.data.messageId);if(W){let B=X.data.payload,_=G.get(X.data.messageId);if(_&&B.dataUrl)_.push({type:"image_url",image_url:{url:B.dataUrl}}),W.content=Zq(_)}}if(X.data.partType==="tool_call"){let W=L.get(X.data.messageId);if(W?.role!=="assistant"){if(W=Z.get(X.data.messageId),!W)W={role:"assistant",content:"",tool_calls:[]},Z.set(X.data.messageId,W),J.push(W)}if(W.role==="assistant"){let B=X.data.payload,_=B.toolCallId??X.data.partId;Q.set(X.data.partId,_),V.set(_,W),W.tool_calls??=[],W.tool_calls.push({id:_,type:"function",function:{name:B.toolName??"unknown",arguments:JSON.stringify(B.input??{})}})}}if(X.data.partType==="tool_result"){let W=X.data.payload,B=x1(W),_=B.error?`Error: ${B.error.message}`:typeof B.llmContent==="string"?B.llmContent:JSON.stringify(B.llmContent),f=W;J.push({role:"tool",content:_,tool_call_id:Q.get(X.data.messageId)??W.toolCallId,name:W.toolName,metadata:f})}if(X.data.partType==="summary"){let W=X.data.payload,B=X.data.payload;J.push({role:"system",content:W.text??"",metadata:B})}if(X.data.partType==="subtask_ref"){let W=L.get(X.data.messageId)??V.get(X.data.messageId);if(W){let B=X.data.payload,_=W.metadata??{};W.metadata={..._,subtaskRef:B}}}}}for(let X of y0(C)){if(X.completion===void 0||H.has(X.start.reviewId))continue;J.push({role:"assistant",content:O1(X.start,X.completion),metadata:{codeReview:{...F1(X.start,X.completion),synthetic:!0}}})}return J}static projectionDeriver(){return($,q,J)=>{try{let L=v(J,q);return this.projectMetadataFromEntries($,q,J,L)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection($,q,J=0,L=!1,G={}){try{let Z=await l0();if(!Z)return null;await I$(Z,this.projectionDeriver(),J);let Q=[],V=[];if($!==void 0)Q.push("project_path=?"),V.push($);y2(G,"",Q,V);let C=Q.length>0?` WHERE ${Q.join(" AND ")}`:"",Y=Z.prepare(`SELECT metadata_json, is_subagent FROM sessions${C}`).all(...V),H=[];for(let W of Y){if(!q&&W.is_subagent===1)continue;try{let B=JSON.parse(W.metadata_json);if($!==void 0&&B.projectPath!==$)continue;H.push(B)}catch{}}let X=await Promise.all(H.map((W)=>this.reconcileInterruptedTask(W)));return k$(X.filter((W)=>Kq(W,G)),L)}catch{return null}}static async scanStoredSessions($,q=!1,J=0,L=!1,G={}){let Z=$?K.resolve($):void 0,Q=await this.scanStoredSessionsFromProjection(Z,q,J,L,G);if(Q)return Q;let V=Z?[{storagePath:B0(Z),projectPath:Z}]:await this.listAllProjectStorageDirectories(),C=[];for(let Y of V){let H;try{H=await E$(Y.storagePath)}catch(X){if(X.code==="ENOENT")continue;throw X}for(let X of H){if(!X.endsWith(".jsonl"))continue;let W=X.slice(0,-6),B=K.join(Y.storagePath,X);try{let _=await this.readStoredSessionMetadata(B,W,Y.projectPath);if(Z!==void 0&&_.projectPath!==Z){N0.warn(`[SessionService] Skipping out-of-scope session transcript: ${W}`);continue}if(!q&&_.relationType==="subagent")continue;if(!j2(_,G))continue;C.push(_)}catch(_){let f=_.code;if(f==="ENOENT")continue;if(f)throw _;N0.warn(`[SessionService] Skipping invalid session transcript: ${W}`)}}}return k$(C,L)}static async listAllProjectStorageDirectories(){let $=K.join(l(),"projects"),q;try{q=await E$($,{withFileTypes:!0,encoding:"utf8"})}catch(J){if(J.code==="ENOENT")return[];throw J}return q.filter((J)=>J.isDirectory()).map((J)=>({storagePath:K.join($,J.name),projectPath:Gq(J.name)}))}static async readStoredSessionMetadata($,q,J){let L=await L0($,"utf-8"),G=this.parseStoredSession(L,q);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(G,q,J,$))}static async reconcileInterruptedTask($){let q=$.taskOwnerPid;if($.taskStatus!=="running"||q===void 0||s1(q))return $;let J;try{J=await d.acquire($.sessionId,$.projectPath)}catch(Z){if(!(Z instanceof i))throw Z;let Q=await L0($.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(Q,$.sessionId),$.sessionId,$.projectPath,$.filePath)}let L=new S($.filePath),G;try{try{await L.appendValidated((Z)=>{let Q=this.projectMetadataFromEntries(Z,$.sessionId,$.projectPath,$.filePath);if(Q.taskStatus!=="running"||Q.taskOwnerPid!==q||s1(q))throw new P$;let V=new Date().toISOString(),C={id:I(),sessionId:$.sessionId,timestamp:V,type:"session_updated",cwd:$.projectPath,gitBranch:r($.projectPath),version:t(),data:{sessionId:$.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:V,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:V}};return G=[...Z,C],C})}catch(Z){if(!(Z instanceof P$))throw Z}if(!G){let Z=await L0($.filePath,"utf-8");G=this.parseStoredSession(Z,$.sessionId)}return this.projectMetadataFromEntries(G,$.sessionId,$.projectPath,$.filePath)}finally{await J.release()}}static projectMetadataFromEntries($,q,J,L){if($.length===0)throw Error(`Empty session transcript: ${q}`);let G=this.getSessionCreatedEntry($,q),Z=$.reduce((z,H0)=>H0.type==="session_updated"?{...z,...H0.data}:z,{...G.data}),Q=h($),V=_1(K1(Q)),Y=y0(Q).at(-1),H=Q.findLastIndex((z)=>z.type==="review_started"&&z.data.reviewId===Y?.start.reviewId||z.type==="review_completed"&&z.data.reviewId===Y?.start.reviewId),X=Q.findLastIndex((z)=>(z.type==="session_created"||z.type==="session_updated")&&Object.hasOwn(z.data,"taskStatus")),W=Y!==void 0&&H>X,B=W?Y.completion===void 0?"running":Y.completion.status==="completed"||Y.completion.status==="stale"?"completed":Y.completion.status==="aborted"?"cancelled":Y.completion.status==="interrupted"?"interrupted":"failed":void 0,_=Q.filter((z)=>z.type==="message_created"&&["user","assistant"].includes(z.data.role)).length,f=Q.some((z)=>z.type==="part_created"&&z.data.partType==="tool_result"&&typeof z.data.payload.error==="string"),b=a1.has(Z.taskStatus)?Z.taskStatus:void 0,T=B??b??(f?"failed":"completed"),Z0=typeof Z.taskOwnerPid==="number"&&Number.isInteger(Z.taskOwnerPid)&&Z.taskOwnerPid>0?Z.taskOwnerPid:void 0,G0=v$.has(Z.taskIsolation)?Z.taskIsolation:void 0,y=typeof Z.taskSourceProjectPath==="string"&&K.isAbsolute(Z.taskSourceProjectPath)?K.resolve(Z.taskSourceProjectPath):void 0,j=G.cwd;if(j!==void 0&&!K.isAbsolute(j))throw Error(`Session catalog cwd must be absolute: ${q}`);let A=j===void 0?J:K.resolve(j),M=e1(Z.taskWorktree),E=M?.sessionId===q&&K.resolve(M.workspaceRoot)===A?M:void 0,F=qq(Z.taskDiffStat),w=Jq(Z.taskDispatch),u$=i0.has(Z.taskPriority)?Z.taskPriority:w?.taskPriority,h$=d0.has(Z.taskKind)?Z.taskKind:w?.taskKind,c$=typeof Z.taskDueAt==="string"&&Number.isFinite(Date.parse(Z.taskDueAt))?new Date(Z.taskDueAt).toISOString():w?.taskDueAt,o0=typeof Z.taskModelId==="string"&&Z.taskModelId.trim()?Z.taskModelId:w?.modelId,l$=typeof Z.selectedModelId==="string"&&Z.selectedModelId.trim()?Z.selectedModelId:o0,n$=p0(Z.permissionMode)?Z.permissionMode:w?.permissionMode,p$=D0(Z.reasoningEffort)?Z.reasoningEffort:w?.reasoningEffort,i$=T0(Z.serviceTier)?Z.serviceTier:w?.serviceTier,d$=f0(Z.responseVerbosity)?Z.responseVerbosity:w?.responseVerbosity,r0=z0(Z.communicationStyle)?Z.communicationStyle:w?.communicationStyle,t0=Object.hasOwn(Z,"communicationStyleDigest")?typeof Z.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(Z.communicationStyleDigest)?Z.communicationStyleDigest:void 0:r0===w?.communicationStyle?w?.communicationStyleDigest:void 0,a0=Object.hasOwn(Z,"projectInstructionsDigest")?typeof Z.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(Z.projectInstructionsDigest)?Z.projectInstructionsDigest:void 0:w?.projectInstructionsDigest,s0=Fq(Z.archivedAt)?Z.archivedAt:void 0,e0=Lq(Z.taskRetriedFrom),Y0=$q(Z.taskDelivery),W0=typeof Z.taskQueuePosition==="number"&&Number.isInteger(Z.taskQueuePosition)&&Z.taskQueuePosition>0?Z.taskQueuePosition:void 0,M0=typeof Z.taskQueueDepth==="number"&&Number.isInteger(Z.taskQueueDepth)&&Z.taskQueueDepth>=0?Z.taskQueueDepth:void 0,$$=typeof Z.taskConcurrencyLimit==="number"&&Number.isInteger(Z.taskConcurrencyLimit)&&Z.taskConcurrencyLimit>0?Z.taskConcurrencyLimit:void 0,U=W?Y?.completion?Y.completion.status==="completed"?void 0:`Code review ${X$(Y.completion.status)}`:`Reviewing ${Y?.start.target.label??"changes"}`:void 0,m=W?T==="failed"&&U?_$(U):void 0:O$(Z.taskFailure)?Z.taskFailure:T==="failed"&&typeof Z.taskStatusReason==="string"?_$(Z.taskStatusReason):void 0;return{sessionId:q,projectPath:A,gitBranch:G.gitBranch,rootId:Z.rootId||q,parentId:Z.parentId,relationType:Z.relationType,resumedFrom:Z.resumedFrom,rootAgentId:Z.rootAgentId,resumeDepth:Z.resumeDepth,title:Z.title,agentType:Z.agentType,model:Z.model,selectedModelId:l$,permissionMode:n$,reasoningEffort:p$,serviceTier:i$,responseVerbosity:d$,communicationStyle:r0,communicationStyleDigest:t0,projectInstructionsDigest:a0,pendingInteraction:V,taskStatus:T,taskStatusReason:m?.message??U??(typeof Z.taskStatusReason==="string"?Z.taskStatusReason:void 0),taskFailure:m,taskStartedAt:W?Y?.start.startedAt:typeof Z.taskStartedAt==="string"?Z.taskStartedAt:void 0,taskCompletedAt:W?Y?.completion?.completedAt:typeof Z.taskCompletedAt==="string"?Z.taskCompletedAt:void 0,taskPromptSummary:W?Y?P2(Y.start.target):"/review uncommitted":typeof Z.taskPromptSummary==="string"?Z.taskPromptSummary:void 0,taskPriority:u$,taskKind:h$,taskDueAt:c$,taskModelId:o0,taskRetryAvailable:w!==void 0,taskRetriedFrom:e0,taskDelivery:Y0,taskIsolation:G0,taskSourceProjectPath:y,taskWorktreePath:E?.worktreeRoot,taskWorktreeBranch:E?.branch,taskBaseCommit:E?.baseCommit,taskDiffStat:F,taskQueuePosition:W0,taskQueueDepth:M0,taskConcurrencyLimit:$$,archivedAt:s0,taskOwnerPid:W?void 0:Z0,taskWorktree:E,taskDispatch:w,messageCount:_,firstMessageTime:$[0].timestamp,lastMessageTime:$.at(-1).timestamp,hasErrors:f||T==="failed",filePath:L}}static toPublicMetadata($){let{filePath:q,taskOwnerPid:J,taskWorktree:L,taskDispatch:G,...Z}=$;return Z}static getSessionFilePath($,q){return v($,q)}static getSessionCreatedEntry($,q){let J=$.find((L)=>L.type==="session_created");if(!J)throw new Oq(q);return J}static resolveCatalogWorkspace($){if(!K.isAbsolute($))throw Error("Session catalog cwd must be absolute");return K.resolve($)}static validateSessionWorkspace($,q,J){let L=this.getSessionCreatedEntry($,q);if(L.data.sessionId!==q)throw Error(`Session creation record sessionId mismatch: ${q}`);if(!K.isAbsolute(L.cwd)||K.resolve(L.cwd)!==J)throw Error(`Session creation record cwd mismatch: ${q}`)}static resolveForkWorkspace($){if(!K.isAbsolute($))throw Error("Fork workspace paths must be absolute");return K.resolve($)}static parseStoredSession($,q){return Yq($,`session ${q}`)}static isCorruptSessionJSONLError($){return $ instanceof Error&&$.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError($,q){if(!this.isCorruptSessionJSONLError($)||!($ instanceof Error))return $;let J=$.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${q}${J?` at line ${J}`:""}`,{cause:$.cause})}static async readStableSessionSnapshot($,q,J=3){for(let L=0;L<J;L+=1){let G=await R0.stat($),Z=await R0.readFile($),Q=this.parseStoredSession(Z,q),V=await R0.stat($);if(G.size===V.size&&G.mtimeNs===V.mtimeNs&&G.dev===V.dev&&G.ino===V.ino)return Q}throw Error("Session changed while creating fork; retry the operation")}}function Zq($){if($.length===1&&$[0]?.type==="text")return $[0].text;return[...$]}
118
+ export{F$ as Ub,o$ as Vb,A0 as Wb,t$ as Xb,W4 as Yb,i as Zb,d as _b,bq as $b,L1 as ac,s as bc,z4 as cc,M4 as dc,K1 as ec,x4 as fc,y0 as gc,b4 as hc,X$ as ic,O1 as jc,F1 as kc,S4 as lc,y4 as mc,j4 as nc,rq as oc,f1 as pc,T1 as qc,tq as rc,m4 as sc,D1 as tc,_$ as uc,o as vc,v0 as wc,a4 as xc,s4 as yc,e4 as zc,$8 as Ac,x1 as Bc,q8 as Cc,L8 as Dc,E1 as Ec,G8 as Fc,T$ as Gc,D$ as Hc,H8 as Ic,B8 as Jc,I1 as Kc,u0 as Lc,U8 as Mc,r1 as Nc,c1 as Oc,D8 as Pc,t1 as Qc,z8 as Rc,v2 as Sc,$5 as Tc,q5 as Uc,Oq as Vc,C0 as Wc,n as Xc,R as Yc};
@@ -0,0 +1 @@
1
+ import{Gh as a,Hh as b,Ih as c,Jh as d,Kh as e,Lh as f}from"./chunk-fs9j9gas.js";import"./chunk-6jsmac0q.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1,2 +1,2 @@
1
1
  import{clampThinkingLevel as t,getSupportedThinkingLevels as i}from"@earendil-works/pi-ai";var f=["auto","off","minimal","low","medium","high","xhigh","max"];function s(e){return typeof e==="string"&&f.includes(e)}function g(e,o){let n=i(e);if(o!=="auto"&&!n.includes(o))throw Error(`Reasoning effort ${o} is not supported by ${e.name}`);return{selection:o,effective:o==="auto"?t(e,"high"):o,supported:n}}
2
- export{s as te,g as ue};
2
+ export{s as we,g as xe};
@@ -0,0 +1 @@
1
+ import{wd as a,xd as b,yd as c}from"./chunk-mgtcjwhy.js";import"./chunk-fv8b98tz.js";import"./chunk-q14mgye7.js";import"./chunk-v508x7cg.js";import"./chunk-g9xjcfrf.js";import"./chunk-7rfhmbqw.js";import"./chunk-t6phsb5h.js";import"./chunk-7m5q8vxf.js";import"./chunk-sk8h4m9m.js";import"./chunk-hg8d4vhj.js";import"./chunk-sb84vdcf.js";import"./chunk-hjr9r44k.js";import"./chunk-ffa6hhee.js";import"./chunk-t1633e8m.js";import"./chunk-m5f934fh.js";import"./chunk-fs9j9gas.js";import"./chunk-rwvaapta.js";import"./chunk-83caxxbt.js";import"./chunk-shr5cg46.js";import"./chunk-6jsmac0q.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};