blade-code 0.10.63 → 0.10.65

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 (106) hide show
  1. package/dist/blade.js +2 -2
  2. package/dist/{chunk-kxrss9sv.js → chunk-015t2dey.js} +1 -1
  3. package/dist/chunk-0h74p1h8.js +1 -0
  4. package/dist/chunk-18nkg8hr.js +1 -0
  5. package/dist/chunk-197qz36b.js +1 -0
  6. package/dist/{chunk-khkhsaan.js → chunk-1jm8njkw.js} +1 -1
  7. package/dist/{chunk-y8r2knxm.js → chunk-1vt7e9e7.js} +2 -2
  8. package/dist/chunk-2vdq0fav.js +1 -0
  9. package/dist/{chunk-87jz5600.js → chunk-2yxdneb9.js} +1 -1
  10. package/dist/chunk-4a75gwa1.js +1 -0
  11. package/dist/{chunk-rwy763tf.js → chunk-4t89y8nj.js} +1 -1
  12. package/dist/{chunk-jk8bqc5b.js → chunk-53tb8vvv.js} +2 -2
  13. package/dist/{chunk-6x1g554w.js → chunk-57gp2px5.js} +1 -1
  14. package/dist/{chunk-3tednchw.js → chunk-5gjqdbxb.js} +2 -2
  15. package/dist/{chunk-69rc9hw6.js → chunk-5ha0vf37.js} +1 -1
  16. package/dist/{chunk-w4sp56dn.js → chunk-5ntrhs8k.js} +1 -1
  17. package/dist/{chunk-6rg6mngq.js → chunk-5qaacj3x.js} +1 -1
  18. package/dist/{chunk-cz68x56m.js → chunk-6tacv9rs.js} +2 -2
  19. package/dist/chunk-76ks3ygm.js +10 -0
  20. package/dist/{chunk-ej6h16ae.js → chunk-793067rd.js} +2 -2
  21. package/dist/{chunk-7b467h8k.js → chunk-7mdbwjxj.js} +1 -1
  22. package/dist/chunk-8wvk5rgg.js +1 -0
  23. package/dist/{chunk-xsx1av03.js → chunk-98qmtexa.js} +34 -34
  24. package/dist/{chunk-cr154zrx.js → chunk-98vestg4.js} +1 -1
  25. package/dist/{chunk-cq77ah56.js → chunk-9ebwtazz.js} +1 -1
  26. package/dist/{chunk-94d8hhqc.js → chunk-9yvw5xy3.js} +2 -2
  27. package/dist/{chunk-6g3qzz9h.js → chunk-a1m7wr7r.js} +1 -1
  28. package/dist/chunk-a49dy92d.js +140 -0
  29. package/dist/{chunk-cm9mph7j.js → chunk-aphcj8rz.js} +1 -1
  30. package/dist/{chunk-av10vmxk.js → chunk-arzhhj0e.js} +1 -1
  31. package/dist/chunk-b7p7ywe6.js +1 -0
  32. package/dist/{chunk-2xbmkyb2.js → chunk-bnp9asmd.js} +1 -1
  33. package/dist/{chunk-b19f55s7.js → chunk-ca5mm1gk.js} +1 -1
  34. package/dist/chunk-cxc2q3yy.js +1 -0
  35. package/dist/{chunk-wy4pn9sk.js → chunk-czb954vz.js} +1 -1
  36. package/dist/{chunk-kjvntyr5.js → chunk-d39xaa7w.js} +1 -1
  37. package/dist/{chunk-atqnan6x.js → chunk-e11kmyt3.js} +1 -1
  38. package/dist/{chunk-9r0yebs1.js → chunk-edd8n5r0.js} +1 -1
  39. package/dist/{chunk-2z3xe3rw.js → chunk-eg5mh9m9.js} +1 -1
  40. package/dist/{chunk-1jc7d3nt.js → chunk-eharmsjt.js} +2 -2
  41. package/dist/{chunk-9rjaem5f.js → chunk-ejsggxs4.js} +2 -2
  42. package/dist/chunk-fv3aggr5.js +1 -0
  43. package/dist/chunk-fz60jh3y.js +2 -0
  44. package/dist/{chunk-fp1h8wdh.js → chunk-gafk33py.js} +1 -1
  45. package/dist/{chunk-0jxh2zq5.js → chunk-h127mgg2.js} +2 -2
  46. package/dist/{chunk-detkh4dd.js → chunk-hbbpe5f0.js} +1 -1
  47. package/dist/{chunk-0ft3egjr.js → chunk-j6w1vf2q.js} +2 -2
  48. package/dist/{chunk-d1t91jgz.js → chunk-k4t45b64.js} +1 -1
  49. package/dist/{chunk-95hvy6dn.js → chunk-ka2kn5bs.js} +2 -2
  50. package/dist/chunk-ky32s7az.js +2 -0
  51. package/dist/chunk-m19xed90.js +1 -0
  52. package/dist/chunk-m6a1c1tg.js +8 -0
  53. package/dist/chunk-mr5c4yzr.js +1 -0
  54. package/dist/{chunk-8ekk8pa7.js → chunk-ngmajm4h.js} +1 -1
  55. package/dist/{chunk-8b1ehxzh.js → chunk-pfmmvpfh.js} +3 -3
  56. package/dist/chunk-pr8a6xfm.js +1 -0
  57. package/dist/chunk-pwehsv52.js +159 -0
  58. package/dist/{chunk-eeac8teg.js → chunk-r94jtbd2.js} +1 -1
  59. package/dist/{chunk-ng0tkmrn.js → chunk-rabt8yyf.js} +2 -2
  60. package/dist/{chunk-j8akkmc8.js → chunk-rd7jwwse.js} +1 -1
  61. package/dist/{chunk-1hb0rt7n.js → chunk-s16x4qkb.js} +1 -1
  62. package/dist/{chunk-83wm4akj.js → chunk-s1xp6g8m.js} +1 -1
  63. package/dist/{chunk-hpehkz2x.js → chunk-sbpb7pcc.js} +2 -2
  64. package/dist/{chunk-2xsrqsk9.js → chunk-svczh6hn.js} +2 -2
  65. package/dist/chunk-tb4jmrkp.js +2 -0
  66. package/dist/chunk-w4eskwzj.js +1 -0
  67. package/dist/{chunk-fp2fh7cn.js → chunk-wzkr0p09.js} +2 -2
  68. package/dist/{chunk-j9snkjpe.js → chunk-y51v2jvh.js} +2 -2
  69. package/dist/chunk-y8zk4r3y.js +1 -0
  70. package/dist/{chunk-k4ermznt.js → chunk-yrtmkb4a.js} +1 -1
  71. package/dist/{chunk-pdrqnywp.js → chunk-z228cmc5.js} +1 -1
  72. package/dist/{chunk-6fdvffcc.js → chunk-zpwasxzh.js} +2 -2
  73. package/dist/chunk-zxwdtn6q.js +112 -0
  74. package/dist/web/assets/{ChatView-B6IO9U-D.js → ChatView-Jfq-sqKG.js} +2 -2
  75. package/dist/web/assets/{CodeBlockHighlighter-DVGtFQgX.js → CodeBlockHighlighter-C9DvlG-V.js} +1 -1
  76. package/dist/web/assets/{FilePreview-C-8_o7yw.js → FilePreview-YPtQcXr3.js} +1 -1
  77. package/dist/web/assets/{MarkdownRenderer-D04IKQhF.js → MarkdownRenderer-CpUKw2Gk.js} +3 -3
  78. package/dist/web/assets/{SettingsModal-BMoZLVEe.js → SettingsModal-BfDHa4xn.js} +1 -1
  79. package/dist/web/assets/{TaskSwitcher-CIuCEbvU.js → TaskSwitcher-DacXxQcV.js} +1 -1
  80. package/dist/web/assets/{TerminalPanel-fTk9D5hU.js → TerminalPanel-CDq3_gCr.js} +1 -1
  81. package/dist/web/assets/index-t4mGaG1Z.js +11 -0
  82. package/dist/web/index.html +1 -1
  83. package/package.json +1 -1
  84. package/dist/chunk-0d1197b9.js +0 -1
  85. package/dist/chunk-2yws8pqt.js +0 -1
  86. package/dist/chunk-5sk6v1et.js +0 -10
  87. package/dist/chunk-86gc2mqb.js +0 -1
  88. package/dist/chunk-8an49nbn.js +0 -204
  89. package/dist/chunk-9c31jemm.js +0 -1
  90. package/dist/chunk-9kmtcgm6.js +0 -2
  91. package/dist/chunk-adz2756v.js +0 -111
  92. package/dist/chunk-cx05we7e.js +0 -1
  93. package/dist/chunk-dpzx4mgb.js +0 -1
  94. package/dist/chunk-dq9ya06q.js +0 -1
  95. package/dist/chunk-g0n88mhg.js +0 -1
  96. package/dist/chunk-m0t7g2vg.js +0 -1
  97. package/dist/chunk-nnbfk60b.js +0 -1
  98. package/dist/chunk-nnc1abkf.js +0 -1
  99. package/dist/chunk-q7pznpyh.js +0 -1
  100. package/dist/chunk-qs4erqd0.js +0 -2
  101. package/dist/chunk-tf4p1778.js +0 -1
  102. package/dist/chunk-ttkwrqtp.js +0 -2
  103. package/dist/chunk-vhckw5e7.js +0 -1
  104. package/dist/chunk-wwsg165p.js +0 -116
  105. package/dist/chunk-yagna3ws.js +0 -8
  106. package/dist/web/assets/index-CO5sUiJn.js +0 -11
@@ -1 +0,0 @@
1
- import{Rc as a,Sc as b,Tc as c,Uc as d,Vc as e,Wc as f,Xc as g,Yc as h}from"./chunk-wwsg165p.js";import"./chunk-y8r2knxm.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{d as syncSession,e as syncAll,h as searchProjectionText,c as resetProjectionDbCache,f as removeSessionFromProjection,g as rebuildProjectionIndex,b as getProjectionDb,a as getIndexDbPath};
@@ -1,2 +0,0 @@
1
- var _=20,T=5242880,A=32000;
2
- export{_ as eg,T as fg,A as gg};
@@ -1,111 +0,0 @@
1
- import{Hc as u,Ic as W$,Jc as Of,Kc as U$,Lc as I,Mc as _f,Nc as R$,Oc as Nf,Pc as Gf,Qc as xf,Sc as M0,Vc as Vf,Wc as D$}from"./chunk-wwsg165p.js";import{Yd as J0}from"./chunk-69rc9hw6.js";import{He as Z0}from"./chunk-detkh4dd.js";import{Te as rf}from"./chunk-87jz5600.js";import{eg as H$,fg as Y$}from"./chunk-9kmtcgm6.js";import{kg as Af}from"./chunk-kjvntyr5.js";import{Lg as U0}from"./chunk-y8r2knxm.js";import{Sg as x0,Vg as V0}from"./chunk-fp1h8wdh.js";import{Zg as p}from"./chunk-6fdvffcc.js";import{fh as K$,gh as q0,hh as X$,ih as A,jh as m,lh as N0,mh as l,nh as O0}from"./chunk-cz68x56m.js";import{readdir as Lf,readFile as a,rm as f0,stat as E0}from"node:fs/promises";import*as J from"node:path";import{nanoid as j}from"nanoid";import{createHash as j$,randomUUID as m$}from"node:crypto";import*as v from"node:fs/promises";import*as H0 from"node:path";import{execFileSync as E$}from"node:child_process";import{createHash as b$}from"node:crypto";import{readFileSync as k$}from"node:fs";var w$=/^[a-f0-9]{64}$/;function Yf(f){if(!f||typeof f!=="object")return!1;let $=f;return($.platform==="linux"||$.platform==="darwin"||$.platform==="win32")&&typeof $.fingerprint==="string"&&w$.test($.fingerprint)}var Wf={readFile:(f)=>k$(f,"utf8"),execFile:(f,$)=>E$(f,$,{encoding:"utf8",timeout:f==="powershell.exe"?3000:2000,windowsHide:!0})},y$=(f)=>{try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}};function u0(f,$){return{platform:f,fingerprint:b$("sha256").update(`${f}\x00${$}`).digest("hex")}}function S$(f,$){let T=$.readFile(`/proc/${f}/stat`).trim(),q=T.lastIndexOf(")");if(q<0)throw Error("Invalid /proc process stat");let L=T.slice(q+2).split(/\s+/)[19];if(!L||!/^\d+$/.test(L))throw Error("Missing process start ticks");return L}function K0(f,$=process.platform,T=Wf){if(!Number.isInteger(f)||f<=1)return;try{if($==="linux")return u0($,S$(f,T));if($==="darwin"){let q=T.execFile("ps",["-o","lstart=","-p",String(f)]).trim();return q?u0($,q):void 0}if($==="win32"){let q=`(Get-CimInstance Win32_Process -Filter "ProcessId = ${f}").CreationDate.ToUniversalTime().ToString('O')`,B=T.execFile("powershell.exe",["-NoProfile","-NonInteractive","-Command",q]).trim();return B?u0($,B):void 0}}catch{return}return}function Uf(f,$){return K0(f,$.platform)?.fingerprint===$.fingerprint}function tT(f,$,T=Wf,q=y$){if(!Number.isInteger(f)||f<=1)return!1;let B=K0(f,$.platform,T);if(B)return B.fingerprint===$.fingerprint;return!q(f)}var zf=1;function I$(f,$){let T=j$("sha256").update($).digest("hex");return H0.join(q0(f),".locks",`${T}.lock`)}function X0(f,$){return f instanceof Error&&"code"in f&&f.code===$}async function n0(f){try{let $=JSON.parse(await v.readFile(f,"utf8"));if($.version!==zf||typeof $.sessionId!=="string"||typeof $.ownerId!=="string"||!Number.isInteger($.pid)||($.pid??0)<=0||$.processIdentity!==void 0&&!Yf($.processIdentity)||typeof $.acquiredAt!=="string")return;return $}catch{return}}async function Rf(f){let $=await n0(f);if($)return $;return await new Promise((T)=>setTimeout(T,10)),n0(f)}function v$(f){try{return process.kill(f,0),!0}catch($){return X0($,"EPERM")}}async function Df(f,$){let T;try{return T=await v.open(f,"wx",384),await T.writeFile(`${JSON.stringify($)}
2
- `,"utf8"),!0}catch(q){if(X0(q,"EEXIST"))return!1;if(T)await v.unlink(f).catch(()=>{return});throw q}finally{await T?.close().catch(()=>{return})}}class P extends Error{code="BLADE_SESSION_IN_USE";constructor(f){super(f?`Session is already active in another Blade process (PID ${f}). 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 h{filePath;record;released=!1;constructor(f,$){this.filePath=f;this.record=$}static async acquire(f,$=Af()){let T=I$($,f),q={version:zf,sessionId:f,ownerId:m$(),pid:process.pid,processIdentity:K0(process.pid),acquiredAt:new Date().toISOString()};if(await v.mkdir(H0.dirname(T),{recursive:!0,mode:448}),await Df(T,q))return new h(T,q);let B=await Rf(T);if(B&&v$(B.pid)&&(!B.processIdentity||Uf(B.pid,B.processIdentity)))throw new P(B.pid);if(await v.unlink(T).catch((L)=>{if(!X0(L,"ENOENT"))throw L}),await Df(T,q))return new h(T,q);throw new P((await Rf(T))?.pid)}async release(){if(this.released)return;if(this.released=!0,(await n0(this.filePath))?.ownerId!==this.record.ownerId)return;await v.unlink(this.filePath).catch(($)=>{if(!X0($,"ENOENT"))throw $})}}var q1=1;function P0(f){return f!==null&&typeof f==="object"&&!Array.isArray(f)}function u$(f){if(!P0(f)||typeof f.type!=="string")return!1;if(f.type==="text")return typeof f.text==="string";return f.type==="image_url"&&P0(f.image_url)&&typeof f.image_url.url==="string"}function n$(f){if(!P0(f))return!1;if(!["system","user","assistant","tool"].includes(String(f.role)))return!1;return typeof f.content==="string"||Array.isArray(f.content)&&f.content.every(u$)}function gf(f){if(!Array.isArray(f)||f.length===0||f.length>4096)return;let $=JSON.stringify(f);if(Buffer.byteLength($)>16777216)return;let T=JSON.parse($);if(!Array.isArray(T)||!T.every(n$))return;return T}function L1(f){let $=gf(f);if(!$)throw Error("Compaction replacement context is invalid or exceeds limits");return $}function Mf(f){return gf(f)}function P$(f,$){for(let T of f){if(T.type!=="part_created"||T.data.partType!=="tool_result")continue;let q=T.data.payload;if(!q||typeof q!=="object"||Array.isArray(q))continue;let B=q;if(B.toolCallId===$||T.data.partId===$||T.data.messageId===$)return B}return}function Ef(f){let $=u(f),T=new Map;for(let q of $){if(q.type==="interaction_requested"){T.set(q.data.requestId,{request:q.data,hasToolResult:!1,hasRecoveryToolResult:!1});continue}if(q.type==="interaction_responded"){let B=T.get(q.data.requestId);if(B)B.response=q.data;continue}if(q.type==="interaction_recovered"){let B=T.get(q.data.requestId);if(B)B.recovery=q.data}}for(let q of T.values()){let B=P$($,q.request.toolCallId);q.hasToolResult=B!==void 0;let L=B?.metadata&&typeof B.metadata==="object"?B.metadata:void 0;q.hasRecoveryToolResult=L?.interactionRecovery===!0&&L.requestId===q.request.requestId}return[...T.values()]}function bf(f){return Ef(f).reverse().find(($)=>!$.response&&!$.recovery)}function O1(f){let $=new Map;for(let T of Ef(f))$.set(T.request.toolCallId,T);return[...$.values()].filter((T)=>T.response&&!T.recovery&&(!T.hasToolResult||T.hasRecoveryToolResult))}function kf(f){if(!f)return;return{type:f.request.interactionType,requestId:f.request.requestId}}function Y0(f){let $=new Map,T=[];for(let q of f){if(q.type==="review_started"){if(!$.has(q.data.reviewId))T.push(q.data.reviewId),$.set(q.data.reviewId,{start:q.data});continue}if(q.type!=="review_completed")continue;let B=$.get(q.data.reviewId);if(B&&B.completion===void 0)B.completion=q.data}return T.map((q)=>$.get(q)).filter((q)=>q!==void 0)}function N1(f){return Y0(f).reverse().find(($)=>$.completion===void 0)}function h0(f){switch(f){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 wf(f,$){let T=["## Code Review","",`Target: ${f.target.label}`,`Status: ${h0($.status)}`,"",$.overallExplanation||"No overall explanation was provided."];if($.findings.length===0)T.push("","No actionable findings.");else{T.push("","### Findings");for(let[q,B]of $.findings.entries()){let L=B.codeLocation.lineStart===B.codeLocation.lineEnd?`${B.codeLocation.lineStart}`:`${B.codeLocation.lineStart}-${B.codeLocation.lineEnd}`;T.push("",`${q+1}. ${B.title}`,` ${B.codeLocation.path}:L${L} · confidence ${B.confidenceScore.toFixed(2)}`,` ${B.body}`)}}if($.error)T.push("",`Error: ${$.error}`);return T.join(`
3
- `)}function yf(f,$){return{reviewId:f.reviewId,phase:"completed",status:$.status,target:{kind:f.target.kind,label:f.target.label,...f.target.baseSha?{reference:f.target.baseSha}:{},...f.target.commitSha?{reference:f.target.commitSha}:{}},overallExplanation:$.overallExplanation,findings:$.findings.map((T)=>({title:T.title,body:T.body,priority:T.priority,confidenceScore:T.confidenceScore,codeLocation:{...T.codeLocation}})),...$.error?{error:$.error}:{}}}var c0={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 h$(f){try{if(f instanceof Error)return f.message;if(f!==null&&typeof f==="object"&&"message"in f&&typeof f.message==="string")return f.message;return String(f)}catch{return"Unknown error"}}function c$(f){let $=f.toLowerCase();if(/\b(401|unauthorized|authentication|invalid (?:api[ _-]?)?key|api[ _-]?key|credential)\b/.test($))return"authentication";if(/\b(403|forbidden|permission denied|not permitted)\b/.test($))return"permission";if(/\b(429|rate limit|too many requests|quota)\b/.test($))return"rate_limit";if(/\b(timeout|timed out|deadline exceeded|etimedout)\b/.test($))return"timeout";if(/\b(econnreset|econnrefused|enotfound|network|socket|connection)\b/.test($))return"network";if(/\b(model not found|model unavailable|unsupported model|no such model)\b/.test($))return"model_unavailable";if(/\b(context (?:length|window)|maximum context|too many tokens|token limit)\b/.test($))return"context_limit";if(/\b(image|vision|multimodal|unsupported input|does not support)\b/.test($))return"unsupported_input";if(/\btask admission\b.*\b(capacity|queue)\b/.test($))return"capacity";return"runtime"}function l$(f){try{if(!f||typeof f!=="object"||!("name"in f)||f.name!=="TaskAdmissionQueueFullError"&&f.name!=="SessionRuntimeCapacityError"||!("resource"in f))return;return f.resource==="pending_count"||f.resource==="pending_bytes"||f.resource==="resident_runtimes"?f.resource:void 0}catch{return}}function Sf(f){return{code:f,...c0[f]}}function l0(f){let $=l$(f);if($)return{...Sf("capacity"),resource:$};return Sf(c$(h$(f)))}function p0(f){if(!f||typeof f!=="object")return!1;let $=f;if(typeof $.code!=="string"||!($.code in c0))return!1;let T=c0[$.code],q=$.resource===void 0||$.resource==="pending_count"||$.resource==="pending_bytes"||$.resource==="resident_runtimes";return $.message===T.message&&$.retryable===T.retryable&&q&&($.code==="capacity"||$.resource===void 0)}import{promises as L0,realpathSync as i$}from"node:fs";import W0 from"node:path";import*as r from"fs/promises";import*as H from"path";var jf=[".git",".claude","node_modules",".env",".env.local",".env.production",".env.development",".env.test"];class d extends Error{code;constructor(f,$){super(f);this.code=$;this.name="PathSecurityError"}}class i0{static normalize(f,$){let T=H.isAbsolute(f)?f:H.resolve($,f),q=H.normalize(T),B=H.normalize($);if(!this.isWithinWorkspace(q,B))throw new d(`Path outside workspace: ${f} (resolved to ${q}, workspace: ${B})`,"PATH_OUTSIDE_WORKSPACE");return q}static checkRestricted(f){let $=f.split(H.sep);for(let T of jf)if($.includes(T))throw new d(`Access denied: "${T}" is a protected directory`,"RESTRICTED_PATH")}static checkTraversal(f){if(f.includes(".."))throw new d(`Path traversal not allowed: ${f}`,"PATH_TRAVERSAL")}static async validatePath(f,$){this.checkTraversal(f);let T=this.normalize(f,$);this.checkRestricted(T);try{await r.access(T)}catch(q){throw new d(`Path not found: ${f}`,"PATH_NOT_FOUND")}return T}static async resolveSymlink(f,$){try{let T=await r.realpath(f),q=await r.realpath($);if(!this.isWithinWorkspace(T,q))throw new d(`Symlink points outside workspace: ${f} -> ${T}`,"SYMLINK_OUTSIDE_WORKSPACE");return T}catch(T){if(T instanceof d)throw T;return f}}static getRelativePath(f,$){return H.relative($,f)}static isWithinWorkspace(f,$){let T=H.resolve(f),q=H.resolve($),B=H.relative(q,T);return B===""||B!==".."&&!B.startsWith(`..${H.sep}`)&&!H.isAbsolute(B)}static async isWithinWorkspaceResolved(f,$){let T=H.resolve($),q=H.isAbsolute(f)?H.resolve(f):H.resolve(T,f);if(!this.isWithinWorkspace(q,T))return!1;let B;try{B=await r.realpath(T)}catch{return!1}let L=q;while(!0){try{let O=await r.realpath(L);return this.isWithinWorkspace(O,B)}catch(O){let G=O.code;if(G!=="ENOENT"&&G!=="ENOTDIR")return!1}let C=H.dirname(L);if(C===L)return!1;L=C}}static isRestricted(f){let $=f.split(H.sep);return jf.some((T)=>$.includes(T))}}var B0=U0("Tool");class c{static instance=null;accessedFiles=new Map;pathAliases=new Map;constructor(){}static getInstance(){if(!c.instance)c.instance=new c;return c.instance}async recordFileRead(f,$){try{let T=await L0.stat(f),q={filePath:W0.resolve(f),accessTime:Date.now(),mtime:T.mtimeMs,sessionId:$,lastOperation:"read"};this.setRecord(q),await this.recordAliases(f,q.filePath),B0.debug(`记录文件读取: ${f}`)}catch(T){B0.warn(`记录文件读取失败: ${f}`,T)}}async recordFileEdit(f,$,T="edit"){try{let q=await L0.stat(f),B={filePath:W0.resolve(f),accessTime:Date.now(),mtime:q.mtimeMs,sessionId:$,lastOperation:T};this.setRecord(B),await this.recordAliases(f,B.filePath),B0.debug(`记录文件${T==="edit"?"编辑":"写入"}: ${f}`)}catch(q){B0.warn(`记录文件${T==="edit"?"编辑":"写入"}失败: ${f}`,q)}}hasFileBeenRead(f,$){let T=this.accessedFiles.get(this.resolveTrackedPath(f));if(!T)return!1;return $?T.has($):T.size>0}async checkFileModification(f,$){let T=this.getFileRecord(f,$);if(!T)return{modified:!1,message:"文件未被跟踪"};try{let q=await L0.stat(f);if(Math.abs(q.mtimeMs-T.mtime)>1)return{modified:!0,message:`文件在访问后被修改(访问时间: ${new Date(T.accessTime).toISOString()}, 当前修改时间: ${q.mtime.toISOString()})`};return{modified:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{modified:!0,message:"文件已被删除"};return{modified:!1,message:`无法检查文件状态: ${B.message}`}}}async checkExternalModification(f,$){let T=this.getFileRecord(f,$);if(!T)return{isExternal:!1,message:"文件未被跟踪"};try{let q=await L0.stat(f);if(q.mtimeMs-T.mtime>2000)return{isExternal:!0,message:`文件在 ${new Date(T.accessTime).toISOString()} (${T.lastOperation}) 之后被外部程序修改(当前修改时间: ${q.mtime.toISOString()})`};return{isExternal:!1}}catch(q){let B=q;if(B.code==="ENOENT")return{isExternal:!0,message:"文件已被删除"};return B0.warn(`检查文件外部修改失败: ${f}`,q),{isExternal:!1,message:`无法检查文件状态: ${B.message}`}}}getFileRecord(f,$){let T=this.accessedFiles.get(this.resolveTrackedPath(f));if(!T)return;if($)return T.get($);return[...T.values()].sort((q,B)=>B.accessTime-q.accessTime)[0]}getTrackedRecords(){return[...this.accessedFiles.values()].flatMap((f)=>[...f.values()])}clearFileRecord(f,$){let T=this.resolveTrackedPath(f);if(!$){this.accessedFiles.delete(T),this.removeAliases(T);return}let q=this.accessedFiles.get(T);if(q?.delete($),q?.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}clearAll(){this.accessedFiles.clear(),this.pathAliases.clear()}clearSession(f,$){for(let[T,q]of this.accessedFiles.entries()){if($&&!i0.isWithinWorkspace(T,$))continue;if(q.delete(f),q.size===0)this.accessedFiles.delete(T),this.removeAliases(T)}}getTrackedFiles(){return Array.from(this.accessedFiles.keys())}getTrackedFileCount(){return this.accessedFiles.size}static resetInstance(){c.instance=null}setRecord(f){let $=this.accessedFiles.get(f.filePath);if(!$)$=new Map,this.accessedFiles.set(f.filePath,$);$.set(f.sessionId,f)}async recordAliases(f,$){this.pathAliases.set(W0.resolve(f),$);let T=await L0.realpath(f).catch(()=>{return});if(T)this.pathAliases.set(T,$)}resolveTrackedPath(f){let $=W0.resolve(f);if(this.accessedFiles.has($))return $;let T=this.pathAliases.get($);if(T)return T;try{let q=i$.native($);return this.pathAliases.get(q)??q}catch{return $}}removeAliases(f){for(let[$,T]of this.pathAliases)if(T===f)this.pathAliases.delete($)}}import*as C0 from"node:crypto";import{promises as F}from"node:fs";import*as K from"node:path";import d0 from"write-file-atomic";var mf="missing";class R0{sessionId;workspaceRoot;enableCheckpoints;maxSnapshots;snapshotDir;manifestPath;trackedFileBackups=new Map;snapshots=[];constructor(f){if(A(f.sessionId),this.sessionId=f.sessionId,f.workspaceRoot&&!K.isAbsolute(f.workspaceRoot))throw Error("Snapshot workspace root must be absolute");this.workspaceRoot=f.workspaceRoot?K.resolve(f.workspaceRoot):void 0,this.enableCheckpoints=f.enableCheckpoints??!0,this.maxSnapshots=f.maxSnapshots??10;let $=O0();this.snapshotDir=K.join($,"file-history",this.sessionId),this.manifestPath=K.join(this.snapshotDir,"manifest.json")}async initialize(){if(!this.enableCheckpoints)return;if(this.workspaceRoot)await this.selectWorkspaceSnapshotDir();await F.mkdir(this.snapshotDir,{recursive:!0,mode:493}),await this.loadManifest()}async selectWorkspaceSnapshotDir(){let f=O0(),$=await F.realpath(this.workspaceRoot).catch(()=>this.workspaceRoot),T=C0.createHash("sha256").update($).digest("hex").slice(0,24),q=K.join(f,"file-history",this.sessionId),B=K.join(f,"file-history","workspaces",T,this.sessionId),L=K.join(B,"manifest.json");try{await F.access(L)}catch{await this.migrateLegacySnapshotDir(q,B,$)}this.snapshotDir=B,this.manifestPath=L}async migrateLegacySnapshotDir(f,$,T){let q;try{q=JSON.parse(await F.readFile(K.join(f,"manifest.json"),"utf8"))}catch{return}if(q.schemaVersion!==1||!Array.isArray(q.snapshots)||!q.snapshots.every((B)=>this.isWithinWorkspace(B.filePath,T)))return;await F.mkdir(K.dirname($),{recursive:!0,mode:493});try{await F.rename(f,$)}catch(B){let L=B.code;if(L!=="ENOENT"&&L!=="EEXIST"&&L!=="ENOTEMPTY")throw B}}isWithinWorkspace(f,$){if(!K.isAbsolute(f))return!1;let T=K.relative($,K.resolve(f));return T===""||T!==".."&&!T.startsWith(`..${K.sep}`)&&!K.isAbsolute(T)}async createSnapshot(f,$){if(!this.enableCheckpoints)return{backupFileName:"",version:0,backupTime:new Date};let T=await this.resolveFileIdentity(f),q=!0;try{await F.access(T)}catch{q=!1}let B=this.trackedFileBackups.get(T),L=B?B.version+1:1,C=this.generateFileHash(T,L),O=this.getSnapshotPath(C,L),G=new Date;if(q){let N=await F.readFile(T);await F.writeFile(O,N)}let _={backupFileName:C,version:L,backupTime:G};return this.trackedFileBackups.set(T,_),this.snapshots.push({messageId:$,backupFileName:C,timestamp:G,filePath:T,version:L,existedBefore:q}),await this.cleanupOldSnapshots(T),await this.persistManifest(),_}async recordPostEditState(f,$){if(!this.enableCheckpoints||!$.backupFileName)return;let T=await this.resolveFileIdentity(f),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===$.backupFileName&&B.version===$.version);if(!q)throw Error(`未找到待完成的快照: ${T}`);q.postEditHash=await this.hashFile(T),await this.persistManifest()}async discardSnapshot(f,$){if(!this.enableCheckpoints||!$.backupFileName)return;let T=await this.resolveFileIdentity(f),q=this.snapshots.find((B)=>B.filePath===T&&B.backupFileName===$.backupFileName&&B.version===$.version);if(!q)return;this.removeSnapshot(q),await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),await this.persistManifest()}async rewindLatest(f){let $=await this.resolveFileIdentity(f),T=this.snapshots.slice().reverse().find((L)=>L.filePath===$&&L.postEditHash!==void 0);if(!T?.postEditHash)throw Error(`未找到可回退快照: ${$}`);if(await this.hashFile($)!==T.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${$}`);let B=this.getSnapshotPath(T.backupFileName,T.version);if(T.existedBefore){let L=await F.readFile(B);await F.mkdir(K.dirname($),{recursive:!0}),await F.writeFile($,L)}else await F.rm($,{force:!0});return this.removeSnapshot(T),await F.rm(B,{force:!0}),await this.persistManifest(),T}async restoreSnapshot(f,$){let T=await this.resolveFileIdentity(f),q=this.snapshots.slice().reverse().find((L)=>L.messageId===$&&L.filePath===T);if(!q)throw Error(`未找到快照: messageId=${$}, filePath=${T}`);let B=this.getSnapshotPath(q.backupFileName,q.version);if(q.existedBefore){let L=await F.readFile(B);await F.mkdir(K.dirname(T),{recursive:!0}),await F.writeFile(T,L)}else await F.rm(T,{force:!0})}async listSnapshots(f){let $=await this.resolveFileIdentity(f);return this.snapshots.filter((T)=>T.filePath===$)}async listAllSnapshots(){return this.snapshots.filter((f)=>f.postEditHash!==void 0)}async previewRewind(f){let $=this.buildRewindPlan(f);return{files:$.map((T)=>T.filePath),snapshotCount:$.reduce((T,q)=>T+q.selected.length,0)}}async rewindSnapshots(f){let $=this.buildRewindPlan(f);if($.length===0)return{files:[],snapshotCount:0};let T=new Map;for(let B of $){let L,C=!0;try{L=await F.readFile(B.filePath)}catch(G){if(G.code!=="ENOENT")throw G;C=!1}if((L?C0.createHash("sha256").update(L).digest("hex"):mf)!==B.latest.postEditHash)throw Error(`文件在 Blade 编辑后已被修改,拒绝覆盖: ${B.filePath}`);if(T.set(B.filePath,{existed:C,content:L}),B.target.existedBefore)await F.access(this.getSnapshotPath(B.target.backupFileName,B.target.version))}let q=[...this.snapshots];try{for(let L of $)if(L.target.existedBefore){let C=await F.readFile(this.getSnapshotPath(L.target.backupFileName,L.target.version));await F.mkdir(K.dirname(L.filePath),{recursive:!0}),await d0(L.filePath,C)}else await F.rm(L.filePath,{force:!0});let B=new Set($.flatMap((L)=>L.selected));this.snapshots=this.snapshots.filter((L)=>!B.has(L)),this.rebuildTrackedFileBackups(),await this.persistManifest(),await Promise.all([...B].map((L)=>F.rm(this.getSnapshotPath(L.backupFileName,L.version),{force:!0}).catch(()=>{return})))}catch(B){this.snapshots=q,this.rebuildTrackedFileBackups();let L=[];for(let[C,O]of T)try{if(O.existed&&O.content)await d0(C,O.content);else await F.rm(C,{force:!0})}catch(G){L.push(G)}if(L.length>0)throw AggregateError([B,...L],"快照回退失败且无法完整恢复回退前状态");throw B}return{files:$.map((B)=>B.filePath),snapshotCount:$.reduce((B,L)=>B+L.selected.length,0)}}async commitSnapshots(f){let $=this.buildRewindPlan(f),T=new Set($.flatMap((B)=>B.selected));if(T.size===0)return{files:[],snapshotCount:0};let q=[...this.snapshots];this.snapshots=this.snapshots.filter((B)=>!T.has(B)),this.rebuildTrackedFileBackups();try{await this.persistManifest()}catch(B){throw this.snapshots=q,this.rebuildTrackedFileBackups(),B}return await Promise.all([...T].map((B)=>F.rm(this.getSnapshotPath(B.backupFileName,B.version),{force:!0}).catch(()=>{return}))),{files:$.map((B)=>B.filePath),snapshotCount:T.size}}buildRewindPlan(f){let $=new Set(f),T=this.snapshots.filter((L)=>L.postEditHash!==void 0),q=T.filter((L)=>$.has(L.messageId));return[...new Set(q.map((L)=>L.filePath))].sort().map((L)=>{let C=T.filter((N)=>N.filePath===L),O=C.filter((N)=>$.has(N.messageId)),G=C.indexOf(O[0]),_=C.slice(G);if(_.length!==O.length||_.some((N)=>!$.has(N.messageId)))throw Error(`请求的快照不是文件历史的连续后缀: ${L}`);return{filePath:L,selected:O,target:O[0],latest:O.at(-1)}})}async loadManifest(){try{let f=await F.readFile(this.manifestPath,"utf-8"),$=JSON.parse(f);if($.schemaVersion!==1||!Array.isArray($.snapshots))throw Error("Unsupported snapshot manifest");this.snapshots=await Promise.all($.snapshots.map(async(T)=>({...T,filePath:await this.resolveFileIdentity(T.filePath),timestamp:new Date(T.timestamp)}))),this.rebuildTrackedFileBackups()}catch(f){if(f.code!=="ENOENT")throw f;this.snapshots=[],this.trackedFileBackups.clear()}}async persistManifest(){if(this.snapshots.length===0){await F.rm(this.manifestPath,{force:!0});return}let f={schemaVersion:1,snapshots:this.snapshots.map(($)=>({...$,timestamp:$.timestamp.toISOString()}))};await d0(this.manifestPath,JSON.stringify(f,null,2),{encoding:"utf-8",mode:384})}async cleanupOldSnapshots(f){let T=this.snapshots.filter((q)=>q.filePath===f).slice(0,-this.maxSnapshots);for(let q of T)await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0}),this.removeSnapshot(q)}async cleanup(f=0){let $=this.snapshots.slice().sort((q,B)=>B.timestamp.getTime()-q.timestamp.getTime()),T=new Set($.slice(0,f));for(let q of this.snapshots)if(!T.has(q))await F.rm(this.getSnapshotPath(q.backupFileName,q.version),{force:!0});this.snapshots=$.slice(0,f).reverse(),this.rebuildTrackedFileBackups(),await this.persistManifest()}getSnapshotPath(f,$){return K.join(this.snapshotDir,`${f}@v${$}`)}async resolveFileIdentity(f){let $=K.resolve(f),T=[],q=$;while(!0){try{let L=await F.realpath(q);return K.join(L,...T.reverse())}catch(L){let C=L.code;if(C!=="ENOENT"&&C!=="ENOTDIR")throw L}let B=K.dirname(q);if(B===q)return $;T.push(K.basename(q)),q=B}}async hashFile(f){try{let $=await F.readFile(f);return C0.createHash("sha256").update($).digest("hex")}catch($){if($.code==="ENOENT")return mf;throw $}}removeSnapshot(f){let $=this.snapshots.indexOf(f);if($>=0)this.snapshots.splice($,1);this.rebuildTrackedFileBackups()}rebuildTrackedFileBackups(){this.trackedFileBackups.clear();for(let f of this.snapshots){let $=this.trackedFileBackups.get(f.filePath);if(!$||$.version<f.version)this.trackedFileBackups.set(f.filePath,{backupFileName:f.backupFileName,version:f.version,backupTime:f.timestamp})}}generateFileHash(f,$){let T=C0.createHash("md5");return T.update(`${f}:${$}`),T.digest("hex").substring(0,16)}getSnapshotDir(){return this.snapshotDir}getSessionId(){return this.sessionId}getTrackedFileCount(){return this.trackedFileBackups.size}getSnapshotCount(){return this.snapshots.length}}var D1=1200,A1=2000,z1=2000,g1=2000;function vf(f){return typeof f==="object"&&f!==null&&!Array.isArray(f)}function d$(f){if(typeof f==="string"&&f.length>0)return f;if(vf(f)&&typeof f.message==="string")return f.message;return}function r$(f,$){if(f===null||f===void 0)return $??"";if(typeof f==="string")return f;if(typeof f==="object")return f;return String(f)}function uf(f){let $=f.error!==null&&f.error!==void 0,T=$?d$(f.error)??"Tool execution failed":void 0,q=vf(f.metadata)?f.metadata:void 0;return{success:!$,llmContent:r$(f.output,T),...T?{error:{type:"execution_error",message:T}}:{},...q?{metadata:q}:{}}}function o0(f,$){if(f.length<=$)return f;let T=Math.max(0,$);if(T>0&&T<f.length&&/[\uD800-\uDBFF]/.test(f.charAt(T-1)))T-=1;return f.slice(0,T)}function If(f,$){if(f.length<=$)return f;let T=Math.max(0,f.length-$);if(T<f.length&&/[\uDC00-\uDFFF]/.test(f.charAt(T)))T+=1;return f.slice(T)}function r0(f,$){if(f.length<=$)return f;if($<=0)return"";let T=`
4
- ... (display clipped) ...
5
- `,q=f.indexOf(`
6
- `),B=q>=0&&/^(?:stdout|stderr):$/.test(f.slice(0,q))?`${f.slice(0,q)}
7
- `:"",L=B?f.slice(B.length):f,C=$-B.length-T.length;if(C<=0)return If(f,$);let O=Math.min(Math.floor(C/3),L.length),G=Math.max(0,C-O);return B+o0(L,O)+T+If(L,G)}function o$(f){let $=f.split(`
8
- `),T=$.at(-1);if(!T?.startsWith("Output truncated"))return{body:f};return{body:$.slice(0,-1).join(`
9
- `),suffix:T}}function t$(f){let T=f.indexOf(`
10
- stderr:
11
- `);if(!f.startsWith(`stdout:
12
- `)||T<0)return[f];return[f.slice(0,T),f.slice(T+1)]}function M1(f,$){if(!Number.isSafeInteger($)||$<=0)throw Error("maxChars must be a positive safe integer");if(!f.detail||f.detail.length<=$)return f;let{body:T,suffix:q}=o$(f.detail),B=q?`
13
- ${o0(q,$)}`:"",L=Math.max(0,$-B.length),C=t$(T),O;if(C.length===2){let N=Math.max(0,L-1),x=Math.floor(N/2),V=N-x;O=`${r0(C[0],x)}
14
- ${r0(C[1],V)}`}else O=r0(T,L);let G=o0(`${O}${B}`,$);return{...f,detail:G}}var b1={clientVisible:!1};function nf(f){if(f.metadata&&typeof f.metadata==="object"&&!Array.isArray(f.metadata)&&f.metadata.clientVisible===!1)return!1;return!(f.role==="user"&&typeof f.content==="string"&&f.content.startsWith("This turn made a non-trivial implementation. Before finishing, call Task ")&&f.content.endsWith("Only a fresh structured PASS verdict allows completion."))}import{createHash as _T}from"node:crypto";import af from"node:path";import{StringDecoder as e$}from"node:string_decoder";var w1=1048576;function t0(f,$){let T=$;while(T<f.length&&(f[T]&192)===128)T+=1;return T}class a0{maxBytes;chunks=[];retainedBytes=0;omittedBytes=0;totalBytes=0;constructor(f=1048576){this.maxBytes=f;if(!Number.isSafeInteger(f)||f<=0)throw Error("maxBytes must be a positive safe integer")}append(f){let $=Buffer.isBuffer(f)?f:Buffer.from(f);if($.length===0)return;if(this.totalBytes+=$.length,$.length>this.maxBytes){this.retainOversizedChunkTail($);return}this.chunks.push($),this.retainedBytes+=$.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 f=this.peek();return this.chunks.length=0,this.retainedBytes=0,this.omittedBytes=0,f}retainedChunkCountForTests(){return this.chunks.length}retainOversizedChunkTail(f){this.omittedBytes+=this.retainedBytes,this.chunks.length=0,this.retainedBytes=0;let $=t0(f,f.length-this.maxBytes);if(this.omittedBytes+=$,$===f.length)return;let T=Buffer.from(f.subarray($));this.chunks.push(T),this.retainedBytes=T.length}trimToLimit(){let f=!1;while(this.retainedBytes>this.maxBytes){let $=this.chunks[0];if(!$)return;let T=this.retainedBytes-this.maxBytes;if($.length<=T){this.chunks.shift(),this.retainedBytes-=$.length,this.omittedBytes+=$.length,f=!0;continue}let q=t0($,T);this.chunks[0]=$.subarray(q),this.retainedBytes-=q,this.omittedBytes+=q,f=!0}if(f)this.realignRetainedStart()}realignRetainedStart(){while(this.chunks.length>0){let f=this.chunks[0];if(f.length===0){this.chunks.shift();continue}let $=t0(f,0);if($===0)return;if(this.retainedBytes-=$,this.omittedBytes+=$,$===f.length)this.chunks.shift();else{this.chunks[0]=f.subarray($);return}}}compactChunks(){if(this.chunks.length<=32)return;let f=Buffer.concat(this.chunks,this.retainedBytes);if(this.chunks.length=0,f.length>0)this.chunks.push(f)}}var D0={maxLines:30,maxChars:3000,keepHead:10,keepTail:10,summarize:!0},o={maxLines:100,maxChars:1e4,keepHead:40,keepTail:40,summarize:!0},Pf={maxLines:200,maxChars:20000,keepHead:80,keepTail:80,summarize:!1},a$={maxLines:150,maxChars:15000,keepHead:50,keepTail:50,summarize:!0},s$=[{pattern:/^git\s+(rm|add)\s+(-r|--cached|-rf|-f)?\s*/i,config:D0,summaryTemplate:(f)=>`Successfully processed ${f} files`},{pattern:/^(npm|pnpm|yarn|bun)\s+(install|i|add|remove|uninstall)/i,config:D0,summaryTemplate:(f)=>`Package operation completed (${f} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(build|compile|bundle)/i,config:o,summaryTemplate:(f)=>`Build completed (${f} lines of output)`},{pattern:/^(npm|pnpm|yarn|bun)\s+(run|exec)\s+(test|lint|check)/i,config:Pf},{pattern:/^git\s+(status|branch|remote)/i,config:o},{pattern:/^git\s+(log|diff|show)/i,config:Pf},{pattern:/^(ls|dir|tree)\s+/i,config:o,summaryTemplate:(f)=>`Listed ${f} items`},{pattern:/^find\s+/i,config:o,summaryTemplate:(f)=>`Found ${f} matches`},{pattern:/^(grep|rg|ag)\s+/i,config:o,summaryTemplate:(f)=>`Found ${f} matching lines`},{pattern:/^(docker|podman)\s+(build|pull|push)/i,config:D0,summaryTemplate:(f)=>`Docker operation completed (${f} lines)`},{pattern:/^(pip|pip3|poetry|pipenv)\s+(install|uninstall)/i,config:D0,summaryTemplate:(f)=>`Python package operation completed (${f} lines)`},{pattern:/^(cargo|rustup)\s+(build|install|update)/i,config:o,summaryTemplate:(f)=>`Rust operation completed (${f} lines)`},{pattern:/^(go)\s+(build|get|mod)/i,config:o,summaryTemplate:(f)=>`Go operation completed (${f} lines)`}];function hf(f,$,T){let q=$,B=T??f.length;if(q>0){let L=f.charCodeAt(q);if(L>=56320&&L<=57343)q+=1}if(B<f.length){let L=f.charCodeAt(B-1);if(L>=55296&&L<=56319)B-=1}return f.slice(q,B)}class s0{static getConfigForCommand(f){for(let{pattern:$,config:T,summaryTemplate:q}of s$)if($.test(f))return{config:T,summaryTemplate:q};return{config:a$}}static truncate(f,$){let{config:T,summaryTemplate:q}=this.getConfigForCommand($);return this.truncateWithConfig(f,T,q)}static truncateWithConfig(f,$,T){let q=f.length,B=f.split(`
15
- `),L=B.length;if(L<=$.maxLines&&q<=$.maxChars)return{content:f,truncated:!1,originalLines:L,originalChars:q};let C=B.slice(0,$.keepHead),O=B.slice(-$.keepTail),G=L-$.keepHead-$.keepTail,_=C.join(`
16
- `);if(_+=`
17
-
18
- ... (${G} lines truncated, showing first ${$.keepHead} and last ${$.keepTail} of ${L} total) ...
19
-
20
- `,_+=O.join(`
21
- `),_.length>$.maxChars){let x=Math.floor($.maxChars/2)-50,V=hf(_,0,x),Z=hf(_,_.length-x);_=`${V}
22
-
23
- ... (content truncated to ${$.maxChars} chars) ...
24
-
25
- ${Z}`}let N=$.summarize&&T?T(L,q):void 0;if(N)_+=`
26
-
27
- [Summary: ${N}]`;return{content:_,truncated:!0,originalLines:L,originalChars:q,summary:N}}static truncateForLLM(f,$,T){let q=this.truncate(f,T),B=this.truncate($,T),L;if(q.truncated||B.truncated){let C=[];if(q.truncated)C.push(`stdout: ${q.originalLines} lines -> ${q.content.split(`
28
- `).length} lines`);if(B.truncated)C.push(`stderr: ${B.originalLines} lines -> ${B.content.split(`
29
- `).length} lines`);L=`Output truncated: ${C.join(", ")}`}return{stdout:q.content,stderr:B.content,truncationInfo:L}}static shouldTruncate(f,$){let{config:T}=this.getConfigForCommand($);return f.split(`
30
- `).length>T.maxLines||f.length>T.maxChars}static getStats(f){return{lines:f.split(`
31
- `).length,chars:f.length,words:f.split(/\s+/).filter(Boolean).length}}}var cf=32768,fT=1048576,$T=65536,TT=3600000,lf=4096,qT=/[\u001B\u009B][[\]()#;?]*(?:(?:(?:[a-zA-Z\d]*(?:;[-a-zA-Z\d/#&.:=?%@~_]+)*)?\u0007)|(?:(?:\d{1,4}(?:[;:]\d{0,4})*)?[\dA-PR-TZcf-nq-uy=><~]))/g;class e0{stream;executionId;onEvent;output=new a0(fT/2);decoder=new e$("utf8");sniffChunks=[];sniffBytes=0;binary=!1;totalBytes=0;streamedBytes=0;streamTruncated=!1;pendingEvents=[];constructor(f,$,T){this.stream=f;this.executionId=$;this.onEvent=T}append(f){let $=Buffer.isBuffer(f)?f:Buffer.from(f);if($.length===0)return;if(this.totalBytes+=$.length,this.sniffBytes<lf){let q=$.subarray(0,Math.min($.length,lf-this.sniffBytes));this.sniffChunks.push(q),this.sniffBytes+=q.length,this.binary=this.binary||Buffer.concat(this.sniffChunks).includes(0)}if(this.binary)return;let T=pf(this.decoder.write($));this.output.append(T),this.emit(T)}finish(){if(this.binary)return;let f=pf(this.decoder.end());this.output.append(f),this.emit(f)}snapshot(){let f=this.output.peek();if(this.binary)return{content:`[binary ${this.stream} omitted: ${this.totalBytes} bytes]`,omittedBytes:this.totalBytes,binary:!0};return{content:f.content,omittedBytes:f.omittedBytes,binary:!1}}async flushEvents(){await Promise.all(this.pendingEvents),this.pendingEvents.length=0}emit(f){if(!f||!this.onEvent||this.streamTruncated)return;let $=$T-this.streamedBytes;if($<=0){this.streamTruncated=!0;return}let T=LT(f,$);if(this.streamedBytes+=Buffer.byteLength(T),T.length<f.length)this.streamTruncated=!0;this.pendingEvents.push(Promise.resolve(this.onEvent({type:"output",executionId:this.executionId,stream:this.stream,chunk:T,streamedBytes:this.streamedBytes,streamTruncated:this.streamTruncated})).then(()=>{return}))}}function pf(f){return f.replace(qT,"")}function LT(f,$){let T=Buffer.from(f);if(T.length<=$)return f;let q=$;while(q>0&&(T[q]&192)===128)q-=1;return T.subarray(0,q).toString("utf8")}function df(f){return f.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function BT(f){let $=f.trim();if(!$)throw Error("User shell command cannot be empty");if($.length>cf)throw Error(`User shell command exceeds ${cf} characters`);if($.includes("\x00"))throw Error("User shell command contains a null byte");return $}function CT(){return{execute(f,$){return new Promise((T)=>{let q=process.platform==="win32"?process.env.COMSPEC||"cmd.exe":process.env.SHELL||"/bin/bash",B=process.platform==="win32"?["/d","/s","/c",f]:["-l","-c",f],{child:L,processTree:C}=rf(q,B,{cwd:$.cwd,env:$.env,stdio:["ignore","pipe","pipe"]}),O="",G="",_=!1,N=!1,x=!1,V,Z=()=>{return V??=C.terminate(),V},E=setTimeout(()=>{_=!0,Z()},$.timeoutMs),g=()=>{N=!0,Z()};if($.signal.addEventListener("abort",g,{once:!0}),$.signal.aborted)g();L.stdout?.on("data",(W)=>{$.onOutput?.("stdout",W)}),L.stderr?.on("data",(W)=>{$.onOutput?.("stderr",W)});let b=async(W)=>{if(x)return;if(x=!0,clearTimeout(E),$.signal.removeEventListener("abort",g),_||N)await Z();T({...W,stdout:"",stderr:"",timedOut:_,aborted:N})};L.once("error",(W)=>{b({exitCode:null,error:W.message})}),L.once("close",(W)=>{b({exitCode:W})})})}}}async function u1(f,$){let T=BT(f),q=$.timeoutMs??TT,B=new e0("stdout",$.executionId,$.onEvent),L=new e0("stderr",$.executionId,$.onEvent),C=Date.now();await $.onEvent?.({type:"started",executionId:$.executionId,command:T});let O,G=!1,_=!1;try{O=await($.executor??CT()).execute(T,{cwd:$.cwd,env:$.env,timeoutMs:q,signal:$.signal,onOutput:(g,b)=>{if(g==="stdout")G=!0;else _=!0;(g==="stdout"?B:L).append(b)}})}catch(g){O={exitCode:null,stdout:"",stderr:"",error:g instanceof Error?g.message:String(g)}}if(!G)B.append(O.stdout);if(!_)L.append(O.stderr);B.finish(),L.finish(),await Promise.all([B.flushEvents(),L.flushEvents()]);let N=B.snapshot(),x=L.snapshot(),V=s0.truncateForLLM(N.content.trim(),x.content.trim(),T),Z=O.aborted||$.signal.aborted?"aborted":O.timedOut?"timed_out":O.error?"spawn_error":O.exitCode===0?"completed":"failed",E={version:1,command:T,status:Z,exitCode:O.exitCode,durationMs:Math.max(0,Date.now()-C),stdout:V.stdout,stderr:O.error?[V.stderr,O.error].filter(Boolean).join(`
32
- `):V.stderr,stdoutOmittedBytes:N.omittedBytes,stderrOmittedBytes:x.omittedBytes,binaryOutput:N.binary||x.binary,truncated:Boolean(V.truncationInfo)||N.omittedBytes>0||x.omittedBytes>0};return await $.onEvent?.({type:"completed",executionId:$.executionId,record:E}),E}function n1(f){let $=[f.stdout?`stdout:
33
- ${f.stdout}`:"",f.stderr?`stderr:
34
- ${f.stderr}`:""].filter(Boolean).join(`
35
- `);return["<user_shell_command>",`<command>${df(f.command)}</command>`,"<result>",`Status: ${f.status}`,`Exit code: ${f.exitCode??"null"}`,`Duration: ${(f.durationMs/1000).toFixed(3)} seconds`,`Output:
36
- ${df($||"(no output)")}`,"</result>","</user_shell_command>"].join(`
37
- `)}function of(f){let $=[f.stdout,f.stderr?`stderr:
38
- ${f.stderr}`:""].filter(Boolean).join(`
39
- `);return[`! ${f.command}`,$||"(no output)"].join(`
40
- `)}function OT(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if($.version!==1||typeof $.command!=="string"||!["completed","failed","aborted","timed_out","spawn_error"].includes(String($.status))||$.exitCode!==null&&typeof $.exitCode!=="number"||typeof $.durationMs!=="number"||typeof $.stdout!=="string"||typeof $.stderr!=="string"||typeof $.stdoutOmittedBytes!=="number"||typeof $.stderrOmittedBytes!=="number"||typeof $.binaryOutput!=="boolean"||typeof $.truncated!=="boolean")return;return $}function A0(f){if(!f||typeof f!=="object"||Array.isArray(f))return;return OT(f.userShellCommand)}var z0=16777216,tf=65536,i1=1048576,NT=8,g0=200,GT=/(?:^|[_-])(?:api[_-]?key|authorization|bearer|cookie|credential|password|passwd|private[_-]?key|refresh[_-]?token|secret|session[_-]?token|token)(?:$|[_-])/i,xT=/(?<![:/A-Za-z0-9._-])\/[^\s"'`<>]+/g,VT=/(?<![A-Za-z0-9._-])[A-Za-z]:[\\/][^\s"'`<>]+/g,JT=new RegExp("\\u001b(?:\\[[0-?]*[ -/]*[@-~]|\\][^\\u0007]*(?:\\u0007|\\u001b\\\\))","g"),ZT=/-----BEGIN [^-]*PRIVATE KEY-----[\s\S]*?-----END [^-]*PRIVATE KEY-----/g;function w(f,$){return f.count+=1,$}function FT(f){return GT.test(f.replace(/[A-Z]/g,($)=>`_${$.toLowerCase()}`))}function QT(f){return[...f].filter(($)=>{if($===`
41
- `||$==="\r"||$==="\t")return!0;let T=$.codePointAt(0)??0;if(T<32||T===127)return!1;if(T>=57344&&T<=63743)return!1;if(T>=983040&&T<=1048573)return!1;if(T>=1048576&&T<=1114109)return!1;if(T>=917504&&T<=917631)return!1;return!/[\p{Cf}\p{Cn}]/u.test($)}).join("")}function k(f,$){let T=f.normalize("NFKC"),q=T.replace(JT,"");if(q!==T)$.count+=1;T=q,T=T.replace(ZT,()=>w($,"[redacted-private-key]")),T=T.replace(/\bBearer\s+[^\s"'`]+/gi,()=>w($,"Bearer [redacted]")).replace(/\bsk-[A-Za-z0-9_-]{8,}\b/g,()=>w($,"[redacted-key]")).replace(/\bAKIA[0-9A-Z]{16}\b/g,()=>w($,"[redacted-aws-key]")).replace(/\b(api[_-]?key|access[_-]?token|authorization|cookie|password|passwd|refresh[_-]?token|secret|session[_-]?token)\b(\s*[:=]\s*)([^\s,;]+)/gi,(L,C,O)=>`${C}${O}${w($,"[redacted]")}`);let B=QT(T);if(B!==T)$.count+=1;return B.replace(/\r\n?/g,`
42
- `)}function sf(f,$,T){if(/^data:[^;,]+;base64,/i.test(f))return w(T,"[binary omitted]");let q=k(f,T),B=af.resolve($);for(let L of[B,B.startsWith("/private/")?B.slice(8):`/private${B}`])q=q.replaceAll(L,".");return q=q.replace(xT,(L)=>L.startsWith("./")?L:w(T,"[host-path]")),q=q.replace(VT,()=>w(T,"[host-path]")),q=q.replace(/\bhttps?:\/\/[^\s"'`]+/gi,(L)=>{try{let C=new URL(L);if(C.username||C.password||C.search||C.hash)T.count+=1;return C.username="",C.password="",C.search="",C.hash="",C.toString()}catch{return w(T,"[redacted-url]")}}),q}function Tf(f,$,T,q=0,B){if(B&&FT(B))return w(T,"[redacted]");if(q>=NT)return w(T,"[depth limit]");if(typeof f==="string")return sf(f,$,T);if(f===null||typeof f==="boolean"||typeof f==="number"&&Number.isFinite(f))return f;if(Array.isArray(f)){let L=f.slice(0,g0).map((C)=>Tf(C,$,T,q+1));if(f.length>L.length)L.push(w(T,`[${f.length-L.length} items omitted]`));return L}if(f&&typeof f==="object"){let L={},C=Object.entries(f);for(let[O,G]of C.slice(0,g0))L[k(O,T)]=Tf(G,$,T,q+1,O);if(C.length>g0)L["[entries omitted]"]=C.length-g0;return L}return String(f)}function KT(f,$){let T=Buffer.from(f,"utf8");if(T.length<=$)return f;let q=T.subarray(0,$).toString("utf8");while(Buffer.byteLength(q,"utf8")>$)q=q.slice(0,-1);return q}function XT(f,$,T){let q=JSON.stringify(Tf(f,$,T),null,2);if(Buffer.byteLength(q,"utf8")<=tf)return q;T.count+=1;let B=`
43
- ... [activity truncated]`;return KT(q,tf-Buffer.byteLength(B))+B}function qf(f,$=""){let T=Math.max(2,...[...f.matchAll(/`+/g)].map((B)=>B[0].length)),q="`".repeat(T+1);return`${q}${$}
44
- ${f}
45
- ${q}`}function ff(f){return f.replace(/\s+/g," ").trim()}function HT(f){let $=new Map,T=new Map,q=new Map,B=0;for(let L of u(f)){if(L.type==="message_created"){let N=T.get(L.data.messageId);if(N)N.role=L.data.role,N.metadata=L.data.metadata,$.set(L.data.messageId,N),T.delete(L.data.messageId);else if(!$.has(L.data.messageId))$.set(L.data.messageId,{order:B++,role:L.data.role,parts:[],metadata:L.data.metadata});continue}if(L.type!=="part_created"&&L.type!=="part_updated")continue;let C=$.get(L.data.messageId)??T.get(L.data.messageId);if(!C)C={order:B++,role:"activity",parts:[]},T.set(L.data.messageId,C);let O=`${L.data.messageId}\x00${L.data.partType}\x00${L.data.partId}`,G=q.get(O);if(G){G.event=L;continue}let _={order:B++,event:L};q.set(O,_),C.parts.push(_)}return[...$.values(),...T.values()].sort((L,C)=>L.order-C.order)}function $f(f,$,T,q){return`## Activity: ${f}
46
-
47
- ${qf(XT($,T.projectPath,q),"json")}`}function ef(f,$,T={}){let q={count:0},B=T.includeReasoning===!0,L=[],C=0,O=0,G=0;for(let b of HT(f)){let W=A0(b.metadata);if(W){let D=k(W.command,q),R=k([W.stdout,W.stderr?`stderr:
48
- ${W.stderr}`:""].filter(Boolean).join(`
49
- `)||"(no output)",q);L.push(`## User shell command
50
-
51
- ${qf(`$ ${D}
52
- ${R}`,"console")}`),C+=1;continue}let s=[],e=[],y=[],S=Number.POSITIVE_INFINITY;for(let D of b.parts.sort((R,z)=>R.order-z.order)){let{partType:R,payload:z}=D.event.data;if(R==="text"){let Q=z.text;if(typeof Q==="string"&&Q.trim())s.push(k(Q,q)),S=Math.min(S,D.order)}else if(R==="image"){let Q=z.mimeType;e.push(typeof Q==="string"?`[Image: ${k(Q,q)}]`:"[Image]"),S=Math.min(S,D.order)}else if(R==="reasoning"&&B){let Q=z.text;if(typeof Q==="string"&&Q.trim())y.push({order:D.order,markdown:`## Reasoning
53
-
54
- ${k(Q,q).trim()}`}),G+=1}else if(R==="tool_call"){let Q=z,M=typeof Q.toolName==="string"?k(Q.toolName,q):"unknown";y.push({order:D.order,markdown:$f(`${M} call`,Q.input??{},$,q)}),O+=1}else if(R==="tool_result"){let Q=z,M=typeof Q.toolName==="string"?k(Q.toolName,q):"unknown";y.push({order:D.order,markdown:$f(`${M} result`,typeof Q.error==="string"?{error:Q.error}:{output:Q.output??null},$,q)}),O+=1}else if(R==="summary"){let Q=z.text;if(typeof Q==="string"&&Q.trim())y.push({order:D.order,markdown:`## Summary
55
-
56
- ${k(Q,q).trim()}`})}else if(R==="subtask_ref")y.push({order:D.order,markdown:$f("Subagent",z,$,q)}),O+=1;else if(R==="diff"||R==="patch"){let Q=typeof z==="string"?z:JSON.stringify(z,null,2);y.push({order:D.order,markdown:`## File changes
57
-
58
- ${qf(sf(Q,$.projectPath,q),"diff")}`}),O+=1}}if((b.role==="user"||b.role==="assistant")&&(s.length>0||e.length>0))y.push({order:S,markdown:`## ${b.role==="user"?"User":"Assistant"}
59
-
60
- ${[...s,...e].join(`
61
-
62
- `).trim()}`}),C+=1;L.push(...y.sort((D,R)=>D.order-R.order).map((D)=>D.markdown))}if(L.length===0)throw Error("No conversation content to export");let _=`${L.join(`
63
-
64
- `)}
65
- `,N=Buffer.byteLength(_,"utf8");if(N>z0)throw Error(`Session export exceeds ${z0} bytes`);let x=_T("sha256").update(_).digest("hex"),V=af.basename($.taskSourceProjectPath??$.projectPath),Z=$.selectedModelId??$.taskModelId,g=["# Blade conversation","",`- Session: \`${$.sessionId}\``,...$.title?[`- Title: ${ff(k($.title,q))}`]:[],`- Project: \`${ff(k(V,q))}\``,...Z?[`- Model: \`${ff(k(Z,q))}\``]:[],...$.permissionMode?[`- Permission mode: ${$.permissionMode}`]:[],`- Created: ${$.firstMessageTime}`,`- Updated: ${$.lastMessageTime}`,`- State: ${$.archivedAt?"archived":"active"}`,`- Reasoning: ${B?"included":"omitted"}`,...$.reasoningEffort?[`- Reasoning effort: ${$.reasoningEffort}`]:[],...$.serviceTier?[`- Service tier: ${$.serviceTier}`]:[],...$.responseVerbosity?[`- Response verbosity: ${$.responseVerbosity}`]:[],...$.communicationStyle?[`- Communication style: ${$.communicationStyle}`]:[],...$.communicationStyleDigest?[`- Communication style SHA-256: \`${$.communicationStyleDigest}\``]:[],...$.projectInstructionsDigest?[`- Project instructions SHA-256: \`${$.projectInstructionsDigest}\``]:[],`- Content SHA-256: \`${x}\``,`- Content bytes: ${N}`,`- Redactions: ${q.count}`,"","---",""].join(`
66
- `)+`
67
- `+_;if(Buffer.byteLength(g,"utf8")>z0)throw Error(`Session export exceeds ${z0} bytes`);return{filename:`blade-session-${$.sessionId.slice(0,12)}.md`,markdown:g,contentSha256:x,contentBytes:N,messageCount:C,activityCount:O,reasoningIncluded:B,reasoningCount:G,redactionCount:q.count}}import{createHash as YT}from"node:crypto";import WT from"ajv";var O$="StructuredOutput",f$=65536,$$=131072,t1=2,T$=20,q$=1000,L$=200;function t(f){return f!==null&&typeof f==="object"&&!Array.isArray(f)}function B$(f,$){if(!t(f))throw Error(`${$} must be a JSON object`);let T;try{T=JSON.stringify(f)}catch(B){throw Error(`${$} must be JSON-serializable`,{cause:B})}if(T===void 0)throw Error(`${$} must be JSON-serializable`);let q=JSON.parse(T);if(!t(q))throw Error(`${$} must be a JSON object`);return q}function UT(f){let $=0,T=0,q=(B,L)=>{if($++,$>q$)throw Error(`Output schema exceeds the ${q$} node complexity limit`);if(L>T$)throw Error(`Output schema exceeds the ${T$} level depth limit`);if(Array.isArray(B)){for(let C of B)q(C,L+1);return}if(!t(B))return;if("$ref"in B){let C=B.$ref;if(typeof C!=="string"||!(C==="#"||C.startsWith("#/$defs/")||C.startsWith("#/definitions/")))throw Error("Output schema only supports self-contained local $ref values")}if("properties"in B&&t(B.properties)){if(T+=Object.keys(B.properties).length,T>L$)throw Error(`Output schema exceeds the ${L$} property limit`)}for(let C of Object.values(B))q(C,L+1)};q(f,0)}function RT(f){if(!f||f.length===0)return"Structured output does not match the requested schema";return f.slice(0,8).map(($)=>{return`${$.instancePath||"root"}: ${$.message??$.keyword}`}).join("; ")}function DT(f){let $=new WT({allErrors:!0,strict:!1,allowUnionTypes:!0,validateFormats:!1});try{return $.compile(f)}catch(T){throw Error(`Invalid output schema: ${T instanceof Error?T.message:String(T)}`)}}function _$(f){let $=B$(f,"Output schema"),T=JSON.stringify($);if(Buffer.byteLength(T)>f$)throw Error(`Output schema exceeds ${f$} bytes`);if($.type!=="object")throw Error('Output schema root type must be "object"');UT($);let B=DT($),L=YT("sha256").update(T).digest("hex");return{schema:$,schemaDigest:L,declaration:{name:O$,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:$,constrainedSampling:{type:"json_schema",strict:"prefer"}},validate(C){let O;try{O=B$(C,"Structured output")}catch(_){return{success:!1,message:_ instanceof Error?_.message:String(_)}}let G=JSON.stringify(O);if(Buffer.byteLength(G)>$$)return{success:!1,message:`Structured output exceeds ${$$} bytes`};if(!B(O))return{success:!1,message:RT(B.errors)};return{success:!0,output:O}}}}function C$(f,$){if(!t(f))return;let T=t(f.structuredOutput)?f.structuredOutput:f;if(T.schemaDigest!==$.schemaDigest||!("output"in T))return;let q=$.validate(T.output);return q.success?q.output:void 0}function a1(f,$){for(let T=f.length-1;T>=0;T--){let q=f[T];if(!q)continue;if(q.role==="user")return;if(q.role==="assistant"){let C=C$(q.metadata,$);if(C)return{output:C,completed:!0};continue}if(q.role!=="tool"||q.name!==O$)continue;let B=t(q.metadata)?q.metadata:void 0,L=C$(B?.metadata,$);if(L)return{output:L,completed:!1}}return}var _0=U0("Service"),N$=new Set(["queued","running","completed","failed","cancelled","interrupted"]),Jf=new Set(["local","worktree"]),AT=new Set(["default","autoEdit","yolo","plan"]),zT=new Set(["applied","discarded","conflicted"]),gT=86400000;class Zf extends Error{}function G$(f){try{return process.kill(f,0),!0}catch($){return $ instanceof Error&&"code"in $&&$.code==="EPERM"}}function x$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(["sessionId","name","branch","baseCommit","originalBranch","repositoryRoot","originalWorkspaceRoot","worktreeRoot","workspaceRoot"].some((q)=>typeof $[q]!=="string"||!$[q])||typeof $.sourceHadChanges!=="boolean"||$.sourceStateFingerprint!==void 0&&(typeof $.sourceStateFingerprint!=="string"||!/^[a-f0-9]{64}$/.test($.sourceStateFingerprint)))return;return $}function V$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(!zT.has(String($.status))||typeof $.updatedAt!=="string"||!Number.isFinite(Date.parse($.updatedAt))||$.sourceCommit!==void 0&&(typeof $.sourceCommit!=="string"||!/^[a-f0-9]{40,64}$/.test($.sourceCommit))||$.changedFiles!==void 0&&(typeof $.changedFiles!=="number"||!Number.isInteger($.changedFiles)||$.changedFiles<0)||$.message!==void 0&&(typeof $.message!=="string"||!$.message.trim()||$.message.length>500))return;return{status:$.status,updatedAt:$.updatedAt,...typeof $.sourceCommit==="string"?{sourceCommit:$.sourceCommit}:{},...typeof $.changedFiles==="number"?{changedFiles:$.changedFiles}:{},...typeof $.message==="string"?{message:$.message}:{}}}function J$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(["changedFiles","additions","deletions","commits"].some((q)=>typeof $[q]!=="number"||!Number.isInteger($[q])||$[q]<0))return;return $}function Z$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f,T;if($.outputSchema!==void 0)try{T=_$($.outputSchema).schema}catch{return}if($.version!==1||typeof $.prompt!=="string"||!$.prompt.trim()||$.prompt.length>32000||typeof $.sourceProjectPath!=="string"||!J.isAbsolute($.sourceProjectPath)||!Jf.has($.isolation)||!b0($.permissionMode)||$.title!==void 0&&(typeof $.title!=="string"||!$.title.trim()||$.title.length>200)||$.modelId!==void 0&&(typeof $.modelId!=="string"||!$.modelId.trim()||$.modelId.length>500)||$.reasoningEffort!==void 0&&!J0($.reasoningEffort)||$.serviceTier!==void 0&&!V0($.serviceTier)||$.responseVerbosity!==void 0&&!x0($.responseVerbosity)||$.communicationStyle!==void 0&&!Z0($.communicationStyle)||$.communicationStyleDigest!==void 0&&(typeof $.communicationStyleDigest!=="string"||!/^[a-f0-9]{64}$/.test($.communicationStyleDigest))||$.projectInstructionsDigest!==void 0&&(typeof $.projectInstructionsDigest!=="string"||!/^[a-f0-9]{64}$/.test($.projectInstructionsDigest)))return;let q;if($.attachments!==void 0){if(!Array.isArray($.attachments)||$.attachments.length>H$)return;let B=0;for(let L of $.attachments){if(!L||typeof L!=="object"||Array.isArray(L))return;let C=L;if(!["file","image","url"].includes(String(C.type)))return;for(let O of["path","url","content","mimeType","name"])if(C[O]!==void 0&&typeof C[O]!=="string")return;B+=typeof C.content==="string"?Buffer.byteLength(C.content):0}if(B>Y$)return;q=$.attachments.map((L)=>{let C=L;return{type:C.type,...C.path!==void 0?{path:C.path}:{},...C.url!==void 0?{url:C.url}:{},...C.content!==void 0?{content:C.content}:{},...C.mimeType!==void 0?{mimeType:C.mimeType}:{},...C.name!==void 0?{name:C.name}:{}}})}return{version:1,prompt:$.prompt,...typeof $.title==="string"?{title:$.title}:{},sourceProjectPath:J.resolve($.sourceProjectPath),isolation:$.isolation,permissionMode:$.permissionMode,...typeof $.modelId==="string"?{modelId:$.modelId}:{},...J0($.reasoningEffort)?{reasoningEffort:$.reasoningEffort}:{},...V0($.serviceTier)?{serviceTier:$.serviceTier}:{},...x0($.responseVerbosity)?{responseVerbosity:$.responseVerbosity}:{},...Z0($.communicationStyle)?{communicationStyle:$.communicationStyle}:{},...typeof $.communicationStyleDigest==="string"?{communicationStyleDigest:$.communicationStyleDigest}:{},...typeof $.projectInstructionsDigest==="string"?{projectInstructionsDigest:$.projectInstructionsDigest}:{},...q?{attachments:q}:{},...T?{outputSchema:T}:{}}}function b0(f){return typeof f==="string"&&AT.has(f)}function F$(f){if(!f||typeof f!=="object"||Array.isArray(f))return;let $=f;if(typeof $.sessionId!=="string"||!$.sessionId||typeof $.projectPath!=="string"||!J.isAbsolute($.projectPath))return;return{sessionId:$.sessionId,projectPath:J.resolve($.projectPath)}}var A$={stat(f){return E0(f,{bigint:!0})},readFile(f){return a(f,"utf-8")}},G0=A$;function Aq(f){G0=f}function zq(){G0=A$}class z$ extends Error{constructor(f){super(`Session has no durable creation record: ${f}`);this.name="SessionMissingCreationError"}}class $0 extends Error{sessionId;archivedBySessionId;code="BLADE_SESSION_ARCHIVED";constructor(f,$){super(f===$?`Session is archived: ${f}`:`Session is archived by ancestor ${$}: ${f}`);this.sessionId=f;this.archivedBySessionId=$;this.name="SessionArchivedError"}}class n extends Error{code="BLADE_SESSION_ARCHIVE_CONFLICT";constructor(f){super(f);this.name="SessionArchiveConflictError"}}function Bf(f,$){return`${f}\x00${$}`}function MT(f){if(f.kind==="base")return`/review base ${f.baseSha??f.label}`;if(f.kind==="commit")return`/review commit ${f.commitSha??f.label}`;return"/review uncommitted"}function g$(f){return typeof f==="string"&&f.length<=64&&Number.isFinite(Date.parse(f))}function ET(f){let $=new Map(f.map((T)=>[Bf(T.projectPath,T.sessionId),T]));return f.map((T)=>{let q=T,B=new Set;while(q){let G=Bf(q.projectPath,q.sessionId);if(B.has(G))break;if(B.add(G),g$(q.archivedAt))return{...T,archivedAt:q.archivedAt,archivedBySessionId:q.sessionId};q=q.parentId?$.get(Bf(q.projectPath,q.parentId)):void 0}let{archivedAt:L,archivedBySessionId:C,...O}=T;return O})}function Cf(f,$){let T=ET(f);if($===null)return T;return T.filter((q)=>Boolean(q.archivedAt)===$)}class X{static toUISafeMessages(f){let $=Date.now(),T=f.length,q=[];return f.forEach((B,L)=>{if(B.role!=="user"&&B.role!=="assistant"||!nf(B))return;let C;if(typeof B.content==="string")C=B.content;else if(Array.isArray(B.content))C=B.content.map((x)=>x.type==="text"?x.text:"[Image]").join("");else C="";let O=C.trim();if(!O)return;let G=A0(B.metadata),_=G?of(G):O,N=q[q.length-1];if(N&&N.role===B.role&&N.content===_)return;q.push({id:`restored-${$}-${L}`,role:B.role,content:_,timestamp:$-(T-L)*1000,metadata:B.metadata&&typeof B.metadata==="object"?B.metadata:void 0})}),q}static async listSessionPage(f={}){let $=Nf(f),T=await this.listSessionPageFromProjection($);if(T)return T;let B=(await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,$.cursor?5000:0,$.archived)).sort(Gf),L=xf(B,$);return{sessions:L.sessions.map((C)=>this.toPublicMetadata(C)),nextCursor:L.nextCursor}}static async listSessionPageFromProjection(f){let $=R$(f);try{let T=await M0();if(!T)return null;await Vf(T,this.projectionDeriver(),f.cursor?5000:0);let q=[],B=[];if(f.cwd)q.push("s.project_path = ?"),B.push(f.cwd);if(!f.includeSubagents)q.push("s.is_subagent = 0");if(q.push(f.archived?"a.session_id IS NOT NULL":"a.session_id IS NULL"),$){q.push(`(
68
- s.last_message_time < ?
69
- OR (
70
- s.last_message_time = ?
71
- AND (
72
- s.project_sort_key > ?
73
- OR (s.project_sort_key = ? AND s.session_sort_key > ?)
74
- )
75
- )
76
- )`);let G=_f($.projectPath);B.push($.lastMessageTime,$.lastMessageTime,G,G,_f($.sessionId))}let L=T.prepare(`WITH RECURSIVE archive_members(
77
- project_path, session_id, archive_root_id, effective_archived_at, depth
78
- ) AS (
79
- SELECT project_path, session_id, session_id, archived_at, 0
80
- FROM sessions
81
- WHERE archived_at IS NOT NULL
82
- UNION ALL
83
- SELECT child.project_path, child.session_id, parent.archive_root_id,
84
- parent.effective_archived_at, parent.depth + 1
85
- FROM sessions child
86
- JOIN archive_members parent
87
- ON child.project_path = parent.project_path
88
- AND child.parent_id = parent.session_id
89
- WHERE parent.depth < 128
90
- ),
91
- ranked_archive AS (
92
- SELECT project_path, session_id, archive_root_id,
93
- effective_archived_at,
94
- ROW_NUMBER() OVER (
95
- PARTITION BY project_path, session_id
96
- ORDER BY depth ASC, archive_root_id ASC
97
- ) AS rank
98
- FROM archive_members
99
- )
100
- SELECT s.metadata_json, a.archive_root_id, a.effective_archived_at
101
- FROM sessions s
102
- LEFT JOIN ranked_archive a
103
- ON a.project_path = s.project_path
104
- AND a.session_id = s.session_id
105
- AND a.rank = 1
106
- ${q.length>0?`WHERE ${q.join(" AND ")}`:""}
107
- ORDER BY s.last_message_time DESC,
108
- s.project_sort_key ASC,
109
- s.session_sort_key ASC
110
- LIMIT ?`).all(...B,f.limit+1),C=await Promise.all(L.map(async(G)=>{let _=JSON.parse(G.metadata_json);if(G.archive_root_id&&G.effective_archived_at)return this.reconcileInterruptedTask({..._,archivedAt:G.effective_archived_at,archivedBySessionId:G.archive_root_id});let{archivedAt:N,archivedBySessionId:x,...V}=_;return this.reconcileInterruptedTask(V)})),O=xf(C,f);return{sessions:O.sessions.map((G)=>this.toPublicMetadata(G)),nextCursor:O.nextCursor}}catch{return null}}static async listSessions(f={}){let $=Nf(f),T=await this.scanStoredSessions($.cwd??void 0,$.includeSubagents,0,$.archived),q=new Set;return T.sort(Gf).flatMap((B)=>{let L=`${B.projectPath}\x00${B.sessionId}`;if(q.has(L))return[];return q.add(L),[this.toPublicMetadata(B)]})}static async collectStaleEmptySessions(f={}){let $=f.now??Date.now(),T=f.olderThanMs??gT;if(!Number.isFinite(T)||T<0)throw Error("Stale empty session age must be a non-negative number");let q=f.projectPath?[{storagePath:q0(this.resolveCatalogWorkspace(f.projectPath)),projectPath:this.resolveCatalogWorkspace(f.projectPath)}]:await this.listAllProjectStorageDirectories(),B=0;for(let L of q){let C;try{C=await Lf(L.storagePath)}catch(O){if(O.code==="ENOENT")continue;throw O}for(let O of C){if(!O.endsWith(".jsonl"))continue;let G=O.slice(0,-6);if(!X$(G))continue;let _=J.join(L.storagePath,O);try{let x=await E0(_);if($-x.mtimeMs<T)continue;if(await Promise.all([E0(J.join(L.storagePath,`${G}.inbox.json`)).then(()=>!0).catch(()=>!1),E0(N0(L.projectPath,G)).then(()=>!0).catch(()=>!1)]).then((Z)=>Z.some(Boolean)))continue}catch(x){if(x.code==="ENOENT")continue;throw x}let N;try{N=await h.acquire(G,L.projectPath)}catch(x){if(x instanceof P)continue;throw x}try{if(!await new I(_).deleteValidated((V)=>V.length===1&&V[0]?.type==="session_created"&&V[0].data.relationType!=="subagent"))continue;B++,await f0(J.join(L.storagePath,`${G}.inbox.json`),{force:!0}),await f0(N0(L.projectPath,G),{force:!0}),await this.removeFromProjection(G,L.projectPath)}catch(x){_0.warn(`[SessionService] Skipping stale empty session cleanup: ${G}`,x)}finally{await N.release()}}}return B}static async findSessionMetadata(f,$){if(A(f),$!==void 0){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f);try{let L=await this.readStoredSessionMetadata(B,f,q);if(L.projectPath!==q)return;if(!L.parentId||L.archivedAt)return this.toPublicMetadata(Cf([L],null)[0]??L);let C=await this.scanStoredSessions(q,!0,0,null);return this.toPublicMetadata(C.find((O)=>O.sessionId===f)??L)}catch(L){if(L.code==="ENOENT")return;throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).filter((q)=>q.sessionId===f);if(T.length===0)return;if(T.length>1)throw Error(`Ambiguous session ID: ${f}`);return this.toPublicMetadata(T[0])}static async loadSession(f,$){try{if($){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f);try{return await this.loadSessionFromFile(B,f,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${f}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===f);if(!T)throw Error(`未找到会话: ${f}`);return await this.loadSessionFromFile(T.filePath,f)}catch(T){throw _0.error(`[SessionService] 加载会话失败 (${f}):`,T),T}}static async loadSessionModelContext(f,$){try{if($){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f);try{return await this.loadSessionModelContextFromFile(B,f,q)}catch(L){if(L.code==="ENOENT")throw Error(`未找到会话: ${f}`);throw L}}let T=(await this.scanStoredSessions(void 0,!0,0,null)).find((q)=>q.sessionId===f);if(!T)throw Error(`未找到会话: ${f}`);return await this.loadSessionModelContextFromFile(T.filePath,f)}catch(T){throw _0.error(`[SessionService] 加载模型上下文失败 (${f}):`,T),T}}static async exportSessionMarkdown(f,$,T={}){A(f);let q=this.resolveCatalogWorkspace($),B=m(q,f),L;try{L=await this.readStableSessionSnapshot(B,f)}catch(G){throw this.sanitizeStoredSessionError(G,f)}let C=this.projectMetadataFromEntries(L,f,q,B);if(C.projectPath!==q)throw Error(`Session export workspace mismatch: ${f}`);let O=C.archivedAt;if(!O&&C.parentId)O=(await this.findArchivedAncestor(C.parentId,q))?.archivedAt;return ef(L,{...C,archivedAt:O},T)}static async listRewindCheckpoints(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=m(T,f),B=await this.readStableSessionSnapshot(q,f);this.validateSessionWorkspace(B,f,T);let L=new R0({sessionId:f,workspaceRoot:T});await L.initialize();let C=W$(B),O=[];for(let G of C){let _=Of(B,G.messageId),N=await L.previewRewind(_.snapshotMessageIds);O.push({...G,fileCount:N.files.length})}return O}static async rewindSession(f,$,T){A(f);let q=this.resolveCatalogWorkspace($);await this.assertSessionWritable(f,q);let B=m(q,f),L=new I(B),C;try{await L.appendValidatedAsync(async(O)=>{this.validateSessionWorkspace(O,f,q);let G=Of(O,T.targetMessageId),_=new R0({sessionId:f,workspaceRoot:q});await _.initialize();let N=await _.previewRewind(G.snapshotMessageIds),x=T.mode==="conversation"?await _.commitSnapshots(G.snapshotMessageIds):await _.rewindSnapshots(G.snapshotMessageIds),V=new Date().toISOString(),Z={id:j(),sessionId:f,timestamp:V,type:"session_rewound",cwd:q,gitBranch:l(q),version:p(),data:{rewindId:j(),targetMessageId:T.targetMessageId,mode:T.mode,restoredFiles:T.mode==="conversation"?[]:x.files,createdAt:V}},E=u([...O,Z]);return C={checkpoint:{...G.checkpoint,fileCount:N.files.length},mode:T.mode,removedTurns:G.removedTurns,restoredFiles:Z.data.restoredFiles,messages:this.convertJSONLToMessages(E)},Z})}catch(O){throw this.sanitizeStoredSessionError(O,f)}if(!C)throw Error(`Session rewind did not produce a result: ${f}`);for(let O of C.restoredFiles)c.getInstance().clearFileRecord(O);return C}static async forkSession(f,$){A(f);let T=$.newSessionId??`fork-${Date.now()}-${j(8)}`;A(T);let q=this.resolveForkWorkspace($.sourceProjectPath),B=this.resolveForkWorkspace($.targetProjectPath);if(q!==B)throw Error("Session forks must stay in the source workspace");let L=m(q,f),C=await this.readStableSessionSnapshot(L,f),O=this.getSessionCreatedEntry(C,f);if(O.data.sessionId!==f)throw Error("Fork source session_created.data.sessionId must match the requested session ID");if(!J.isAbsolute(O.cwd)||J.resolve(O.cwd)!==q)throw Error("Fork source session_created.cwd must resolve to the requested source workspace");let G=this.projectMetadataFromEntries(C,f,q,L);if(G.archivedAt)throw new $0(f,f);if(G.parentId){let Y=await this.findArchivedAncestor(G.parentId,q);if(Y)throw new $0(f,Y.sessionId)}let _=u(C),N=new Date().toISOString(),x=O.data.rootId||f,V=l(B),Z=p(),{status:E,taskStatus:g,taskStatusReason:b,taskFailure:W,taskStartedAt:s,taskCompletedAt:e,taskOwnerPid:y,taskPromptSummary:S,taskDispatch:D,taskModelId:R,taskRetriedFrom:z,taskDelivery:Q,taskIsolation:M,taskSourceProjectPath:k0,taskWorktree:Ff,taskDiffStat:Qf,taskQueuePosition:Kf,taskQueueDepth:Xf,taskConcurrencyLimit:Hf,pendingInteraction:w0,...y0}=O.data,S0={id:j(),sessionId:T,timestamp:N,type:"session_created",cwd:B,gitBranch:V,version:Z,data:{...y0,sessionId:T,rootId:x,parentId:f,relationType:"fork",taskStatus:"completed",taskCompletedAt:N,taskIsolation:"local",taskSourceProjectPath:B,createdAt:N,updatedAt:N}},j0=_.filter((Y)=>Y.type!=="session_created"&&Y.type!=="inbox_acknowledged"&&Y.type!=="interaction_requested"&&Y.type!=="interaction_responded"&&Y.type!=="interaction_recovered"&&Y.type!=="review_started"&&Y.type!=="review_completed").map((Y)=>{let i={...Y,id:j(),sessionId:T,cwd:B,gitBranch:V,version:Z};if(Y.type==="session_updated"){let{status:Q0,taskStatus:U,taskStatusReason:v0,taskFailure:bT,taskStartedAt:kT,taskCompletedAt:wT,taskOwnerPid:yT,taskPromptSummary:ST,taskDispatch:jT,taskModelId:mT,taskRetriedFrom:IT,taskDelivery:vT,taskIsolation:uT,taskSourceProjectPath:nT,taskWorktree:PT,taskDiffStat:hT,taskQueuePosition:cT,taskQueueDepth:lT,taskConcurrencyLimit:pT,pendingInteraction:iT,...M$}=Y.data;return{...i,type:"session_updated",data:{...M$,sessionId:T,rootId:x,parentId:f,relationType:"fork"}}}if(Y.type==="message_created"){let{inboxMessageId:Q0,...U}=Y.data;return{...i,type:"message_created",data:U}}return i}),m0={id:j(),sessionId:T,timestamp:N,type:"session_updated",cwd:B,gitBranch:V,version:Z,data:{sessionId:T,rootId:x,parentId:f,relationType:"fork",taskStatus:"completed",taskStatusReason:null,taskFailure:null,taskStartedAt:null,taskCompletedAt:N,taskOwnerPid:null,taskIsolation:"local",taskSourceProjectPath:B,taskWorktree:null,taskDiffStat:null,taskDelivery:null,taskQueuePosition:null,taskQueueDepth:null,taskConcurrencyLimit:null,updatedAt:N}},T0=[S0,...j0,m0],F0=m(B,T);try{await new I(F0).createExclusive(T0)}catch(Y){if(Y.code==="EEXIST")throw Error(`Fork session already exists: ${T}`,{cause:Y});throw Y}let I0=this.projectMetadataFromEntries(T0,T,B,F0);return{sessionId:T,parentSessionId:f,projectPath:B,messages:this.convertJSONLToMessages(T0),metadata:this.toPublicMetadata(I0)}}static async deleteSession(f,$){if(A(f),$){if(!J.isAbsolute($))throw Error("Session catalog cwd must be absolute");let q=J.resolve($),B=this.getSessionFilePath(q,f),L=new I(B),C;try{C=await L.deleteValidated((O)=>{return this.projectMetadataFromEntries(O,f,q,B).projectPath===q})}catch(O){if(!this.isCorruptSessionJSONLError(O))throw O;C=await L.delete()}if(!C)return 0;return await f0(J.join(J.dirname(B),`${f}.inbox.json`),{force:!0}),await f0(N0(q,f),{force:!0}),await this.removeFromProjection(f,q),1}let T=(await this.scanStoredSessions(void 0,!0)).filter((q)=>q.sessionId===f);if(T.length===0)return 0;return await Promise.all(T.map(async(q)=>{await new I(q.filePath).delete(),await f0(J.join(J.dirname(q.filePath),`${q.sessionId}.inbox.json`),{force:!0}),await f0(N0(q.projectPath,q.sessionId),{force:!0}),await this.removeFromProjection(q.sessionId,q.projectPath)})),T.length}static async removeFromProjection(f,$){try{let T=await M0();if(T)D$(T,f,$)}catch{}}static validateTaskMetadataUpdate(f,$){if(f.taskPromptSummary!==void 0&&f.taskPromptSummary!==null&&(!f.taskPromptSummary.trim()||f.taskPromptSummary.length>1000))throw Error("Session task prompt summary must contain 1-1000 characters");if(f.taskFailure!==void 0&&f.taskFailure!==null&&!p0(f.taskFailure))throw Error("Invalid session task failure");if(f.taskDispatch!==void 0&&f.taskDispatch!==null&&!Z$(f.taskDispatch))throw Error("Invalid durable task dispatch");if(f.taskModelId!==void 0&&f.taskModelId!==null&&(!f.taskModelId.trim()||f.taskModelId.length>500))throw Error("Invalid session task model ID");if(f.selectedModelId!==void 0&&f.selectedModelId!==null&&(!f.selectedModelId.trim()||f.selectedModelId.length>500))throw Error("Invalid selected session model ID");if(f.permissionMode!==void 0&&f.permissionMode!==null&&!b0(f.permissionMode))throw Error("Invalid session permission mode");if(f.reasoningEffort!==void 0&&f.reasoningEffort!==null&&!J0(f.reasoningEffort))throw Error("Invalid session reasoning effort");if(f.serviceTier!==void 0&&f.serviceTier!==null&&!V0(f.serviceTier))throw Error("Invalid session service tier");if(f.responseVerbosity!==void 0&&f.responseVerbosity!==null&&!x0(f.responseVerbosity))throw Error("Invalid session response verbosity");if(f.communicationStyle!==void 0&&f.communicationStyle!==null&&!Z0(f.communicationStyle))throw Error("Invalid session communication style");if(f.communicationStyleDigest!==void 0&&f.communicationStyleDigest!==null&&!/^[a-f0-9]{64}$/.test(f.communicationStyleDigest))throw Error("Invalid session communication style digest");if(f.projectInstructionsDigest!==void 0&&f.projectInstructionsDigest!==null&&!/^[a-f0-9]{64}$/.test(f.projectInstructionsDigest))throw Error("Invalid session project instructions digest");if(f.taskRetriedFrom!==void 0&&f.taskRetriedFrom!==null&&!F$(f.taskRetriedFrom))throw Error("Invalid session task retry source");if(f.taskDelivery!==void 0&&f.taskDelivery!==null&&!V$(f.taskDelivery))throw Error("Invalid session task delivery");if(f.taskIsolation!==void 0&&f.taskIsolation!==null&&!Jf.has(f.taskIsolation))throw Error(`Invalid session task isolation: ${String(f.taskIsolation)}`);if(f.taskSourceProjectPath!==void 0&&f.taskSourceProjectPath!==null&&!J.isAbsolute(f.taskSourceProjectPath))throw Error("Session task source project path must be absolute");if(f.taskWorktree!==void 0&&f.taskWorktree!==null){let T=x$(f.taskWorktree);if(!T||T.sessionId!==$||![T.repositoryRoot,T.originalWorkspaceRoot,T.worktreeRoot,T.workspaceRoot].every((q)=>J.isAbsolute(q)))throw Error("Invalid session task worktree metadata")}if(f.taskDiffStat!==void 0&&f.taskDiffStat!==null&&!J$(f.taskDiffStat))throw Error("Invalid session task diff stat");if(f.taskQueuePosition!==void 0&&f.taskQueuePosition!==null&&(!Number.isInteger(f.taskQueuePosition)||f.taskQueuePosition<1))throw Error("Invalid session task queue position");if(f.taskQueueDepth!==void 0&&f.taskQueueDepth!==null&&(!Number.isInteger(f.taskQueueDepth)||f.taskQueueDepth<0))throw Error("Invalid session task queue depth");if(f.taskConcurrencyLimit!==void 0&&f.taskConcurrencyLimit!==null&&(!Number.isInteger(f.taskConcurrencyLimit)||f.taskConcurrencyLimit<1))throw Error("Invalid session task concurrency limit");if(typeof f.taskQueuePosition==="number"&&typeof f.taskQueueDepth==="number"&&f.taskQueuePosition>f.taskQueueDepth)throw Error("Session task queue position exceeds queue depth")}static async createSessionMetadata(f,$,T={}){A(f),X.validateTaskMetadataUpdate(T,f);let q=X.resolveCatalogWorkspace($);if(T.taskWorktree&&J.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=new Date().toISOString(),L={id:j(),sessionId:f,timestamp:B,type:"session_created",cwd:q,gitBranch:l(q),version:p(),data:{sessionId:f,rootId:f,...T.title!==void 0?{title:T.title}:{},taskStatus:T.taskStatus??"queued",...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},createdAt:B,updatedAt:B}},C=X.getSessionFilePath(q,f);return await new I(C).createExclusive([L]),X.toPublicMetadata(X.projectMetadataFromEntries([L],f,q,C))}static async assertSessionWritable(f,$){let T=await this.findSessionMetadata(f,$);if(!T)throw Error(`Session not found: ${f}`);if(T.archivedAt)throw new $0(f,T.archivedBySessionId??f);return T}static async findArchivedAncestor(f,$){let T=new Set,q=f;while(q){if(T.has(q))throw Error("Session lineage contains a cycle");T.add(q),A(q);let B=m($,q),L;try{L=await a(B,"utf8")}catch(O){if(O.code==="ENOENT")return;throw O}let C=this.projectMetadataFromEntries(this.parseStoredSession(L,q),q,$,B);if(C.projectPath!==$)throw Error("Session lineage escapes the requested workspace");if(C.archivedAt)return{sessionId:C.sessionId,archivedAt:C.archivedAt};q=C.parentId}return}static async listSessionArchiveMembers(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=await this.scanStoredSessions(T,!0,0,null);if(!q.some((C)=>C.sessionId===f))throw Error(`Session not found: ${f}`);let B=new Set([f]),L=!0;while(L){L=!1;for(let C of q)if(C.parentId&&B.has(C.parentId)&&!B.has(C.sessionId))B.add(C.sessionId),L=!0}return q.filter((C)=>B.has(C.sessionId)).sort((C,O)=>C.sessionId.localeCompare(O.sessionId)).map((C)=>this.toPublicMetadata(C))}static async archiveSession(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=await this.findSessionMetadata(f,T);if(!q)throw Error(`Session not found: ${f}`);if(q.archivedAt)return q;let B=await this.listSessionArchiveMembers(f,T),L=B.find((O)=>O.taskStatus==="queued"||O.taskStatus==="running");if(L)throw new n(`Stop session ${L.sessionId} before archiving this session tree`);let C=[];try{for(let N of B)C.push(await h.acquire(N.sessionId,T));let O=m(T,f),G=new I(O),_=[];return await G.appendValidated((N)=>{let x=this.projectMetadataFromEntries(N,f,T,O);if(x.archivedAt)throw new n(`Session archive state changed concurrently: ${f}`);if(x.taskStatus==="queued"||x.taskStatus==="running")throw new n(`Stop session ${f} before archiving it`);let V=new Date().toISOString(),Z={id:j(),sessionId:f,timestamp:V,type:"session_updated",cwd:T,gitBranch:l(T),version:p(),data:{sessionId:f,archivedAt:V,updatedAt:V}};return _=[...N,Z],Z}),this.toPublicMetadata({...this.projectMetadataFromEntries(_,f,T,O),archivedBySessionId:f})}catch(O){if(O instanceof n)throw O;if(O instanceof P)throw new n(O.message);throw this.sanitizeStoredSessionError(O,f)}finally{for(let O of C.reverse())await O.release()}}static async unarchiveSession(f,$){A(f);let T=this.resolveCatalogWorkspace($),q=await this.findSessionMetadata(f,T);if(!q)throw Error(`Session not found: ${f}`);if(!q.archivedAt)return q;if(q.archivedBySessionId&&q.archivedBySessionId!==f)throw new n(`Unarchive ancestor ${q.archivedBySessionId} to restore session ${f}`);let B;try{B=await h.acquire(f,T);let L=m(T,f),C=new I(L),O=[];return await C.appendValidated((G)=>{if(!this.projectMetadataFromEntries(G,f,T,L).archivedAt)throw new n(`Session archive state changed concurrently: ${f}`);let N=new Date().toISOString(),x={id:j(),sessionId:f,timestamp:N,type:"session_updated",cwd:T,gitBranch:l(T),version:p(),data:{sessionId:f,archivedAt:null,updatedAt:N}};return O=[...G,x],x}),this.toPublicMetadata(this.projectMetadataFromEntries(O,f,T,L))}catch(L){if(L instanceof n)throw L;if(L instanceof P)throw new n(L.message);throw this.sanitizeStoredSessionError(L,f)}finally{await B?.release()}}static async updateSessionMetadata(f,$,T){if(A(f),X.validateTaskMetadataUpdate(T,f),T.taskStatus!==void 0&&!N$.has(T.taskStatus))throw Error(`Invalid session task status: ${String(T.taskStatus)}`);if(T.taskOwnerPid!==void 0&&T.taskOwnerPid!==null&&(!Number.isInteger(T.taskOwnerPid)||T.taskOwnerPid<=0))throw Error("Session task owner PID must be a positive integer");let q=X.resolveCatalogWorkspace($);if(T.taskWorktree&&J.resolve(T.taskWorktree.workspaceRoot)!==q)throw Error("Session task worktree must match the catalog workspace");let B=X.getSessionFilePath(q,f),L=new I(B),C=[];try{await L.appendValidatedAsync(async(O)=>{let G=X.getSessionCreatedEntry(O,f);if(G.data.sessionId!==f)throw Error(`Session metadata creation record sessionId mismatch: ${f}`);if(!J.isAbsolute(G.cwd)||J.resolve(G.cwd)!==q)throw Error(`Session metadata creation record cwd mismatch: ${f}`);let _=X.projectMetadataFromEntries(O,f,q,B);if(_.archivedAt)throw new $0(f,f);if(_.parentId){let V=await X.findArchivedAncestor(_.parentId,q);if(V)throw new $0(f,V.sessionId)}let N=new Date().toISOString(),x={id:j(),sessionId:f,timestamp:N,type:"session_updated",cwd:q,gitBranch:l(q),version:p(),data:{sessionId:f,...T.title!==void 0?{title:T.title}:{},...T.taskStatus!==void 0?{taskStatus:T.taskStatus}:{},...T.taskStatusReason!==void 0?{taskStatusReason:T.taskStatusReason}:{},...T.taskFailure!==void 0?{taskFailure:T.taskFailure}:{},...T.taskStartedAt!==void 0?{taskStartedAt:T.taskStartedAt}:{},...T.taskCompletedAt!==void 0?{taskCompletedAt:T.taskCompletedAt}:{},...T.taskOwnerPid!==void 0?{taskOwnerPid:T.taskOwnerPid}:{},...T.taskPromptSummary!==void 0?{taskPromptSummary:T.taskPromptSummary}:{},...T.taskDispatch!==void 0?{taskDispatch:T.taskDispatch}:{},...T.taskModelId!==void 0?{taskModelId:T.taskModelId}:{},...T.taskRetriedFrom!==void 0?{taskRetriedFrom:T.taskRetriedFrom}:{},...T.taskDelivery!==void 0?{taskDelivery:T.taskDelivery}:{},...T.taskIsolation!==void 0?{taskIsolation:T.taskIsolation}:{},...T.taskSourceProjectPath!==void 0?{taskSourceProjectPath:T.taskSourceProjectPath}:{},...T.taskWorktree!==void 0?{taskWorktree:T.taskWorktree}:{},...T.taskDiffStat!==void 0?{taskDiffStat:T.taskDiffStat}:{},...T.taskQueuePosition!==void 0?{taskQueuePosition:T.taskQueuePosition}:{},...T.taskQueueDepth!==void 0?{taskQueueDepth:T.taskQueueDepth}:{},...T.taskConcurrencyLimit!==void 0?{taskConcurrencyLimit:T.taskConcurrencyLimit}:{},...T.selectedModelId!==void 0?{selectedModelId:T.selectedModelId}:{},...T.permissionMode!==void 0?{permissionMode:T.permissionMode}:{},...T.reasoningEffort!==void 0?{reasoningEffort:T.reasoningEffort}:{},...T.serviceTier!==void 0?{serviceTier:T.serviceTier}:{},...T.responseVerbosity!==void 0?{responseVerbosity:T.responseVerbosity}:{},...T.communicationStyle!==void 0?{communicationStyle:T.communicationStyle}:{},...T.communicationStyleDigest!==void 0?{communicationStyleDigest:T.communicationStyleDigest}:{},...T.projectInstructionsDigest!==void 0?{projectInstructionsDigest:T.projectInstructionsDigest}:{},updatedAt:N}};return C=[...O,x],x})}catch(O){throw X.sanitizeStoredSessionError(O,f)}return X.toPublicMetadata(X.projectMetadataFromEntries(C,f,q,B))}static async setSessionPermissionMode(f,$,T){if(A(f),!b0(T))throw Error("Invalid session permission mode");let q=X.resolveCatalogWorkspace($),B=await X.findSessionMetadata(f,q);if(B?.permissionMode===T)return B;if(B)return X.updateSessionMetadata(f,q,{permissionMode:T});try{return await X.createSessionMetadata(f,q,{taskStatus:"completed",permissionMode:T})}catch(L){if(L.code!=="EEXIST")throw L;return X.updateSessionMetadata(f,q,{permissionMode:T})}}static async findSessionTaskWorktree(f,$){A(f);let T=X.resolveCatalogWorkspace($),q=X.getSessionFilePath(T,f);try{return(await X.readStoredSessionMetadata(q,f,T)).taskWorktree}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,f)}}static async findSessionTaskDispatch(f,$){A(f);let T=X.resolveCatalogWorkspace($),q=X.getSessionFilePath(T,f);try{return(await X.readStoredSessionMetadata(q,f,T)).taskDispatch}catch(B){if(B.code==="ENOENT")return;throw X.sanitizeStoredSessionError(B,f)}}static async loadSessionFromFile(f,$,T){let q=await a(f,"utf-8"),B=this.parseStoredSession(q,$);if(T!==void 0){if(this.projectMetadataFromEntries(B,$,T,f).projectPath!==T)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToMessages(B)}static async loadSessionModelContextFromFile(f,$,T){let q=await a(f,"utf-8"),B=this.parseStoredSession(q,$);if(T!==void 0){if(this.projectMetadataFromEntries(B,$,T,f).projectPath!==T)throw Error(`未找到会话: ${$}`)}return this.convertJSONLToModelContext(B)}static convertJSONLToModelContext(f){let $=u(f),T=-1,q;for(let L=0;L<$.length;L++){let C=$[L];if(C?.type!=="part_created"||C.data.partType!=="summary")continue;let O=C.data.payload;if(T=L,q=Mf(O.replacementMessages),!q)q=[{role:"user",content:O.text??"",metadata:C.data.payload}]}if(T<0||!q)return this.convertJSONLToMessages($);let B=this.convertJSONLToMessages($.slice(T+1));return[...q,...B]}static convertJSONLToMessages(f){let $=[],T=new Map,q=new Map,B=new Map,L=new Map,C=new Map,O=u(f),G=new Set;for(let _ of O){if(_.type==="message_created"){let N=_.data.metadata&&typeof _.data.metadata==="object"&&!Array.isArray(_.data.metadata)?_.data.metadata:void 0,x=N?.codeReview&&typeof N.codeReview==="object"&&!Array.isArray(N.codeReview)?N.codeReview:void 0;if(x?.phase==="completed"&&typeof x.reviewId==="string")G.add(x.reviewId);let V=_.data.role==="assistant"&&_.data.parentMessageId?B.get(_.data.parentMessageId):void 0,Z=V??{role:_.data.role,content:"",..._.data.metadata||_.data.inboxMessageId?{metadata:{..._.data.metadata&&typeof _.data.metadata==="object"&&!Array.isArray(_.data.metadata)?_.data.metadata:{},..._.data.inboxMessageId?{inboxMessageId:_.data.inboxMessageId}:{}}}:{}};if(T.set(_.data.messageId,Z),q.set(_.data.messageId,[]),!V)$.push(Z)}if(_.type==="part_created"){if(_.data.partType==="reasoning"){let N=T.get(_.data.messageId);if(N){let x=_.data.payload;N.reasoningContent=(N.reasoningContent??"")+(x.text??"")}}if(_.data.partType==="text"){let N=T.get(_.data.messageId);if(N){let x=_.data.payload,V=q.get(_.data.messageId);if(V)V.push({type:"text",text:x.text??""}),N.content=Q$(V);else N.content=x.text??""}}if(_.data.partType==="image"){let N=T.get(_.data.messageId);if(N){let x=_.data.payload,V=q.get(_.data.messageId);if(V&&x.dataUrl)V.push({type:"image_url",image_url:{url:x.dataUrl}}),N.content=Q$(V)}}if(_.data.partType==="tool_call"){let N=T.get(_.data.messageId);if(N?.role!=="assistant"){if(N=B.get(_.data.messageId),!N)N={role:"assistant",content:"",tool_calls:[]},B.set(_.data.messageId,N),$.push(N)}if(N.role==="assistant"){let x=_.data.payload,V=x.toolCallId??_.data.partId;L.set(_.data.partId,V),C.set(V,N),N.tool_calls??=[],N.tool_calls.push({id:V,type:"function",function:{name:x.toolName??"unknown",arguments:JSON.stringify(x.input??{})}})}}if(_.data.partType==="tool_result"){let N=_.data.payload,x=uf(N),V=x.error?`Error: ${x.error.message}`:typeof x.llmContent==="string"?x.llmContent:JSON.stringify(x.llmContent),Z=N;$.push({role:"tool",content:V,tool_call_id:L.get(_.data.messageId)??N.toolCallId,name:N.toolName,metadata:Z})}if(_.data.partType==="summary"){let N=_.data.payload,x=_.data.payload;$.push({role:"system",content:N.text??"",metadata:x})}if(_.data.partType==="subtask_ref"){let N=T.get(_.data.messageId)??C.get(_.data.messageId);if(N){let x=_.data.payload,V=N.metadata??{};N.metadata={...V,subtaskRef:x}}}}}for(let _ of Y0(O)){if(_.completion===void 0||G.has(_.start.reviewId))continue;$.push({role:"assistant",content:wf(_.start,_.completion),metadata:{codeReview:{...yf(_.start,_.completion),synthetic:!0}}})}return $}static projectionDeriver(){return(f,$,T)=>{try{let q=m(T,$);return this.projectMetadataFromEntries(f,$,T,q)}catch{return null}}}static projectionDeriverForSearch(){return this.projectionDeriver()}static async scanStoredSessionsFromProjection(f,$,T=0,q=!1){try{let B=await M0();if(!B)return null;await Vf(B,this.projectionDeriver(),T);let L=f?B.prepare("SELECT metadata_json, is_subagent FROM sessions WHERE project_path=?").all(f):B.prepare("SELECT metadata_json, is_subagent FROM sessions").all(),C=[];for(let O of L){if(!$&&O.is_subagent===1)continue;try{let G=JSON.parse(O.metadata_json);if(f!==void 0&&G.projectPath!==f)continue;C.push(G)}catch{}}return Cf(await Promise.all(C.map((O)=>this.reconcileInterruptedTask(O))),q)}catch{return null}}static async scanStoredSessions(f,$=!1,T=0,q=!1){let B=f?J.resolve(f):void 0,L=await this.scanStoredSessionsFromProjection(B,$,T,q);if(L)return L;let C=B?[{storagePath:q0(B),projectPath:B}]:await this.listAllProjectStorageDirectories(),O=[];for(let G of C){let _;try{_=await Lf(G.storagePath)}catch(N){if(N.code==="ENOENT")continue;throw N}for(let N of _){if(!N.endsWith(".jsonl"))continue;let x=N.slice(0,-6),V=J.join(G.storagePath,N);try{let Z=await this.readStoredSessionMetadata(V,x,G.projectPath);if(B!==void 0&&Z.projectPath!==B){_0.warn(`[SessionService] Skipping out-of-scope session transcript: ${x}`);continue}if(!$&&Z.relationType==="subagent")continue;O.push(Z)}catch(Z){let E=Z.code;if(E==="ENOENT")continue;if(E)throw Z;_0.warn(`[SessionService] Skipping invalid session transcript: ${x}`)}}}return Cf(O,q)}static async listAllProjectStorageDirectories(){let f=J.join(O0(),"projects"),$;try{$=await Lf(f,{withFileTypes:!0,encoding:"utf8"})}catch(T){if(T.code==="ENOENT")return[];throw T}return $.filter((T)=>T.isDirectory()).map((T)=>({storagePath:J.join(f,T.name),projectPath:K$(T.name)}))}static async readStoredSessionMetadata(f,$,T){let q=await a(f,"utf-8"),B=this.parseStoredSession(q,$);return this.reconcileInterruptedTask(this.projectMetadataFromEntries(B,$,T,f))}static async reconcileInterruptedTask(f){let $=f.taskOwnerPid;if(f.taskStatus!=="running"||$===void 0||G$($))return f;let T;try{T=await h.acquire(f.sessionId,f.projectPath)}catch(L){if(!(L instanceof P))throw L;let C=await a(f.filePath,"utf-8");return this.projectMetadataFromEntries(this.parseStoredSession(C,f.sessionId),f.sessionId,f.projectPath,f.filePath)}let q=new I(f.filePath),B;try{try{await q.appendValidated((L)=>{let C=this.projectMetadataFromEntries(L,f.sessionId,f.projectPath,f.filePath);if(C.taskStatus!=="running"||C.taskOwnerPid!==$||G$($))throw new Zf;let O=new Date().toISOString(),G={id:j(),sessionId:f.sessionId,timestamp:O,type:"session_updated",cwd:f.projectPath,gitBranch:l(f.projectPath),version:p(),data:{sessionId:f.sessionId,taskStatus:"interrupted",taskStatusReason:"Task owner process exited before completion",taskCompletedAt:O,taskOwnerPid:null,taskQueuePosition:null,taskQueueDepth:null,updatedAt:O}};return B=[...L,G],G})}catch(L){if(!(L instanceof Zf))throw L}if(!B){let L=await a(f.filePath,"utf-8");B=this.parseStoredSession(L,f.sessionId)}return this.projectMetadataFromEntries(B,f.sessionId,f.projectPath,f.filePath)}finally{await T.release()}}static projectMetadataFromEntries(f,$,T,q){if(f.length===0)throw Error(`Empty session transcript: ${$}`);let B=this.getSessionCreatedEntry(f,$),L=f.reduce((U,v0)=>v0.type==="session_updated"?{...U,...v0.data}:U,{...B.data}),C=u(f),O=kf(bf(C)),_=Y0(C).at(-1),N=C.findLastIndex((U)=>U.type==="review_started"&&U.data.reviewId===_?.start.reviewId||U.type==="review_completed"&&U.data.reviewId===_?.start.reviewId),x=C.findLastIndex((U)=>(U.type==="session_created"||U.type==="session_updated")&&Object.hasOwn(U.data,"taskStatus")),V=_!==void 0&&N>x,Z=V?_.completion===void 0?"running":_.completion.status==="completed"||_.completion.status==="stale"?"completed":_.completion.status==="aborted"?"cancelled":_.completion.status==="interrupted"?"interrupted":"failed":void 0,E=C.filter((U)=>U.type==="message_created"&&["user","assistant"].includes(U.data.role)).length,g=C.some((U)=>U.type==="part_created"&&U.data.partType==="tool_result"&&typeof U.data.payload.error==="string"),b=N$.has(L.taskStatus)?L.taskStatus:void 0,W=Z??b??(g?"failed":"completed"),s=typeof L.taskOwnerPid==="number"&&Number.isInteger(L.taskOwnerPid)&&L.taskOwnerPid>0?L.taskOwnerPid:void 0,e=Jf.has(L.taskIsolation)?L.taskIsolation:void 0,y=typeof L.taskSourceProjectPath==="string"&&J.isAbsolute(L.taskSourceProjectPath)?J.resolve(L.taskSourceProjectPath):void 0,S=B.cwd;if(S!==void 0&&!J.isAbsolute(S))throw Error(`Session catalog cwd must be absolute: ${$}`);let D=S===void 0?T:J.resolve(S),R=x$(L.taskWorktree),z=R?.sessionId===$&&J.resolve(R.workspaceRoot)===D?R:void 0,Q=J$(L.taskDiffStat),M=Z$(L.taskDispatch),k0=typeof L.taskModelId==="string"&&L.taskModelId.trim()?L.taskModelId:M?.modelId,Ff=typeof L.selectedModelId==="string"&&L.selectedModelId.trim()?L.selectedModelId:k0,Qf=b0(L.permissionMode)?L.permissionMode:M?.permissionMode,Kf=J0(L.reasoningEffort)?L.reasoningEffort:M?.reasoningEffort,Xf=V0(L.serviceTier)?L.serviceTier:M?.serviceTier,Hf=x0(L.responseVerbosity)?L.responseVerbosity:M?.responseVerbosity,w0=Z0(L.communicationStyle)?L.communicationStyle:M?.communicationStyle,y0=Object.hasOwn(L,"communicationStyleDigest")?typeof L.communicationStyleDigest==="string"&&/^[a-f0-9]{64}$/.test(L.communicationStyleDigest)?L.communicationStyleDigest:void 0:w0===M?.communicationStyle?M?.communicationStyleDigest:void 0,S0=Object.hasOwn(L,"projectInstructionsDigest")?typeof L.projectInstructionsDigest==="string"&&/^[a-f0-9]{64}$/.test(L.projectInstructionsDigest)?L.projectInstructionsDigest:void 0:M?.projectInstructionsDigest,j0=g$(L.archivedAt)?L.archivedAt:void 0,m0=F$(L.taskRetriedFrom),T0=V$(L.taskDelivery),F0=typeof L.taskQueuePosition==="number"&&Number.isInteger(L.taskQueuePosition)&&L.taskQueuePosition>0?L.taskQueuePosition:void 0,I0=typeof L.taskQueueDepth==="number"&&Number.isInteger(L.taskQueueDepth)&&L.taskQueueDepth>=0?L.taskQueueDepth:void 0,Y=typeof L.taskConcurrencyLimit==="number"&&Number.isInteger(L.taskConcurrencyLimit)&&L.taskConcurrencyLimit>0?L.taskConcurrencyLimit:void 0,i=V?_?.completion?_.completion.status==="completed"?void 0:`Code review ${h0(_.completion.status)}`:`Reviewing ${_?.start.target.label??"changes"}`:void 0,Q0=V?W==="failed"&&i?l0(i):void 0:p0(L.taskFailure)?L.taskFailure:W==="failed"&&typeof L.taskStatusReason==="string"?l0(L.taskStatusReason):void 0;return{sessionId:$,projectPath:D,gitBranch:B.gitBranch,rootId:L.rootId||$,parentId:L.parentId,relationType:L.relationType,resumedFrom:L.resumedFrom,rootAgentId:L.rootAgentId,resumeDepth:L.resumeDepth,title:L.title,agentType:L.agentType,model:L.model,selectedModelId:Ff,permissionMode:Qf,reasoningEffort:Kf,serviceTier:Xf,responseVerbosity:Hf,communicationStyle:w0,communicationStyleDigest:y0,projectInstructionsDigest:S0,pendingInteraction:O,taskStatus:W,taskStatusReason:Q0?.message??i??(typeof L.taskStatusReason==="string"?L.taskStatusReason:void 0),taskFailure:Q0,taskStartedAt:V?_?.start.startedAt:typeof L.taskStartedAt==="string"?L.taskStartedAt:void 0,taskCompletedAt:V?_?.completion?.completedAt:typeof L.taskCompletedAt==="string"?L.taskCompletedAt:void 0,taskPromptSummary:V?_?MT(_.start.target):"/review uncommitted":typeof L.taskPromptSummary==="string"?L.taskPromptSummary:void 0,taskModelId:k0,taskRetryAvailable:M!==void 0,taskRetriedFrom:m0,taskDelivery:T0,taskIsolation:e,taskSourceProjectPath:y,taskWorktreePath:z?.worktreeRoot,taskWorktreeBranch:z?.branch,taskBaseCommit:z?.baseCommit,taskDiffStat:Q,taskQueuePosition:F0,taskQueueDepth:I0,taskConcurrencyLimit:Y,archivedAt:j0,taskOwnerPid:V?void 0:s,taskWorktree:z,taskDispatch:M,messageCount:E,firstMessageTime:f[0].timestamp,lastMessageTime:f.at(-1).timestamp,hasErrors:g||W==="failed",filePath:q}}static toPublicMetadata(f){let{filePath:$,taskOwnerPid:T,taskWorktree:q,taskDispatch:B,...L}=f;return L}static getSessionFilePath(f,$){return m(f,$)}static getSessionCreatedEntry(f,$){let T=f.find((q)=>q.type==="session_created");if(!T)throw new z$($);return T}static resolveCatalogWorkspace(f){if(!J.isAbsolute(f))throw Error("Session catalog cwd must be absolute");return J.resolve(f)}static validateSessionWorkspace(f,$,T){let q=this.getSessionCreatedEntry(f,$);if(q.data.sessionId!==$)throw Error(`Session creation record sessionId mismatch: ${$}`);if(!J.isAbsolute(q.cwd)||J.resolve(q.cwd)!==T)throw Error(`Session creation record cwd mismatch: ${$}`)}static resolveForkWorkspace(f){if(!J.isAbsolute(f))throw Error("Fork workspace paths must be absolute");return J.resolve(f)}static parseStoredSession(f,$){return U$(f,`session ${$}`)}static isCorruptSessionJSONLError(f){return f instanceof Error&&f.message.startsWith("Invalid session JSONL ")}static sanitizeStoredSessionError(f,$){if(!this.isCorruptSessionJSONLError(f)||!(f instanceof Error))return f;let T=f.message.match(/ at line (\d+)$/)?.[1];return Error(`Invalid session JSONL in session ${$}${T?` at line ${T}`:""}`,{cause:f.cause})}static async readStableSessionSnapshot(f,$,T=3){for(let q=0;q<T;q+=1){let B=await G0.stat(f),L=await G0.readFile(f),C=this.parseStoredSession(L,$),O=await G0.stat(f);if(B.size===O.size&&B.mtimeNs===O.mtimeNs&&B.dev===O.dev&&B.ino===O.ino)return C}throw Error("Session changed while creating fork; retry the operation")}}function Q$(f){if(f.length===1&&f[0]?.type==="text")return f[0].text;return[...f]}
111
- export{i0 as Kb,Yf as Lb,K0 as Mb,Uf as Nb,tT as Ob,P as Pb,h as Qb,q1 as Rb,L1 as Sb,bf as Tb,O1 as Ub,Y0 as Vb,N1 as Wb,h0 as Xb,wf as Yb,yf as Zb,l0 as _b,c as $b,R0 as ac,D1 as bc,A1 as cc,z1 as dc,g1 as ec,uf as fc,M1 as gc,b1 as hc,nf as ic,w1 as jc,a0 as kc,s0 as lc,u1 as mc,n1 as nc,of as oc,A0 as pc,i1 as qc,O$ as rc,f$ as sc,t1 as tc,_$ as uc,a1 as vc,gT as wc,Aq as xc,zq as yc,z$ as zc,$0 as Ac,n as Bc,X as Cc};
@@ -1 +0,0 @@
1
- import{$c as a,ad as b,bd as c}from"./chunk-ng0tkmrn.js";import"./chunk-jk8bqc5b.js";import"./chunk-fp2fh7cn.js";import"./chunk-v508x7cg.js";import"./chunk-wy4pn9sk.js";import"./chunk-2xbmkyb2.js";import"./chunk-2xsrqsk9.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-6fdvffcc.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{a as validatePermissions,c as validateOutput,b as loadConfiguration};
@@ -1 +0,0 @@
1
- import{Ab as o,Cb as p,Db as q,Eb as r,eb as a,fb as b,hb as c,lb as d,mb as e,nb as f,ob as g,pb as h,qb as i,rb as j,sb as k,xb as l,yb as m,zb as n}from"./chunk-8an49nbn.js";import"./chunk-9r0yebs1.js";import"./chunk-adz2756v.js";import"./chunk-2z3xe3rw.js";import"./chunk-wwsg165p.js";import"./chunk-wy4pn9sk.js";import"./chunk-0jxh2zq5.js";import"./chunk-69rc9hw6.js";import"./chunk-d1t91jgz.js";import"./chunk-detkh4dd.js";import"./chunk-8b1ehxzh.js";import"./chunk-87jz5600.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-6fdvffcc.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{g as saveUserMessage,i as saveToolUse,j as saveToolResult,k as saveCompaction,h as saveAssistantMessage,d as isRootSystemPrompt,m as handleTaskListUpdate,n as handleSkillActivation,o as extractModelSwitch,r as executeLoopGenerator,f as drainLoop,c as checkStopHook,a as checkOutputRecovery,b as checkIncompleteIntent,q as checkAndCompactInLoop,p as applyToolDomainEffects,l as StreamingToolExecutor,e as ConversationState};
@@ -1 +0,0 @@
1
- import{f as a,g as i,h as l,i as m}from"./chunk-yagna3ws.js";import"./chunk-83wm4akj.js";import"./chunk-eeac8teg.js";import"./chunk-6x1g554w.js";import"./chunk-1hb0rt7n.js";import"./chunk-ttkwrqtp.js";import"./chunk-xsx1av03.js";import"./chunk-atqnan6x.js";import"./chunk-qs4erqd0.js";import"./chunk-8an49nbn.js";import"./chunk-9r0yebs1.js";import"./chunk-adz2756v.js";import"./chunk-2z3xe3rw.js";import"./chunk-wwsg165p.js";import{ed as n}from"./chunk-9rjaem5f.js";import"./chunk-3tednchw.js";import{Ad as s}from"./chunk-fp2fh7cn.js";import"./chunk-v508x7cg.js";import"./chunk-wy4pn9sk.js";import"./chunk-0jxh2zq5.js";import"./chunk-j9snkjpe.js";import"./chunk-69rc9hw6.js";import"./chunk-hpehkz2x.js";import"./chunk-0ft3egjr.js";import"./chunk-d1t91jgz.js";import"./chunk-detkh4dd.js";import"./chunk-2xbmkyb2.js";import"./chunk-8b1ehxzh.js";import"./chunk-87jz5600.js";import"./chunk-2xsrqsk9.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-6fdvffcc.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";import v from"chalk";var C={command:"serve",describe:"Start a headless Blade server (no browser)",builder:a,handler:async(p)=>{let r=i(p);if(await s(),!process.env.BLADE_SERVER_PASSWORD)console.log(v.yellow("Warning: BLADE_SERVER_PASSWORD is not set; server is unsecured."));let e=await m.listenAsync(r);if(console.log(`Blade server listening on http://${e.hostname}:${e.port}`),r.hostname==="0.0.0.0"){let o=l();for(let g of o)console.log(` Network: http://${g}:${e.port}`)}let t,c=new Promise((o)=>{t=o}),d=n(async()=>{await e.stop(),t()});try{await c}finally{d(),await e.stop()}}};export{C as serveCommand};
@@ -1 +0,0 @@
1
- import{Vd as a,Wd as b,Xd as c}from"./chunk-j9snkjpe.js";import"./chunk-69rc9hw6.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{b as resolveModelConfig,c as getModelDisplayName,a as getModelApiKeyEnvironmentVariable};
@@ -1 +0,0 @@
1
- import{Zc as a,_c as b}from"./chunk-95hvy6dn.js";import"./chunk-6fdvffcc.js";import"./chunk-av10vmxk.js";export{a as globalOptions,b as cliConfig};
@@ -1 +0,0 @@
1
- import{$g as d,Yg as a,Zg as b,_g as c,ah as e,bh as f}from"./chunk-6fdvffcc.js";import"./chunk-av10vmxk.js";export{b as getVersion,c as getPackageName,a as getPackageInfo,e as getFormattedVersion,d as getDescription,f as getCopyright};
@@ -1 +0,0 @@
1
- import{$d as b,_d as a,ae as c}from"./chunk-hpehkz2x.js";import"./chunk-2xsrqsk9.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-6fdvffcc.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{c as snapshotWorkspaceModelResources,b as resolveWorkspaceModelResources,a as cloneWorkspaceModelConfig};
@@ -1 +0,0 @@
1
- import{Ae as i,Be as j,se as a,te as b,ue as c,ve as d,we as e,xe as f,ye as g,ze as h}from"./chunk-0ft3egjr.js";import"./chunk-d1t91jgz.js";import"./chunk-detkh4dd.js";import"./chunk-2xbmkyb2.js";import"./chunk-8b1ehxzh.js";import"./chunk-87jz5600.js";import"./chunk-2xsrqsk9.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-6fdvffcc.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{g as withWorkspaceAgentResources,i as snapshotWorkspaceAgentResources,f as resolveWorkspaceAgentResources,j as resetWorkspaceAgentResources,d as refreshWorkspaceCommunicationStyles,h as getWorkspaceAgentResourceCacheStats,e as configureInvocationPluginDirs,c as WorkspaceAgentResourceCapacityError,a as MAX_RESIDENT_WORKSPACE_AGENT_RESOURCES,b as MAX_ACTIVE_WORKSPACE_AGENT_RESOURCES};
@@ -1,2 +0,0 @@
1
- import{ag as J,bg as $,cg as O,dg as K}from"./chunk-7b467h8k.js";import{eg as v,fg as S,gg as l}from"./chunk-9kmtcgm6.js";import{Lg as o}from"./chunk-y8r2knxm.js";import{nh as n}from"./chunk-cz68x56m.js";var G=[{min:0,max:59},{min:0,max:23},{min:1,max:31},{min:1,max:12},{min:0,max:7}],a={Sun:0,Mon:1,Tue:2,Wed:3,Thu:4,Fri:5,Sat:6},f=new Map;function D(Q,Z,W){let B=new Set;for(let X of Q.split(",")){let[Y,k]=X.split("/"),V=k?Number.parseInt(k,10):1;if(!Number.isInteger(V)||V<1)throw Error(`Invalid cron step in "${Q}"`);let j=Z,H=W;if(Y!=="*"&&Y!=="")if(Y.includes("-")){let[U,i]=Y.split("-");j=Number.parseInt(U,10),H=Number.parseInt(i,10)}else j=Number.parseInt(Y,10),H=j;if(!Number.isInteger(j)||!Number.isInteger(H)||j<Z||H>W||j>H)throw Error(`Invalid cron range "${Y}" in field "${Q}"`);for(let U=j;U<=H;U+=V)B.add(U)}return B}function C(Q){let Z=Q.trim().split(/\s+/);if(Z.length!==5)throw Error(`Cron expression must have 5 fields (min hour dom mon dow), got ${Z.length}`);let[W,B,X,Y,k]=Z,V=D(k,G[4].min,G[4].max),j=new Set([...V].map((H)=>H===7?0:H));return{minutes:D(W,G[0].min,G[0].max),hours:D(B,G[1].min,G[1].max),daysOfMonth:D(X,G[2].min,G[2].max),months:D(Y,G[3].min,G[3].max),daysOfWeek:j,domRestricted:X.trim()!=="*",dowRestricted:k.trim()!=="*"}}function t(Q,Z){if(!Z)return{minute:Q.getMinutes(),hour:Q.getHours(),dayOfMonth:Q.getDate(),month:Q.getMonth()+1,dayOfWeek:Q.getDay()};let W=f.get(Z);if(!W)W=new Intl.DateTimeFormat("en-US",{timeZone:Z,month:"numeric",day:"numeric",hour:"numeric",minute:"numeric",weekday:"short",hourCycle:"h23"}),f.set(Z,W);let B=Object.fromEntries(W.formatToParts(Q).filter((X)=>X.type!=="literal").map((X)=>[X.type,X.value]));return{minute:Number(B.minute),hour:Number(B.hour),dayOfMonth:Number(B.day),month:Number(B.month),dayOfWeek:a[B.weekday]??-1}}function r(Q,Z,W){let B=t(Z,W);if(!Q.minutes.has(B.minute))return!1;if(!Q.hours.has(B.hour))return!1;if(!Q.months.has(B.month))return!1;let X=Q.daysOfMonth.has(B.dayOfMonth),Y=Q.daysOfWeek.has(B.dayOfWeek);if(Q.domRestricted&&Q.dowRestricted)return X||Y;if(Q.domRestricted)return X;if(Q.dowRestricted)return Y;return!0}function T(Q,Z,W){let B=C(Q),X=new Date(Z.getTime());X.setSeconds(0,0),X.setMinutes(X.getMinutes()+1);let Y=new Date(Z.getTime());Y.setFullYear(Y.getFullYear()+4);while(X.getTime()<=Y.getTime()){if(r(B,X,W))return new Date(X.getTime());X.setMinutes(X.getMinutes()+1)}return null}var E={s:1000,m:60000,h:3600000,d:86400000};function DJ(Q){let W=Q.trim().toLowerCase().match(/^(\d+)\s*([smhd]?)$/);if(!W)return null;let B=Number.parseInt(W[1],10);if(!Number.isInteger(B)||B<=0)return null;let X=W[2]||"m";return B*E[X]}function y(Q){for(let Z of["d","h","m","s"]){let W=E[Z];if(Q%W===0)return`${Q/W}${Z}`}return`${Math.round(Q/1000)}s`}function A(Q,Z,W){switch(Q.kind){case"cron":{if(!Q.cron)return null;try{return T(Q.cron,Z,Q.timezone)}catch{return null}}case"interval":{if(!Q.intervalMs||Q.intervalMs<=0)return null;let X=new Date((W??Z).getTime()+Q.intervalMs);return X.getTime()<=Z.getTime()?new Date(Z.getTime()+1000):X}case"once":{if(!Q.runAt)return null;let B=new Date(Q.runAt);if(Number.isNaN(B.getTime()))return null;return B.getTime()>Z.getTime()?B:null}default:return null}}function _(Q){switch(Q.kind){case"cron":if(!Q.cron)return"cron trigger requires a cron expression";try{if(C(Q.cron),Q.timezone)new Intl.DateTimeFormat("en-US",{timeZone:Q.timezone}).format();return null}catch(Z){return Z instanceof Error?Z.message:"invalid cron expression"}case"interval":if(!Q.intervalMs||Q.intervalMs<60000)return"interval trigger requires intervalMs >= 60000 (1 minute)";return null;case"once":{if(!Q.runAt)return"once trigger requires runAt timestamp";let Z=new Date(Q.runAt);if(Number.isNaN(Z.getTime()))return"once trigger runAt is not a valid date";return null}default:return"unknown trigger kind"}}function FJ(Q){switch(Q.kind){case"cron":return`cron: ${Q.cron??"?"}`;case"interval":return`every ${Q.intervalMs?y(Q.intervalMs):"?"}`;case"once":return`once at ${Q.runAt??"?"}`;default:return"unknown"}}import{mkdir as bJ,readFile as wJ}from"node:fs/promises";import s from"node:path";import{nanoid as LJ}from"nanoid";import PJ from"write-file-atomic";var w=$(K(["default","autoEdit","yolo","plan"]));var N=$(K(["user","assistant","system","tool"])),p=$(J.Union([J.Object({type:J.Literal("text"),text:J.String()}),J.Object({type:J.Literal("image_url"),image_url:J.Object({url:J.String()})})])),h=J.Union([J.String(),J.Array(p)]),NJ=$(J.Object({id:J.String(),role:N,content:h,timestamp:J.Number(),metadata:J.Optional(J.Record(J.String(),J.Unknown())),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),e=$(K(["queued","running","completed","failed","cancelled","interrupted"])),F=$(K(["local","worktree"])),JJ=$(K(["applied","discarded","conflicted"])),QJ=$(J.Object({status:JJ,updatedAt:J.String(),sourceCommit:J.Optional(J.String()),changedFiles:J.Optional(J.Integer({minimum:0})),message:J.Optional(J.String())})),ZJ=$(J.Object({changedFiles:J.Integer({minimum:0}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),commits:J.Integer({minimum:0})})),$J=$(J.Object({path:J.String({minLength:1}),patch:J.String({maxLength:2097152}),additions:J.Integer({minimum:0}),deletions:J.Integer({minimum:0}),binary:J.Boolean(),truncated:J.Boolean()})),qJ=$(J.Object({sessionId:J.String(),projectPath:J.String(),baseCommit:J.String(),files:J.Array($J,{maxItems:100}),truncated:J.Boolean()})),BJ=J.Union([J.String(),J.Number(),J.Boolean(),J.Array(J.String())]),KJ=$(J.Object({name:J.String(),type:K(["string","number","integer","boolean","select","multi-select"]),title:J.String(),description:J.Optional(J.String()),required:J.Boolean(),defaultValue:J.Optional(BJ),options:J.Optional(J.Array(J.Object({value:J.String(),label:J.String()}))),format:J.Optional(K(["date","uri","email","date-time"])),minimum:J.Optional(J.Number()),maximum:J.Optional(J.Number()),minLength:J.Optional(J.Number()),maxLength:J.Optional(J.Number()),minItems:J.Optional(J.Number()),maxItems:J.Optional(J.Number())})),xJ=$(J.Object({serverName:J.String(),mode:K(["form","url"]),message:J.String(),fields:J.Optional(J.Array(KJ)),requestedSchema:J.Optional(J.Record(J.String(),J.Unknown())),url:J.Optional(J.String()),domain:J.Optional(J.String()),elicitationId:J.Optional(J.String())})),WJ=$(J.Object({type:K(["permission","question","elicitation"]),requestId:J.String()})),XJ=$(J.Object({code:K(["authentication","permission","rate_limit","timeout","network","model_unavailable","context_limit","unsupported_input","capacity","runtime"]),message:J.String({minLength:1,maxLength:500}),retryable:J.Boolean(),resource:J.Optional(K(["pending_count","pending_bytes","resident_runtimes"]))})),L=$(K(["auto","off","minimal","low","medium","high","xhigh","max"])),P=$(K(["auto","standard","fast","flex"])),M=$(K(["auto","low","medium","high"])),b=$(J.Union([K(["auto","pragmatic","friendly","explanatory"]),J.String({minLength:7,maxLength:300,pattern:"^(?:(?:user|project):[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3}|plugin:[a-z0-9][a-z0-9._-]{0,63}:[a-z0-9][a-z0-9._-]{0,63}(?::[a-z0-9][a-z0-9._-]{0,63}){0,3})$"})])),z=$(J.Object({sessionId:J.String(),projectPath:J.String(),title:J.Optional(J.String()),gitBranch:J.Optional(J.String()),rootId:J.String(),parentId:J.Optional(J.String()),relationType:J.Optional(K(["subagent","fork"])),resumedFrom:J.Optional(J.String()),rootAgentId:J.Optional(J.String()),resumeDepth:J.Optional(J.Integer({minimum:0})),taskStatus:O(e,"completed"),taskStatusReason:J.Optional(J.String()),taskFailure:J.Optional(XJ),taskStartedAt:J.Optional(J.String()),taskCompletedAt:J.Optional(J.String()),taskPromptSummary:J.Optional(J.String()),taskModelId:J.Optional(J.String()),selectedModelId:J.Optional(J.String()),permissionMode:J.Optional(w),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),communicationStyleDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),projectInstructionsDigest:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"})),taskRetryAvailable:J.Optional(J.Boolean()),taskRetriedFrom:J.Optional(J.Object({sessionId:J.String(),projectPath:J.String()})),taskDelivery:J.Optional(QJ),taskIsolation:J.Optional(F),taskSourceProjectPath:J.Optional(J.String()),taskWorktreePath:J.Optional(J.String()),taskWorktreeBranch:J.Optional(J.String()),taskBaseCommit:J.Optional(J.String()),taskDiffStat:J.Optional(ZJ),taskQueuePosition:J.Optional(J.Integer({minimum:1})),taskQueueDepth:J.Optional(J.Integer({minimum:0})),taskConcurrencyLimit:J.Optional(J.Integer({minimum:1})),archivedAt:J.Optional(J.String()),archivedBySessionId:J.Optional(J.String()),pendingInteraction:J.Optional(WJ),messageCount:J.Number(),firstMessageTime:J.String(),lastMessageTime:J.String(),hasErrors:J.Boolean()})),fJ=$(J.Object({sessions:J.Array(z),nextCursor:J.Optional(J.String())})),CJ=$(J.Object({session:z,archivedSessionIds:J.Array(J.String())})),EJ=$(J.Object({session:z,restoredSessionIds:J.Array(J.String())})),RJ=$(J.Object({version:J.Literal(1),sessionId:J.String(),goalId:J.String(),objective:J.String(),status:K(["active","verifying","paused","blocked","usage_limited","budget_limited","complete"]),tokenBudget:J.Optional(J.Number()),tokensUsed:J.Number(),timeUsedSeconds:J.Number(),continuationCount:J.Number(),statusReason:J.Optional(J.String()),completionVerification:J.Optional(J.Object({attempt:J.Integer({minimum:1}),status:K(["pending","pass","fail","partial"]),requestedAt:J.String(),completedAt:J.Optional(J.String()),verifierSessionId:J.Optional(J.String()),summary:J.Optional(J.String()),evidenceSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),createdAt:J.String(),updatedAt:J.String()})),u=$(J.Object({role:N,content:h,metadata:J.Optional(J.Unknown()),reasoningContent:J.Optional(J.String()),thinkingContent:J.Optional(J.String()),tool_call_id:J.Optional(J.String()),name:J.Optional(J.String()),tool_calls:J.Optional(J.Unknown())})),SJ=$(J.Object({session:z,messages:J.Array(u)})),d=$(K(["conversation","code","both"])),YJ=$(J.Object({messageId:J.String(),preview:J.String(),createdAt:J.String(),fileCount:J.Integer({minimum:0})})),lJ=$(J.Object({targetMessageId:J.String({minLength:1}),mode:O(d,"conversation")})),hJ=$(J.Object({checkpoint:YJ,mode:d,removedTurns:J.Integer({minimum:1}),restoredFiles:J.Array(J.String()),messages:J.Array(u)})),HJ=K(["running","completed","failed","cancelled"]),R=$(J.Object({id:J.String(),subagentType:J.String(),description:J.String(),status:HJ,background:J.Boolean(),rootAgentId:J.String(),resumedFrom:J.Optional(J.String()),resumeDepth:J.Integer({minimum:0}),createdAt:J.Number(),lastActiveAt:J.Number(),completedAt:J.Optional(J.Number()),restartRecovery:J.Optional(J.Object({outcome:K(["completed","interrupted","failed"]),recoveredAt:J.Number()})),result:J.Optional(J.Object({success:J.Boolean(),message:J.String(),error:J.Optional(J.String()),verificationCommands:J.Optional(J.Array(J.String())),verificationVerdict:J.Optional(K(["pass","fail","partial"])),modifiedFiles:J.Optional(J.Array(J.String()))})),stats:J.Optional(J.Object({tokens:J.Optional(J.Number()),toolCalls:J.Optional(J.Number()),duration:J.Optional(J.Number())}))})),uJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"})})),dJ=$(J.Object({source:R,session:R})),mJ=$(J.Object({sessionId:J.String(),projectPath:J.String()})),cJ=$(J.Object({path:J.String(),name:J.String(),gitBranch:J.Optional(J.String()),available:J.Boolean(),isCurrent:J.Boolean(),boundAt:J.String()})),gJ=$(J.Union([J.Object({cancelled:J.Literal(!0)}),J.Object({cancelled:J.Literal(!1),path:J.String({minLength:1})})])),nJ=$(J.Object({type:J.String(),seq:J.Optional(J.Number()),properties:J.Record(J.String(),J.Unknown())})),m=J.Object({type:K(["file","image","url"]),path:J.Optional(J.String()),url:J.Optional(J.String()),content:J.Optional(J.String({maxLength:S})),mimeType:J.Optional(J.String()),name:J.Optional(J.String())}),c=J.Record(J.String(),J.Unknown()),oJ=$(J.Object({prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),title:J.Optional(J.String({minLength:1,maxLength:200})),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),sJ=$(J.Object({session:z,runId:J.String(),messageId:J.String(),status:K(["queued","running"]),queuePosition:J.Optional(J.Integer({minimum:1})),queueDepth:J.Optional(J.Integer({minimum:0})),maxConcurrentTasks:J.Optional(J.Integer({minimum:1}))})),iJ=$(J.Object({action:K(["apply","discard"])})),q=$(J.Object({kind:K(["cron","interval","once"]),cron:J.Optional(J.String({minLength:1,maxLength:120})),intervalMs:J.Optional(J.Integer({minimum:60000})),runAt:J.Optional(J.String({minLength:1,maxLength:40})),timezone:J.Optional(J.String({minLength:1,maxLength:80}))})),jJ=$(J.Object({modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default")})),x=$(J.Object({id:J.String(),title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,dispatch:jJ,enabled:J.Boolean(),createdAt:J.String(),updatedAt:J.String(),nextRunAt:J.Union([J.String(),J.Null()]),expiresAt:J.Union([J.String(),J.Null()]),lastRunAt:J.Optional(J.String()),lastRunSessionId:J.Optional(J.String()),lastStatus:J.Optional(K(["queued","running","completed","failed","cancelled","interrupted","error"])),lastError:J.Optional(J.String()),runCount:J.Integer({minimum:0})})),aJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.String({minLength:1,maxLength:32000,pattern:"\\S"}),projectPath:J.String({minLength:1}),trigger:q,modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:O(F,"worktree"),permissionMode:O(w,"default"),enabled:O(J.Boolean(),!0)})),tJ=$(J.Object({title:J.Optional(J.String({minLength:1,maxLength:200})),prompt:J.Optional(J.String({minLength:1,maxLength:32000,pattern:"\\S"})),trigger:J.Optional(q),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),isolation:J.Optional(F),permissionMode:J.Optional(w),enabled:J.Optional(J.Boolean())})),rJ=$(J.Object({schedules:J.Array(x)})),TJ=$(J.Object({content:J.String({maxLength:l}),projectPath:J.Optional(J.String()),modelId:J.Optional(J.String({minLength:1,maxLength:500})),reasoningEffort:J.Optional(L),serviceTier:J.Optional(P),responseVerbosity:J.Optional(M),communicationStyle:J.Optional(b),permissionMode:J.Optional(w),attachments:J.Optional(J.Array(m,{maxItems:v})),outputSchema:J.Optional(c)})),UJ=K(["completed","failed","aborted","timed_out","spawn_error"]),kJ=$(J.Object({version:J.Literal(1),command:J.String(),status:UJ,exitCode:J.Union([J.Integer(),J.Null()]),durationMs:J.Number({minimum:0}),stdout:J.String(),stderr:J.String(),stdoutOmittedBytes:J.Integer({minimum:0}),stderrOmittedBytes:J.Integer({minimum:0}),binaryOutput:J.Boolean(),truncated:J.Boolean()})),yJ=$(J.Object({command:J.String({minLength:1,maxLength:32768,pattern:"^(?![\\s\\S]*\\u0000)(?=[\\s\\S]*\\S)[\\s\\S]*$"}),projectPath:J.Optional(J.String())})),pJ=$(J.Object({executionId:J.String(),messageId:J.String(),record:kJ,auxiliary:J.Boolean(),delivery:J.Optional(K(["current_turn","next_turn"])),queued:J.Optional(J.Integer({minimum:0}))})),eJ=$(J.Object({projectPath:J.String(),kind:K(["uncommitted","base","commit"]),ref:J.Optional(J.String({maxLength:200})),instructions:J.Optional(J.String({maxLength:4000})),modelId:J.Optional(J.String({minLength:1,maxLength:200}))})),JQ=$(J.Object({reviewId:J.String(),status:J.Literal("running")})),QQ=$(J.Object({messageId:J.String(),role:N,content:J.String(),timestamp:J.String()})),ZQ=$(J.Object({approved:J.Boolean(),remember:J.Optional(J.Boolean()),scope:J.Optional(K(["once","session","project"])),targetMode:J.Optional(w),feedback:J.Optional(J.String()),answers:J.Optional(J.Record(J.String(),J.Union([J.String(),J.Array(J.String())]))),elicitation:J.Optional(J.Object({action:K(["accept","decline","cancel"]),content:J.Optional(J.Record(J.String(),J.Union([J.String({maxLength:4000}),J.Number(),J.Boolean(),J.Array(J.String({maxLength:1000}),{maxItems:100})]),{maxProperties:32}))}))})),VJ=$(J.Object({id:b,name:J.String({minLength:1,maxLength:80}),description:J.String({minLength:1,maxLength:256}),source:K(["built-in","user","project","plugin"]),contentSha256:J.Optional(J.String({pattern:"^[a-f0-9]{64}$"}))})),$Q=$(J.Object({id:J.String(),displayName:J.Optional(J.String()),provider:J.String(),model:J.String(),contextWindow:J.Optional(J.Number()),maxTokens:J.Optional(J.Number()),reasoning:J.Optional(J.Boolean()),supportedReasoningEfforts:J.Optional(J.Array(K(["off","minimal","low","medium","high","xhigh","max"]))),supportedServiceTiers:J.Optional(J.Array(K(["standard","fast","flex"]))),supportedResponseVerbosities:J.Optional(J.Array(K(["low","medium","high"]))),communicationStyles:J.Optional(J.Array(VJ,{maxItems:36})),input:J.Optional(J.Array(K(["text","image"]))),overrides:J.Optional(J.Object({baseUrl:J.Optional(J.String()),temperature:J.Optional(J.Number()),maxOutputTokens:J.Optional(J.Number()),timeout:J.Optional(J.Number()),streamIdleTimeout:J.Optional(J.Number({minimum:1000}))}))})),BQ=$(K(["vs-dark","vs-light","hc-black"])),GJ=$(K(["light","dark","system"])),OJ=$(J.Object({language:J.String(),codeTheme:J.String(),uiTheme:GJ,autoSaveSessions:J.Boolean(),notifyBuild:J.Boolean(),notifyErrors:J.Boolean(),notifySounds:J.Boolean(),privacyTelemetry:J.Boolean(),privacyCrash:J.Boolean(),communicationStyle:J.Optional(b)})),KQ=$(J.Partial(OJ));var g=o("Service"),MJ=1;function IJ(){return s.join(n(),"schedules.json")}class I{filePath;static instance;static getInstance(){if(!I.instance)I.instance=new I;return I.instance}writeChain=Promise.resolve();constructor(Q=IJ()){this.filePath=Q}async readFile(){try{let Q=await wJ(this.filePath,"utf-8"),Z=JSON.parse(Q);if(!Z||!Array.isArray(Z.schedules))return[];let W=[],B=0;for(let X of Z.schedules){let Y=x.safeParse(X);if(Y.success)W.push(Y.data);else B+=1}if(B>0)g.warn(`[ScheduleStore] Ignored ${B} invalid persisted schedule(s)`);return W}catch(Q){let Z=Q;if(Z.code!=="ENOENT")g.warn("[ScheduleStore] Failed to read schedules; treating as empty:",Z);return[]}}async writeFile(Q){await bJ(s.dirname(this.filePath),{recursive:!0,mode:493});let Z={version:MJ,schedules:Q};await PJ(this.filePath,JSON.stringify(Z,null,2),{mode:384})}serializeWrite(Q){let Z=this.writeChain.then(Q,Q);return this.writeChain=Z.then(()=>{return},()=>{return}),Z}async list(){return this.readFile()}async get(Q){return(await this.readFile()).find((W)=>W.id===Q)}async create(Q){return this.serializeWrite(async()=>{let Z=Q.trigger.kind==="cron"&&!Q.trigger.timezone?{...Q.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Q.trigger,W=_(Z);if(W)throw Error(W);let B=new Date;if(Z.kind==="once"&&new Date(Z.runAt).getTime()<=B.getTime())throw Error("once trigger runAt must be in the future");let X=B.toISOString(),Y=A(Z,B),k={id:LJ(10),title:Q.title,prompt:Q.prompt,projectPath:Q.projectPath,trigger:Z,dispatch:{modelId:Q.modelId,reasoningEffort:Q.reasoningEffort,serviceTier:Q.serviceTier,responseVerbosity:Q.responseVerbosity,communicationStyle:Q.communicationStyle,isolation:Q.isolation??"worktree",permissionMode:Q.permissionMode??"default"},enabled:Q.enabled??!0,createdAt:X,updatedAt:X,nextRunAt:Y?Y.toISOString():null,expiresAt:null,runCount:0},V=await this.readFile();return V.push(k),await this.writeFile(V),k})}async update(Q,Z){return this.serializeWrite(async()=>{let W=await this.readFile(),B=W.findIndex((H)=>H.id===Q);if(B===-1)return;let X=W[B];if(Z.trigger){let H=Z.trigger.kind==="cron"&&!Z.trigger.timezone?{...Z.trigger,timezone:Intl.DateTimeFormat().resolvedOptions().timeZone}:Z.trigger,U=_(H);if(U)throw Error(U);if(H.kind==="once"&&new Date(H.runAt).getTime()<=Date.now())throw Error("once trigger runAt must be in the future");Z={...Z,trigger:H}}let Y={...X,...Z,dispatch:Z.dispatch?{...X.dispatch,...Z.dispatch}:X.dispatch,updatedAt:new Date().toISOString()},k=!X.enabled,V=Y.enabled,j=Z.trigger!==void 0;if((j||k&&V)&&Z.nextRunAt===void 0){let H=new Date,U=A(Y.trigger,H);if(Y.nextRunAt=U?U.toISOString():null,j)Y.expiresAt=null}return W[B]=Y,await this.writeFile(W),Y})}async remove(Q){return this.serializeWrite(async()=>{let Z=await this.readFile(),W=Z.filter((B)=>B.id!==Q);if(W.length===Z.length)return!1;return await this.writeFile(W),!0})}async setEnabled(Q,Z){return this.update(Q,{enabled:Z})}}var LQ=I.getInstance();
2
- export{DJ as xa,A as ya,_ as za,FJ as Aa,qJ as Ba,z as Ca,lJ as Da,uJ as Ea,oJ as Fa,sJ as Ga,iJ as Ha,x as Ia,aJ as Ja,tJ as Ka,rJ as La,TJ as Ma,yJ as Na,eJ as Oa,I as Pa,LQ as Qa};
@@ -1 +0,0 @@
1
- import{Ad as g,Bd as h,Cd as i,Dd as j,Ed as k,Fd as l,Gd as m,Hd as n,Id as o,Jd as p,Kd as q,ud as a,vd as b,wd as c,xd as d,yd as e,zd as f}from"./chunk-fp2fh7cn.js";import"./chunk-v508x7cg.js";import"./chunk-wy4pn9sk.js";import"./chunk-2xsrqsk9.js";import"./chunk-khkhsaan.js";import"./chunk-7b467h8k.js";import"./chunk-9kmtcgm6.js";import"./chunk-kjvntyr5.js";import"./chunk-8ekk8pa7.js";import"./chunk-y8r2knxm.js";import"./chunk-1jc7d3nt.js";import"./chunk-fp1h8wdh.js";import"./chunk-6fdvffcc.js";import"./chunk-ej6h16ae.js";import"./chunk-cm9mph7j.js";import"./chunk-cz68x56m.js";import"./chunk-av10vmxk.js";export{a as vanillaStore,c as sessionActions,l as getThinkingModeEnabled,b as getState,n as getServiceTier,o as getResponseVerbosity,m as getReasoningEffort,j as getModelById,e as getMessages,k as getMcpServers,i as getCurrentModel,f as getConfig,p as getCommunicationStyle,h as getAllModels,g as ensureStoreInitialized,q as configActions,d as appActions};
@@ -1,2 +0,0 @@
1
- import{K as I}from"./chunk-xsx1av03.js";import{Cc as D}from"./chunk-adz2756v.js";import w from"node:path";function C(a){let t=a.replace(/\s+/g," ").trim();return t.length<=72?t:`${t.slice(0,69)}...`}function P(a){let t=a.replace(/\s+/g," ").trim();return t.length<=500?t:`${t.slice(0,497)}...`}function S(a){return`task/${a.replace(/[^a-zA-Z0-9_-]/g,"-").slice(0,40)}`}class z{static async createSessionTask(a){if(!a.prompt.trim())throw Error("Task prompt must not be blank");if(!w.isAbsolute(a.sourceProjectPath))throw Error("Task source project path must be absolute");let t=w.resolve(a.sourceProjectPath),s;try{return s=a.isolation==="worktree"?await I.enter({sessionId:a.sessionId,workspaceRoot:t,name:S(a.sessionId)}):void 0,{metadata:await D.createSessionMetadata(a.sessionId,s?.workspaceRoot??t,{title:a.title?.trim()||C(a.prompt),taskPromptSummary:P(a.prompt),taskDispatch:a.dispatch,taskModelId:a.dispatch?.modelId,selectedModelId:a.dispatch?.modelId,permissionMode:a.dispatch?.permissionMode,reasoningEffort:a.dispatch?.reasoningEffort,serviceTier:a.dispatch?.serviceTier,responseVerbosity:a.dispatch?.responseVerbosity,communicationStyle:a.dispatch?.communicationStyle,communicationStyleDigest:a.dispatch?.communicationStyleDigest,projectInstructionsDigest:a.dispatch?.projectInstructionsDigest,taskRetriedFrom:a.retriedFrom,taskIsolation:a.isolation,taskSourceProjectPath:t,taskWorktree:s}),taskWorktree:s}}catch(k){if(s)await I.exit({sessionId:a.sessionId,action:"remove",discardChanges:!0}).catch(()=>{return});throw k}}}var N=256,Z=8388608,_=30000;class c extends Error{kind;pendingItems;pendingBytes;constructor(a,t,s){super(t,s);this.kind=a;this.name="BoundedSerialEgressError",this.pendingItems=s?.pendingItems,this.pendingBytes=s?.pendingBytes}}function m(a){a.catch(()=>{return})}class F{options;pending=[];flushWaiters=[];pendingBytes=0;nextSequence=0;completedSequence=0;draining=!1;closed=!1;failure;activeWriteAbort;activeWriteStop;activeWriteTimeout;constructor(a){this.options=a;if(this.assertPositiveInteger(a.maxPendingItems,"maxPendingItems"),this.assertPositiveInteger(a.maxPendingBytes,"maxPendingBytes"),this.assertPositiveInteger(a.writeTimeoutMs,"writeTimeoutMs"),a.signal?.addEventListener("abort",this.handleAbort,{once:!0}),a.signal?.aborted)this.handleAbort()}offer(a){if(this.closed)return{accepted:!1,error:this.failure??new c("closed","Egress is already closed")};let t;try{t=this.options.sizeOf(a)}catch(i){return this.rejectAdmission(new c("invalid_size","Egress size calculation failed",{cause:i}))}if(!Number.isSafeInteger(t)||t<0)return this.rejectAdmission(new c("invalid_size","Egress size must be a non-negative safe integer"));if(t>this.options.maxPendingBytes)return this.rejectAdmission(new c("oversized",`Egress value requires ${t} bytes; limit is ${this.options.maxPendingBytes}`));if(this.pending.length>=this.options.maxPendingItems||this.pendingBytes+t>this.options.maxPendingBytes)return this.rejectAdmission(new c("overflow",`Egress pending limit exceeded (${this.pending.length} items, ${this.pendingBytes} bytes)`));let s,k,h=new Promise((i,f)=>{s=i,k=f});return m(h),this.nextSequence+=1,this.pending.push({value:a,bytes:t,sequence:this.nextSequence,resolve:s,reject:k,completion:h}),this.pendingBytes+=t,this.startDrain(),{accepted:!0,completion:h}}flush(){if(this.failure){let h=Promise.reject(this.failure);return m(h),h}let a=this.nextSequence;if(a<=this.completedSequence)return Promise.resolve();let t,s,k=new Promise((h,i)=>{t=h,s=i});return m(k),this.flushWaiters.push({targetSequence:a,resolve:t,reject:s}),k}close(a){let t=a instanceof c?a:new c("closed","Egress was closed",{cause:a});this.fail(t)}stats(){return{closed:this.closed,pendingItems:this.pending.length,pendingBytes:this.pendingBytes}}handleAbort=()=>{this.fail(new c("aborted","Egress was aborted",{cause:this.options.signal?.reason}))};rejectAdmission(a){return this.fail(a),{accepted:!1,error:a}}startDrain(){if(this.draining||this.closed)return;this.draining=!0;let a=this.drain();m(a)}async drain(){try{while(!this.closed){let a=this.pending[0];if(!a)return;try{await this.writeOne(a.value)}catch(t){this.fail(this.normalizeWriteError(t));return}if(this.closed||this.pending[0]!==a)return;this.pending.shift(),this.pendingBytes-=a.bytes,this.completedSequence=a.sequence,a.resolve(),this.settleFlushWaiters()}}finally{if(this.draining=!1,!this.closed&&this.pending.length>0)this.startDrain()}}async writeOne(a){let t=new AbortController;this.activeWriteAbort=t;let s,k,h=new Promise((W,T)=>{k=T});m(h),this.activeWriteStop=k;let i=Promise.resolve().then(()=>this.options.write(a,t.signal));m(i);let f=new Promise((W,T)=>{s=setTimeout(()=>{let M=new c("write_timeout",`Egress write timed out after ${this.options.writeTimeoutMs}ms`);t.abort(M),T(M)},this.options.writeTimeoutMs),this.activeWriteTimeout=s});m(f);try{await Promise.race([i,f,h])}finally{if(s!==void 0)clearTimeout(s);if(this.activeWriteTimeout===s)this.activeWriteTimeout=void 0;if(this.activeWriteAbort===t)this.activeWriteAbort=void 0;if(this.activeWriteStop===k)this.activeWriteStop=void 0}}normalizeWriteError(a){if(a instanceof c)return a;return new c("write_failed","Egress write failed",{cause:a})}fail(a){if(this.closed)return;if(a.pendingItems??=this.pending.length,a.pendingBytes??=this.pendingBytes,this.closed=!0,this.failure=a,this.options.signal?.removeEventListener("abort",this.handleAbort),this.activeWriteTimeout!==void 0)clearTimeout(this.activeWriteTimeout),this.activeWriteTimeout=void 0;this.activeWriteAbort?.abort(a),this.activeWriteStop?.(a),this.activeWriteAbort=void 0,this.activeWriteStop=void 0;let t=this.pending.splice(0);this.pendingBytes=0;for(let s of t)s.reject(a);for(let s of this.flushWaiters.splice(0))s.reject(a);try{this.options.onFailure?.(a)}catch{}}settleFlushWaiters(){for(let a=0;a<this.flushWaiters.length;){let t=this.flushWaiters[a];if(t.targetSequence>this.completedSequence){a+=1;continue}this.flushWaiters.splice(a,1),t.resolve()}}assertPositiveInteger(a,t){if(!Number.isSafeInteger(a)||a<=0)throw RangeError(`${t} must be a positive safe integer`)}}
2
- export{z as v,N as w,Z as x,_ as y,c as z,F as A};
@@ -1 +0,0 @@
1
- import{a,b,c,d,e}from"./chunk-k4ermznt.js";import"./chunk-6fdvffcc.js";import"./chunk-av10vmxk.js";export{b as setSkipUntilVersion,d as performUpgrade,c as getUpgradeCommand,e as checkVersionOnStartup,a as checkVersion};