@tansr/cli 0.10.2 → 0.11.0

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 (133) hide show
  1. package/package.json +1 -1
  2. package/tansr-artifacts.json +1222 -830
  3. package/tansr-bg-A35DNHK2.mjs +5 -0
  4. package/tansr-chunk-2CIB4KCJ.mjs +5 -0
  5. package/{tansr-chunk-XXBNISJJ.mjs → tansr-chunk-2HZJSKHM.mjs} +2 -2
  6. package/{tansr-chunk-E67N3BDI.mjs → tansr-chunk-2PB54HDR.mjs} +2 -2
  7. package/tansr-chunk-33QZBUL6.mjs +6 -0
  8. package/tansr-chunk-3YSQG6KY.mjs +5 -0
  9. package/tansr-chunk-4DAH4AIH.mjs +7 -0
  10. package/{tansr-chunk-S77B4PI7.mjs → tansr-chunk-4IWNKAT5.mjs} +2 -2
  11. package/tansr-chunk-4YAEV3T6.mjs +9 -0
  12. package/tansr-chunk-546BDI3V.mjs +7 -0
  13. package/tansr-chunk-6N333TUL.mjs +241 -0
  14. package/{tansr-chunk-ZY3IR67Q.mjs → tansr-chunk-6QKU3GNA.mjs} +2 -2
  15. package/tansr-chunk-AHUB2IHT.mjs +5 -0
  16. package/tansr-chunk-AOH7YPF3.mjs +8 -0
  17. package/{tansr-chunk-C6COFFZK.mjs → tansr-chunk-B2O4DB4K.mjs} +2 -2
  18. package/tansr-chunk-C2NTVBEY.mjs +5 -0
  19. package/{tansr-chunk-UCG4D6ER.mjs → tansr-chunk-C75DEEUJ.mjs} +2 -2
  20. package/tansr-chunk-ECYZ457U.mjs +5 -0
  21. package/tansr-chunk-EFN24XG3.mjs +25 -0
  22. package/tansr-chunk-ENRIN7EG.mjs +7 -0
  23. package/{tansr-chunk-RVSBSUXE.mjs → tansr-chunk-ITZBYACC.mjs} +2 -2
  24. package/{tansr-chunk-J72JGEKH.mjs → tansr-chunk-IZZYKHSW.mjs} +3 -3
  25. package/tansr-chunk-JIC3VWLQ.mjs +252 -0
  26. package/tansr-chunk-JTGWG4BG.mjs +32 -0
  27. package/tansr-chunk-LA3LGOYQ.mjs +11 -0
  28. package/tansr-chunk-MAMODDQN.mjs +5 -0
  29. package/tansr-chunk-N644DEOO.mjs +5 -0
  30. package/tansr-chunk-NQOYEFEE.mjs +5 -0
  31. package/tansr-chunk-O7P4OFK7.mjs +7 -0
  32. package/tansr-chunk-OEHA7T4Q.mjs +26 -0
  33. package/{tansr-chunk-CI7LFRTK.mjs → tansr-chunk-OKNSOZDU.mjs} +7 -7
  34. package/tansr-chunk-OT4KIQLR.mjs +9 -0
  35. package/tansr-chunk-OUOTEH4A.mjs +5 -0
  36. package/tansr-chunk-Q3XDAUKT.mjs +65 -0
  37. package/tansr-chunk-RFH7OCN6.mjs +5 -0
  38. package/tansr-chunk-RUYIVG72.mjs +12 -0
  39. package/tansr-chunk-SCFXBKV6.mjs +8 -0
  40. package/tansr-chunk-SHLU4JN2.mjs +5 -0
  41. package/{tansr-chunk-M774GK3P.mjs → tansr-chunk-SIV2666W.mjs} +2 -2
  42. package/tansr-chunk-SX3XZNN6.mjs +6 -0
  43. package/tansr-chunk-SXNTYWJY.mjs +8 -0
  44. package/tansr-chunk-UVL2XWKL.mjs +5 -0
  45. package/tansr-chunk-V4HGMAJS.mjs +375 -0
  46. package/{tansr-chunk-OB47UYHK.mjs → tansr-chunk-W2WIN3M2.mjs} +2 -2
  47. package/tansr-chunk-WAYVH5ON.mjs +5 -0
  48. package/tansr-chunk-WPKFARCU.mjs +11 -0
  49. package/{tansr-chunk-726Y5F3M.mjs → tansr-chunk-YEYFEVYF.mjs} +2 -2
  50. package/tansr-chunk-YK3CE3JM.mjs +5 -0
  51. package/tansr-chunk-YOSRXZWY.mjs +5 -0
  52. package/tansr-compaction-history-LZXZTWBV.mjs +5 -0
  53. package/tansr-compaction-log-H2SPLK24.mjs +5 -0
  54. package/tansr-indexed-CPYJVPFI.mjs +5 -0
  55. package/tansr-lock-XWDVZMLY.mjs +5 -0
  56. package/tansr-main-6GDLXIRQ.mjs +7 -0
  57. package/tansr-render-SVMDLHLN.mjs +6 -0
  58. package/tansr-restore-7PS7WCJR.mjs +5 -0
  59. package/tansr-run-acp-entry-EQGUKZ5R.mjs +68 -0
  60. package/tansr-run-approvals-entry-SEYBHLS2.mjs +12 -0
  61. package/{tansr-run-auth-entry-X3SXNPOI.mjs → tansr-run-auth-entry-R3GKGKWX.mjs} +2 -2
  62. package/tansr-run-doctor-B3XK72DW.mjs +11 -0
  63. package/tansr-run-headless-entry-4XTAVPTW.mjs +84 -0
  64. package/tansr-run-init-entry-GH2KDGI6.mjs +5 -0
  65. package/tansr-run-logout-entry-PLGYDEOB.mjs +5 -0
  66. package/tansr-run-mcp-serve-entry-UHK4WSKL.mjs +14 -0
  67. package/tansr-run-orchestrate-entry-M7R3433X.mjs +11 -0
  68. package/tansr-run-org-entry-UONLGJIJ.mjs +17 -0
  69. package/tansr-run-policy-entry-NNQCV5WS.mjs +16 -0
  70. package/tansr-run-profile-entry-PV6OO7FV.mjs +14 -0
  71. package/tansr-run-serve-entry-GWZQZ37P.mjs +16 -0
  72. package/tansr-run-sessions-entry-WL7YLRJL.mjs +25 -0
  73. package/tansr-run-update-entry-YI47IPCC.mjs +5 -0
  74. package/tansr-spill-YVUTIFOS.mjs +5 -0
  75. package/tansr-src-LPMSGRKO.mjs +5 -0
  76. package/{tansr-src-JAODAP53.mjs → tansr-src-RQJPOVDN.mjs} +50 -50
  77. package/tansr-startup-account-MYFJ3NOL.mjs +7 -0
  78. package/{tansr-startup-model-SREG5HNN.mjs → tansr-startup-model-BCGEYUM4.mjs} +3 -3
  79. package/tansr-storage-journal-4E274MUA.mjs +5 -0
  80. package/tansr-todos-replay-TVQKP7OD.mjs +5 -0
  81. package/tansr-tui-3Q7Z3ALV.mjs +73 -0
  82. package/tansr.mjs +1 -1
  83. package/tansrd.mjs +444 -265
  84. package/tansr-bg-QY4G2SNZ.mjs +0 -5
  85. package/tansr-chunk-2C6JKHKM.mjs +0 -25
  86. package/tansr-chunk-53SL6W6G.mjs +0 -6
  87. package/tansr-chunk-5T7X32UX.mjs +0 -6
  88. package/tansr-chunk-6OXR4F5Y.mjs +0 -67
  89. package/tansr-chunk-BCOFZJWA.mjs +0 -279
  90. package/tansr-chunk-BX7CF5RQ.mjs +0 -25
  91. package/tansr-chunk-F7C6ITED.mjs +0 -5
  92. package/tansr-chunk-H6JYYWPW.mjs +0 -35
  93. package/tansr-chunk-HRKJLVKC.mjs +0 -7
  94. package/tansr-chunk-I3TOVAA6.mjs +0 -5
  95. package/tansr-chunk-J2ED6CI4.mjs +0 -5
  96. package/tansr-chunk-KSBP64Q5.mjs +0 -12
  97. package/tansr-chunk-LSYPDTQG.mjs +0 -22
  98. package/tansr-chunk-MWHLITGY.mjs +0 -11
  99. package/tansr-chunk-NA22YT73.mjs +0 -5
  100. package/tansr-chunk-NCIMR6LB.mjs +0 -5
  101. package/tansr-chunk-OSK64SU3.mjs +0 -5
  102. package/tansr-chunk-Q6MUMULP.mjs +0 -5
  103. package/tansr-chunk-QEKVLX7W.mjs +0 -5
  104. package/tansr-chunk-QHEQQ2JB.mjs +0 -9
  105. package/tansr-chunk-QNHXB55W.mjs +0 -11
  106. package/tansr-chunk-QWGSXFEJ.mjs +0 -7
  107. package/tansr-chunk-SJFDQLLC.mjs +0 -5
  108. package/tansr-chunk-TYJWMSVW.mjs +0 -5
  109. package/tansr-chunk-TZJHQ3TT.mjs +0 -38
  110. package/tansr-chunk-UAEARRRH.mjs +0 -8
  111. package/tansr-chunk-WGXWBU37.mjs +0 -8
  112. package/tansr-chunk-ZQ3ZK7IL.mjs +0 -37
  113. package/tansr-main-5V46X7QH.mjs +0 -7
  114. package/tansr-render-PUEISX75.mjs +0 -6
  115. package/tansr-run-acp-entry-ANNUR7IB.mjs +0 -63
  116. package/tansr-run-approvals-entry-SLLTFTSX.mjs +0 -12
  117. package/tansr-run-doctor-RYIQQOOK.mjs +0 -10
  118. package/tansr-run-headless-entry-I53HJDNX.mjs +0 -78
  119. package/tansr-run-init-entry-USPWKDRI.mjs +0 -5
  120. package/tansr-run-logout-entry-KO7ZL2M5.mjs +0 -5
  121. package/tansr-run-mcp-serve-entry-YMQH7WSF.mjs +0 -14
  122. package/tansr-run-orchestrate-entry-YN3M6BWY.mjs +0 -11
  123. package/tansr-run-org-entry-STRRZVI4.mjs +0 -17
  124. package/tansr-run-policy-entry-4ENHRAMQ.mjs +0 -16
  125. package/tansr-run-profile-entry-THJMZ7ZA.mjs +0 -14
  126. package/tansr-run-serve-entry-N5PK7ACI.mjs +0 -99
  127. package/tansr-run-sessions-entry-KIT7PALM.mjs +0 -23
  128. package/tansr-run-update-entry-HYSKHBB6.mjs +0 -5
  129. package/tansr-sqlite-event-store-UQLSSZKP.mjs +0 -26
  130. package/tansr-sqlite-spool-implementation-LHEIRSUX.mjs +0 -29
  131. package/tansr-src-KOEPYVXX.mjs +0 -5
  132. package/tansr-startup-account-QUJKOV6V.mjs +0 -7
  133. package/tansr-tui-DXGFMSII.mjs +0 -75
@@ -1,7 +1,7 @@
1
1
  import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
2
  import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
3
  const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
- import{a as N}from"./tansr-chunk-Q6MUMULP.mjs";import{a as Z}from"./tansr-chunk-AMMPDY4V.mjs";import{x as Ae}from"./tansr-chunk-WGXWBU37.mjs";import{l as V}from"./tansr-chunk-HRKJLVKC.mjs";import{ef as R}from"./tansr-chunk-BCOFZJWA.mjs";import{k as xe,m as c,o as Ie}from"./tansr-chunk-NA22YT73.mjs";import{Fb as F}from"./tansr-chunk-QWGSXFEJ.mjs";var d={launchTask:"cli.bg.launch.task",launchLog:"cli.bg.launch.log",launchWorktree:"cli.bg.launch.worktree",listHeader:"cli.bg.list.header",listEmpty:"cli.bg.list.empty",listLine:"cli.bg.list.line",showHeader:"cli.bg.show.header",showStatus:"cli.bg.show.status",showSelfHealed:"cli.bg.show.self_healed",showPid:"cli.bg.show.pid",showStarted:"cli.bg.show.started",showEnded:"cli.bg.show.ended",showExitCode:"cli.bg.show.exit_code",showCwd:"cli.bg.show.cwd",showWorktree:"cli.bg.show.worktree",showSession:"cli.bg.show.session",showPrompt:"cli.bg.show.prompt",showLog:"cli.bg.show.log",showTailHeader:"cli.bg.show.tail_header",notFound:"cli.bg.error.not_found",showUsage:"cli.bg.error.show_usage",killUsage:"cli.bg.error.kill_usage",killNotRunning:"cli.bg.kill.not_running",killStale:"cli.bg.kill.stale",killFailed:"cli.bg.error.kill_failed",killDone:"cli.bg.kill.done",killStopped:"cli.bg.kill.stopped",killExited:"cli.bg.kill.exited",killIdentity:"cli.bg.kill.identity",killForceIdentity:"cli.bg.kill.force_identity",killForced:"cli.bg.kill.forced",runnerEndpointFailed:"cli.bg.error.runner_endpoint_failed",cleanDone:"cli.bg.clean.done",cleanDoneWithLogs:"cli.bg.clean.done_with_logs",cleanEmpty:"cli.bg.clean.empty",registryWriteFailed:"cli.bg.error.registry_write_failed"},gt=Object.values(d);import{randomBytes as oe}from"node:crypto";import{mkdir as mt,readFile as ie,readdir as kt,rename as Ne,rm as I,writeFile as Oe}from"node:fs/promises";import{existsSync as yt,mkdirSync as Rt,readFileSync as ee,readdirSync as ht,renameSync as St,rmSync as te,writeFileSync as wt}from"node:fs";import E from"node:path";var ve="background",ne=120,De=["running","completed","failed"],Ce=["sentinel","pid-probe"],Le=[15,30,60,120,250,500,1e3],Pt=new Set(["EPERM","EACCES","EBUSY"]),Tt=e=>new Promise(t=>setTimeout(t,e));function Me(e){let t=e.code;return typeof t=="string"&&Pt.has(t)}async function Fe(e,t){let n=e?.sleep??Tt;for(let r=0;;r+=1)try{return await t()}catch(i){let o=Le[r];if(!Me(i)||o===void 0)throw i;await n(o)}}function T(e){return E.join(V(e),ve)}function _(e,t){return E.join(T(e),`${t}.json`)}function se(e,t){return E.join(T(e),`${t}.log`)}function U(e,t){return E.join(T(e),`${t}.final`)}var ae=".sock";function ue(e,t){return E.join(T(e),`${t}${ae}`)}function ce(e=()=>new Date){return`bg-${e().getTime().toString(36)}-${oe(2).toString("hex")}`}function de(e){let t=F(e).replace(/\s+/g," ").trim();return t.length<=ne?t:`${t.slice(0,ne-1)}…`}function le(e){return e.map(t=>F(t))}async function Ge(e,t,n){let r=_(e,t.id);await mt(E.dirname(r),{recursive:!0});let i=`${r}.tmp-${process.pid}-${oe(2).toString("hex")}`;try{await Oe(i,JSON.stringify(t,null,2),"utf8"),await n(i,r)}catch(o){throw await I(i,{force:!0}).catch(()=>{}),o}}async function G(e,t,n){let r=n?.rename??(async(i,o)=>Ne(i,o));await Fe(n,()=>Ge(e,t,r))}function A(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.id!="string"||n.id===""||typeof n.promptSummary!="string"||typeof n.cwd!="string"||!Array.isArray(n.argv)||n.argv.some(o=>typeof o!="string")||typeof n.logPath!="string"||!De.includes(n.status)||typeof n.startedAt!="string"||!((n.pid===void 0||typeof n.pid=="number")&&(n.sessionId===void 0||typeof n.sessionId=="string")&&(n.worktreePath===void 0||typeof n.worktreePath=="string")&&(n.endedAt===void 0||typeof n.endedAt=="string")&&(n.exitCode===void 0||typeof n.exitCode=="number")&&(n.selfHealed===void 0||Ce.includes(n.selfHealed))&&(n.runner===void 0||Et(n.runner))&&(n.process===void 0||Bt(n.process))))return null;let i={schemaVersion:1,id:n.id,promptSummary:n.promptSummary,cwd:n.cwd,argv:n.argv,logPath:n.logPath,status:n.status,startedAt:n.startedAt};if(n.pid!==void 0&&(i.pid=n.pid),n.sessionId!==void 0&&(i.sessionId=n.sessionId),n.worktreePath!==void 0&&(i.worktreePath=n.worktreePath),n.endedAt!==void 0&&(i.endedAt=n.endedAt),n.exitCode!==void 0&&(i.exitCode=n.exitCode),n.selfHealed!==void 0&&(i.selfHealed=n.selfHealed),n.runner!==void 0){let o=n.runner;i.runner={endpoint:o.endpoint,token:o.token}}if(n.process!==void 0){let o=n.process;i.process={...o.startTime!==void 0?{startTime:o.startTime}:{},...o.cmdlineSha256!==void 0?{cmdlineSha256:o.cmdlineSha256}:{}}}return i}function Et(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.endpoint=="string"&&t.endpoint!==""&&typeof t.token=="string"&&t.token!==""}function Bt(e){if(typeof e!="object"||e===null)return!1;let t=e,n=r=>r===void 0||typeof r=="string"&&r!=="";return n(t.startTime)&&n(t.cmdlineSha256)}function H(e){let{runner:t,...n}=e;return t===void 0?n:{...n,runner:{endpoint:t.endpoint}}}function Ue(e,t){let n;try{n=JSON.parse(e)}catch{return null}if(typeof n!="object"||n===null)return null;let r=n;if(r.schemaVersion!==1||r.id!==t||r.status!=="completed"&&r.status!=="failed"||typeof r.endedAt!="string"||r.exitCode!==void 0&&typeof r.exitCode!="number")return null;let i={status:r.status,endedAt:r.endedAt};return r.exitCode!==void 0&&(i.exitCode=r.exitCode),i}async function q(e,t){let n;try{n=await ie(_(e,t),"utf8")}catch{return null}return A(n)}function He(e,t){return{...e,status:t.status,endedAt:t.endedAt,...t.exitCode!==void 0?{exitCode:t.exitCode}:{},selfHealed:"sentinel"}}async function $e(e,t,n,r){let i=U(e,t.id),o=r??yt(i);if(t.status!=="running")return o&&await I(i,{force:!0}).catch(()=>{}),t;if(o){let l=null;try{l=Ue(await ie(i,"utf8"),t.id)}catch{l=null}if(l!==null){let h=He(t,l);return await G(e,h,n.io).then(()=>!0).catch(()=>!1)&&await I(i,{force:!0}).catch(()=>{}),h}}let s=n.pidAlive??D;if(t.pid===void 0||s(t.pid))return t;let a=await q(e,t.id);if(a===null)return null;if(a.status!=="running")return a;let u=n.now??(()=>new Date),f={...a,status:"failed",endedAt:u().toISOString(),selfHealed:"pid-probe"};return await G(e,f,n.io).catch(()=>{}),f}function _t(e,t,n,r){let i=U(e,t.id);if(t.status!=="running"){if(r)try{te(i,{force:!0})}catch{}return t}if(r){let f=null;try{f=Ue(ee(i,"utf8"),t.id)}catch{f=null}if(f!==null){let l=He(t,f);try{re(e,l),te(i,{force:!0})}catch{}return l}}let o=n.pidAlive??D;if(t.pid===void 0||o(t.pid))return t;let s=null;try{s=A(ee(_(e,t.id),"utf8"))}catch{return null}if(s===null)return null;if(s.status!=="running")return s;let a=n.now??(()=>new Date),u={...s,status:"failed",endedAt:a().toISOString(),selfHealed:"pid-probe"};try{re(e,u)}catch{}return u}async function Y(e,t,n={}){let r=await q(e,t);return r===null?null:$e(e,r,n)}async function O(e,t,n,r){let i=r?.rename??(async(o,s)=>Ne(o,s));return Fe(r,async()=>{let o=await q(e,t);if(o===null)return null;let s={...o,...n,schemaVersion:1,id:o.id};return await Ge(e,s,i),s})}async function v(e,t,n,r){try{let s=await O(e,t,n,r);return s===null?null:{record:s,via:"record"}}catch(s){if(!Me(s))throw s}let i=await q(e,t);if(i===null)return null;let o={schemaVersion:1,id:t,...n};return await Oe(U(e,t),JSON.stringify(o,null,2),"utf8"),{record:{...i,...n},via:"sentinel"}}async function z(e,t={}){let n;try{n=await kt(T(e))}catch{return[]}let r=new Set(n.filter(o=>o.endsWith(".final"))),i=[];for(let o of n.filter(s=>s.endsWith(".json")))try{let s=await ie(E.join(T(e),o),"utf8"),a=A(s);if(a===null)continue;let u=await $e(e,a,t,r.has(`${a.id}.final`));u!==null&&i.push(u)}catch{continue}return i.sort((o,s)=>s.startedAt.localeCompare(o.startedAt)||s.id.localeCompare(o.id)),i}function bt(e,t={}){let n;try{n=ht(T(e))}catch{return[]}let r=new Set(n.filter(o=>o.endsWith(".final"))),i=[];for(let o of n.filter(s=>s.endsWith(".json")))try{let s=A(ee(E.join(T(e),o),"utf8"));if(s===null)continue;let a=_t(e,s,t,r.has(`${s.id}.final`));a!==null&&i.push(a)}catch{continue}return i.sort((o,s)=>s.startedAt.localeCompare(o.startedAt)||s.id.localeCompare(o.id)),i}function re(e,t){let n=_(e,t.id);Rt(E.dirname(n),{recursive:!0});let r=`${n}.tmp-${process.pid}-${oe(2).toString("hex")}`;try{wt(r,JSON.stringify(t,null,2),"utf8"),St(r,n)}catch(i){try{te(r,{force:!0})}catch{}throw i}}async function fe(e,t,n){await I(_(e,t.id),{force:!0}),await I(U(e,t.id),{force:!0}),await I(ue(e,t.id),{force:!0}),n&&await I(t.logPath,{force:!0})}function D(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function $(e,t=D){return e.status!=="running"?e.status:e.pid===void 0||!t(e.pid)?"stale":"running"}import{createHash as xt}from"node:crypto";import{rm as Ke}from"node:fs/promises";import je from"node:net";import It from"node:os";import At from"node:path";var X="TANSR_BG_RUNNER_ENDPOINT",K="TANSR_BG_RUNNER_TOKEN",We=1e3,Nt=2e3,Ot=4096,vt=100;function pe(e,t,n=process.platform){if(n==="win32"){let i=xt("sha1").update(e).digest("hex").slice(0,8);return`\\\\.\\pipe\\tansr-bg-${t}-${i}`}let r=ue(e,t);return Buffer.byteLength(r)<=vt?r:At.join(It.tmpdir(),`tansr-${t}${ae}`)}function Dt(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t;return typeof n.op!="string"||typeof n.token!="string"?null:{op:n.op,token:n.token}}function Ct(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}async function ge(e){let t=e.platform??process.platform,n=e.pid??process.pid,r=!1,i=new Set,o=je.createServer(a=>{i.add(a),a.setEncoding("utf8"),a.setTimeout(Nt,()=>a.destroy()),a.on("close",()=>{i.delete(a)}),a.on("error",()=>{});let u="",f=!1,l=h=>{f||(f=!0,a.end(JSON.stringify(h)+`
4
+ import{z as Ae}from"./tansr-chunk-OT4KIQLR.mjs";import{a as Z}from"./tansr-chunk-AMMPDY4V.mjs";import{b as R}from"./tansr-chunk-YOSRXZWY.mjs";import{p as N}from"./tansr-chunk-WAYVH5ON.mjs";import{l as V}from"./tansr-chunk-AHUB2IHT.mjs";import{k as xe,m as c,o as Ie}from"./tansr-chunk-YK3CE3JM.mjs";import{Sb as F}from"./tansr-chunk-ENRIN7EG.mjs";var d={launchTask:"cli.bg.launch.task",launchLog:"cli.bg.launch.log",launchWorktree:"cli.bg.launch.worktree",listHeader:"cli.bg.list.header",listEmpty:"cli.bg.list.empty",listLine:"cli.bg.list.line",showHeader:"cli.bg.show.header",showStatus:"cli.bg.show.status",showSelfHealed:"cli.bg.show.self_healed",showPid:"cli.bg.show.pid",showStarted:"cli.bg.show.started",showEnded:"cli.bg.show.ended",showExitCode:"cli.bg.show.exit_code",showCwd:"cli.bg.show.cwd",showWorktree:"cli.bg.show.worktree",showSession:"cli.bg.show.session",showPrompt:"cli.bg.show.prompt",showLog:"cli.bg.show.log",showTailHeader:"cli.bg.show.tail_header",notFound:"cli.bg.error.not_found",showUsage:"cli.bg.error.show_usage",killUsage:"cli.bg.error.kill_usage",killNotRunning:"cli.bg.kill.not_running",killStale:"cli.bg.kill.stale",killFailed:"cli.bg.error.kill_failed",killDone:"cli.bg.kill.done",killStopped:"cli.bg.kill.stopped",killExited:"cli.bg.kill.exited",killIdentity:"cli.bg.kill.identity",killForceIdentity:"cli.bg.kill.force_identity",killForced:"cli.bg.kill.forced",runnerEndpointFailed:"cli.bg.error.runner_endpoint_failed",cleanDone:"cli.bg.clean.done",cleanDoneWithLogs:"cli.bg.clean.done_with_logs",cleanEmpty:"cli.bg.clean.empty",registryWriteFailed:"cli.bg.error.registry_write_failed"},gt=Object.values(d);import{randomBytes as oe}from"node:crypto";import{mkdir as mt,readFile as ie,readdir as kt,rename as Ne,rm as I,writeFile as Oe}from"node:fs/promises";import{existsSync as yt,mkdirSync as Rt,readFileSync as ee,readdirSync as ht,renameSync as St,rmSync as te,writeFileSync as wt}from"node:fs";import E from"node:path";var ve="background",ne=120,De=["running","completed","failed"],Ce=["sentinel","pid-probe"],Le=[15,30,60,120,250,500,1e3],Pt=new Set(["EPERM","EACCES","EBUSY"]),Tt=e=>new Promise(t=>setTimeout(t,e));function Me(e){let t=e.code;return typeof t=="string"&&Pt.has(t)}async function Fe(e,t){let n=e?.sleep??Tt;for(let r=0;;r+=1)try{return await t()}catch(i){let o=Le[r];if(!Me(i)||o===void 0)throw i;await n(o)}}function T(e){return E.join(V(e),ve)}function _(e,t){return E.join(T(e),`${t}.json`)}function se(e,t){return E.join(T(e),`${t}.log`)}function U(e,t){return E.join(T(e),`${t}.final`)}var ae=".sock";function ue(e,t){return E.join(T(e),`${t}${ae}`)}function ce(e=()=>new Date){return`bg-${e().getTime().toString(36)}-${oe(2).toString("hex")}`}function de(e){let t=F(e).replace(/\s+/g," ").trim();return t.length<=ne?t:`${t.slice(0,ne-1)}…`}function le(e){return e.map(t=>F(t))}async function Ge(e,t,n){let r=_(e,t.id);await mt(E.dirname(r),{recursive:!0});let i=`${r}.tmp-${process.pid}-${oe(2).toString("hex")}`;try{await Oe(i,JSON.stringify(t,null,2),"utf8"),await n(i,r)}catch(o){throw await I(i,{force:!0}).catch(()=>{}),o}}async function G(e,t,n){let r=n?.rename??(async(i,o)=>Ne(i,o));await Fe(n,()=>Ge(e,t,r))}function A(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t;if(n.schemaVersion!==1||typeof n.id!="string"||n.id===""||typeof n.promptSummary!="string"||typeof n.cwd!="string"||!Array.isArray(n.argv)||n.argv.some(o=>typeof o!="string")||typeof n.logPath!="string"||!De.includes(n.status)||typeof n.startedAt!="string"||!((n.pid===void 0||typeof n.pid=="number")&&(n.sessionId===void 0||typeof n.sessionId=="string")&&(n.worktreePath===void 0||typeof n.worktreePath=="string")&&(n.endedAt===void 0||typeof n.endedAt=="string")&&(n.exitCode===void 0||typeof n.exitCode=="number")&&(n.selfHealed===void 0||Ce.includes(n.selfHealed))&&(n.runner===void 0||Et(n.runner))&&(n.process===void 0||Bt(n.process))))return null;let i={schemaVersion:1,id:n.id,promptSummary:n.promptSummary,cwd:n.cwd,argv:n.argv,logPath:n.logPath,status:n.status,startedAt:n.startedAt};if(n.pid!==void 0&&(i.pid=n.pid),n.sessionId!==void 0&&(i.sessionId=n.sessionId),n.worktreePath!==void 0&&(i.worktreePath=n.worktreePath),n.endedAt!==void 0&&(i.endedAt=n.endedAt),n.exitCode!==void 0&&(i.exitCode=n.exitCode),n.selfHealed!==void 0&&(i.selfHealed=n.selfHealed),n.runner!==void 0){let o=n.runner;i.runner={endpoint:o.endpoint,token:o.token}}if(n.process!==void 0){let o=n.process;i.process={...o.startTime!==void 0?{startTime:o.startTime}:{},...o.cmdlineSha256!==void 0?{cmdlineSha256:o.cmdlineSha256}:{}}}return i}function Et(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.endpoint=="string"&&t.endpoint!==""&&typeof t.token=="string"&&t.token!==""}function Bt(e){if(typeof e!="object"||e===null)return!1;let t=e,n=r=>r===void 0||typeof r=="string"&&r!=="";return n(t.startTime)&&n(t.cmdlineSha256)}function H(e){let{runner:t,...n}=e;return t===void 0?n:{...n,runner:{endpoint:t.endpoint}}}function Ue(e,t){let n;try{n=JSON.parse(e)}catch{return null}if(typeof n!="object"||n===null)return null;let r=n;if(r.schemaVersion!==1||r.id!==t||r.status!=="completed"&&r.status!=="failed"||typeof r.endedAt!="string"||r.exitCode!==void 0&&typeof r.exitCode!="number")return null;let i={status:r.status,endedAt:r.endedAt};return r.exitCode!==void 0&&(i.exitCode=r.exitCode),i}async function q(e,t){let n;try{n=await ie(_(e,t),"utf8")}catch{return null}return A(n)}function He(e,t){return{...e,status:t.status,endedAt:t.endedAt,...t.exitCode!==void 0?{exitCode:t.exitCode}:{},selfHealed:"sentinel"}}async function $e(e,t,n,r){let i=U(e,t.id),o=r??yt(i);if(t.status!=="running")return o&&await I(i,{force:!0}).catch(()=>{}),t;if(o){let l=null;try{l=Ue(await ie(i,"utf8"),t.id)}catch{l=null}if(l!==null){let h=He(t,l);return await G(e,h,n.io).then(()=>!0).catch(()=>!1)&&await I(i,{force:!0}).catch(()=>{}),h}}let s=n.pidAlive??D;if(t.pid===void 0||s(t.pid))return t;let a=await q(e,t.id);if(a===null)return null;if(a.status!=="running")return a;let u=n.now??(()=>new Date),f={...a,status:"failed",endedAt:u().toISOString(),selfHealed:"pid-probe"};return await G(e,f,n.io).catch(()=>{}),f}function _t(e,t,n,r){let i=U(e,t.id);if(t.status!=="running"){if(r)try{te(i,{force:!0})}catch{}return t}if(r){let f=null;try{f=Ue(ee(i,"utf8"),t.id)}catch{f=null}if(f!==null){let l=He(t,f);try{re(e,l),te(i,{force:!0})}catch{}return l}}let o=n.pidAlive??D;if(t.pid===void 0||o(t.pid))return t;let s=null;try{s=A(ee(_(e,t.id),"utf8"))}catch{return null}if(s===null)return null;if(s.status!=="running")return s;let a=n.now??(()=>new Date),u={...s,status:"failed",endedAt:a().toISOString(),selfHealed:"pid-probe"};try{re(e,u)}catch{}return u}async function Y(e,t,n={}){let r=await q(e,t);return r===null?null:$e(e,r,n)}async function O(e,t,n,r){let i=r?.rename??(async(o,s)=>Ne(o,s));return Fe(r,async()=>{let o=await q(e,t);if(o===null)return null;let s={...o,...n,schemaVersion:1,id:o.id};return await Ge(e,s,i),s})}async function v(e,t,n,r){try{let s=await O(e,t,n,r);return s===null?null:{record:s,via:"record"}}catch(s){if(!Me(s))throw s}let i=await q(e,t);if(i===null)return null;let o={schemaVersion:1,id:t,...n};return await Oe(U(e,t),JSON.stringify(o,null,2),"utf8"),{record:{...i,...n},via:"sentinel"}}async function z(e,t={}){let n;try{n=await kt(T(e))}catch{return[]}let r=new Set(n.filter(o=>o.endsWith(".final"))),i=[];for(let o of n.filter(s=>s.endsWith(".json")))try{let s=await ie(E.join(T(e),o),"utf8"),a=A(s);if(a===null)continue;let u=await $e(e,a,t,r.has(`${a.id}.final`));u!==null&&i.push(u)}catch{continue}return i.sort((o,s)=>s.startedAt.localeCompare(o.startedAt)||s.id.localeCompare(o.id)),i}function bt(e,t={}){let n;try{n=ht(T(e))}catch{return[]}let r=new Set(n.filter(o=>o.endsWith(".final"))),i=[];for(let o of n.filter(s=>s.endsWith(".json")))try{let s=A(ee(E.join(T(e),o),"utf8"));if(s===null)continue;let a=_t(e,s,t,r.has(`${s.id}.final`));a!==null&&i.push(a)}catch{continue}return i.sort((o,s)=>s.startedAt.localeCompare(o.startedAt)||s.id.localeCompare(o.id)),i}function re(e,t){let n=_(e,t.id);Rt(E.dirname(n),{recursive:!0});let r=`${n}.tmp-${process.pid}-${oe(2).toString("hex")}`;try{wt(r,JSON.stringify(t,null,2),"utf8"),St(r,n)}catch(i){try{te(r,{force:!0})}catch{}throw i}}async function fe(e,t,n){await I(_(e,t.id),{force:!0}),await I(U(e,t.id),{force:!0}),await I(ue(e,t.id),{force:!0}),n&&await I(t.logPath,{force:!0})}function D(e){try{return process.kill(e,0),!0}catch(t){return t.code==="EPERM"}}function $(e,t=D){return e.status!=="running"?e.status:e.pid===void 0||!t(e.pid)?"stale":"running"}import{createHash as xt}from"node:crypto";import{rm as Ke}from"node:fs/promises";import je from"node:net";import It from"node:os";import At from"node:path";var X="TANSR_BG_RUNNER_ENDPOINT",K="TANSR_BG_RUNNER_TOKEN",We=1e3,Nt=2e3,Ot=4096,vt=100;function pe(e,t,n=process.platform){if(n==="win32"){let i=xt("sha1").update(e).digest("hex").slice(0,8);return`\\\\.\\pipe\\tansr-bg-${t}-${i}`}let r=ue(e,t);return Buffer.byteLength(r)<=vt?r:At.join(It.tmpdir(),`tansr-${t}${ae}`)}function Dt(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null)return null;let n=t;return typeof n.op!="string"||typeof n.token!="string"?null:{op:n.op,token:n.token}}function Ct(e,t){if(e.length!==t.length)return!1;let n=0;for(let r=0;r<e.length;r+=1)n|=e.charCodeAt(r)^t.charCodeAt(r);return n===0}async function ge(e){let t=e.platform??process.platform,n=e.pid??process.pid,r=!1,i=new Set,o=je.createServer(a=>{i.add(a),a.setEncoding("utf8"),a.setTimeout(Nt,()=>a.destroy()),a.on("close",()=>{i.delete(a)}),a.on("error",()=>{});let u="",f=!1,l=h=>{f||(f=!0,a.end(JSON.stringify(h)+`
5
5
  `))};a.on("data",h=>{if(f)return;if(u+=h,Buffer.byteLength(u)>Ot){l({ok:!1,error:"malformed"});return}let k=u.indexOf(`
6
6
  `);if(k<0)return;let B=Dt(u.slice(0,k));if(B===null){l({ok:!1,error:"malformed"});return}if(!Ct(B.token,e.token)){l({ok:!1,error:"token_mismatch"});return}if(B.op==="ping"){l({ok:!0,id:e.id,pid:n});return}if(B.op==="stop"){l({ok:!0,id:e.id,pid:n,stopping:!0}),r||(r=!0,a.once("finish",()=>{e.onStop()}));return}l({ok:!1,error:"unknown_op"})})});t!=="win32"&&await Ke(e.endpoint,{force:!0}).catch(()=>{});let s=await new Promise(a=>{o.once("error",u=>{a({ok:!1,message:u.message})}),o.listen(e.endpoint,()=>{a({ok:!0})})});return s.ok?(o.unref(),{ok:!0,handle:{endpoint:e.endpoint,close:async()=>{for(let a of i)a.destroy();await new Promise(a=>{o.close(()=>a())}),t!=="win32"&&await Ke(e.endpoint,{force:!0}).catch(()=>{})}}}):s}function me(e,t,n,r={}){let i=r.timeoutMs??We;return new Promise(o=>{let s=!1,a="",u=je.connect(e),f=k=>{s||(s=!0,clearTimeout(l),u.destroy(),o(k))},l=setTimeout(()=>f({ok:!1,code:"timeout"}),i);u.setEncoding("utf8"),u.once("connect",()=>{u.write(JSON.stringify({op:n,token:t})+`
7
7
  `)}),u.on("error",()=>f({ok:!1,code:"unreachable"}));let h=()=>{let k=a.indexOf(`
@@ -26,4 +26,4 @@ import{a as N}from"./tansr-chunk-Q6MUMULP.mjs";import{a as Z}from"./tansr-chunk-
26
26
  `),0}let Ee=await b(p),Be=await dt(p.logPath);return n.write((y.json?JSON.stringify({...Ee,logTail:Be.join(`
27
27
  `)}):ln(Ee,Be))+`
28
28
  `),0}export{d as a,gt as b,ve as c,ne as d,De as e,Ce as f,Le as g,T as h,_ as i,se as j,U as k,ce as l,de as m,le as n,G as o,A as p,H as q,Y as r,O as s,v as t,z as u,bt as v,re as w,fe as x,D as y,$ as z,X as A,K as B,We as C,pe as D,ge as E,me as F,ke as G,ye as H,qe as I,j as J,he as K,Xe as L,we as M,Qe as N,Ze as O,zt as P,W as Q,et as R,rn as S,Te as T,on as U,sn as V,tt as W,it as X,st as Y,at as Z,ut as _,ct as $,dt as aa,cn as ba,fn as ca};
29
- //# sourceMappingURL=tansr-chunk-OB47UYHK.mjs.map
29
+ //# sourceMappingURL=tansr-chunk-W2WIN3M2.mjs.map
@@ -0,0 +1,5 @@
1
+ import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
+ import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
+ const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
+ import{c as at,i as lt,j as ct,k as pe}from"./tansr-chunk-AHUB2IHT.mjs";import{a as Pt,b as _t}from"./tansr-chunk-RFH7OCN6.mjs";import{f as He,n as kt,o as Ce,p as be,s as Ot,u as Pe}from"./tansr-chunk-SHLU4JN2.mjs";import{Ib as At,Jb as vt,Kb as ye,Lb as Fe,Mb as Ct,Na as ge,Nb as Ve,Ob as Ye,ke as Qe,le as bt,pb as g,ub as K,wb as Ge}from"./tansr-chunk-JIC3VWLQ.mjs";import{P as U,R as me,S as wt,Sa as Rt,Ta as Et,qb as It,rb as ve}from"./tansr-chunk-6N333TUL.mjs";import{m as p}from"./tansr-chunk-YK3CE3JM.mjs";import{B as gt,b as Ie,n as ut,r as pt,s as ft,y as mt}from"./tansr-chunk-4DAH4AIH.mjs";import{A as H,Ob as dt,Vb as Le,e as fe,y as Ee}from"./tansr-chunk-ENRIN7EG.mjs";import{C as St,F as ht,G as se,a as L,p as De,q as Ae,t as Ue,v as D,x as yt}from"./tansr-chunk-LA3LGOYQ.mjs";var Ke="compaction_attempt";var Nt=()=>new Date;function Tt(e){return e!==void 0?{schemeId:e.id,schemeFingerprint:e.fingerprint}:{}}function jn(e,t,n){return{type:Ke,version:1,phase:"started",compactionId:e.compactionId,trigger:e.trigger,...e.mechanism!==void 0?{mechanism:e.mechanism}:{},...e.beforeTokens!==void 0?{beforeTokens:e.beforeTokens}:{},...Tt(t),...e.agentId!==void 0?{agentId:e.agentId}:{},at:(n??Nt)().toISOString()}}function qn(e,t,n){let o=e.outcome,r={type:Ke,version:1,compactionId:e.compactionId,trigger:e.trigger,...e.mechanism!==void 0?{mechanism:e.mechanism}:{},...e.durationMs!==void 0?{durationMs:e.durationMs}:{},...Tt(t),...e.agentId!==void 0?{agentId:e.agentId}:{},at:(n??Nt)().toISOString()};return o===void 0?{...r,phase:"succeeded"}:o.ok?{...r,phase:"succeeded",beforeTokens:o.measurementBefore.contextTokens,afterTokens:o.measurementAfter.contextTokens}:{...r,phase:"failed",beforeTokens:o.measurementBefore.contextTokens,reason:o.reason,...o.errorKind!==void 0?{errorKind:o.errorKind}:{}}}function _e(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.type!==Ke||t.version!==1)return null;let n=t.phase;return n!=="started"&&n!=="succeeded"&&n!=="failed"||typeof t.compactionId!="string"||typeof t.trigger!="string"||typeof t.at!="string"?null:e}function ke(e){let t=[];for(let n of e)if(n.phase!=="started"){if(n.phase==="succeeded"){if(n.beforeTokens===void 0||n.afterTokens===void 0)continue;t.push({trigger:n.trigger,ok:!0,reclaimedTokens:Math.max(0,n.beforeTokens-n.afterTokens),durationMs:n.durationMs??0,...n.schemeId!==void 0?{schemeId:n.schemeId}:{},...n.schemeFingerprint!==void 0?{schemeFingerprint:n.schemeFingerprint}:{}});continue}t.push({trigger:n.trigger,ok:!1,...n.reason!==void 0?{reason:n.reason}:{},...n.errorKind!==void 0?{errorKind:n.errorKind}:{},durationMs:n.durationMs??0,...n.schemeId!==void 0?{schemeId:n.schemeId}:{},...n.schemeFingerprint!==void 0?{schemeFingerprint:n.schemeFingerprint}:{}})}return t}import{readdir as kn,stat as On}from"node:fs/promises";import Je from"node:path";import A from"node:path";import{randomUUID as et}from"node:crypto";import{isDeepStrictEqual as Rn}from"node:util";import{stat as En,lstat as Re,open as In,mkdir as Ht,utimes as An}from"node:fs/promises";var We="agent_notification",Mt="agent_notification_ack";function Jn(e){return e.channel==="report"?{type:We,version:1,channel:"report",agentId:e.agentId,notificationId:e.notificationId,message:e.message,wake:e.wake}:{type:We,version:1,channel:"settled",agentId:e.agentId,notificationId:e.notificationId,outcome:e.outcome,summary:e.summary}}function Ln(e){return{type:Mt,version:1,agentId:e.agentId,notificationId:e.notificationId}}function ie(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.type!==We||t.version!==1||typeof t.agentId!="string"||typeof t.notificationId!="string")return null;let n=t.channel;return n==="report"?typeof t.message!="string"||typeof t.wake!="boolean"?null:e:n==="settled"?typeof t.outcome!="string"||typeof t.summary!="string"?null:e:null}function ae(e){if(typeof e!="object"||e===null)return null;let t=e;return t.type!==Mt||t.version!==1||typeof t.agentId!="string"||typeof t.notificationId!="string"?null:e}function xt(e){let t=new Set;for(let o of e){if(o.kind!=="queue_ack")continue;let r=ae(o.payload);r!==null&&t.add(r.notificationId)}let n=[];for(let o of e){if(o.kind!=="queue_enqueue")continue;let r=ie(o.payload);r!==null&&(t.has(r.notificationId)||n.push({enqueueEventId:o.eventId,seq:o.seq,payload:r}))}return n}var jt="permission_mode_change",Oe="session_grant",qt="approval_requested",Bt="approval_decided",Jt="session_grants_restored",le=1;var Se=()=>new Date;function Gn(e){return{type:jt,version:le,from:e.from,to:e.to,trigger:e.trigger,at:(e.now??Se)().toISOString()}}function Fn(e){let t={type:Oe,version:le,rules:[...e.rules],behavior:e.behavior,origin:e.origin,...e.scope!==void 0?{scope:e.scope}:{},...e.toolName!==void 0?{toolName:e.toolName}:{},at:(e.now??Se)().toISOString()};return Le(t)}function Vn(e){let t={type:Jt,version:le,entries:e.entries.map(n=>({...n})),skipped:e.skipped,...e.skippedScope===void 0?{}:{skippedScope:e.skippedScope},at:(e.now??Se)().toISOString()};return Le(t)}function Yn(e){return{type:qt,version:le,callId:e.callId,toolName:e.toolName,at:(e.now??Se)().toISOString()}}function Qn(e){let t=(e.now??Se)();return{type:Bt,version:le,callId:e.callId,toolName:e.toolName,decision:e.decision,...e.scope!==void 0?{scope:e.scope}:{},...e.cancelled===!0?{cancelled:!0}:{},...e.requestedAtMs!==void 0?{elapsedMs:Math.max(0,t.getTime()-e.requestedAtMs)}:{},at:t.toISOString()}}function Lt(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.version!==le||typeof t.at!="string")return null;let n=t.type;return n===jt?typeof t.from!="string"||typeof t.to!="string"||typeof t.trigger!="string"?null:e:n===Oe?!Array.isArray(t.rules)||!t.rules.every(o=>typeof o=="string")||typeof t.behavior!="string"||typeof t.origin!="string"?null:e:n===qt?typeof t.callId!="string"||typeof t.toolName!="string"?null:e:n===Bt?typeof t.callId!="string"||typeof t.toolName!="string"||typeof t.decision!="string"?null:e:n===Jt?!Array.isArray(t.entries)||!t.entries.every(o=>typeof o=="object"&&o!==null&&typeof o.rule=="string"&&typeof o.behavior=="string")||typeof t.skipped!="number"?null:e:null}var on=128;function Hn(e=on){let t=new Map,n=()=>{if(t.size<=e)return;let o=t.keys().next();o.done||t.delete(o.value)};return{markRequested(o,r){t.set(o,{requestedAtMs:r}),n()},markDecided(o,r){let s=t.get(o);s!==void 0&&(s.decidedAtMs=r)},consume(o){let r=t.get(o);if(r!==void 0&&(t.delete(o),r.decidedAtMs!==void 0))return{requestedAt:new Date(r.requestedAtMs).toISOString(),decidedAt:new Date(r.decidedAtMs).toISOString()}}}}var rn=1440*60*1e3;function Ne(e){let t=[];for(let n of e){if(n.kind!=="event")continue;let o=Lt(n.payload);o===null||o.type!==Oe||t.push({seq:n.seq,payload:o})}return t}var sn=new Set(["allow","deny","ask"]);function $n(e,t={}){let n=(t.now??(()=>new Date))().getTime(),o=t.ttlMs??rn,r=[],s=new Set,i=0;for(let a of e){let{payload:l}=a,d=Date.parse(l.at);if(Number.isNaN(d)||n-d>o){i+=1;continue}if(!sn.has(l.behavior)){i+=1;continue}let f=l.behavior;for(let m of l.rules){let c=`${f}\0${m}`;s.has(c)||(s.add(c),r.push({rule:m,behavior:f}))}}return{entries:r,skipped:i}}var an=5;function zn(e,t=an){let n=e.map(o=>o.behavior==="allow"?o.rule:`${o.behavior}:${o.rule}`);return n.length<=t?n.join(", "):`${n.slice(0,t).join(", ")} …(+${n.length-t})`}var Dt="session_event";var ln=()=>new Date;function Zn(e,t,n){return t==="silenced"||t==="merged"&&e.phase===void 0?null:{type:Dt,version:1,kind:e.kind,severity:e.severity,origin:e.origin,scope:e.scope,detail:e.detail,mode:e.mode,...e.phase!==void 0?{phase:e.phase}:{},count:e.count,occurredAt:e.occurredAt,change:t,at:(n??ln)().toISOString()}}function Te(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.type!==Dt||t.version!==1||typeof t.kind!="string"||typeof t.scope!="string")return null;let n=t.phase;if(n!==void 0&&n!=="enter"&&n!=="exit")return null;let o=t.change;return o!=="new"&&o!=="merged"?null:e}function cn(e){return e==="kernel"||e==="tui"||e==="providers"||e==="platform"||e==="tool"?e:"kernel"}function Me(e){let t=new Map;for(let n of e){if(n.kind!=="event")continue;let o=Te(n.payload);if(o===null||o.phase===void 0)continue;let r=`${o.kind}\0${o.scope}`;o.phase==="enter"?t.has(r)||t.set(r,{kind:o.kind,scope:o.scope,origin:cn(o.origin)}):t.delete(r)}return[...t.values()]}function xe(e){let t=null;for(let n of e){if(n.kind!=="event")continue;let o=Te(n.payload);o===null||o.kind!=="model_switched"||o.scope!==""&&(t=o.scope)}return t}import{mkdir as dn,rename as un}from"node:fs/promises";import pn from"node:path";var M={journalClosed:"cli.sessions.journal_closed",journalUnavailable:"cli.sessions.journal_unavailable",preparedHistoryUnavailable:"cli.sessions.prepared_history_unavailable",historyPreparationChanged:"cli.sessions.history_preparation_changed",persistFailed:"cli.sessions.persist_failed",checkpointFailed:"cli.sessions.checkpoint_failed",resumeNotFound:"cli.sessions.resume.not_found",resumeFailed:"cli.sessions.resume.failed",resumeRestored:"cli.sessions.resume.restored",resumeForked:"cli.sessions.resume.forked",resumeNone:"cli.sessions.resume.none",resumeAlreadyCurrent:"cli.sessions.resume.already_current",syntheticToolResult:"cli.sessions.synthetic_tool_result",warningIntegrityBreak:"cli.sessions.warning.integrity_break",warningSynthesized:"cli.sessions.warning.synthesized_results",warningTruncated:"cli.sessions.warning.truncated_messages",warningOversizeReplaced:"cli.sessions.warning.oversize_replaced",warningMicrocompactReplayed:"cli.sessions.warning.microcompact_replayed",warningPruneReplayed:"cli.sessions.warning.prune_replayed",warningUnknownKinds:"cli.sessions.warning.unknown_kinds",resumeStyleUnknown:"cli.sessions.resume.output_style_unknown",resumeUsageStale:"cli.sessions.resume.usage_stale",resumeGrantsRestored:"cli.sessions.resume.grants_restored",exportUsage:"cli.sessions.export.usage",exportUnknownFormat:"cli.sessions.export.unknown_format",exportNotFound:"cli.sessions.export.not_found",exportFailed:"cli.sessions.export.failed",exportWritten:"cli.sessions.export.written",usage:"cli.sessions.usage",migrateUsage:"cli.sessions.migrate.usage",migrateFailed:"cli.sessions.migrate.failed",pruneUsage:"cli.sessions.prune.usage",pruneInvalidNumber:"cli.sessions.prune.invalid_number",pruneCandidate:"cli.sessions.prune.candidate",pruneSidecarOnlyEntry:"cli.sessions.prune.sidecar_only_entry",pruneSidecarOnlySummary:"cli.sessions.prune.sidecar_only_summary",pruneBrokenEntry:"cli.sessions.prune.broken_entry",pruneBrokenHint:"cli.sessions.prune.broken_hint",pruneSummary:"cli.sessions.prune.summary",pruneKept:"cli.sessions.prune.kept",pruneNothing:"cli.sessions.prune.nothing",pruneDryRunHint:"cli.sessions.prune.dry_run_hint",pruneDeleted:"cli.sessions.prune.deleted",pruneSkippedLocked:"cli.sessions.prune.skipped_locked",pruneSkippedFresh:"cli.sessions.prune.skipped_fresh",pruneApplied:"cli.sessions.prune.applied",pruneAborted:"cli.sessions.prune.aborted"},to=Object.values(M);function lo(e){return({content:t})=>{let n=e.put({content:t,kind:"tool-result"});return n!==void 0?{path:n.path}:void 0}}function je(e,t=It({resolveDir:()=>Ot(e)})){return(n,o)=>t.registerExisting?.({content:o,kind:"tool-result"})?.path}async function Ut(e,t){let n=await mn(e,t,{migrateToVault:!1,readOnly:!0});return n.ok?{ok:!0,messages:n.messages,spillRecovery:n.spillRecovery,warnings:n.warnings,...n.projectedTodos!==void 0?{projectedTodos:n.projectedTodos}:{},...n.meta?.cwd!==void 0?{storedCwd:n.meta.cwd}:{},...n.compactBoundary!==void 0?{compactBoundary:n.compactBoundary}:{},...n.heldBy!==void 0?{heldBy:n.heldBy}:{}}:{ok:!1,reason:n.reason,detail:n.detail}}function $e(e){for(let t of e){if(t.branchId!==U||t.kind!=="compact_boundary")continue;let n=H.safeParse(t.payload);return n.success?n.data:void 0}}async function fn(e,t,n,o){let r=new Set([t]),s=$e(n);for(let i=0;s!==void 0&&i<32;i++){let a=s.sourceSessionId;if(r.has(a))return;r.add(a);try{let l=D(e,a),d=await me(l,{repair:!1}),f=d.records.find(m=>m.seq===s.sourceSeq&&m.sessionId===a);if(d.integrityBreakAt!==void 0||d.repairs.length!==0||f===void 0)return;be(o,e,l,{sessionId:a,seq:f.seq,eventId:f.eventId,hash:f.integrity.hash}),s=$e(d.records)}catch{return}}}async function mn(e,t,n={}){let o=n.readOnly===!0,r=!o&&(n.migrateToVault??!0),s;try{s=D(e,t)}catch(c){return{ok:!1,reason:"not_found",detail:c instanceof Error?c.message:String(c)}}let i=!1;try{if(await Gt(s)===!1)return{ok:!1,reason:"not_found",detail:t}}catch(c){return{ok:!1,reason:"io_error",detail:c instanceof Error?c.message:String(c)}}let a=await W(s),l=async(c,u)=>(u??await W(c))||await mt(c).catch(()=>!1)||await he(c)!==null;if(!await l(s,a)){let c=pe(e);if(c===null)return{ok:!1,reason:"not_found",detail:t};let u;try{u=D(c,t)}catch{return{ok:!1,reason:"not_found",detail:t}}let v=await W(u);if(!await l(u,v))return{ok:!1,reason:"not_found",detail:t};if(r&&v)s=u,a=!0,i=!0;else if(r)try{await dn(pn.dirname(s),{recursive:!0,mode:at}),await un(u,s),a=v}catch{s=u,a=v,i=!0}else s=u,a=v}let d=null,f;if(o||i)try{let c=await De(s);if(!c.alive&&a){let u=await De(Ft(s)).catch(()=>null);u?.alive&&(c=u)}c.alive&&c.pid!==void 0&&(f={pid:c.pid,...c.host!==void 0?{host:c.host}:{},...c.startedAt!==void 0?{startedAt:c.startedAt}:{}})}catch(c){return{ok:!1,reason:"io_error",detail:c instanceof Error?c.message:String(c)}}else if(!a)try{d=await Ae(s)}catch(c){return c instanceof L&&c.code==="SESSION_LOCKED"?{ok:!1,reason:"locked",detail:c.message}:{ok:!1,reason:"io_error",detail:c instanceof Error?c.message:String(c)}}let m=async()=>{d!==null&&await d.release()};try{if(a){let E;try{E=await Vt(s,!o&&!i,n.segmentation,!0)}catch(j){if(j instanceof L&&j.code==="SESSION_LOCKED")return{ok:!1,reason:"locked",detail:j.message};if(!(j instanceof g)&&!(j instanceof L))return{ok:!1,reason:"io_error",detail:j instanceof Error?j.message:String(j)};throw j}d=E.lock??null;let{projection:y,messages:q,cursor:V}=E.view.state,B=ge(q);if(B.messages.length===0)return await m(),{ok:!1,reason:"not_found",detail:t};let Y=Ce(e,s,!0);for(let j of y.spillAncestors)be(Y.recovery,e,D(e,j.sessionId),j);let Q=ve(B.messages,{preserveUnprovenResults:!0,resolvePersistedPath:je(s,Y.store),resolvePrunedPath:Pe(s,Y.store)}),J=E.meta??await se(s);if(J.sessionId!==t)throw new L("JOURNAL_RECONCILIATION_REQUIRED",p("cli.sessions.journal.resumeIdentityDiffers"));let ee=d!==null&&!i&&B.droppedMessages===0;ee||await m();let re=[];B.synthesizedResults>0&&re.push(p(M.warningSynthesized,{count:B.synthesizedResults})),B.droppedMessages>0&&re.push(p(M.warningTruncated,{count:B.droppedMessages}));let it=y.lastEffectiveModel??(J.provider&&J.model?`${J.provider}/${J.model}`:null);return{ok:!0,sessionId:t,messages:Q.messages,spillRecovery:Y.recovery,journalMessageCount:y.messageCount,continuable:ee,...ee&&d!==null?{lock:d}:{},...f===void 0?{}:{heldBy:f},lastEventId:V.lastEventId,lastSeq:V.lastSeq,cursor:V,warnings:re,meta:J,pendingAgentNotifications:y.pendingAgentNotifications,compactionAttempts:[],sessionGrants:y.sessionGrants,sessionEventConditions:y.sessionEventConditions,...y.compactBoundary===null?{}:{compactBoundary:y.compactBoundary},...it===null?{}:{lastEffectiveModel:it},...y.usageSnapshot===null?{}:{usageSnapshot:y.usageSnapshot},journalProjection:y,projectedTodos:y.todos,projectedCompactions:y.compactions}}let c=await gt(s,{reconcile:d!==null});if(c!==null){let E=c,y=ce(E.projection);if(y.messageCount!==E.snapshot.length)throw new L("JOURNAL_RECONCILIATION_REQUIRED",p("cli.sessions.journal.workingSetProjectionDiffers"));let q=ge(E.snapshot);if(q.messages.length===0)return await m(),{ok:!1,reason:"not_found",detail:t};let V=Ce(e,s,!0);for(let re of y.spillAncestors)be(V.recovery,e,D(e,re.sessionId),re);let B=ve(q.messages,{preserveUnprovenResults:!0,resolvePersistedPath:je(s,V.store),resolvePrunedPath:Pe(s,V.store)}),Y=[...E.repairs];q.synthesizedResults>0&&Y.push(p(M.warningSynthesized,{count:q.synthesizedResults})),q.droppedMessages>0&&Y.push(p(M.warningTruncated,{count:q.droppedMessages}));let Q=await se(s);if(Q.sessionId!==t)throw new L("JOURNAL_RECONCILIATION_REQUIRED",p("cli.sessions.journal.resumeIdentityDiffers"));let J=y.lastEffectiveModel??(Q.provider&&Q.model?`${Q.provider}/${Q.model}`:null),ee=d!==null&&!i&&q.droppedMessages===0;return ee||await m(),{ok:!0,sessionId:t,messages:B.messages,spillRecovery:V.recovery,journalMessageCount:y.messageCount,continuable:ee,...ee&&d!==null?{lock:d}:{},...f!==void 0?{heldBy:f}:{},lastEventId:E.cursor.lastEventId,lastSeq:E.cursor.lastSeq,cursor:E.cursor,warnings:Y,meta:Q,...y.compactBoundary!==null?{compactBoundary:y.compactBoundary}:{},pendingAgentNotifications:y.pendingAgentNotifications,compactionAttempts:[],sessionGrants:y.sessionGrants,sessionEventConditions:y.sessionEventConditions,...J!==null?{lastEffectiveModel:J}:{},...y.usageSnapshot!==null?{usageSnapshot:y.usageSnapshot}:{},journalProjection:y,projectedTodos:y.todos,projectedCompactions:y.compactions}}let u=await me(s,o?{repair:!1}:{}),v=wt(u.records),w=ge(v.messages),_=u.integrityBreakAt===void 0,R=Ce(e,s,_);_&&await fn(e,t,u.records,R.recovery);let O=ve(w.messages,{resolvePersistedPath:_?je(s,R.store):()=>{},resolvePrunedPath:_?Pe(s,R.store):()=>{}});if(w.messages.length===0)return await m(),{ok:!1,reason:"not_found",detail:t};let T=u.records.filter(E=>E.branchId===U&&(E.kind==="user_prompt"||E.kind==="assistant_message"||E.kind==="tool_result")&&E.visibility.model).length,I=u.records[u.records.length-1]?.eventId??null,S=[...v.warnings,...u.repairs];u.integrityBreakAt!==void 0&&S.push(p(M.warningIntegrityBreak,{index:u.integrityBreakAt})),u.unknownKinds!==void 0&&S.push(p(M.warningUnknownKinds,{count:u.unknownKinds.length,kinds:u.unknownKinds.join(", ")})),w.synthesizedResults>0&&S.push(p(M.warningSynthesized,{count:w.synthesizedResults})),w.droppedMessages>0&&S.push(p(M.warningTruncated,{count:w.droppedMessages})),O.clampReplacedCount>0&&S.push(p(M.warningOversizeReplaced,{count:O.clampReplacedCount})),O.pruneReplayedCount>0&&S.push(p(M.warningPruneReplayed,{count:O.pruneReplayedCount})),O.evictReplayedCount>0&&S.push(p(M.warningMicrocompactReplayed,{count:O.evictReplayedCount}));let N=d!==null&&!i&&v.warnings.length===0&&w.droppedMessages===0&&u.integrityBreakAt===void 0,b;try{b=await se(s)}catch{}let P=$e(u.records),C=xt(u.records),h=ze(u.records),k=Ne(u.records),x=Me(u.records),X=b?.provider!==void 0&&b.provider!==""&&b.model!==void 0&&b.model!==""?`${b.provider}/${b.model}`:null,oe=xe(u.records)??X,Z=bt(u.records);return!N||d===null?(await m(),{ok:!0,sessionId:t,messages:O.messages,spillRecovery:R.recovery,journalMessageCount:T,continuable:!1,...f!==void 0?{heldBy:f}:{},lastEventId:I,lastSeq:v.lastSeq,cursor:u.cursor,warnings:S,...b!==void 0?{meta:b}:{},...P!==void 0?{compactBoundary:P}:{},pendingAgentNotifications:C,compactionAttempts:h,sessionGrants:k,sessionEventConditions:x,...oe!==null?{lastEffectiveModel:oe}:{},...Z!==void 0?{usageSnapshot:Z}:{}}):{ok:!0,sessionId:t,messages:O.messages,spillRecovery:R.recovery,journalMessageCount:T,continuable:!0,lock:d,lastEventId:I,lastSeq:v.lastSeq,cursor:u.cursor,warnings:S,...b!==void 0?{meta:b}:{},...P!==void 0?{compactBoundary:P}:{},pendingAgentNotifications:C,compactionAttempts:h,sessionGrants:k,sessionEventConditions:x,...oe!==null?{lastEffectiveModel:oe}:{},...Z!==void 0?{usageSnapshot:Z}:{}}}catch(c){return await m(),{ok:!1,reason:"corrupt",detail:c instanceof Error?c.message:String(c)}}}var gn="TodoWrite";function yn(e){if(e===null||typeof e!="object")return null;let t=e,n=t.id,o=t.content,r=t.status;return typeof n!="string"||n.trim()===""||typeof o!="string"||o.trim()===""||typeof r!="string"||!Rt.includes(r)?null:{id:n,content:o,status:r}}function Sn(e){if(e===null||typeof e!="object")return null;let t=e;if(typeof t.merge!="boolean"||!Array.isArray(t.todos))return null;let n=[],o=new Set;for(let r of t.todos){let s=yn(r);if(s===null||o.has(s.id))return null;o.add(s.id),n.push(s)}return{merge:t.merge,todos:n}}function hn(e){let t=[];for(let n of e)if(n.role==="assistant")for(let o of n.blocks){if(o.t!=="tool_call"||o.name!==gn)continue;let r=Sn(o.args);r!==null&&t.push({callId:o.id,...r})}return t}function Xe(e){return{items:e?.items.map(t=>({...t}))??[],sawTodoWrite:e?.sawTodoWrite??!1,pending:[]}}function Ze(e,t){let n=new Map;for(let i of t)for(let a of i.blocks)a.t==="tool_result"&&n.set(a.callId,a.isError===!0);let o=new Et;o.replace(e.items);let r=e.sawTodoWrite,s=[];for(let i of[...e.pending,...hn(t)]){let a=n.get(i.callId);if(a===void 0){s.push({...i,todos:i.todos.map(l=>({...l}))});continue}if(!a){r=!0;try{i.merge?o.merge(i.todos):o.replace(i.todos)}catch{}}}return{items:o.list(),sawTodoWrite:r,pending:s}}function wn(e){let{items:t,sawTodoWrite:n}=Ze(Xe(),e);return{items:t,sawTodoWrite:n}}async function To(e,t){if(t.projectedTodos!==void 0)return t.projectedTodos.sawTodoWrite?t.projectedTodos.items.map(s=>({...s})):null;let n=[],o=t.compactBoundary?.sourceSessionId;if(o!==void 0)try{let s=await Ut(e,o);s.ok&&n.push(s.messages)}catch{}n.push([...t.messages]);let r=wn(n.flat());return r.sawTodoWrite?r.items:null}function qe(){return{format:"cli-journal-resume-v1",messageCount:0,pendingAgentNotifications:[],sessionGrants:[],sessionEventConditions:[],lastEffectiveModel:null,usageSnapshot:null,compactBoundary:null,todos:Xe(),inheritedTodoCalls:[],compactions:null,spillAncestors:[]}}function ce(e){if(e===null||typeof e!="object")throw de();let t=e;if(t.format!=="cli-journal-resume-v1"||!Number.isSafeInteger(t.messageCount)||t.messageCount<0||!Array.isArray(t.pendingAgentNotifications)||!Array.isArray(t.sessionGrants)||!Array.isArray(t.sessionEventConditions)||!Array.isArray(t.spillAncestors)||t.todos===null||typeof t.todos!="object"||!Array.isArray(t.todos.items)||!Array.isArray(t.todos.pending)||typeof t.todos.sawTodoWrite!="boolean"||!Array.isArray(t.inheritedTodoCalls)||!t.inheritedTodoCalls.every(n=>typeof n=="string")||!(t.lastEffectiveModel===null||typeof t.lastEffectiveModel=="string")||t.compactBoundary!==null&&!H.safeParse(t.compactBoundary).success||t.usageSnapshot!==null&&(Qe(t.usageSnapshot?.payload)===void 0||!Number.isSafeInteger(t.usageSnapshot.staleMessages)||t.usageSnapshot.staleMessages<0))throw de();for(let n of t.pendingAgentNotifications)if(ie(n.payload)===null||typeof n.enqueueEventId!="string"||!Number.isSafeInteger(n.seq))throw de();for(let n of t.spillAncestors)if(typeof n.sessionId!="string"||typeof n.eventId!="string"||!Number.isSafeInteger(n.seq)||n.seq<0||!/^[a-f0-9]{64}$/.test(n.hash))throw de();return t}function de(){return new L("JOURNAL_RECONCILIATION_REQUIRED",p("cli.sessions.storage.journalResumeProjectionInvalid"))}function Fo(e,t,n){let o=qe();return o.todos=structuredClone(e.todos),o.inheritedTodoCalls=n.flatMap(r=>r.role==="assistant"?r.blocks.flatMap(s=>s.t==="tool_call"&&s.name==="TodoWrite"?[s.id]:[]):[]),o.compactions=structuredClone(e.compactions),o.spillAncestors=[t,...e.spillAncestors.filter(r=>r.sessionId!==t.sessionId)].slice(0,32),o}function Yt(e=qe()){return{seed:e,async reduce(t,n,o){let r=structuredClone(ce(t));for(let i of n){let a=i.kind==="queue_ack"?ae(i.payload):null;a!==null&&(o.set(`cli:notification-ack:${a.notificationId}`,{eventId:i.eventId,seq:i.seq}),r.pendingAgentNotifications=r.pendingAgentNotifications.filter(l=>l.payload.notificationId!==a.notificationId))}let s=[];for(let i of n){let a=i.kind==="queue_enqueue"?ie(i.payload):null;if(a!==null&&await o.get(`cli:notification-ack:${a.notificationId}`)===void 0&&r.pendingAgentNotifications.push({enqueueEventId:i.eventId,seq:i.seq,payload:a}),i.branchId===U&&i.visibility.model&&(i.kind==="user_prompt"||i.kind==="assistant_message"||i.kind==="tool_result")&&(s.push(fe.parse(i.payload)),r.messageCount++,r.usageSnapshot!==null&&(r.usageSnapshot={...r.usageSnapshot,staleMessages:r.usageSnapshot.staleMessages+1})),i.branchId===U&&i.kind==="compact_boundary"&&r.compactBoundary===null){let u=H.safeParse(i.payload);u.success&&(r.compactBoundary=u.data)}if(i.kind!=="event")continue;let d=Qe(i.payload);d!==void 0&&(r.usageSnapshot={payload:d,staleMessages:0});let f=xe([i]);f!==null&&(r.lastEffectiveModel=f);let m=Te(i.payload);if(m?.phase!==void 0){let u=r.sessionEventConditions.findIndex(v=>v.kind===m.kind&&v.scope===m.scope);m.phase==="exit"?u>=0&&r.sessionEventConditions.splice(u,1):u<0&&r.sessionEventConditions.push(...Me([i]))}for(let u of Ne([i])){let v=Date.parse(u.payload.at);if(Number.isFinite(v))for(let w of u.payload.rules){let _=r.sessionGrants.findIndex(R=>R.payload.behavior===u.payload.behavior&&R.payload.rules[0]===w);if(_<0||v>=Date.parse(r.sessionGrants[_].payload.at)){let R={...u,eventId:i.eventId,payload:{...u.payload,rules:[w]}};_<0?r.sessionGrants.push(R):r.sessionGrants[_]=R}}}let c=_e(i.payload);if(c!==null)for(let u of ke([c]))r.compactions=_t(r.compactions??void 0,u)}if(s.length>0){let i=new Set(r.inheritedTodoCalls);r.todos=Ze(r.todos,s.map(a=>({...a,blocks:a.blocks.filter(l=>!(l.t==="tool_call"&&i.has(l.id)))}))),r.inheritedTodoCalls=[]}return r}}}var G="session-storage",te=32*1024*1024,Kt="cli:notification-ack:";function Wt(e){return e.format==="journal.batch.v1"?e.metadata:e}function nt(e){if(e?.format!=="journal.batch.v1"||!Array.isArray(e.records)||!Array.isArray(e.metadata?.acknowledged)||e.records.length===0||e.records[0].seq!==e.metadata.firstSeq||e.records.at(-1).seq!==e.metadata.lastSeq)throw new g("integrity",p("cli.sessions.journal.invalidBatch"));return{records:e.records,acknowledged:e.metadata.acknowledged,...e.metadata.seed===void 0?{}:{seed:e.metadata.seed},...e.metadata.snapshot===void 0?{}:{snapshot:e.metadata.snapshot}}}var $t=new WeakMap,$=new Map,z=e=>process.platform==="win32"?A.resolve(e).toLowerCase():A.resolve(e),zt=new Map,Qt=new Set;function tr(e,t){Ct(t),zt.set(z(A.join(e,"sessions")),t)}function ne(e){return zt.get(z(A.dirname(e)))}async function ue(e,t=te*2,n){let o=ne(e);if(!o)return;let r={...o,onSourceIo(l){l.operation==="get"&&n?.(l.bytes),o.onSourceIo?.(l)}},s=await Ve({...r,create:!1});if(!s)return;let i=await W(e);return await Ht(e,{recursive:!0}),{handle:await Ye({...r,directory:A.join(e,G),contentDirectory:A.join(e,G,"content"),identity:s,mode:i?"reopen":"create",readBudgetBytes:t,maxBlobBytes:te}),scope:F(e)}}function ot(e,t,n){let o={signal:n};return{async describe(r){let s=await e.describeMaterial(t,r,o);if(s&&(s.kind==="segment"||s.kind==="content"))throw new g("identity_mismatch",p("cli.sessions.journal.externalKindDiffers"));return s},readRange:(r,s,i)=>e.readMaterial(t,r,{offset:s,bytes:i},o),async list(r,s,i){let a=await e.listMaterials(t,{kind:r,after:s,limit:i},o);return{...a,materials:a.materials}}}}function Xt(e){let t=z(e);if(Qt.has(t))return;Qt.add(t);let n=async o=>{let r=$.get(t)?.coldHandle();if(r)return o({handle:r,scope:F(e)});let s=await ue(e);if(!s)throw new g("not_found",p("cli.sessions.journal.coldSourceUnavailable"));try{return await o(s)}finally{await s.handle.close()}};He(e,{async borrowRead(o=new AbortController().signal){let r=$.get(t)?.coldHandle();if(r)return{access:ot(r,F(e),o),release:async()=>{}};let s=await ue(e);if(!s)throw new g("not_found",p("cli.sessions.journal.coldSourceUnavailable"));return{access:ot(s.handle,s.scope,o),release:()=>s.handle.close()}},describe:(o,r)=>n(async({handle:s,scope:i})=>{let a=await s.describeMaterial(i,o,r?{signal:r}:void 0);if(a&&(a.kind==="segment"||a.kind==="content"))throw new g("identity_mismatch",p("cli.sessions.journal.externalKindDiffers"));return a}),readRange:(o,r,s,i)=>n(({handle:a,scope:l})=>a.readMaterial(l,o,{offset:r,bytes:s},i?{signal:i}:void 0)),list:(o,r,s)=>n(async({handle:i,scope:a})=>{let l=await i.listMaterials(a,{kind:o,after:r,limit:s});return{...l,materials:l.materials}})})}async function Gt(e){if(!ne(e))return;Xt(e);let t=await ue(e);if(!t)return!1;let n={signal:new AbortController().signal};try{if(!await t.handle.describe(t.scope,n))return!1;try{return await Re(A.join(e,"meta.json")),!0}catch(l){if(l.code!=="ENOENT")throw l}let o=`checkpoints/${A.basename(e)}/cli-session-meta.json`,r=await t.handle.describeMaterial(t.scope,o,n);if(!r||r.bytes>64*1024)throw new g("recovery_required",p("cli.sessions.journal.originalMetadataUnavailable"));let s=await t.handle.readMaterial(t.scope,o,{offset:0,bytes:r.bytes},n);if(K(s)!==r.sha256)throw new g("integrity",p("cli.sessions.journal.originalMetadataDigestDiffers"));if(Ue.parse(JSON.parse(Buffer.from(s).toString())).sessionId!==t.scope.sessionId)throw new g("identity_mismatch",p("cli.sessions.journal.originalMetadataScopeDiffers"));let a=await Ae(e);try{try{await Re(A.join(e,"meta.json"))}catch(l){if(l.code!=="ENOENT")throw l;await ht(A.join(e,"meta.json"),s)}}finally{await a.release()}return!0}finally{await t.handle.close()}}function F(e){let t=ne(e);return t?{...t.scope,sessionId:A.basename(e)}:{applicationScopeId:"cli-native-session",endUserId:K(A.resolve(A.dirname(e))),sessionId:A.basename(e)}}function Ft(e){return A.join(e,G,"sessions",Ge(F(e)))}function Be(e){return{storageId:`cli-${K(A.resolve(e))}`,generation:"1"}}function vn(e){let t=K(`${Kt}${e}`);return{operationKey:`cli-ack-${t}`,intentDigest:t,batchId:`cli-ack-${t}`}}var Cn=vn;function bn(e){if(!Number.isSafeInteger(e?.lastSeq)||e.lastSeq<-1||e.recordCount!==e.lastSeq+1||!Number.isSafeInteger(e.byteLength)||e.byteLength<0||(e.lastSeq<0?e.lastHash!==null||e.lastEventId!==null:typeof e.lastEventId!="string"||!/^[a-f0-9]{64}$/.test(e.lastHash??"")))throw new g("integrity",p("cli.sessions.journal.invalidCursor"));return e}function we(e){try{let t=JSON.parse(e);if(!t?.meta)return;let n=Ue.safeParse(t.meta);return n.success?n.data:void 0}catch{return}}function tt(e){let t=JSON.parse(e);if(t.format!=="cli-session-log-v1"||t.journal?.version!==1)throw new g("recovery_required",p("cli.sessions.journal.descriptionUnavailable"));let n=t.journal;if(bn(n.cursor),n.compactBoundary!==null&&!H.safeParse(n.compactBoundary).success)throw new g("integrity",p("cli.sessions.journal.invalidBoundaryDescriptor"));let o=n.sourceAnchor;if(o!==null&&(typeof o?.sessionId!="string"||typeof o.eventId!="string"||!Number.isSafeInteger(o.seq)||o.seq<0||!/^[a-f0-9]{64}$/.test(o.hash)))throw new g("integrity",p("cli.sessions.journal.invalidSourceDescriptor"));if(o!==null&&(n.compactBoundary?.sourceSessionId!==o.sessionId||n.compactBoundary.sourceSeq!==o.seq))throw new g("integrity",p("cli.sessions.journal.sourceDescriptorBoundaryDiffers"));return n}function Pn(e){let t=e;if(t?.format!=="cli-session-log-v1"||!Array.isArray(t.messages)||!Number.isSafeInteger(t.cursor?.lastSeq)||t.cursor.lastSeq<-1||t.cursor.recordCount!==t.cursor.lastSeq+1||!Number.isSafeInteger(t.cursor.byteLength)||t.cursor.byteLength<0||(t.cursor.lastSeq<0?t.cursor.lastHash!==null||t.cursor.lastEventId!==null:typeof t.cursor.lastEventId!="string"||!/^[a-f0-9]{64}$/.test(t.cursor.lastHash??"")))throw new g("integrity",p("cli.sessions.journal.invalidSnapshotShape"));let n=ce(t.projection),o=t.messages.map(r=>fe.parse(r));if(n.messageCount!==o.length)throw new g("integrity",p("cli.sessions.journal.snapshotProjectionDiffers"));return{...t,messages:o,projection:n}}async function W(e){try{return await En(A.join(e,G,"storage.json")),!0}catch(t){if(t.code==="ENOENT")return!1;throw t}}async function Zt(e){if(!await W(e))return null;let t=A.join(e,G,"sessions",Ge(F(e))),n=A.join(t,"head.json"),o=await Re(n);if(!o.isFile()||o.isSymbolicLink()||o.size>te)throw new g("integrity",p("cli.sessions.journal.invalidStorageDescriptor"));let r=await In(n,"r"),s=Buffer.alloc(0);try{let l=0;for(;;){if(l>=12288)throw new g("recovery_required",p("cli.sessions.journal.descriptorSourceBoundExceeded"));let d=Buffer.alloc(Math.min(256,12288-l)),f=await r.read(d,0,d.length,l);if(!f.bytesRead)throw new g("integrity",p("cli.sessions.journal.descriptorShortened"));l+=f.bytesRead;let m=d.subarray(0,f.bytesRead),c=m.indexOf(10);if(s=Buffer.concat([s,c<0?m:m.subarray(0,c)]),c>=0)break}if((await r.stat()).size!==o.size)throw new g("integrity",p("cli.sessions.journal.descriptorChangedDuringRead"))}finally{await r.close()}let i=JSON.parse(s.toString());if(i.format!=="sto-file-v2"||!/^[a-f0-9]{32}$/.test(i.segment))throw new g("integrity",p("cli.sessions.journal.invalidStorageDescriptor"));let a=await Re(A.join(t,"segments",`${i.segment}.jsonl`));if(!a.isFile()||a.isSymbolicLink())throw new g("integrity",p("cli.sessions.journal.invalidStorageSegment"));return{mtimeMs:Math.max(o.mtimeMs,a.mtimeMs),bytes:o.size+a.size}}async function st(e,t,n=!1,o,r=e,s){let i=A.join(e,G),a=ne(e),l=s??await W(e),d=t||a&&!l?"create":"reopen",f=a?await Ve({...a,create:t,requestKey:`cli-cold-root-${K(JSON.stringify(a.scope))}`}):Be(r);if(!f)throw new g("not_found",p("cli.sessions.journal.coldIdentityUnavailable"));a&&await Ht(e,{recursive:!0});let m=a?await Ye({...a,directory:i,contentDirectory:A.join(i,"content"),identity:f,mode:d,segmentation:o===!1?{enabled:!1}:o??{},maxBlobBytes:te,externalMaterials:kt({sessionDir:e,sourceGeneration:f.generation})}):void 0,c=F(r);m&&Xt(e);let u=m?He(e,{async borrowRead(w=new AbortController().signal){return{access:ot(m,c,w),release:async()=>{}}},async describe(w,_){let R=await m.describeMaterial(c,w,_?{signal:_}:void 0);if(R&&(R.kind==="segment"||R.kind==="content"))throw new g("identity_mismatch",p("cli.sessions.journal.externalKindDiffers"));return R},readRange:(w,_,R,O)=>m.readMaterial(c,w,{offset:_,bytes:R},O?{signal:O}:void 0),async list(w,_,R){let O=await m.listMaterials(c,{kind:w,after:_,limit:R});return{...O,materials:O.materials}}}):void 0,v=m?.storage??await ye({directory:i,identity:f,mode:d,...e===r?{lockDirectory:()=>e}:{},segmentation:o===!1?{enabled:!1}:o??{},...n?{readOnly:!0}:{}});try{let w=m?.content??await Fe({directory:A.join(i,"content"),identity:f,mode:d,maxBlobBytes:te}),_=At({storage:v,content:w,ownerId:vt(),leaseMs:3e5,maxSnapshotBytes:te,maxContentReads:v.limits.maxTailEntries+1,maxContentReadBytes:te*2,projector:{empty:()=>({format:"cli-session-log-v1",messages:[],projection:qe(),cursor:{...ut}}),decodeSnapshot:R=>Pn(JSON.parse(Buffer.from(R).toString("utf8"))),encodeSnapshot:R=>Buffer.from(JSON.stringify(R)),async apply(R,O,T,I){let S=JSON.parse(O.body);if(S.format!=="journal.batch.v1"&&S.format!=="journal.batch.ref.v1"||O.kind!==S.format)throw new g("integrity",p("cli.sessions.journal.unknownEntry"));let N=S.format==="journal.batch.ref.v1"?JSON.parse(Buffer.from(await I.readContent(S.content)).toString("utf8")):S,b=nt(N),P=Wt(S);if(P.firstSeq!==N.metadata.firstSeq||P.lastSeq!==N.metadata.lastSeq)throw new g("integrity",p("cli.sessions.journal.originalContentRangeDiffers"));let C={...R.cursor},h=b.records.map(E=>{let y=Ee.parse(E);if(y.sessionId!==T.scope.sessionId||y.seq!==C.lastSeq+1||y.integrity.previousHash!==C.lastHash||Ie(y)!==y.integrity.hash)throw new g("integrity",p("cli.sessions.journal.recordChainDiffers"));return C={recordCount:C.recordCount+1,lastSeq:y.seq,lastEventId:y.eventId,lastHash:y.integrity.hash,byteLength:C.byteLength+Buffer.byteLength(JSON.stringify(y))+1},y}),k=new Map(b.acknowledged.map(E=>[`${Kt}${E}`,!0])),x=Yt(),X=ce(await x.reduce(b.seed??R.projection,h,{async get(E){return k.get(E)},set(E,y){k.set(E,y)}})),oe=h.filter(E=>E.branchId===U&&E.visibility.model&&["user_prompt","assistant_message","tool_result"].includes(E.kind)).map(E=>fe.parse(E.payload)),Z=b.snapshot??[...R.messages,...oe];if(Z.length!==X.messageCount)throw new g("integrity",p("cli.sessions.journal.batchProjectionDiffers"));return{format:"cli-session-log-v1",messages:Z,projection:X,cursor:C}}}});return{storage:v,runtime:_,scope:c,cold:m,unbind:u}}catch(w){throw await v.close(),u?.(),w}}async function nr(e,t){if(ne(e)||ne(t))throw new g("invalid",p("cli.sessions.journal.implicitColdCustodyUpgrade"));let n=await st(e,!await W(e),!1,void 0,t);return{runtime:n.runtime,storage:n.storage,scope:n.scope,async close(){await n.runtime.close(),await n.storage.close()}}}var rt=class e{#t;#a;#e;#n;#l;#c;#o;#d;#s=!1;#u=!1;#r;#i;constructor(t,n,o,r,s,i,a,l){this.#n=z(t),this.#t=n,this.#a=o,this.#e=r,this.#o=s,this.#l=i,this.#c=a,this.#d=l??we(r.head.metadata),this.#i=setInterval(()=>{r.renew().catch(()=>{})},6e4),this.#i.unref()}static async open(t,n,o,r,s,i){let{storage:a,runtime:l,scope:d,cold:f,unbind:m}=await st(t,n,!1,r,t,s);try{n&&await l.create({scope:d,requestKey:`cli-create-${d.sessionId}`,metadata:JSON.stringify({format:"cli-session-log-v1",...i?{meta:i}:{}})});let c=await l.open(d),u=new e(t,a,l,c,o,f,m,i);return $.set(z(t),u),u}catch(c){throw await l.close(),await a.close(),m?.(),c}}get nextSeq(){return this.#e.state.cursor.lastSeq+1}head(){return this.#e.head}lockPath(){return A.join(this.#n,"lock")}async touchLock(){let t=new Date;await An(A.join(this.#n,"lock"),t,t).catch(()=>{})}coldHandle(){return this.#l}async readOperation(t){if(this.#s)throw new g("closed",p("cli.sessions.journal.writerClosing"));return this.#t.getOperation(this.#e.head.scope,t)}cursor(){return{...this.#e.state.cursor}}indexedProjection(){return this.#e.state.projection}snapshot(){return this.#e.state.messages}async append(t){return(await this.appendBatch([t]))[0]}async appendBatch(t,n){if(this.#s)throw new g("closed",p("cli.sessions.journal.writerClosed"));if(t.length===0)return[];let o=et(),r=et(),s=K(JSON.stringify(t)),i=[];return await this.#e.update(async(a,l)=>{let d=[],f=a.state.cursor;for(let h of t){let k=Ee.parse({...h,schemaVersion:dt(h.payload)?2:1,seq:f.lastSeq+1,completeness:"complete",integrity:{previousHash:f.lastHash,hash:""}});k.integrity.hash=Ie(k),d.push(k),f={recordCount:f.recordCount+1,lastSeq:k.seq,lastEventId:k.eventId,lastHash:k.integrity.hash,byteLength:f.byteLength+Buffer.byteLength(JSON.stringify(k))+1}}let m=[],c=[],u=new Set(d.flatMap(h=>{let k=h.kind==="queue_ack"?ae(h.payload):h.kind==="queue_enqueue"?ie(h.payload):null;return k===null?[]:[k.notificationId]}));for(let h of u){let k=Cn(h),x=await this.#t.getOperation(a.head.scope,k.operationKey,{signal:l.signal});if(l.assertCurrent(),x!==null&&(x.kind!=="cli.notification-ack"||x.intentDigest!==k.intentDigest||x.batchId!==k.batchId||x.status!=="committed"||x.result!==JSON.stringify({notificationId:h})))throw new g("recovery_required",p("cli.sessions.journal.notificationAckUnresolved"));x!==null?m.push(h):d.some(X=>X.kind==="queue_ack"&&ae(X.payload)?.notificationId===h)&&c.push({expectedStatus:null,operation:{key:k.operationKey,kind:"cli.notification-ack",intentDigest:k.intentDigest,batchId:k.batchId,status:"committed",result:JSON.stringify({notificationId:h}),lastSeq:a.head.lastSeq,logDigest:a.head.logDigest}})}let v={records:d,acknowledged:m,...this.#o===void 0?{}:{seed:this.#o}},w=d.filter(h=>h.visibility.model&&["user_prompt","assistant_message","tool_result"].includes(h.kind)).map(h=>h.payload);n?.snapshot!==void 0&&!Rn(n.snapshot,[...a.state.messages,...w])&&(v.snapshot=[...n.snapshot]);let _={firstSeq:d[0].seq,lastSeq:d.at(-1).seq},{records:R,...O}=v,T={format:"journal.batch.v1",records:R,metadata:{...O,..._}},I=JSON.stringify(T);Buffer.byteLength(JSON.stringify(I))>this.#t.limits.maxEntryBytes-1024&&(T={format:"journal.batch.ref.v1",content:await l.putContent(Buffer.from(I)),..._}),i=d;let S=this.#o??a.state.projection,N=d.find(h=>h.branchId===U&&h.kind==="compact_boundary"),b=S.compactBoundary??(N===void 0?null:H.parse(N.payload)),P={version:1,cursor:f,compactBoundary:b,sourceAnchor:b===null?null:S.spillAncestors.find(h=>h.sessionId===b.sourceSessionId)??null},C=this.#d??we(a.head.metadata);return{input:{batchId:o,operationKey:r,intentDigest:s,metadata:JSON.stringify({format:"cli-session-log-v1",journal:P,...C?{meta:C}:{}}),entries:[{entryId:et(),kind:T.format,body:JSON.stringify(T)}],operations:c}}}),this.#o=void 0,i}async close(){if(this.#u)return;if(this.#r!==void 0)return this.#r;this.#s=!0,clearInterval(this.#i);let t=(async()=>{await this.#a.close(),await this.#t.close(),this.#c?.(),$.get(this.#n)===this&&$.delete(this.#n),this.#u=!0})();this.#r=t;try{await t}finally{this.#r===t&&(this.#r=void 0)}}};function _n(e,t){let n=!1,o,r={lockPath:e?.lockPath??t.lockPath(),touch:()=>e?e.touch():t.touchLock(),async release(){if(n)return;if(o!==void 0)return o;let s=(async()=>{await t.close(),await e?.release(),n=!0})();o=s;try{await s}finally{o===s&&(o=void 0)}}};return $t.set(r,t),r}function or(e){return $t.get(e)}async function rr(e,t){let n=$.get(z(e));if(n)return n.readOperation(t);let r=(await ue(e))?.handle.storage??await ye({directory:A.join(e,G),identity:Be(e),mode:"reopen"});try{return await r.getOperation(F(e),t)}finally{await r.close()}}async function sr(e){let t=$.get(z(e));if(t!==void 0)return{descriptor:tt(t.head().metadata),readBytes:0};let n=0;if(ne(e)){let r=await ue(e,65536,s=>{n+=s});if(!r)throw new g("not_found",p("cli.sessions.journal.coldSourceUnavailable"));try{let s=await r.handle.describe(r.scope);if(!s)throw new g("not_found",p("cli.sessions.journal.descriptorMissing"));return{descriptor:tt(s.metadata),readBytes:n}}finally{await r.handle.close()}}let o=await ye({directory:A.join(e,G),identity:Be(e),mode:"reopen",readOnly:!0,readBudgetBytes:64*1024,onIo(r){(r.kind==="read"||r.kind==="index-read")&&(n+=r.bytes)}});try{let r=(await o.list(F(e),1))[0];if(!r)throw new g("not_found",p("cli.sessions.journal.descriptorMissing"));return{descriptor:tt(r.metadata),readBytes:n}}finally{await o.close()}}async function Vt(e,t,n,o){if(t!==void 0&&t!==!1){let d=typeof t=="object"?t:void 0,f=await rt.open(e,!1,void 0,n,o),m=we(f.head().metadata);return{view:{head:f.head(),state:{format:"cli-session-log-v1",messages:[...f.snapshot()],projection:f.indexedProjection(),cursor:f.cursor()}},lock:_n(d,f),...m?{meta:m}:{}}}let r=$.get(z(e));if(r!==void 0){let d=we(r.head().metadata);return{view:{head:r.head(),state:{format:"cli-session-log-v1",messages:[...r.snapshot()],projection:r.indexedProjection(),cursor:r.cursor()}},...d?{meta:d}:{}}}let{storage:s,runtime:i,scope:a,unbind:l}=await st(e,!1,!0,void 0,e,o);try{let d=await i.read(a);if(d===null)throw new g("not_found",p("cli.sessions.journal.sessionMissing"));let f=we(d.head.metadata);return{view:d,...f?{meta:f}:{}}}finally{await i.close(),await s.close(),l?.()}}async function ir(e,t){if(!Number.isSafeInteger(t.maxBytes)||t.maxBytes<1||!Number.isSafeInteger(t.maxRecords)||t.maxRecords<1||t.beforeSeq!==void 0&&(!Number.isSafeInteger(t.beforeSeq)||t.beforeSeq<0))throw new TypeError(p("cli.sessions.journal.invalidHistoryPageBudget"));let n=A.join(e,G),o=Be(e),r=F(e),s=Math.max(1,Math.floor(t.maxBytes/2)),i=t.maxBytes-s,a=0,l=0,d=!1,f=t.beforeSeq,m=[],c,u,v={signal:new AbortController().signal};try{u=await ue(e,s,I=>{a+=I}),c=u?.handle.storage??await ye({directory:n,identity:o,mode:"reopen",readOnly:!0,readBudgetBytes:s,onIo(I){(I.kind==="read"||I.kind==="index-read")&&(a+=I.bytes)}});let w=u?await u.handle.describe(r,v):(await c.list(r,1))[0];if(w==null)return{records:[],clipped:!1,readBytes:a,view:"published_checkpoint"};d=w.ownerId!==null;let _=async I=>(await c.scanEntries(r,{afterSeq:I-1,limit:1,maxBytes:Math.max(1,Math.min(c.limits.maxTailBytes,s))},v)).entries[0],R=I=>I?.kind==="journal.batch.v1"||I?.kind==="journal.batch.ref.v1"?JSON.parse(I.body):void 0,O=w.lastSeq;if(t.beforeSeq!==void 0){let I=1,S=w.lastSeq,N=0;for(;I<=S;){let b=Math.floor((I+S)/2),P=b,C;for(;P>=I&&C===void 0;)C=R(await _(P--));if(P++,C===void 0){I=b+1;continue}let h=Wt(C);if(!Number.isSafeInteger(h.firstSeq)||!Number.isSafeInteger(h.lastSeq))throw new g("integrity",p("cli.sessions.journal.invalidHistoryRange"));h.firstSeq<t.beforeSeq?(N=P,I=b+1):S=P-1}O=N}let T=u?.handle.content;for(let I=O;I>0;I--){let S=R(await _(I));if(S===void 0)continue;let N;if(S.format==="journal.batch.ref.v1"){if(S.content.bytes>i-l){d=!0,f=S.firstSeq;continue}if(T===void 0){let h=await Re(A.join(n,"content","content.json"));if(h.size>i-l-S.content.bytes){d=!0,f=S.firstSeq;continue}l+=h.size,T=await Fe({directory:A.join(n,"content"),identity:o,mode:"reopen",maxBlobBytes:i})}let P=await T.get(r,S.content,v);if(u||(l+=P.byteLength),P.byteLength!==S.content.bytes||K(P)!==S.content.sha256)throw new g("integrity",p("cli.sessions.journal.historyContentDiffers"));let C=JSON.parse(Buffer.from(P).toString("utf8"));if(N=nt(C),S.firstSeq!==C.metadata.firstSeq||S.lastSeq!==C.metadata.lastSeq)throw new g("integrity",p("cli.sessions.journal.originalRangeDiffers"))}else if(S.format==="journal.batch.v1")N=nt(S);else throw new g("integrity",p("cli.sessions.journal.historyEntryShapeDiffers"));let b=N.records.map(P=>Ee.parse(P));for(let P=b.length-1;P>=0;P--){let C=b[P];if(C.sessionId!==r.sessionId||Ie(C)!==C.integrity.hash)throw new g("integrity",p("cli.sessions.journal.originalRecordDiffers"));if(!(t.beforeSeq!==void 0&&C.seq>=t.beforeSeq)){if(m.length===t.maxRecords){d=!0;break}m.push(C),f=C.seq}}if(m.length===t.maxRecords){d||=I>1;break}}}catch(w){if(!(w instanceof g)||w.code!=="recovery_required")throw w;d=!0}finally{await c?.close()}return{records:m.reverse(),clipped:d,readBytes:a+l,...f===void 0?{}:{nextBeforeSeq:f},view:"published_checkpoint"}}function fr(e=process.env){return ct(e)?.root??lt(e)}async function en(e){try{return await On(e)}catch{return null}}async function he(e){let t=await Zt(e).catch(()=>null);if(t!==null)return t;let n=await en(yt(e)),o=await ft(e).catch(()=>null),r=n?.size??0,s;for(let i of o?.segments??[]){let a=await en(St(e,i.n));pt(i,a!==null)&&a!==null&&(r+=a.size,(s===void 0||a.mtimeMs>s)&&(s=a.mtimeMs))}return n!==null?{mtimeMs:n.mtimeMs,bytes:r}:s!==void 0?{mtimeMs:s,bytes:r}:null}function Nn(e,t){let n=Je.resolve(e),o=Je.resolve(t);return process.platform==="win32"?n.toLowerCase()===o.toLowerCase():n===o}async function tn(e,t){let n=Je.join(e,"sessions"),o;try{o=(await kn(n,{withFileTypes:!0})).filter(i=>i.isDirectory()).map(i=>i.name)}catch{return[]}let r=[];for(let s of o){if(t.excludeSessionId!==void 0&&s===t.excludeSessionId)continue;let i=Je.join(n,s);try{let a=await he(i);if(a===null)continue;let l=await se(i);if(l.sessionId!==s||t.cwd!==void 0&&!Nn(l.cwd,t.cwd))continue;let d={sessionId:l.sessionId,cwd:l.cwd,createdAt:l.createdAt,updatedAt:a.mtimeMs};l.title!==void 0&&(d.title=l.title),l.firstUserMessage!==void 0&&(d.firstUserMessage=l.firstUserMessage),l.model!==void 0&&(d.model=l.model),l.provider!==void 0&&(d.provider=l.provider),r.push(d)}catch{continue}}return r}async function Tn(e,t={}){let n=await tn(e,t),o=pe(e);if(o!==null){let r=new Set(n.map(s=>s.sessionId));for(let s of await tn(o,t))r.has(s.sessionId)||n.push(s)}return n.sort((r,s)=>s.updatedAt-r.updatedAt),n}async function nn(e,t){let n;try{n=D(e,t)}catch{return null}if(await he(n)!==null)return n;let o=pe(e);if(o===null)return null;let r=D(o,t);return await he(r)!==null?r:null}async function mr(e,t){return(await Tn(e,{cwd:t}))[0]?.sessionId}function ze(e){let t=[];for(let n of e){if(n.kind!=="event")continue;let o=_e(n.payload);o!==null&&t.push({seq:n.seq,payload:o})}return t}function Mn(e){return e.filter(t=>t.payload.phase!=="started").length}async function xn(e,t){let n=await nn(e,t);if(n===null)return null;try{let o=await me(n,{repair:!1});return ze(o.records)}catch{return null}}async function Rr(e,t){if(t.projectedCompactions!==void 0)return[...t.projectedCompactions?.recent??[]].reverse();let n=[...t.attempts];if(t.compactBoundary!==void 0&&Mn(n)<5){let o=await xn(e,t.compactBoundary.sourceSessionId);o!==null&&(n=[...o,...n])}return ke(n.map(o=>o.payload))}export{Jn as a,Ln as b,ae as c,Gn as d,Fn as e,Vn as f,Yn as g,Qn as h,Hn as i,$n as j,zn as k,Zn as l,jn as m,qn as n,M as o,fr as p,he as q,Tn as r,nn as s,mr as t,ze as u,Rr as v,lo as w,je as x,Ut as y,mn as z,Xe as A,Ze as B,wn as C,To as D,qe as E,ce as F,Fo as G,Yt as H,tr as I,Gt as J,Ft as K,vn as L,W as M,Zt as N,nr as O,rt as P,_n as Q,or as R,rr as S,sr as T,Vt as U,ir as V};
5
+ //# sourceMappingURL=tansr-chunk-WAYVH5ON.mjs.map
@@ -0,0 +1,11 @@
1
+ import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
+ import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
+ const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
+ import{D as H,E as C,F as ie,G as N,H as re,I as j,M as oe,P as T,Q as ae,R as _,o as R,z as F}from"./tansr-chunk-WAYVH5ON.mjs";import{m as J}from"./tansr-chunk-SHLU4JN2.mjs";import{Ib as ne,P,T as L}from"./tansr-chunk-6N333TUL.mjs";import{m as W}from"./tansr-chunk-EFN24XG3.mjs";import{m as S}from"./tansr-chunk-YK3CE3JM.mjs";import{B as z,p as X,s as $,y as q}from"./tansr-chunk-4DAH4AIH.mjs";import{C as I}from"./tansr-chunk-ENRIN7EG.mjs";import{D as Z,F as ee,H as te,J as se,a as k,h as K,n as Y,q as V,v as O}from"./tansr-chunk-LA3LGOYQ.mjs";import{randomUUID as pe}from"node:crypto";import{randomUUID as E}from"node:crypto";import{readFile as Te}from"node:fs/promises";var le=64;function ue(i){for(let e of i){if(e.role!=="user")continue;let t=e.blocks.flatMap(s=>s.t==="text"?[s.text]:[]).join(" ").replace(/\s+/g," ").trim();if(t!=="")return t.length>le?`${t.slice(0,le)}…`:t}}var de=120,Me=/\u001b\[[0-9;]*[A-Za-z]|\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g,Ae=/[\u0000-\u001f\u007f-\u009f]/g;function ce(i){for(let e of i){if(e.role!=="user")continue;let t=e.blocks.flatMap(n=>n.t==="text"?[n.text]:[]).join(" ").replace(Me,"").replace(Ae," ").replace(/\s+/g," ").trim();if(t==="")continue;let s=[...t];return s.length>de?`${s.slice(0,de).join("")}…`:t}}function D(i){return i.role==="assistant"?"assistant_message":i.blocks.some(e=>e.t==="tool_result")?"tool_result":"user_prompt"}var Oe="emergency_seal",_e=1,x=class i{#a;#b;#l;#O;#k;#P;#C;#_;#T;#x;#U;#M;#A=null;#I=Promise.resolve();#s;#N;#r=0;#e=null;#t=null;#d=null;#v=null;#u=null;#o=null;#n=!1;#H;#i=!1;#W=!1;#j;#c=[];#p=[];#h=[];#f=[];#m=[];#g=[];#y=null;#L=null;#R=C();#E=null;constructor(e){if(e.cold){if(e.journalLayout&&e.journalLayout!=="session-log-v1")throw new TypeError(S("cli.sessions.journal.explicitFormat5LayoutRequired"));j(e.storageRoot,e.cold)}this.#a=e.storageRoot,this.#s=e.sessionId,this.#N=[e.sessionId],this.#b=e.cwd,this.#l=e.journalLayout??"session-log-v1",this.#O=e.model,this.#k=e.currentModel,this.#P=e.startedAt??new Date().toISOString(),this.#C=e.outputStyle,this.#_=e.usageReportingDisabled===!0,this.#T=e.platformSessionId,this.#x=e.onError,this.#U=e.segmentation===!1?{enabled:!1}:e.segmentation===void 0?{}:{...e.segmentation},this.#M=e.lockHeartbeatMs??Y}#q(){if(this.#A!==null||this.#i||!Number.isFinite(this.#M)||this.#M<=0)return;let e=setInterval(()=>{let t=this.#e?.lock??this.#t;t?.touch().catch(()=>{})},this.#M);e.unref(),this.#A=e}#J(){this.#A!==null&&(clearInterval(this.#A),this.#A=null)}currentSessionId(){return this.#s}volumeIds(){return[...this.#N].reverse()}#D(e){this.#s=e,this.#N.includes(e)||this.#N.push(e)}persistedCount(){return this.#r}commitHistory(e,t){if(this.#i)return;let s=[...e],n=t?.rewritten===!0,o=t?.compaction!==void 0?{...t.compaction}:void 0;this.#S(()=>this.#Q(s,n,o))}commitHistoryDurable(e,t){if(this.#i)return Promise.reject(new Error(S(R.journalClosed)));let s=structuredClone([...e]),n=t?.compaction===void 0?void 0:{...t.compaction},o=this.#I.then(async()=>{if(this.#n)throw this.#H??new Error(S(R.journalUnavailable));try{await this.#Q(s,t?.rewritten===!0,n,!0)}catch(r){throw this.#G(r),r}});return this.#I=o.catch(()=>{}),o}prepareHistoryRewrite(e,t={}){if(this.#i)return Promise.reject(new Error(S(R.journalClosed)));let s=structuredClone([...e]),n=new i({storageRoot:this.#a,sessionId:E(),cwd:this.#b,model:this.#O,journalLayout:this.#l,startedAt:this.#P,segmentation:this.#U,lockHeartbeatMs:this.#M,...this.#k===void 0?{}:{currentModel:this.#k},...this.#C===void 0?{}:{outputStyle:this.#C},...this.#T===void 0?{}:{platformSessionId:this.#T},...this.#x===void 0?{}:{onError:this.#x},...this.#_?{usageReportingDisabled:!0}:{}}),o=!1,r=!1,p=this.#I.then(async()=>{if(t.signal?.throwIfAborted(),this.#n)throw this.#H??new Error(S(R.journalUnavailable));return n.#c=[...this.#c],n.#p=[...this.#p],n.#f=[...this.#f],n.#m=[...this.#m],n.#g=[...this.#g],n.#h=[...this.#h],n.#L=this.#L,n.#y=this.#L,await n.commitHistoryDurable(s),t.signal?.throwIfAborted(),{sessionId:n.currentSessionId(),publish:()=>{if(o||r)throw new Error(S(R.preparedHistoryUnavailable));if(t.signal?.throwIfAborted(),this.#i||this.#n||this.#I!==v)throw new Error(S(R.historyPreparationChanged));this.#J(),n.#J(),[this.#s,n.#s]=[n.#s,this.#s],this.#N.push(this.#s),[this.#e,n.#e]=[n.#e,this.#e],[this.#r,n.#r]=[n.#r,this.#r],[this.#t,n.#t]=[n.#t,this.#t],[this.#d,n.#d]=[n.#d,this.#d],[this.#v,n.#v]=[n.#v,this.#v],[this.#u,n.#u]=[n.#u,this.#u],[this.#o,n.#o]=[n.#o,this.#o],[this.#R,n.#R]=[n.#R,this.#R],[this.#E,n.#E]=[n.#E,this.#E],this.#c=n.#c,this.#p=n.#p,this.#f=n.#f,this.#m=n.#m,this.#g=n.#g,this.#h=n.#h,this.#y=n.#y,this.#q(),o=!0},dispose:async()=>{r||(r=!0,await n.close())}}}),v=p.then(()=>{},()=>{});return this.#I=v,p.catch(async d=>{throw await n.close(),d})}commitEmergency(e,t){if(this.#i)return Promise.resolve();let s=[...e],n={type:Oe,version:_e,reason:t.reason,...t.signal!==void 0?{signal:t.signal}:{},at:t.at,turn:t.turn,messages:s.length,...t.partialText!==void 0&&t.partialText.length>0?{partialText:t.partialText}:{}};return this.#S(async()=>{await this.#Q(s,!1),!(this.#n||this.#e===null)&&await this.#w(this.#e,n)})}appendFileCheckpoint(e){if(this.#i)return;let t=structuredClone(e);this.#S(async()=>{if(!this.#n){if(this.#e===null){this.#c.push(t);return}await this.#$(this.#e,t)}})}appendRetryLedger(e){if(this.#i)return;let t=structuredClone(e);this.#S(async()=>{if(!this.#n){if(this.#e===null){this.#p.push(t);return}try{await this.#V(this.#e,t)}catch{}}})}appendPermissionRuntime(e){if(this.#i)return;let t=structuredClone(e);this.#S(async()=>{if(!this.#n){if(this.#e===null){this.#f.push(t);return}await this.#w(this.#e,t)}})}appendCompactionAttempt(e){if(this.#i)return;let t=structuredClone(e);this.#S(async()=>{if(!this.#n){if(this.#e===null){this.#m.push(t);return}try{await this.#w(this.#e,t)}catch{}}})}appendUsageSnapshot(e){if(this.#i)return;let t=structuredClone(e);this.#S(async()=>{if(!this.#n){if(this.#L=t,this.#e===null){this.#y=t;return}try{await this.#w(this.#e,t)}catch{}}})}appendSessionEvent(e){if(this.#i)return;let t=structuredClone(e);this.#S(async()=>{if(!this.#n){if(this.#e===null){this.#g.push(t);return}try{await this.#w(this.#e,t)}catch{}}})}appendQueueEnqueue(e){return this.#K("queue_enqueue",e)}appendQueueAck(e){return this.#K("queue_ack",e)}#K(e,t){if(this.#i)return Promise.resolve();let s=structuredClone(t);return this.#S(async()=>{if(!this.#n){if(this.#e===null){this.#h.push({kind:e,payload:s});return}await this.#X(this.#e,e,s)}})}adoptSession(e){return this.#i?e.lock.release():this.#S(async()=>{if(this.#n){await e.lock.release();return}await this.#F(),await this.#B(),this.#t=e.lock,_(e.lock)!==void 0&&(this.#l="session-log-v1"),this.#d=e.lastEventId??null,this.#v=e.lastSeq??null,this.#u=e.cursor??null,this.#E=e.journalProjection??null,this.#R=C(),this.#D(e.sessionId),this.#r=e.persistedCount,this.#o=null,this.#q()})}adoptFresh(e=E()){return this.#i?Promise.resolve():this.#S(async()=>{this.#n||(await this.#F(),await this.#B(),this.#D(e),this.#r=0,this.#d=null,this.#v=null,this.#u=null,this.#o=null,this.#R=C(),this.#E=null)})}async#B(){this.#t!==null&&(await this.#t.release(),this.#t=null)}async close(){if(this.#W)return;if(this.#j!==void 0)return this.#j;this.#i=!0,this.#J();let e=this.#I.then(async()=>{try{await this.#F(),await this.#B(),this.#W=!0}catch(t){throw this.#G(t),t}});this.#j=e,this.#I=e.catch(()=>{});try{await e}finally{this.#j===e&&(this.#j=void 0)}}#S(e){let t=this.#I.then(async()=>{try{await e()}catch(s){this.#G(s)}});return this.#I=t,t}#G(e){let t=!this.#n;if(this.#n=!0,!t)return;this.#H=e;let s=e instanceof Error?e.message:String(e);this.#x?.(S(R.persistFailed,{message:s}))}async#F(){let e=this.#e;if(e!==null){if(e.pendingSessionMeta!==void 0){let t=e.pendingSessionMeta;e.pendingSessionMeta=void 0;let s=E();await e.writer.append({eventId:s,sessionId:this.#s,branchId:P,kind:"event",parentEventId:e.lastEventId,payload:t,producer:"cli",visibility:{...I.internal}}),e.lastEventId=e.writer.cursor().lastEventId}await e.writer.close(),await e.lock.release(),this.#e===e&&(this.#e=null)}}async#Q(e,t=!1,s,n=!1){if(this.#n)return;if(e.length<this.#r||t&&this.#r>0){let d=this.#s,a=this.#e!==null?this.#e.writer.nextSeq-1:this.#v,c=C();if(t&&s!==void 0&&a!==null&&a>=0){let l=this.#e?.sessionDir??O(this.#a,d),u=this.#e?.writer instanceof T?this.#e.writer:this.#t===null?void 0:_(this.#t);if(u!==void 0){let f=u.cursor();if(f.lastEventId===null||f.lastHash===null||f.lastSeq!==a)throw new k("JOURNAL_RECONCILIATION_REQUIRED",S("cli.sessions.journal.compactionSourceAnchorUnavailable"));c=N(u.indexedProjection(),{sessionId:d,seq:f.lastSeq,eventId:f.lastEventId,hash:f.lastHash},u.snapshot())}else if(await q(l)){let f=this.#e?.writer.indexedProjection()??this.#E,h=await z(l,{rehydrateImages:!1,reconcile:!0});if(h===null)throw new k("JOURNAL_RECONCILIATION_REQUIRED",S("cli.sessions.journal.compactionSourceLayoutChanged"));let m=ie(f??h.projection),g=this.#e?.writer.cursor()??this.#u;if(g===null||g.lastEventId===null||g.lastHash===null||g.lastSeq!==a||h.cursor.lastSeq!==g.lastSeq||h.cursor.lastEventId!==g.lastEventId||h.cursor.lastHash!==g.lastHash)throw new k("JOURNAL_RECONCILIATION_REQUIRED",S("cli.sessions.journal.compactionSourceAnchorUnavailable"));c=N(m,{sessionId:d,seq:g.lastSeq,eventId:g.lastEventId,hash:g.lastHash},h.snapshot)}else if(K(this.#l)||this.#l==="session-log-v1"){let{openSessionForResume:f}=await import("./tansr-restore-7PS7WCJR.mjs"),{restoreTodosForResume:h,createTodoReplayState:m}=await import("./tansr-todos-replay-TVQKP7OD.mjs"),{restoreCompactionHistoryForResume:g}=await import("./tansr-compaction-history-LZXZTWBV.mjs"),{accountCompactionEntry:w}=await import("./tansr-compaction-log-H2SPLK24.mjs"),{sessionSpillAncestorAnchors:M}=await import("./tansr-spill-YVUTIFOS.mjs"),y=await f(this.#a,d,{readOnly:!0,migrateToVault:!1});if(!y.ok||y.cursor.lastSeq!==a||y.cursor.lastEventId===null||y.cursor.lastHash===null)throw new k("JOURNAL_RECONCILIATION_REQUIRED",S("cli.sessions.journal.legacyCompactionSourceUnproven"));let b=C(),A=await h(this.#a,y);b.todos=m({items:A??[],sawTodoWrite:A!==null});let ke=await g(this.#a,{attempts:y.compactionAttempts,...y.compactBoundary===void 0?{}:{compactBoundary:y.compactBoundary}});for(let Ce of ke)b.compactions=w(b.compactions??void 0,Ce);b.spillAncestors=M(y.spillRecovery),c=N(b,{sessionId:d,seq:a,eventId:y.cursor.lastEventId,hash:y.cursor.lastHash},y.messages)}}await this.#F(),this.#t!==null&&(await this.#t.release(),this.#t=null),this.#d=null,this.#v=null,this.#u=null,this.#E=null,this.#R=c,this.#o=t&&s!==void 0&&a!==null&&a>=0?{sourceSessionId:d,sourceSeq:a,compactionId:s.compactionId,trigger:s.trigger,...s.beforeTokens!==void 0?{beforeTokens:s.beforeTokens}:{},...s.afterTokens!==void 0?{afterTokens:s.afterTokens}:{},...s.checkpointId!==void 0?{checkpointId:s.checkpointId}:{}}:null,this.#D(E()),this.#r=0,this.#L!==null&&(this.#y=this.#L)}let o=e.slice(this.#r);if(o.length===0&&(!n||e.length===0))return;let r=await this.#ee(e);if(r.writer instanceof T){let d=[],a=r.lastEventId,c=(l,u,f=I.internal)=>{let h=E();d.push({eventId:h,sessionId:this.#s,branchId:P,kind:l,parentEventId:a,payload:u,producer:"cli",visibility:{...f}}),a=h};if(r.pendingSessionMeta!==void 0){let l=r.pendingSessionMeta;r.pendingSessionMeta=void 0,c("event",l)}if(this.#o!==null){let l=this.#o;this.#o=null,c("compact_boundary",l)}if(this.#c.length>0){let l=this.#c;this.#c=[];for(let u of l)await J(r.sessionDir,u),c("file_checkpoint",u)}if(this.#p.length>0){let l=this.#p;this.#p=[];for(let u of l)try{JSON.stringify(u),c("event",u)}catch{}}if(this.#m.length>0){let l=this.#m;this.#m=[];for(let u of l)try{JSON.stringify(u),c("event",u)}catch{}}if(this.#g.length>0){let l=this.#g;this.#g=[];for(let u of l)try{JSON.stringify(u),c("event",u)}catch{}}if(this.#y!==null){let l=this.#y;this.#y=null;try{JSON.stringify(l),c("event",l)}catch{}}if(this.#f.length>0){let l=this.#f;this.#f=[];for(let u of l)c("event",u)}if(this.#h.length>0){let l=this.#h;this.#h=[];for(let{kind:u,payload:f}of l)c(u,f)}for(let l of o)c(D(l),l,I.normal);await r.writer.appendBatch(d,{snapshot:e}),r.lastEventId=r.writer.cursor().lastEventId,this.#r=e.length,await this.#Y(r);return}if(this.#o!==null){let d=this.#o;this.#o=null,await this.#z(r,d)}if(this.#c.length>0){let d=this.#c;this.#c=[];for(let a of d)await this.#$(r,a)}if(this.#p.length>0){let d=this.#p;this.#p=[];for(let a of d)try{await this.#V(r,a)}catch{}}if(this.#m.length>0){let d=this.#m;this.#m=[];for(let a of d)try{await this.#w(r,a)}catch{}}if(this.#g.length>0){let d=this.#g;this.#g=[];for(let a of d)try{await this.#w(r,a)}catch{}}if(this.#y!==null){let d=this.#y;this.#y=null;try{await this.#w(r,d)}catch{}}if(this.#f.length>0){let d=this.#f;this.#f=[];for(let a of d)await this.#w(r,a)}if(this.#h.length>0){let d=this.#h;this.#h=[];for(let{kind:a,payload:c}of d)await this.#X(r,a,c)}let p=r.lastEventId,v=o.map(d=>{let a=E(),c={eventId:a,sessionId:this.#s,branchId:P,kind:D(d),parentEventId:p,payload:d,producer:"cli",visibility:{...I.normal}};return p=a,c});await r.writer.appendBatch(v,r.indexed?{snapshot:e}:void 0),r.lastEventId=r.writer.cursor().lastEventId,this.#r=e.length,await this.#Y(r)}async#Y(e){let t=this.#T;if(t!==void 0)try{let s=t();if(typeof s!="string"||s==="")return;let n=Z(e.sessionDir),o=JSON.parse(await Te(n,"utf8"));if(typeof o!="object"||o===null||Array.isArray(o))return;let r=o;if(r.platformSessionId===s)return;r.platformSessionId=s,await ee(n,`${JSON.stringify(r,null,2)}
5
+ `)}catch{}}async#z(e,t){let s=E();await e.writer.append({eventId:s,sessionId:this.#s,branchId:P,kind:"compact_boundary",parentEventId:e.lastEventId,payload:t,producer:"cli",visibility:{...I.internal}}),e.lastEventId=e.writer.cursor().lastEventId}async#V(e,t){let s=E();await e.writer.append({eventId:s,sessionId:this.#s,branchId:P,kind:"event",parentEventId:e.lastEventId,payload:t,producer:"cli",visibility:{...I.internal}}),e.lastEventId=e.writer.cursor().lastEventId}async#w(e,t){let s=E();await e.writer.append({eventId:s,sessionId:this.#s,branchId:P,kind:"event",parentEventId:e.lastEventId,payload:t,producer:"cli",visibility:{...I.internal}}),e.lastEventId=e.writer.cursor().lastEventId}async#X(e,t,s){let n=E();await e.writer.append({eventId:n,sessionId:this.#s,branchId:P,kind:t,parentEventId:e.lastEventId,payload:s,producer:"cli",visibility:{...I.internal}}),e.lastEventId=e.writer.cursor().lastEventId}async#$(e,t){let s=E();await J(e.sessionDir,t),await e.writer.append({eventId:s,sessionId:this.#s,branchId:P,kind:"file_checkpoint",parentEventId:e.lastEventId,payload:t,producer:"cli",visibility:{...I.internal}}),e.lastEventId=e.writer.cursor().lastEventId}async#Z(e,t){let s=await $(e),n=X(s),o={segmentation:this.#U,...n?{layout:s.layout,projection:re(this.#R)}:{}};if(t===null)return L.open(e,o);try{return await L.openAt(e,t,o)}catch(r){if(!n&&r instanceof k&&r.code==="CURSOR_STALE")return L.open(e,o);throw r}}async#ee(e){if(this.#e!==null)return this.#e;if(this.#t!==null){let w=_(this.#t);if(w!==void 0){let M=this.#t,y=this.#d;this.#E=null,this.#t=null,this.#d=null,this.#v=null,this.#u=null;let b=O(this.#a,this.#s),A={writer:w,indexed:!0,lock:M,lastEventId:y,sessionDir:b};return this.#q(),this.#e=A,A}}let t=ue(e),s=ce(e),n=this.#k?.()??this.#O,o={model:n.model,provider:n.provider};t!==void 0&&(o.title=t),s!==void 0&&(o.firstUserMessage=s);let r=this.#C?.();r!==void 0&&(o.outputStyle=r);let{sessionDir:p,meta:v,created:d}=await se({storageRoot:this.#a,sessionId:this.#s,cwd:this.#b,extra:o,journalLayout:this.#l==="session-log-v1"?"legacy":this.#l,journalProjectionSeed:this.#R}),a=await oe(p);if(this.#l==="session-log-v1"&&!d&&!a&&this.#t===null)throw new k("JOURNAL_RECONCILIATION_REQUIRED",S("cli.sessions.journal.explicitMigrationRequired"));let c=a||d&&this.#l==="session-log-v1",l,u,f=null,h=null;this.#t!==null?(l=this.#t,u=_(l),f=this.#d,h=this.#u,this.#E=null,this.#t=null,this.#d=null,this.#v=null,this.#u=null):c||(l=await V(p));let m;try{m=u??(c?await T.open(p,d||!a,this.#R,this.#U,a,v):await this.#Z(p,h))}catch(w){throw await l?.release(),w}l===void 0&&m instanceof T&&(l=ae(void 0,m));let g={writer:m,indexed:m instanceof T||await q(p),lock:l,lastEventId:f,sessionDir:p};if(this.#q(),m.nextSeq===0){let w={type:"session_meta",version:1,sessionId:this.#s,cwd:this.#b,startedAt:this.#P,provider:n.provider,model:n.model};t!==void 0&&(w.title=t),this.#_&&(w.usageReportingDisabled=!0);let M=E();try{await m.append({eventId:M,sessionId:this.#s,branchId:P,kind:"event",parentEventId:null,payload:w,producer:"cli",visibility:{...I.internal}})}catch(y){throw await m.close(),await l.release(),y}g.lastEventId=g.writer.cursor().lastEventId}return this.#e=g,g}};async function xe(i){i.cold&&j(i.storageRoot,i.cold);let e=r=>new x({storageRoot:i.storageRoot,journalLayout:i.journalLayout??"session-log-v1",sessionId:r,cwd:i.cwd,model:i.model,...i.cold?{cold:i.cold}:{},...i.outputStyle!==void 0?{outputStyle:i.outputStyle}:{},...i.usageReportingDisabled===!0?{usageReportingDisabled:!0}:{},...i.platformSessionId!==void 0?{platformSessionId:i.platformSessionId}:{},...i.onSinkError!==void 0?{onError:i.onSinkError}:{},...i.segmentation!==void 0?{segmentation:i.segmentation}:{}});if(i.resumeSessionId===void 0){let r=i.defaultSessionId??pe();return{ok:!0,sessionId:r,sink:e(r),initialHistory:[]}}let t=await F(i.storageRoot,i.resumeSessionId,{segmentation:i.segmentation});if(!t.ok)return t.reason==="not_found"?{ok:!1,key:R.resumeNotFound,params:{sessionId:i.resumeSessionId}}:{ok:!1,key:R.resumeFailed,params:{sessionId:i.resumeSessionId,message:t.detail}};let s=await H(i.storageRoot,{messages:t.messages,...t.projectedTodos!==void 0?{projectedTodos:t.projectedTodos}:{},...t.compactBoundary!==void 0?{compactBoundary:t.compactBoundary}:{}}),n=s!==null&&s.length>0?{restoredTodos:s}:{};if(t.continuable&&t.lock!==void 0){let r=e(t.sessionId);return await r.adoptSession({sessionId:t.sessionId,lock:t.lock,persistedCount:t.journalMessageCount,lastEventId:t.lastEventId,lastSeq:t.lastSeq,cursor:t.cursor,...t.journalProjection!==void 0?{journalProjection:t.journalProjection}:{}}),{ok:!0,sessionId:t.sessionId,sink:r,initialHistory:t.messages,spillRecovery:t.spillRecovery,...t.meta!==void 0?{meta:t.meta}:{},...n,resumedFromSeq:t.lastSeq,...t.lastEffectiveModel!==void 0?{lastEffectiveModel:t.lastEffectiveModel}:{},...t.usageSnapshot!==void 0?{usageSnapshot:t.usageSnapshot}:{}}}let o=pe();return{ok:!0,sessionId:o,sink:e(o),initialHistory:t.messages,spillRecovery:t.spillRecovery,...t.meta!==void 0?{meta:t.meta}:{},...n,resumedFromSeq:t.lastSeq,...t.lastEffectiveModel!==void 0?{lastEffectiveModel:t.lastEffectiveModel}:{},...t.usageSnapshot!==void 0?{usageSnapshot:t.usageSnapshot}:{}}}import{createHash as Ue}from"node:crypto";import{existsSync as he}from"node:fs";import{chmod as Le,mkdir as fe,readFile as me,rename as Ne,rm as ge,stat as je,writeFile as ye}from"node:fs/promises";import U from"node:path";var ve=1024*1024,Re="blobs",Se=48;function B(i,e){return U.join(i,Re,e.slice(0,2),e.slice(2))}function qe(i){let e=U.resolve(i);return/^[A-Za-z]:/.test(e)?e.charAt(0).toLowerCase()+e.slice(1):e}var G=class{#a;#b;#l;#O;#k;#P=[];#C=new Map;#_=new Map;#T=!1;constructor(e){this.#a=e.storageRoot,this.#b=e.appendRecord,this.#l=e.currentTurn,this.#O=e.maxBytes??ve,this.#k=e.onError}noteTurn(e,t){if(t===void 0)return;let s=t.replace(/\s+/g," ").trim();s!==""&&this.#_.set(e,s.length>Se?`${s.slice(0,Se)}…`:s)}async capture(e){let t=this.#l();for(let s of e){let n=U.resolve(s),o=qe(n);if(this.#C.get(o)!==t)try{let r=await this.#x(n,o,t);if(r===null)continue;this.#P.push(r),this.#C.set(o,t),this.#b(this.#M(r))}catch(r){this.#A(r)}}}listRewindPoints(){let e=new Map;for(let t of this.#P){let s=e.get(t.turn);s===void 0?e.set(t.turn,{files:[t.path],capturedAt:t.capturedAt}):s.files.push(t.path)}return[...e.entries()].sort(([t],[s])=>s-t).map(([t,s])=>{let n=this.#_.get(t);return{turn:t,files:s.files,capturedAt:s.capturedAt,...n!==void 0?{label:n}:{}}})}affectedFiles(e){let t=new Set,s=[];for(let n of this.#P)n.turn<e||t.has(n.key)||(t.add(n.key),s.push(n.path));return s}async restoreToTurn(e){let t=new Map;for(let n of this.#P)n.turn<e||t.has(n.key)||t.set(n.key,n);let s={turn:e,restored:[],deleted:[],skipped:[],failed:[]};for(let n of t.values()){if(n.skipped){s.skipped.push({path:n.path,reason:"too_large"});continue}try{if(n.blobHash===null){await ge(n.path,{force:!0}),s.deleted.push(n.path);continue}let o=await me(B(this.#a,n.blobHash));await fe(U.dirname(n.path),{recursive:!0}),await ye(n.path,o);try{await Le(n.path,n.mode&511)}catch{}s.restored.push(n.path)}catch(o){s.failed.push({path:n.path,message:o instanceof Error?o.message:String(o)})}}return s}async#x(e,t,s){let n=Date.now(),o;try{o=await je(e)}catch(v){if(v.code==="ENOENT")return{key:t,path:e,turn:s,blobHash:null,mode:0,mtimeMs:0,bytes:0,capturedAt:n,skipped:!1};throw v}if(o.isDirectory())return null;if(o.size>this.#O)return{key:t,path:e,turn:s,blobHash:null,mode:o.mode,mtimeMs:o.mtimeMs,bytes:o.size,capturedAt:n,skipped:!0};let r=await me(e),p=Ue("sha256").update(r).digest("hex");return await this.#U(p,r),{key:t,path:e,turn:s,blobHash:p,mode:o.mode,mtimeMs:o.mtimeMs,bytes:r.byteLength,capturedAt:n,skipped:!1}}async#U(e,t){let s=B(this.#a,e);if(he(s))return;await fe(U.dirname(s),{recursive:!0});let n=`${s}.tmp-${process.pid}-${Date.now()}`;await ye(n,t);try{await Ne(n,s)}catch(o){if(await ge(n,{force:!0}),!he(s))throw o}}#M(e){return{path:e.path,blobHash:e.blobHash,mode:e.mode,mtimeMs:e.mtimeMs,turn:e.turn,bytes:e.bytes,capturedAt:e.capturedAt,...e.skipped?{skipped:!0}:{}}}#A(e){if(this.#T)return;this.#T=!0;let t=e instanceof Error?e.message:String(e);this.#k?.(S(R.checkpointFailed,{message:t}))}};var Ee=64,Q=64,Ie=2e3,Fe=["Turn the following user request into a short session title.","Requirements: at most 8 words; same language as the request;","reply with the title only - no quotes, no trailing punctuation, no explanations."].join(`
6
+ `);function we(i){for(let e of i){if(e.role!=="user")continue;let t=e.blocks.flatMap(s=>s.t==="text"?[s.text]:[]).join(" ").replace(/\s+/g," ").trim();if(t!=="")return t}}function Pe(i){let e=i.replace(/\s+/g," ").trim(),t=[['"','"'],["'","'"],["“","”"],["「","」"],["『","』"]];for(let[s,n]of t)if(e.length>s.length+n.length&&e.startsWith(s)&&e.endsWith(n)){e=e.slice(s.length,e.length-n.length).trim();break}if(e=e.replace(/[.。!!??…]+$/u,"").trim(),e!=="")return e.length>Q?`${e.slice(0,Q)}…`:e}function He(i,e){return e===void 0?i:e.aborted?(i.catch(()=>{}),Promise.resolve(void 0)):new Promise(t=>{let s=()=>{i.catch(()=>{}),t(void 0)};e.addEventListener("abort",s,{once:!0}),i.then(n=>{e.removeEventListener("abort",s),t(n)})})}async function be(i){let e=i.text.slice(0,Ie),t={system:[],messages:[{role:"user",blocks:[{t:"text",text:`${Fe}
7
+
8
+ <request>
9
+ ${e}
10
+ </request>`}]}],tools:[],model:i.model,maxTokens:Ee,skipCacheWrite:!0,...i.thinkingOff===!0?{thinking:{off:!0}}:{}},s=ne({observer:i.requestMeasurement,purpose:"title",face:{system:t.system,messages:t.messages,tools:t.tools},model:t.model}),n=new WeakSet,o=a=>{if(!n.has(a)){n.add(a);try{i.onFailureUsage?.(a.usage,{provider:a.provider||i.model.provider,model:a.model||i.model.model})}catch{}}},r={providerUsageReporter:o,...i.signal!==void 0?{signal:i.signal}:{},callMeta:{purpose:"title",...s!==void 0?{requestId:s.requestId}:{}}},p=i.client.stream(t,r),d=await He((async()=>{let a=[],c,l,u=!1;try{for await(let h of p){switch(h.t){case"block_start":h.block.t==="text"&&h.block.text.length>0&&a.push(h.block.text);break;case"text_delta":a.push(h.text);break;case"message_stop":c=h.usage,l=h.ttftMs,u=!0;break;case"error":{let m=W(h);m&&o(m),s?.({outcome:"error",errorKind:h.kind,...m===void 0?{}:{usage:m.usage}});return}default:break}if(u)break}}catch{s?.({outcome:"error",errorKind:"exception"});return}finally{Promise.resolve(p.return(void 0)).catch(()=>{})}if(!u){s?.({outcome:"error",errorKind:"contract"});return}s?.({outcome:"success",...c!==void 0?{usage:c}:{},...l!==void 0?{ttftMs:l}:{},...a.length>0?{responseBlocks:[{t:"text",text:a.join("")}]}:{}});let f=Pe(a.join(""));if(f!==void 0)return{title:f,...c!==void 0?{usage:c}:{}}})(),i.signal);if(d===void 0||i.signal?.aborted===!0){s?.({outcome:"aborted",errorKind:"aborted"});return}return d}function Je(i,e){return{type:"cost.usage.updated",model:i.model,provider:i.provider,purpose:"title",usage:e}}function De(i){let e=!1,t=Promise.resolve(),s=new AbortController,n=async(o,r)=>{let p=i.modelTier();if(p===void 0)return;let v=await be({client:p.client,model:p.model,...i.onUsage===void 0?{}:{onFailureUsage:i.onUsage},...p.thinkingOff===!0?{thinkingOff:!0}:{},text:o,signal:s.signal,...i.requestMeasurement!==void 0?{requestMeasurement:i.requestMeasurement}:{}});if(v!==void 0&&(v.usage!==void 0&&i.onUsage?.(v.usage,p.model),!s.signal.aborted))try{await te(O(i.storageRoot,r),v.title)}catch{}};return{maybeGenerate(o){if(e||s.signal.aborted)return;let r=we(o);if(r===void 0)return;e=!0;let p=i.currentSessionId();t=n(r,p).catch(()=>{})},suppress(){e=!0},idle(){return t},abort(){s.abort()}}}export{ue as a,ce as b,x as c,G as d,Je as e,De as f,xe as g};
11
+ //# sourceMappingURL=tansr-chunk-WPKFARCU.mjs.map
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __tansrCreateRequire } from 'module';const require=__tansrCreateRequire(import.meta.url);
2
2
  import { fileURLToPath as __tansrFileURLToPath } from 'url';import { dirname as __tansrDirname } from 'path';
3
3
  const __filename=__tansrFileURLToPath(import.meta.url);const __dirname=__tansrDirname(__filename);
4
- import{c as p,d as y}from"./tansr-chunk-2C6JKHKM.mjs";import{a as A,b as R,c as h,d as o,e as g,f as _,g as T}from"./tansr-chunk-OKAA4BJC.mjs";var U=_,W=T;function m(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function B(e){return e==null?"":typeof e=="string"||e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof URLSearchParams?e.toString():null}function S(e){let n=e.fetchImpl??fetch,t=e.apiBaseUrl.endsWith("/")?e.apiBaseUrl.slice(0,-1):e.apiBaseUrl,d=`${t}/`,w=p(e.auth.key);return(async(l,s)=>{let a=m(l);if(a!==t&&!a.startsWith(d))return n(l,s);let r=new Headers(s?.headers);if(r.set(A,e.auth.keyId),r.set(R,e.auth.key),a.startsWith(`${t}/t1/`)){let E=B(s?.body);if(E!==null){let u=y({signingKey:w,method:s?.method??"GET",pathWithQuery:H(a,t),body:E,...e.now!==void 0?{now:e.now}:{},...e.nonce!==void 0?{nonce:e.nonce()}:{}});r.set(h,u[h]),r.set(o,u[o]),r.set(g,u[g])}}let c=await n(a,{...s,headers:r}),i=c.headers.get(U);i!==null&&i!==""&&e.onBalance?.(i);let f=c.headers.get(W);return f!==null&&f!==""&&e.onCost?.(f),c})}function H(e,n){try{let t=new URL(e);return t.pathname+t.search}catch{return e.startsWith(n)?e.slice(n.length):e}}export{S as a};
5
- //# sourceMappingURL=tansr-chunk-726Y5F3M.mjs.map
4
+ import{E as p,F as y}from"./tansr-chunk-EFN24XG3.mjs";import{a as A,b as R,c as h,d as o,e as g,f as _,g as T}from"./tansr-chunk-OKAA4BJC.mjs";var U=_,W=T;function m(e){return typeof e=="string"?e:e instanceof URL?e.href:e.url}function B(e){return e==null?"":typeof e=="string"||e instanceof Uint8Array?e:e instanceof ArrayBuffer?new Uint8Array(e):ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):e instanceof URLSearchParams?e.toString():null}function S(e){let n=e.fetchImpl??fetch,t=e.apiBaseUrl.endsWith("/")?e.apiBaseUrl.slice(0,-1):e.apiBaseUrl,d=`${t}/`,w=p(e.auth.key);return(async(l,s)=>{let a=m(l);if(a!==t&&!a.startsWith(d))return n(l,s);let r=new Headers(s?.headers);if(r.set(A,e.auth.keyId),r.set(R,e.auth.key),a.startsWith(`${t}/t1/`)){let E=B(s?.body);if(E!==null){let u=y({signingKey:w,method:s?.method??"GET",pathWithQuery:H(a,t),body:E,...e.now!==void 0?{now:e.now}:{},...e.nonce!==void 0?{nonce:e.nonce()}:{}});r.set(h,u[h]),r.set(o,u[o]),r.set(g,u[g])}}let c=await n(a,{...s,headers:r}),i=c.headers.get(U);i!==null&&i!==""&&e.onBalance?.(i);let f=c.headers.get(W);return f!==null&&f!==""&&e.onCost?.(f),c})}function H(e,n){try{let t=new URL(e);return t.pathname+t.search}catch{return e.startsWith(n)?e.slice(n.length):e}}export{S as a};
5
+ //# sourceMappingURL=tansr-chunk-YEYFEVYF.mjs.map