@code-yeongyu/senpi 2026.11.3-1 → 2026.11.3-2

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 (201) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/bundle/chunks/anthropic-messages-LJAKRKMX.js +11 -0
  3. package/dist/bundle/chunks/{args-O3WS4WCO.js → args-GQTXDYS3.js} +1 -1
  4. package/dist/bundle/chunks/{azure-openai-responses-YLBBQXI7.js → azure-openai-responses-HDEKTPMZ.js} +1 -1
  5. package/dist/bundle/chunks/chatgpt-subscription.js +10 -2
  6. package/dist/bundle/chunks/{chunk-ED7VJGL4.js → chunk-2PGSRQBF.js} +1 -1
  7. package/dist/bundle/chunks/{chunk-4BF4FLT6.js → chunk-3LDASCJN.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-PIAY636U.js → chunk-3QPE75AR.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-FQZZGSYH.js → chunk-4ZGQUOBV.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-S2M5D5GS.js → chunk-5BMIET5O.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-XLLQJALL.js → chunk-67M7HKXO.js} +1 -1
  12. package/dist/bundle/chunks/chunk-6ISOXWH2.js +2 -0
  13. package/dist/bundle/chunks/{chunk-7KLEFHSU.js → chunk-6NPK2O3C.js} +2 -2
  14. package/dist/bundle/chunks/{chunk-BNIZP4OS.js → chunk-7C4W5HMU.js} +1 -1
  15. package/dist/bundle/chunks/chunk-7KIHKE2T.js +2 -0
  16. package/dist/bundle/chunks/{chunk-WCRNJYHO.js → chunk-A4KOQUHT.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-TOOB6OLG.js → chunk-A5PZGQCP.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-TBARMJ75.js → chunk-AVP6DDBF.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-FLM6GZPT.js → chunk-B3GTID4P.js} +1 -1
  20. package/dist/bundle/chunks/{chunk-2XBKE2BZ.js → chunk-BIWFWGUA.js} +1 -1
  21. package/dist/bundle/chunks/{chunk-6LDUM5CL.js → chunk-DCI4QOUX.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-2YFPDNNP.js → chunk-DNZKKG4V.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-W2V7RIBF.js → chunk-E7SA75PP.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-YWD54RHU.js → chunk-EBZ6IP4V.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-J2OBN7TI.js → chunk-G5XUGK4B.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-PX7FF5LE.js → chunk-GKP34H3C.js} +2 -2
  27. package/dist/bundle/chunks/{chunk-PP52OWBB.js → chunk-GLTOBXZY.js} +1 -1
  28. package/dist/bundle/chunks/{chunk-ZNLCKKF6.js → chunk-IJGXAACA.js} +117 -35
  29. package/dist/bundle/chunks/{chunk-LGO25HPL.js → chunk-JCTODLUP.js} +1 -1
  30. package/dist/bundle/chunks/{chunk-3ESZE3DG.js → chunk-KHBCZ6TR.js} +1 -1
  31. package/dist/bundle/chunks/chunk-KJR3XXMI.js +2 -0
  32. package/dist/bundle/chunks/{chunk-FJ2UCBOA.js → chunk-KY4V3TSO.js} +2 -2
  33. package/dist/bundle/chunks/{chunk-4SENPCEA.js → chunk-MCXOJHN2.js} +1 -1
  34. package/dist/bundle/chunks/{chunk-DPBPO5OU.js → chunk-NKI7L5UM.js} +3 -3
  35. package/dist/bundle/chunks/{chunk-CJWSQ6CK.js → chunk-OD7RT7G7.js} +1 -1
  36. package/dist/bundle/chunks/{chunk-F4OHTL2K.js → chunk-OOU3BRUY.js} +1 -1
  37. package/dist/bundle/chunks/{chunk-LPHUMR6R.js → chunk-OT6ALXSJ.js} +1 -1
  38. package/dist/bundle/chunks/{chunk-XGBRBCIQ.js → chunk-Q5CKFBQT.js} +1 -1
  39. package/dist/bundle/chunks/{chunk-F7GBSQRV.js → chunk-QPYDQ4QK.js} +1 -1
  40. package/dist/bundle/chunks/{chunk-MOOFLKLI.js → chunk-QSMT5KVJ.js} +1 -1
  41. package/dist/bundle/chunks/{chunk-SAZ6E74O.js → chunk-RUOTFZQR.js} +1 -1
  42. package/dist/bundle/chunks/{chunk-5DZD623T.js → chunk-RWF6IJQL.js} +2 -2
  43. package/dist/bundle/chunks/{chunk-HBCNDC53.js → chunk-S5Y7NEHB.js} +1 -1
  44. package/dist/bundle/chunks/{chunk-DAPBNRN5.js → chunk-SCBTASM4.js} +1 -1
  45. package/dist/bundle/chunks/chunk-SJWTZ3Z2.js +2 -0
  46. package/dist/bundle/chunks/{chunk-ISZ4EWIS.js → chunk-SODMQEHO.js} +1 -1
  47. package/dist/bundle/chunks/{chunk-WEGTCUO3.js → chunk-SQAQEITV.js} +1 -1
  48. package/dist/bundle/chunks/{chunk-UFVZTQKN.js → chunk-TQQG5L4D.js} +1 -1
  49. package/dist/bundle/chunks/{chunk-VPDQ6MOL.js → chunk-U6A4X3FV.js} +1 -1
  50. package/dist/bundle/chunks/{chunk-ACIFXWJ6.js → chunk-UHUM55TR.js} +1 -1
  51. package/dist/bundle/chunks/{chunk-L5OFGHDA.js → chunk-USKWGPA6.js} +1 -1
  52. package/dist/bundle/chunks/{chunk-7ORS33CE.js → chunk-VDDJADPV.js} +1 -1
  53. package/dist/bundle/chunks/{chunk-R65P6LAT.js → chunk-VIHXG53S.js} +1 -1
  54. package/dist/bundle/chunks/{chunk-SGS76663.js → chunk-VPVD5G32.js} +1 -1
  55. package/dist/bundle/chunks/chunk-WO6I5PRF.js +3 -0
  56. package/dist/bundle/chunks/{chunk-ETCYVVVO.js → chunk-WVEIJ437.js} +1 -1
  57. package/dist/bundle/chunks/{chunk-7565XQAU.js → chunk-XKFG4N3Z.js} +1 -1
  58. package/dist/bundle/chunks/{chunk-57MRFI6E.js → chunk-XMWPCJU6.js} +1 -1
  59. package/dist/bundle/chunks/{chunk-GDPWQJDQ.js → chunk-XPSXUKSD.js} +1 -1
  60. package/dist/bundle/chunks/{chunk-FNBEICAA.js → chunk-YI6KRJDC.js} +1 -1
  61. package/dist/bundle/chunks/{chunk-UURGXV5B.js → chunk-YP47G4YP.js} +1 -1
  62. package/dist/bundle/chunks/{chunk-6BSMXZKQ.js → chunk-YRYDCKUI.js} +1 -1
  63. package/dist/bundle/chunks/{chunk-QTQ3ES2S.js → chunk-YTKZSGMQ.js} +1 -1
  64. package/dist/bundle/chunks/{chunk-V36CXIIB.js → chunk-YXL3PNTL.js} +1 -1
  65. package/dist/bundle/chunks/chunk-Z7HTHT6K.js +2 -0
  66. package/dist/bundle/chunks/{chunk-27XEDYQA.js → chunk-ZTPG27EJ.js} +1 -1
  67. package/dist/bundle/chunks/{cli-main-XM5FWY3Z.js → cli-main-RN7YB427.js} +1 -1
  68. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-FC7QLRU2.js → cloudflare-workers-ai-system-one-N5KFNKK4.js} +1 -1
  69. package/dist/bundle/chunks/credential-accounts-BJX55MTT.js +2 -0
  70. package/dist/bundle/chunks/devin.js +10 -2
  71. package/dist/bundle/chunks/{dispatch-UY6LBJJE.js → dispatch-M7UAPGVY.js} +1 -1
  72. package/dist/bundle/chunks/{google-generative-ai-7PQ4QRHJ.js → google-generative-ai-2TZSCSIS.js} +1 -1
  73. package/dist/bundle/chunks/{google-vertex-DY7EO4EJ.js → google-vertex-7NJJOI7V.js} +1 -1
  74. package/dist/bundle/chunks/{health-write-45CX64T2.js → health-write-YUSPVH7U.js} +1 -1
  75. package/dist/bundle/chunks/{help-fast-path-3EDGRKQM.js → help-fast-path-DWCA77QP.js} +1 -1
  76. package/dist/bundle/chunks/host-command-KJXUTSQ7.js +2 -0
  77. package/dist/bundle/chunks/{host-lifecycle-TGG7KGQH.js → host-lifecycle-QHIJ4G2K.js} +1 -1
  78. package/dist/bundle/chunks/host-lifecycle.js +1 -1
  79. package/dist/bundle/chunks/{host-session-command-OJFARE5Q.js → host-session-command-IPH3WXSG.js} +1 -1
  80. package/dist/bundle/chunks/{host-socket-request-F2R5P34M.js → host-socket-request-XPXJV3CS.js} +1 -1
  81. package/dist/bundle/chunks/interactive-mode-XUXMDYLA.js +2 -0
  82. package/dist/bundle/chunks/{list-tips-3D3A6GFK.js → list-tips-XJY7EL5S.js} +1 -1
  83. package/dist/bundle/chunks/{login-health-YOPTYRTU.js → login-health-226NO44U.js} +1 -1
  84. package/dist/bundle/chunks/main-P7PKMJUG.js +2 -0
  85. package/dist/bundle/chunks/{mistral-conversations-6F2RAIB2.js → mistral-conversations-QMHMHSUF.js} +1 -1
  86. package/dist/bundle/chunks/{multi-session-host-N2RQ7JSZ.js → multi-session-host-ZQY4AN46.js} +1 -1
  87. package/dist/bundle/chunks/{native-loader-NMDTMHMA.js → native-loader-A6DNMGCK.js} +1 -1
  88. package/dist/bundle/chunks/openai-chatgpt.js +11 -3
  89. package/dist/bundle/chunks/{openai-codex-responses-YTWLG4OL.js → openai-codex-responses-GUAHKQE2.js} +1 -1
  90. package/dist/bundle/chunks/{openai-completions-TIFDYHZL.js → openai-completions-UPRTFM54.js} +1 -1
  91. package/dist/bundle/chunks/{openai-images-OAEMY4RG.js → openai-images-IKWNS6VB.js} +1 -1
  92. package/dist/bundle/chunks/{openai-responses-L35NIG5Y.js → openai-responses-AXN5NUHH.js} +1 -1
  93. package/dist/bundle/chunks/openrouter.js +10 -2
  94. package/dist/bundle/chunks/{package-manager-cli-JPNA27E5.js → package-manager-cli-PP7L2Q5M.js} +1 -1
  95. package/dist/bundle/chunks/radius.js +10 -2
  96. package/dist/bundle/chunks/{rg-engine-JDUYBM6L.js → rg-engine-VRSXT6HG.js} +1 -1
  97. package/dist/bundle/chunks/{role-45Y7PQFC.js → role-L5J7ZPCF.js} +1 -1
  98. package/dist/bundle/chunks/rotation-stream-6INZXQFC.js +2 -0
  99. package/dist/bundle/chunks/rpc-mode-W4UATRAT.js +2 -0
  100. package/dist/bundle/chunks/{rpc-monitor-source-5TUR27NY.js → rpc-monitor-source-RMMUPBMS.js} +1 -1
  101. package/dist/bundle/chunks/{run-attached-tui-TI6MELEI.js → run-attached-tui-RLXFGCEP.js} +1 -1
  102. package/dist/bundle/chunks/{schedule-command-OZ5ESMIT.js → schedule-command-ZNFEJNTT.js} +1 -1
  103. package/dist/bundle/chunks/{session-control-endpoint-5YKBYJOO.js → session-control-endpoint-TWTONJWF.js} +1 -1
  104. package/dist/bundle/chunks/{session-picker-CMRV72VA.js → session-picker-KRUVCHOV.js} +1 -1
  105. package/dist/bundle/chunks/session-slot-NJOZCOHQ.js +2 -0
  106. package/dist/bundle/chunks/session-worker.js +218 -135
  107. package/dist/bundle/chunks/{state-store-Q47AYMRI.js → state-store-ZAFZ4JOM.js} +1 -1
  108. package/dist/bundle/chunks/{typesafe-system-one-5JYDJK6S.js → typesafe-system-one-CICIRAYN.js} +1 -1
  109. package/dist/bundle/cli.js +2 -2
  110. package/dist/bundle/host-supervisor.js +1 -1
  111. package/dist/bundle/index.js +1 -1
  112. package/dist/bundle/rpc-entry.js +1 -1
  113. package/dist/bundle/runtime-manifest.json +1 -1
  114. package/dist/core/agent-session.js +5 -3
  115. package/dist/core/auth-storage.d.ts +19 -0
  116. package/dist/core/auth-storage.js +99 -24
  117. package/dist/core/auth-store-load-error.d.ts +29 -0
  118. package/dist/core/auth-store-load-error.js +74 -0
  119. package/dist/core/brand.d.ts +2 -0
  120. package/dist/core/brand.js +1 -0
  121. package/dist/core/credential-pool/failover.d.ts +8 -0
  122. package/dist/core/credential-pool/failover.js +18 -5
  123. package/dist/core/credential-pool/rotation-stream.d.ts +1 -1
  124. package/dist/core/credential-pool/rotation-stream.js +2 -7
  125. package/dist/core/credential-pool/session-slot.d.ts +20 -0
  126. package/dist/core/credential-pool/session-slot.js +26 -0
  127. package/dist/core/credential-recovery-revision.d.ts +10 -0
  128. package/dist/core/credential-recovery-revision.js +19 -0
  129. package/dist/core/execution/executor-body.d.ts +22 -0
  130. package/dist/core/execution/executor-body.js +73 -0
  131. package/dist/core/execution/executor-freeze.d.ts +17 -0
  132. package/dist/core/execution/executor-freeze.js +53 -0
  133. package/dist/core/execution/executor-pipeline.d.ts +9 -0
  134. package/dist/core/execution/executor-pipeline.js +25 -0
  135. package/dist/core/execution/executor-types.d.ts +82 -0
  136. package/dist/core/execution/executor-types.js +2 -0
  137. package/dist/core/execution/executor.d.ts +8 -0
  138. package/dist/core/execution/executor.js +216 -0
  139. package/dist/core/extensions/builtin/anthropic-subscription/account-block-log.d.ts +15 -0
  140. package/dist/core/extensions/builtin/anthropic-subscription/account-block-log.js +18 -0
  141. package/dist/core/extensions/builtin/anthropic-subscription/affinity.d.ts +9 -1
  142. package/dist/core/extensions/builtin/anthropic-subscription/affinity.js +15 -4
  143. package/dist/core/extensions/builtin/anthropic-subscription/failover.d.ts +7 -1
  144. package/dist/core/extensions/builtin/anthropic-subscription/failover.js +19 -2
  145. package/dist/core/extensions/builtin/anthropic-subscription/guidance.d.ts +8 -2
  146. package/dist/core/extensions/builtin/anthropic-subscription/guidance.js +25 -1
  147. package/dist/core/extensions/builtin/anthropic-subscription/provider-diagnostic.d.ts +9 -0
  148. package/dist/core/extensions/builtin/anthropic-subscription/provider-diagnostic.js +59 -0
  149. package/dist/core/extensions/builtin/anthropic-subscription/session-registry-wiring.js +7 -0
  150. package/dist/core/extensions/builtin/anthropic-subscription/stream-guidance.js +5 -3
  151. package/dist/core/extensions/builtin/anthropic-subscription/stream.js +4 -0
  152. package/dist/core/extensions/builtin/btw/index.js +3 -1
  153. package/dist/core/extensions/builtin/cache-keepalive/index.js +3 -1
  154. package/dist/core/extensions/builtin/compaction/index.js +1 -1
  155. package/dist/core/extensions/builtin/compaction/openai-remote.d.ts +3 -1
  156. package/dist/core/extensions/builtin/compaction/openai-remote.js +1 -1
  157. package/dist/core/extensions/builtin/compaction/speculative.js +3 -2
  158. package/dist/core/extensions/builtin/cursor-cli-oauth/account-command.js +3 -1
  159. package/dist/core/extensions/builtin/cursor-cli-oauth/native-bootstrap.js +3 -1
  160. package/dist/core/extensions/builtin/look-at/runner.js +3 -1
  161. package/dist/core/extensions/builtin/mcp/auth/callback.js +3 -4
  162. package/dist/core/extensions/builtin/mcp/auth/oauth-provider.js +2 -1
  163. package/dist/core/model-registry.d.ts +10 -2
  164. package/dist/core/model-registry.js +12 -4
  165. package/dist/core/model-runtime.d.ts +8 -0
  166. package/dist/core/model-runtime.js +38 -0
  167. package/dist/core/retry-fallback/controller-types.d.ts +7 -0
  168. package/dist/core/retry-fallback/controller.d.ts +2 -0
  169. package/dist/core/retry-fallback/controller.js +13 -4
  170. package/dist/core/retry-fallback/credential-recovery.d.ts +18 -0
  171. package/dist/core/retry-fallback/credential-recovery.js +32 -0
  172. package/dist/core/retry-fallback/settings.d.ts +8 -1
  173. package/dist/core/retry-fallback/settings.js +12 -6
  174. package/dist/core/session-log.js +1 -1
  175. package/dist/core/settings-manager.js +4 -1
  176. package/dist/modes/rpc/connection-handler.js +3 -1
  177. package/dist/modes/rpc/effect-commands.d.ts +1 -0
  178. package/dist/modes/rpc/loopless-execute-grant.d.ts +20 -0
  179. package/dist/modes/rpc/loopless-execute-grant.js +26 -0
  180. package/dist/modes/rpc/loopless-runtime-settings.d.ts +30 -0
  181. package/dist/modes/rpc/loopless-runtime-settings.js +69 -0
  182. package/dist/modes/rpc/loopless-tool-call.d.ts +12 -0
  183. package/dist/modes/rpc/loopless-tool-call.js +22 -0
  184. package/dist/modes/rpc/rpc-read-response-types.d.ts +2 -1
  185. package/dist/modes/rpc/rpc-session-state-types.d.ts +10 -0
  186. package/dist/modes/rpc/rpc-types.d.ts +1 -1
  187. package/dist/modes/rpc/runtime-factory-loopless.d.ts +57 -0
  188. package/dist/modes/rpc/runtime-factory-loopless.js +131 -0
  189. package/docs/development.md +1 -1
  190. package/docs/rpc.md +2 -0
  191. package/package.json +6 -6
  192. package/dist/bundle/chunks/anthropic-messages-AFWQB3KN.js +0 -10
  193. package/dist/bundle/chunks/chunk-3WJ2DE2G.js +0 -3
  194. package/dist/bundle/chunks/chunk-ESQBKTNG.js +0 -2
  195. package/dist/bundle/chunks/chunk-MOH5HOHX.js +0 -2
  196. package/dist/bundle/chunks/credential-accounts-YZYSKA7X.js +0 -2
  197. package/dist/bundle/chunks/host-command-PZ4VYQIW.js +0 -2
  198. package/dist/bundle/chunks/interactive-mode-7JSJVVIS.js +0 -2
  199. package/dist/bundle/chunks/main-3YGJ2O4I.js +0 -2
  200. package/dist/bundle/chunks/rotation-stream-WXWJKJZN.js +0 -2
  201. package/dist/bundle/chunks/rpc-mode-Z7MN2ZWA.js +0 -2
@@ -1,5 +1,5 @@
1
1
  import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url); { const __piWorkerThreads = require("node:worker_threads"); if (typeof __piWorkerThreads.markAsUncloneable !== "function") { __piWorkerThreads.markAsUncloneable = () => {}; } }
2
- import{CompactSelection,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,McpPresenterAuthority,SocketPeerRecovery,attachMcpGrantPresentation,correlatedRecord,declarationReply,effectStatusRecord,isCorrelatedReply,observeLifecycleDelivery,sessionQuestionBridges}from"./chunk-5DZD623T.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-VRKA3LIT.js";import{bindPrivateMcpForms}from"./chunk-7ICGN62G.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-XLLQJALL.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-VPDQ6MOL.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,hostGeneration,hostInstanceId}from"./chunk-F4OHTL2K.js";import{LegacyRecordDepthError,serializeJsonLine}from"./chunk-H52J72VA.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{acquireOwnershipSafeLock}from"./chunk-QEESHRTS.js";import{getAgentDir}from"./chunk-ISZ4EWIS.js";import{processIsLive,processStartTimeMs,readProcessIdentity}from"./chunk-O5RYI3IW.js";import{randomUUID as randomUUID4}from"node:crypto";import{tmpdir}from"node:os";import{join as join5}from"node:path";var CompactReadError=class extends Error{constructor(reason){super(`compact read refused (${reason})`),this.name="CompactReadError",this.reason=reason}},CompactReadLease=class{constructor(dispose,valid=()=>{}){this.released=!1,this.operations=0,this.dispose=dispose,this.valid=valid}assert(){if(this.released)throw new CompactReadError("released");this.valid()}async run(read){return this.assert(),this.hold(async()=>{let result=await read();return this.assert(),result})}async hold(read){if(this.released)throw new CompactReadError("released");this.operations++;try{return await read()}finally{--this.operations===0&&this.released&&this.dispose()}}retain(){if(this.released)throw new CompactReadError("released");this.operations++;let ended=!1;return()=>{ended||(ended=!0,--this.operations===0&&this.released&&this.dispose())}}release(){return this.released?!1:(this.released=!0,this.operations===0&&this.dispose(),!0)}};import{dirname as dirname2,join as join4}from"node:path";import{open as open4,rm as rm3}from"node:fs/promises";import{randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";import{constants as constants2}from"node:fs";import{lstat as lstat2,mkdir,open as open2,rename,rm}from"node:fs/promises";import{join as join2}from"node:path";import{execFile}from"node:child_process";import{constants}from"node:fs";import{lstat,open,readFile}from"node:fs/promises";import{join}from"node:path";import{promisify}from"node:util";var ROOT_MARKER=".compact-spool-owner",Owner=external_exports.object({bootNonce:external_exports.string().min(1),pid:external_exports.number().int().positive(),startTime:external_exports.string().min(1).refine(value=>processStartTimeMs(value)!==void 0)}),Marker=external_exports.object({kind:external_exports.enum(["scratch","live"]),token:external_exports.string().min(1),owner:Owner.nullable()}),boot,self;function bootNonce(){return boot??=(async()=>{switch(process.platform){case"darwin":return(await promisify(execFile)("/usr/sbin/sysctl",["-n","kern.bootsessionuuid"],{timeout:2e3})).stdout.trim()||null;case"linux":return(await readFile("/proc/sys/kernel/random/boot_id","utf8")).trim()||null;default:return null}})().catch(cause=>{if(cause instanceof Error)return null;throw cause}),boot}function currentRootOwner(){return self??=(async()=>{let bootNonceValue=await bootNonce();if(!bootNonceValue)return null;let start=await rootProcessIdentity(process.pid);return start.kind==="present"?{bootNonce:bootNonceValue,pid:process.pid,startTime:start.identity}:null})(),self}async function rootProcessIdentity(pid){try{return await readProcessIdentity(pid,process.platform,2e3,processIsLive,"UTC")}catch(cause){if(cause instanceof Error&&"syscall"in cause&&typeof cause.syscall=="string"&&/^spawn(?: |$)/.test(cause.syscall))return{kind:"error",error:cause};throw cause}}async function rootOwnerState(owner){let currentBoot=await bootNonce();if(!owner||!currentBoot)return"unknown";if(owner.bootNonce!==currentBoot)return"dead";let start=await rootProcessIdentity(owner.pid);switch(start.kind){case"absent":return processIsLive(owner.pid)?"unknown":"dead";case"present":return start.identity===owner.startTime?"alive":"dead";case"error":return"unknown"}}function privateRootStat(stat){return stat.isDirectory()&&!stat.isSymbolicLink()&&(process.getuid===void 0||stat.uid===process.getuid()&&(stat.mode&63)===0)}async function readRootMarker(dir){try{let path=join(dir,ROOT_MARKER),entry=await lstat(path);if(!entry.isFile()||entry.isSymbolicLink())return;let handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>8192||process.getuid!==void 0&&(stat.uid!==process.getuid()||(stat.mode&63)!==0))return;let parsed=Marker.safeParse(JSON.parse(await handle.readFile("utf8")));return parsed.success?parsed.data:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error)return;throw cause}}var recoveryAgentDir=getAgentDir(),RecoveryStorageHealth=class{constructor(base){this.failures=0,this.cleared=0,this.dir=join2(base,`.senpi-recovery-health-${process.getuid?.()??"user"}`)}ensureDir(){return this.setup??=(async()=>{if(await mkdir(this.dir,{mode:448,recursive:!0}),!privateRootStat(await lstat2(this.dir)))throw new CompactReadError("ownership")})().catch(cause=>{throw this.setup=void 0,cause}),this.setup}get needsRecovery(){return this.failures>this.cleared}unavailable(){this.failures+=1}async revision(){return await this.ensureDir(),await this.readRevision()??this.advance()}async readRevision(){try{let handle=await open2(join2(this.dir,"revision"),constants2.O_RDONLY|(constants2.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>128)return;let text=(await handle.readFile("utf8")).trim();return/^(0|[1-9]\d*)$/.test(text)?text:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return"0";if(cause instanceof Error&&"code"in cause&&cause.code==="ELOOP")return;throw cause}}async recover(operation){await this.ensureDir();let through=this.failures;if(await operation(),through<=this.cleared)return this.revision();if(this.pending&&await this.pending,through<=this.cleared)return this.revision();this.pending=this.advance().then(revision=>(this.cleared=through,revision));try{return await this.pending}finally{this.pending=void 0}}async advance(){await this.ensureDir();let release=await acquireOwnershipSafeLock(join2(this.dir,"revision.lock")),temporary=join2(this.dir,`${randomUUID()}.tmp`);try{let next=String(BigInt(await this.readRevision()??"0")+1n),file=await open2(temporary,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL|(constants2.O_NOFOLLOW??0),384);try{await file.writeFile(next),await file.sync()}finally{await file.close()}await rename(temporary,join2(this.dir,"revision"));let directory=await open2(this.dir,"r");try{await directory.sync()}finally{await directory.close()}return next}finally{try{await rm(temporary,{force:!0})}finally{await release()}}}};import{randomUUID as randomUUID2}from"node:crypto";import{lstat as lstat3,mkdir as mkdir2,rename as rename2,rm as rm2,rmdir,writeFile as writeFile2}from"node:fs/promises";import{dirname,join as join3}from"node:path";import{open as open3,readFile as readFile2,unlink,writeFile}from"node:fs/promises";var nodeCompactStorageIo={writeFile:(path,data)=>writeFile(path,data,{flag:"wx",mode:384}),readFile:async(path,range)=>{if(!range)return readFile2(path);let handle=await open3(path,"r");try{let{buffer,bytesRead}=await handle.read(Buffer.alloc(range.length),0,range.length,range.offset);return buffer.subarray(0,bytesRead)}finally{await handle.close()}},unlink:path=>unlink(path)};function describeCause(cause){try{return cause instanceof Error?cause.message:String(cause)}catch{return"unprintable failure cause"}}var CompactStorageReadError=class extends Error{constructor(operation,path,cause){super(`compact storage ${operation} failed for ${path}: ${describeCause(cause)}`,{cause}),this.name="CompactStorageReadError",this.operation=operation,this.path=path}};var MARKER=ROOT_MARKER,CompactSpoolRefusedError=class extends Error{constructor(reason,path,cause,cleanupFailure){let detail=cause===void 0?"":`: ${describeCause(cause)}`,kept=cleanupFailure===void 0?"":`; removing the directory failed: ${describeCause(cleanupFailure)}`;super(`compact spool directory refused (${reason}): ${path}${detail}${kept}`,{cause}),this.name="CompactSpoolRefusedError",this.reason=reason,this.path=path}};async function createSpoolDir(dir){await mkdir2(dirname(dir),{recursive:!0,mode:448});try{await mkdir2(dir,{mode:448})}catch(cause){throw cause.code==="EEXIST"?new CompactSpoolRefusedError("pre_existing",dir):cause}let token=randomUUID2(),temporary=join3(dir,`${MARKER}.${token}.tmp`);try{await writeFile2(temporary,JSON.stringify({kind:"scratch",token,owner:await currentRootOwner()}),{flag:"wx",mode:384}),await rename2(temporary,join3(dir,MARKER))}catch(cause){throw await abandonSpoolDir(dir,cause,temporary)}return token}async function abandonSpoolDir(dir,cause,temporary){try{return await rm2(temporary,{force:!0}),cause.code!=="EEXIST"&&await rm2(join3(dir,MARKER),{force:!0}),await rmdir(dir),new CompactSpoolRefusedError("marker_write_failed",dir,cause)}catch(cleanupFailure){return new CompactSpoolRefusedError("marker_write_failed",dir,cause,cleanupFailure)}}async function removeSpoolDir(dir,token){let owned=await lstat3(dir).catch(cause=>{if(cause.code!=="ENOENT")throw cause});if(owned===void 0)return;let refusal3=await refusalFor(dir,owned,token);if(refusal3)throw new CompactSpoolRefusedError(refusal3,dir);await rm2(dir,{recursive:!0,force:!0})}async function refusalFor(dir,owned,token){if(owned.isSymbolicLink())return"symlink";if(!owned.isDirectory())return"not_directory";let markerPath=join3(dir,MARKER),marker=await lstat3(markerPath).catch(()=>{});if(!marker?.isFile()||(await readRootMarker(dir))?.token!==token)return"marker_missing";let uid=process.getuid?.();if(uid!==void 0){if(owned.uid!==uid||marker.uid!==uid)return"foreign_owner";if(((owned.mode|marker.mode)&63)!==0)return"wide_mode"}}var RECLAIM_WORK_ALLOWANCE_BYTES=1024*1024,RECLAIM_RETRY_DELAYS_MS=[100,400,1600,6400,25600],FAILURE_HISTORY=32,FILE_PREFIX={spill_write:"leaf",value_write:"value",node_write:"node"},HALTING=new Set(["spill_write","value_write","node_write","spool_create"]),CompactSpoolStorage=class{assertReadable(){if(this.retired)throw new CompactReadError("retired")}beginRead(){this.assertReadable(),this.reads++,this.reading??=Promise.withResolvers();let done=!1;return()=>{done||(done=!0,--this.reads===0&&(this.reading?.resolve(),this.reading=void 0))}}constructor(dir,io,health=new RecoveryStorageHealth(recoveryAgentDir)){this.failures=[],this.nextFile=1,this.chain=Promise.resolve(),this.queued=0,this.spillQueued=!1,this.halted=!1,this.retired=!1,this.pendingIoCopyBytes=0,this.spillBytesWritten=0,this.reclaimDebtBytes=0,this.reads=0,this.dir=dir,this.io=io,this.health=health}async repair(){let revision=await this.health.recover(async()=>{let path=join4(dirname2(this.dir),`.senpi-repair-${randomUUID3()}`);try{let file=await open4(path,"wx",384);try{await file.writeFile("repair"),await file.sync()}finally{await file.close()}}finally{await rm3(path,{force:!0})}});return this.halted=!1,this.spoolToken===void 0&&(this.dirReady=void 0),this.scheduleSpill(),await this.idle(),revision}async idle(){for(;this.queued>0;)await this.chain}async retire(){this.retired=!0,await this.reading?.promise,await this.idle();let token=this.spoolToken;if(token!==void 0){try{await removeSpoolDir(this.dir,token)}catch(cause){throw this.fail("reclaim",this.dir,cause,0),cause}this.spoolToken=void 0,this.reclaimDebtBytes=0}}async readFile(path,bytes,operation,range){let done=this.beginRead();try{let result=await this.readCommittedFile(path,bytes,operation,range);return this.assertReadable(),result}finally{done()}}async readCommittedFile(path,bytes,operation,range){let data;try{data=await this.io.readFile(path,range)}catch(cause){throw this.readFailure(operation,path,cause)}if(data.byteLength!==bytes)throw this.readFailure(operation,path,new Error(`expected ${bytes} bytes, found ${data.byteLength}`));return data}async writeFile(data,operation,retainedInMemoryBytes){let path=await this.ensureDir(retainedInMemoryBytes);if(path===void 0)return;let file=join4(path,`${FILE_PREFIX[operation]??"page"}-${this.nextFile++}.bin`);this.pendingIoCopyBytes+=data.byteLength;try{return this.health.needsRecovery?await this.health.recover(()=>this.io.writeFile(file,data)):await this.io.writeFile(file,data),this.spillBytesWritten+=data.byteLength,file}catch(cause){try{this.fail(operation,file,cause,retainedInMemoryBytes)}finally{this.discard(file,data.byteLength)}return}finally{this.pendingIoCopyBytes-=data.byteLength}}discard(path,bytes){this.retired||(this.reclaimDebtBytes+=bytes,this.enqueue("reclaim",()=>this.reclaim(path,bytes,0)))}async reclaim(path,bytes,attempt){try{await this.io.unlink(path)}catch(cause){if(cause.code!=="ENOENT"){this.fail("reclaim",path,cause,0);let delay=RECLAIM_RETRY_DELAYS_MS[attempt];delay!==void 0&&setTimeout(()=>{this.retired||this.enqueue("reclaim",()=>this.reclaim(path,bytes,attempt+1))},delay).unref?.();return}}this.reclaimDebtBytes-=bytes,this.scheduleSpill()}get spillAllowed(){return!this.halted&&!this.retired}get spillStopped(){return this.halted||this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES}enqueue(operation,job){this.queued++,this.chain=this.chain.then(job).catch(cause=>{operation==="spill_write"&&(this.spillQueued=!1),!(this.retired&&cause instanceof CompactReadError&&cause.reason==="retired")&&this.fail(operation,this.dir,cause,0)}).finally(()=>{this.queued--})}ensureDir(retained){return this.dirReady??=createSpoolDir(this.dir).then(token=>(this.spoolToken=token,this.dir),cause=>{this.fail("spool_create",this.dir,cause,retained)}),this.dirReady}readFailure(operation,path,cause){return this.fail(operation,path,cause,0),new CompactStorageReadError(operation,path,cause)}fail(operation,path,cause,retained){(HALTING.has(operation)||operation==="page_write")&&this.health.unavailable(),HALTING.has(operation)&&(this.halted=!0),this.record({operation,path,cause:describeCause(cause),retainedInMemoryBytes:retained})}record(failure){this.failures.push(failure),this.failures.length>FAILURE_HISTORY&&this.failures.shift()}};var COMPACT_SEGMENT_BYTES=65536,CompactSegmentStorage=class extends CompactSpoolStorage{async writeSegment(texts,operation){let data=Buffer.from(texts.join(""),"utf16le"),path=await this.writeFile(data,operation,data.byteLength);if(path!==void 0)return{path,bytes:data.byteLength,operation,live:new Map,liveBytes:0,readers:0,rewritten:!1}}segmentRuns(entries){let runs=[],bytes=0;for(let[entry,size]of entries){let run=runs.at(-1);run&&bytes+size<=COMPACT_SEGMENT_BYTES?(run.push(entry),bytes+=size):(runs.push([entry]),bytes=size)}return runs}async writeSegments(texts,operation){let placements=[],written=[],complete=!1;try{for(let run of this.segmentRuns(texts.map((text,n)=>[n,text.length*2]))){let segment=await this.writeSegment(run.map(n=>texts[n]),operation);if(!segment)return;written.push(segment);let offset=0;for(let n of run)placements[n]=[segment,offset],offset+=texts[n].length*2}return complete=!0,placements}finally{if(!complete)for(let stray of written)this.discard(stray.path,stray.bytes)}}place(segment,id,offset,bytes){let slot={segment,offset,bytes};return segment.live.set(id,slot),segment.liveBytes+=bytes,slot}leave(id,slot){let segment=slot.segment;segment.live.delete(id),segment.liveBytes-=slot.bytes,this.settle(segment)}async readSlot(slot){let{segment,offset,bytes}=slot;segment.readers++;try{return await this.readFile(segment.path,bytes,"leaf_read",{offset,length:bytes})}finally{segment.readers--,this.settle(segment)}}settle(segment){segment.live.size?!segment.rewritten&&segment.liveBytes*2<segment.bytes&&(segment.rewritten=!0,this.enqueue("reclaim",()=>this.rewrite(segment))):segment.readers||this.discard(segment.path,segment.bytes)}async rewrite(segment){if(!this.spillAllowed||!segment.live.size)return;segment.readers++;let next,copied=0;try{let moving=[...segment.live].sort(([,a],[,b])=>a.offset-b.offset),texts=[];for(let n=0;n<moving.length;){let start=moving[n][1].offset,end=start,run=[];for(;n<moving.length&&moving[n][1].offset===end;n++)run.push(moving[n][1]),end+=moving[n][1].bytes;let data=await this.readFile(segment.path,end-start,"leaf_read",{offset:start,length:end-start});this.pendingIoCopyBytes+=data.byteLength,copied+=data.byteLength;for(let slot of run)texts.push(data.toString("utf16le",slot.offset-start,slot.offset-start+slot.bytes))}next=await this.writeSegment(texts,segment.operation);let offset=0;for(let[id,slot]of moving)next&&segment.live.delete(id)&&(segment.liveBytes-=slot.bytes,next.live.set(id,slot),next.liveBytes+=slot.bytes,slot.segment=next,slot.offset=offset),offset+=slot.bytes}catch(error){if(!(error instanceof CompactReadError&&error.reason==="retired"))throw error}finally{this.pendingIoCopyBytes-=copied,segment.readers--,this.settle(segment),next&&this.settle(next)}}};var CompactCommitDependencies=class{constructor(store,ready){this.pending=new Map,this.dependants=new Map,this.store=store,store.subscribeCommitted(id=>{let keys=this.dependants.get(id);this.dependants.delete(id);for(let key of keys??[]){let pending=this.pending.get(key);pending?.delete(id),pending?.size===0&&(this.pending.delete(key),ready(key))}})}get size(){return this.pending.size}has(key){return this.pending.has(key)}set(key,refs){this.delete(key);let pending=new Set(refs.filter(id=>!this.store.isCommitted(id)));if(pending.size!==0){this.pending.set(key,pending);for(let id of pending){let keys=this.dependants.get(id)??new Set;keys.add(key),this.dependants.set(id,keys)}}}delete(key){for(let id of this.pending.get(key)??[]){let keys=this.dependants.get(id);keys?.delete(key),keys?.size===0&&this.dependants.delete(id)}this.pending.delete(key)}};var CompactTextRoots=class{constructor(store){this.nodes=new Map,this.next=-1,this.store=store,this.pending=new CompactCommitDependencies(store,id=>store.committed(id))}get residentNodes(){return this.nodes.size}own(refs){if(refs.length===0)return 0;if(refs.length===1){let[ref]=refs;return this.store.adjust(ref,1,0),ref}let middle=Math.floor(refs.length/2),left=this.own(refs.slice(0,middle)),right=this.own(refs.slice(middle));if(left===0)return right;if(right===0)return left;let root=this.join(left,right);return this.store.adjust(left,-1,0),this.store.adjust(right,-1,0),root}units(id){return id===0?0:id>0?this.store.leafUnits(id):this.node(id).units}isCommitted(id){return this.nodes.has(id)&&!this.pending.has(id)}append(root,text,structured=!1){this.units(root);let leaf2=this.store.createLeaf(text,structured);if(root===0)return leaf2;let result=this.appendLeaf(root,leaf2);return this.store.adjust(root,-1,0),this.store.adjust(leaf2,-1,0),result}adjust(id,live,pins){let work=[[id,live,pins]];for(let next=work.pop();next;next=work.pop()){let[id2,live2,pins2]=next;if(id2>=0){this.store.adjust(id2,live2,pins2);continue}let node=this.node(id2),beforeLive=+(node.live>0),beforePin=+(node.live===0&&node.pins>0);if(node.live+live2<0||node.pins+pins2<0)throw new CompactReadError("ownership");node.live+=live2,node.pins+=pins2;let liveChange=+(node.live>0)-beforeLive,pinChange=+(node.live===0&&node.pins>0)-beforePin;(liveChange||pinChange)&&work.push([node.right,liveChange,pinChange],[node.left,liveChange,pinChange]),node.live===0&&node.pins===0&&(this.pending.delete(id2),this.nodes.delete(id2))}}async read(root,tail,offset,units,maxLeaves=2,valid=()=>this.store.assertReadable()){this.store.assertReadable(),valid();let length=this.units(root);if(!Number.isSafeInteger(offset)||!Number.isSafeInteger(units)||offset<0||units<0||offset+units>length+tail.length)throw new CompactReadError("range");if(units>COMPACT_LEAF_CODE_UNITS)throw new CompactReadError("size_limit");if(!Number.isSafeInteger(maxLeaves)||maxLeaves<1||maxLeaves>2)throw new CompactReadError("count_limit");let selected=[],visit=(id,start,end)=>{if(!(start>=end||id===0))if(id>0){if(selected.length===maxLeaves)throw new CompactReadError("count_limit");selected.push({id,offset:start,units:end-start})}else{let node=this.node(id),leftUnits=this.units(node.left);visit(node.left,start,Math.min(end,leftUnits)),visit(node.right,Math.max(0,start-leftUnits),end-leftUnits)}};visit(root,offset,Math.min(length,offset+units));let tailUnits=units===0?0:Math.max(0,offset+units-Math.max(offset,length));if(selected.length+ +(tailUnits>0)>maxLeaves)throw new CompactReadError("count_limit");this.store.adjust(root,0,1);let done=this.store.beginRead();try{let result="";for(let part of selected){let text=await this.store.readLeaf(part.id);valid(),result+=text.slice(part.offset,part.offset+part.units)}return valid(),result+tail.slice(Math.max(0,offset-length),Math.max(0,offset-length)+tailUnits)}finally{this.store.adjust(root,0,-1),done()}}node(id){let node=this.nodes.get(id);if(!node)throw new CompactReadError("ownership");return node}async*chunks(root,valid){if(valid(),root!==0)if(root>0){let text=await this.read(root,"",0,this.units(root),1,valid);valid(),yield text}else{let node=this.node(root);yield*this.chunks(node.left,valid),yield*this.chunks(node.right,valid)}}appendLeaf(root,leaf2){let node=this.nodes.get(root);if(!node||node.full)return this.join(root,leaf2);let right=this.appendLeaf(node.right,leaf2),result=this.join(node.left,right);return this.store.adjust(right,-1,0),result}height(id){return id>0?0:this.node(id).height}join(left,right){let id=this.next--;return this.nodes.set(id,{left,right,units:this.units(left)+this.units(right),height:1+Math.max(this.height(left),this.height(right)),full:this.height(left)===this.height(right)&&(this.nodes.get(left)?.full??!0)&&(this.nodes.get(right)?.full??!0),live:1,pins:0}),this.store.adjust(left,1,0),this.store.adjust(right,1,0),this.pending.set(id,[left,right]),id}};var COMPACT_LEAF_CODE_UNITS=32768,VALUE_FLUSH_BATCH=128,CompactWriteError=class extends Error{constructor(reason,limit){super(`compact write refused (${reason}${limit===void 0?"":`: depth above ${limit}`})`),this.name="CompactWriteError",this.reason=reason,this.limit=limit}},CompactContentStore=class extends CompactSegmentStorage{subscribeCommitted(listener){this.subscribers.add(listener)}committed(id){for(let listener of this.subscribers)listener(id)}leafUnits(id){let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.units}constructor(options){super(options.dir,options.io??nodeCompactStorageIo,options.health),this.leaves=new Map,this.ramLeaves=new Set,this.ramValues=new Set,this.valueQueued=!1,this.structuredBytes={resident:0,spilled:0,pinned:0},this.nextLeafId=1,this.residentPayloadBytes=0,this.pinnedOnlyBytes=0,this.spilledLiveBytes=0,this.subscribers=new Set,this.text=new CompactTextRoots(this),this.spillAboveBytes=options.spillAboveBytes??4*1024*1024,this.spillTargetBytes=options.spillTargetBytes??2*1024*1024}createLeaf(text,value=!1){if(this.assertReadable(),text.length>COMPACT_LEAF_CODE_UNITS)throw new CompactWriteError("size_limit");let id=this.nextLeafId++;return this.leaves.set(id,{text,units:text.length,value,live:1,pins:0,state:"ram"}),(value?this.ramValues:this.ramLeaves).add(id),value?this.structuredBytes.resident+=text.length*2:this.residentPayloadBytes+=text.length*2,this.scheduleSpill(),id}ownFile(path,bytes){let id=this.createLeaf("",!0),leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.file={path,bytes},id}adjust(id,live,pins){if(id===0)return;if(id<0)return this.text.adjust(id,live,pins);let leaf2=this.leaves.get(id);if(!leaf2||leaf2.live+live<0||leaf2.pins+pins<0)throw new CompactReadError("ownership");let pinnedOnly=leaf2.live===0&&leaf2.pins>0;if(leaf2.live+=live,leaf2.pins+=pins,pinnedOnly!==(leaf2.live===0&&leaf2.pins>0)){let bytes=(pinnedOnly?-2:2)*leaf2.units;leaf2.value?this.structuredBytes.pinned+=bytes:this.pinnedOnlyBytes+=bytes}if(!(leaf2.live>0||leaf2.pins>0)){if(this.leaves.delete(id),leaf2.file&&this.discard(leaf2.file.path,leaf2.file.bytes),(leaf2.value?this.ramValues:this.ramLeaves).delete(id),leaf2.state==="committed"&&leaf2.slot){leaf2.value?this.structuredBytes.spilled-=leaf2.units*2:this.spilledLiveBytes-=leaf2.units*2,this.leave(id,leaf2.slot);return}leaf2.value?this.structuredBytes.resident-=leaf2.units*2:this.residentPayloadBytes-=leaf2.units*2}}isCommitted(id){return id<=0?id===0||this.text.isCommitted(id):this.leaves.get(id)?.state==="committed"}async readLeaf(id){this.assertReadable();let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");this.adjust(id,0,1);try{if(leaf2.text!==void 0)return leaf2.text;if(!leaf2.slot)throw new CompactReadError("ownership");return(await this.readSlot(leaf2.slot)).toString("utf16le")}finally{this.adjust(id,0,-1)}}status(){return{structuredBytes:{...this.structuredBytes},residentPayloadBytes:this.residentPayloadBytes,pendingIoCopyBytes:this.pendingIoCopyBytes,pinnedOnlyBytes:this.pinnedOnlyBytes,spilledLiveBytes:this.spilledLiveBytes,spillBytesWritten:this.spillBytesWritten,reclaimDebtBytes:this.reclaimDebtBytes,spillFailureRetainedBytes:this.spillStopped?Math.max(0,this.residentPayloadBytes-this.spillTargetBytes):0,spillHalted:this.spillStopped,failures:[...this.failures]}}scheduleSpill(){!this.valueQueued&&this.spillAllowed&&this.ramValues.size&&this.reclaimDebtBytes<=RECLAIM_WORK_ALLOWANCE_BYTES&&(this.valueQueued=!0,this.enqueue("value_write",async()=>{try{await this.flushValues()}finally{this.valueQueued=!1}this.scheduleSpill()})),!(this.spillQueued||!this.spillAllowed||this.residentPayloadBytes<=this.spillAboveBytes)&&(this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES||(this.spillQueued=!0,this.enqueue("spill_write",()=>this.spillNext())))}async spillNext(){let[id]=this.ramLeaves;id!==void 0&&await this.flushLeaf(id),this.spillQueued=!1,this.residentPayloadBytes>this.spillTargetBytes&&(this.spillQueued=this.spillAllowed&&this.ramLeaves.size>0,this.spillQueued&&this.enqueue("spill_write",()=>this.spillNext()))}async flushValues(){if(this.spillStopped)return;let batch=[];for(let id of this.ramValues)if(batch.push([id,this.leafUnits(id)*2]),batch.length===VALUE_FLUSH_BATCH)break;await this.flushLeaves(this.segmentRuns(batch)[0]??[])}flushLeaf(id){return this.flushLeaves([id])}async flushLeaves(ids,operation){if(!this.spillAllowed)return;let batch=[];for(let id of ids){let leaf2=this.leaves.get(id);leaf2?.state!=="ram"||leaf2.text===void 0||(leaf2.state="pending",(leaf2.value?this.ramValues:this.ramLeaves).delete(id),batch.push([id,leaf2,leaf2.text]))}if(!batch.length)return;let placements;try{let texts=batch.map(([,,text])=>text);placements=await this.writeSegments(texts,operation??(batch[0][1].value?"value_write":"spill_write"))}finally{for(let[id,leaf2]of placements?[]:batch)leaf2.state="ram",this.leaves.get(id)===leaf2&&(leaf2.value?this.ramValues:this.ramLeaves).add(id)}if(!placements)return;let placed=[];for(let[n,[id,leaf2]]of batch.entries()){let[segment,offset]=placements[n],bytes=leaf2.units*2;this.leaves.get(id)===leaf2&&!this.retired&&(leaf2.state="committed",leaf2.text=void 0,leaf2.slot=this.place(segment,id,offset,bytes),leaf2.value?(this.structuredBytes.resident-=bytes,this.structuredBytes.spilled+=bytes):(this.residentPayloadBytes-=bytes,this.spilledLiveBytes+=bytes),placed.push(id))}for(let segment of new Set(placements.map(([segment2])=>segment2)))this.settle(segment);for(let id of placed)this.committed(id)}};import{createHash}from"node:crypto";var BOUNDED_ID=/^[A-Za-z0-9][A-Za-z0-9:_-]*$/,CONTENT_DIGEST=/^[0-9a-f]{64}$/,CONTENT_REF=/^c-[0-9]{16}(?::[0-9]{3})*$/,BASE_REF=/^c-[0-9]{16}:base$/,RESERVED_STEP=/:base(?::|$)/,refused=reason=>({ok:!1,reason});function parseBoundedId(value){return value.length===0?refused("empty"):Buffer.byteLength(value)>128?refused("overlong"):BOUNDED_ID.test(value)?{ok:!0,value}:refused("forbidden_character")}function parseContentDigest(value){return value.length===0?refused("empty"):CONTENT_DIGEST.test(value)?{ok:!0,value}:refused("malformed")}function parseContentRef(value){let bounded=parseBoundedId(value);return bounded.ok?RESERVED_STEP.test(value)?refused("reserved"):CONTENT_REF.test(value)?(value.length-18)/4>8?refused("too_deep"):{ok:!0,value}:refused("malformed"):bounded}function parseBaseRef(value){let bounded=parseBoundedId(value);return bounded.ok?BASE_REF.test(value)?{ok:!0,value}:refused("malformed"):bounded}function parsePageRef(value){let base=parseBaseRef(value);if(base.ok)return{ok:!0,value:{kind:"base",ref:base.value}};let content=parseContentRef(value);return content.ok?{ok:!0,value:{kind:"catalog",ref:content.value}}:content}function protocolId(value){let parsed=parseBoundedId(value);if(!parsed.ok)throw new RangeError(`not a bounded protocol id (${parsed.reason}): ${value.length} chars`);return parsed.value}function fixed(value,digits,bound,what){if(!Number.isSafeInteger(value)||value<0||value>=bound)throw new RangeError(`${what} out of range: ${value}`);return String(value).padStart(digits,"0")}function minted(value){let parsed=parseContentRef(value);if(!parsed.ok)throw new RangeError(`catalog ref ${parsed.reason}`);return parsed.value}var catalogRootRef=counter=>minted(`c-${fixed(counter,16,10**16,"catalog counter")}`),childRef=(parent,index)=>minted(`${parent}:${fixed(index,3,128,"catalog child index")}`);function baseRef(root){let parsed=parseBaseRef(`${root}:base`);if(!parsed.ok)throw new RangeError(`base ref ${parsed.reason}`);return parsed.value}var refSteps=ref=>ref.split(":").slice(1).map(Number);var CATALOG_FORMAT="senpi-recovery-catalog",CATALOG_VERSION=1,CATALOG_ENCODING="utf16le",CATALOG_NODE_MAX_UNITS=COMPACT_LEAF_CODE_UNITS,storedBytes=text=>Buffer.from(text,CATALOG_ENCODING);function catalogDigester(domain,length){let tag=Buffer.from(`${CATALOG_FORMAT}/${CATALOG_VERSION}/${CATALOG_ENCODING}/${domain}`,"ascii"),prefix=Buffer.alloc(1+tag.length+8);prefix.writeUInt8(tag.length,0),tag.copy(prefix,1),prefix.writeBigUInt64BE(BigInt(length),1+tag.length);let hash=createHash("sha256").update(prefix),fed=0;return{update:bytes=>{fed+=bytes.length,hash.update(bytes)},finish:()=>{if(fed!==length)throw new RangeError(`catalog digest fed ${fed} of ${length} bytes`);let parsed=parseContentDigest(hash.digest("hex"));if(!parsed.ok)throw new RangeError("sha256 produced a malformed digest");return parsed.value}}}function catalogDigest(domain,bytes){let digester=catalogDigester(domain,bytes.length);return digester.update(bytes),digester.finish()}var HEAD=`{"format":"${CATALOG_FORMAT}","version":${CATALOG_VERSION},"entries":[`,TAIL="]}",encodeEntry=entry=>`{"kind":"${entry.kind}","id":"${entry.id}","length":${entry.length},"digest":"${entry.digest}"}`,CatalogNodeWriter=class{constructor(){this.parts=[],this.units=HEAD.length+TAIL.length}get count(){return this.parts.length}push(entry){if(!Number.isSafeInteger(entry.length)||entry.length<0)throw new RangeError("catalog entry length");let part=encodeEntry(entry),units=this.units+part.length+ +(this.parts.length>0);return this.parts.length===128||units>CATALOG_NODE_MAX_UNITS?!1:(this.parts.push(part),this.units=units,!0)}encode(){return`${HEAD}${this.parts.join(",")}${TAIL}`}},CatalogNodeSchema=external_exports.object({format:external_exports.literal(CATALOG_FORMAT),version:external_exports.literal(CATALOG_VERSION),entries:external_exports.array(external_exports.object({kind:external_exports.string(),id:external_exports.string(),length:external_exports.number().int().nonnegative(),digest:external_exports.string()}).strict()).max(128)}).strict();function decodeCatalogNode(text){let json;try{json=JSON.parse(text)}catch(cause){if(cause instanceof SyntaxError)return{ok:!1,reason:"schema"};throw cause}let parsed=CatalogNodeSchema.safeParse(json);if(!parsed.success)return{ok:!1,reason:"schema"};let entries=[];for(let raw of parsed.data.entries){let kind=parseBoundedId(raw.kind),id=parseBoundedId(raw.id),digest2=parseContentDigest(raw.digest);if(!kind.ok||!id.ok||!digest2.ok)return{ok:!1,reason:"schema"};entries.push({kind:kind.value,id:id.value,length:raw.length,digest:digest2.value})}return{ok:!0,entries}}var FRAGMENT_MAX_BYTES=131072,FRAGMENT_ENVELOPE_MAX_BYTES=Math.ceil(FRAGMENT_MAX_BYTES/3)*4,isIndex=value=>Number.isSafeInteger(value)&&value>=0;function assertRange(offset,length,total){if(!isIndex(offset)||!isIndex(length))throw new CompactReadError("range");if(length>FRAGMENT_MAX_BYTES)throw new CompactReadError("size_limit");if(offset+length>total)throw new CompactReadError("range")}function startAtOrBefore(starts,count,offset){let low=0,high=count-1;for(;low<high;){let middle=low+high+1>>1;(starts[middle]??Number.POSITIVE_INFINITY)<=offset?low=middle:high=middle-1}return low}var FrozenLeafBytes=class{constructor(digest2,leaves,starts,read){this.peakResidentLeaves=0,this.resident=0,this.length=starts[leaves.length]??0,this.digest=digest2,this.leaves=leaves,this.starts=starts,this.read=read}async range(offset,length,valid){assertRange(offset,length,this.length);let out=Buffer.allocUnsafe(length),written=0;for(let index=startAtOrBefore(this.starts,this.leaves.length,offset);written<length;index++){let leaf2=this.leaves[index],start=this.starts[index];if(leaf2===void 0||start===void 0)throw new CompactReadError("integrity");this.peakResidentLeaves=Math.max(this.peakResidentLeaves,++this.resident);try{let stored=storedBytes(await this.read(leaf2));valid?.();let from=Math.max(0,offset-start);written+=stored.copy(out,written,from,Math.min(stored.length,from+length-written))}finally{this.resident-=1}}return out}};async function openFrozenBytes(entry,leaves,read,valid,signal){let digester=catalogDigester("leaf",entry.length),starts=[0],fed=0;for(let leaf2 of leaves){if(signal?.aborted)throw new CompactReadError("aborted");let stored=storedBytes(await read(leaf2));if(valid(),fed+=stored.length,fed>entry.length)throw new CompactReadError("integrity");digester.update(stored),starts.push(fed)}if(fed!==entry.length||digester.finish()!==entry.digest)throw new CompactReadError("integrity");return new FrozenLeafBytes(entry.digest,leaves,starts,read)}async function producePage(bytes,offset,valid){if(!isIndex(offset)||offset>=bytes.length&&bytes.length>0)throw new CompactReadError("range");let length=Math.min(FRAGMENT_MAX_BYTES,bytes.length-offset),page=await bytes.range(offset,length,valid),next=offset+length;return{offset,length,bytes:page,digest:catalogDigest("fragment",page),next:next<bytes.length?next:null,complete:next===bytes.length}}var SKIPPED=new Set(["undefined","function","symbol"]),isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var TRANSFER_STAGING_MAX_BYTES=64*1024*1024,FRAGMENT_MAX_UNITS=FRAGMENT_MAX_BYTES/2,TransferStagingError=class extends Error{constructor(reason){super(`transfer staging refused (${reason})`),this.name="TransferStagingError",this.reason=reason}},StagedReadError=class extends Error{constructor(reason,options){super(`staged read refused (${reason})`,options),this.name="StagedReadError",this.reason=reason}},StagedTransfer=class{constructor(store,entry,settle){this.leaves=[],this.leafDigests=[],this.fed=0,this.open=!0,this.store=store,this.entry=entry,this.settle=settle,this.digester=catalogDigester("leaf",entry.length)}append(text){this.assertOpen();let bytes=text.length*2;bytes>FRAGMENT_MAX_BYTES&&this.refuse("fragment_over_limit"),this.fed+bytes>this.entry.length&&this.refuse("length_mismatch");try{for(let at=0;at<text.length;at+=COMPACT_LEAF_CODE_UNITS){let piece=text.slice(at,at+COMPACT_LEAF_CODE_UNITS);this.leaves.push(this.store.createLeaf(piece)),this.leafDigests.push(catalogDigest("leaf",storedBytes(piece)))}}catch(cause){throw this.abort(),cause}this.digester.update(storedBytes(text)),this.fed+=bytes}commit(){this.assertOpen(),this.fed!==this.entry.length&&this.refuse("length_mismatch"),this.open=!1;let content={ref:{variant:"staged",entry:{...this.entry,digest:this.digester.finish()}},leaves:[...this.leaves],leafDigests:[...this.leafDigests]};return this.settle(content),content}abort(){if(this.open){this.open=!1;for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);this.settle(void 0)}}assertOpen(){if(!this.open)throw new TransferStagingError("staging_closed")}refuse(reason){throw this.abort(),new TransferStagingError(reason)}},TransferStaging=class{constructor(store,maxBytes=TRANSFER_STAGING_MAX_BYTES){this.transfers=new Set,this.staged=new Map,this.reserved=0,this.closed=!1,this.store=store,this.maxBytes=maxBytes}get stagedBytes(){return this.reserved}get residentBytes(){return this.store.status().residentPayloadBytes}begin(kind,id,length){if(this.closed)throw new TransferStagingError("staging_closed");if(!Number.isSafeInteger(length)||length<0||length%2!==0)throw new TransferStagingError("length_mismatch");if(this.reserved+length>this.maxBytes)throw new TransferStagingError("staging_over_byte_limit");this.reserved+=length;let transfer=new StagedTransfer(this.store,{kind,id,length},content=>{this.transfers.delete(transfer),content?this.staged.set(content,length):this.reserved-=length});return this.transfers.add(transfer),transfer}stage(kind,id,text){let transfer=this.begin(kind,id,text.length*2);try{for(let at=0;at<text.length;at+=FRAGMENT_MAX_UNITS)transfer.append(text.slice(at,at+FRAGMENT_MAX_UNITS));return transfer.commit()}catch(cause){throw transfer.abort(),cause}}adopt(content){let bytes=this.staged.get(content);if(bytes===void 0)throw new CompactReadError("ownership");this.staged.delete(content),this.reserved-=bytes}release(content){let bytes=this.staged.get(content);bytes!==void 0&&(this.staged.delete(content),this.reserved-=bytes);for(let leaf2 of content.leaves)this.store.adjust(leaf2,-1,0)}abandon(content){this.staged.has(content)&&this.release(content)}pin(content,pins){for(let leaf2 of content.leaves)this.store.adjust(leaf2,0,pins)}open(content,valid=()=>{}){return openFrozenBytes(content.ref.entry,content.leaves,leaf2=>this.store.readLeaf(leaf2),valid)}async*chunks(content,valid=()=>{}){let length=0;for(let[index,leaf2]of content.leaves.entries()){let text;try{text=await this.store.readLeaf(leaf2)}catch(cause){throw cause instanceof CompactStorageReadError||cause instanceof CompactReadError?new StagedReadError("segment_missing",{cause}):cause}if(valid(),catalogDigest("leaf",storedBytes(text))!==content.leafDigests[index])throw new StagedReadError("segment_mismatch");length+=text.length*2,yield text}if(length!==content.ref.entry.length)throw new StagedReadError("segment_mismatch")}spill(content){for(let leaf2 of content.leaves)this.store.enqueue("spill_write",()=>this.store.flushLeaf(leaf2))}status(){return{...this.store.status(),stagedBytes:this.reserved,openTransfers:this.transfers.size}}idle(){return this.store.idle()}close(){this.closed=!0;for(let transfer of[...this.transfers])transfer.abort();for(let content of[...this.staged.keys()])this.release(content);return this.store.retire()}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join5(tmpdir(),`senpi-event-leases-${randomUUID4()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
2
+ import{CompactSelection,EVENT_RESYNC_CAPABILITY,ExtensionTransportOwner,McpPresenterAuthority,SocketPeerRecovery,attachMcpGrantPresentation,correlatedRecord,declarationReply,effectStatusRecord,isCorrelatedReply,observeLifecycleDelivery,sessionQuestionBridges}from"./chunk-RWF6IJQL.js";import{RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SUBSCRIPTION,RPC_ERROR_SESSION_NOT_ATTACHED,RPC_ERROR_SUBSCRIPTION_LIMIT,RPC_ERROR_UNKNOWN_SUBSCRIPTION,RPC_ERROR_UNSUPPORTED_TRANSPORT}from"./chunk-VRKA3LIT.js";import{bindPrivateMcpForms}from"./chunk-7ICGN62G.js";import{carriesMedia,normalizeJsonValue,omitNormalInlineMedia}from"./chunk-67M7HKXO.js";import{BaseContentHash,compactUpdatesEnabled,fingerprintLine,parseSessionEntryLine}from"./chunk-U6A4X3FV.js";import{COMPACT_EVENTS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,hostGeneration,hostInstanceId}from"./chunk-OOU3BRUY.js";import{LegacyRecordDepthError,serializeJsonLine}from"./chunk-H52J72VA.js";import{external_exports}from"./chunk-KUPQO7MC.js";import{acquireOwnershipSafeLock}from"./chunk-QEESHRTS.js";import{getAgentDir}from"./chunk-SODMQEHO.js";import{processIsLive,processStartTimeMs,readProcessIdentity}from"./chunk-O5RYI3IW.js";import{randomUUID as randomUUID4}from"node:crypto";import{tmpdir}from"node:os";import{join as join5}from"node:path";var CompactReadError=class extends Error{constructor(reason){super(`compact read refused (${reason})`),this.name="CompactReadError",this.reason=reason}},CompactReadLease=class{constructor(dispose,valid=()=>{}){this.released=!1,this.operations=0,this.dispose=dispose,this.valid=valid}assert(){if(this.released)throw new CompactReadError("released");this.valid()}async run(read){return this.assert(),this.hold(async()=>{let result=await read();return this.assert(),result})}async hold(read){if(this.released)throw new CompactReadError("released");this.operations++;try{return await read()}finally{--this.operations===0&&this.released&&this.dispose()}}retain(){if(this.released)throw new CompactReadError("released");this.operations++;let ended=!1;return()=>{ended||(ended=!0,--this.operations===0&&this.released&&this.dispose())}}release(){return this.released?!1:(this.released=!0,this.operations===0&&this.dispose(),!0)}};import{dirname as dirname2,join as join4}from"node:path";import{open as open4,rm as rm3}from"node:fs/promises";import{randomUUID as randomUUID3}from"node:crypto";import{randomUUID}from"node:crypto";import{constants as constants2}from"node:fs";import{lstat as lstat2,mkdir,open as open2,rename,rm}from"node:fs/promises";import{join as join2}from"node:path";import{execFile}from"node:child_process";import{constants}from"node:fs";import{lstat,open,readFile}from"node:fs/promises";import{join}from"node:path";import{promisify}from"node:util";var ROOT_MARKER=".compact-spool-owner",Owner=external_exports.object({bootNonce:external_exports.string().min(1),pid:external_exports.number().int().positive(),startTime:external_exports.string().min(1).refine(value=>processStartTimeMs(value)!==void 0)}),Marker=external_exports.object({kind:external_exports.enum(["scratch","live"]),token:external_exports.string().min(1),owner:Owner.nullable()}),boot,self;function bootNonce(){return boot??=(async()=>{switch(process.platform){case"darwin":return(await promisify(execFile)("/usr/sbin/sysctl",["-n","kern.bootsessionuuid"],{timeout:2e3})).stdout.trim()||null;case"linux":return(await readFile("/proc/sys/kernel/random/boot_id","utf8")).trim()||null;default:return null}})().catch(cause=>{if(cause instanceof Error)return null;throw cause}),boot}function currentRootOwner(){return self??=(async()=>{let bootNonceValue=await bootNonce();if(!bootNonceValue)return null;let start=await rootProcessIdentity(process.pid);return start.kind==="present"?{bootNonce:bootNonceValue,pid:process.pid,startTime:start.identity}:null})(),self}async function rootProcessIdentity(pid){try{return await readProcessIdentity(pid,process.platform,2e3,processIsLive,"UTC")}catch(cause){if(cause instanceof Error&&"syscall"in cause&&typeof cause.syscall=="string"&&/^spawn(?: |$)/.test(cause.syscall))return{kind:"error",error:cause};throw cause}}async function rootOwnerState(owner){let currentBoot=await bootNonce();if(!owner||!currentBoot)return"unknown";if(owner.bootNonce!==currentBoot)return"dead";let start=await rootProcessIdentity(owner.pid);switch(start.kind){case"absent":return processIsLive(owner.pid)?"unknown":"dead";case"present":return start.identity===owner.startTime?"alive":"dead";case"error":return"unknown"}}function privateRootStat(stat){return stat.isDirectory()&&!stat.isSymbolicLink()&&(process.getuid===void 0||stat.uid===process.getuid()&&(stat.mode&63)===0)}async function readRootMarker(dir){try{let path=join(dir,ROOT_MARKER),entry=await lstat(path);if(!entry.isFile()||entry.isSymbolicLink())return;let handle=await open(path,constants.O_RDONLY|(constants.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>8192||process.getuid!==void 0&&(stat.uid!==process.getuid()||(stat.mode&63)!==0))return;let parsed=Marker.safeParse(JSON.parse(await handle.readFile("utf8")));return parsed.success?parsed.data:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error)return;throw cause}}var recoveryAgentDir=getAgentDir(),RecoveryStorageHealth=class{constructor(base){this.failures=0,this.cleared=0,this.dir=join2(base,`.senpi-recovery-health-${process.getuid?.()??"user"}`)}ensureDir(){return this.setup??=(async()=>{if(await mkdir(this.dir,{mode:448,recursive:!0}),!privateRootStat(await lstat2(this.dir)))throw new CompactReadError("ownership")})().catch(cause=>{throw this.setup=void 0,cause}),this.setup}get needsRecovery(){return this.failures>this.cleared}unavailable(){this.failures+=1}async revision(){return await this.ensureDir(),await this.readRevision()??this.advance()}async readRevision(){try{let handle=await open2(join2(this.dir,"revision"),constants2.O_RDONLY|(constants2.O_NOFOLLOW??0));try{let stat=await handle.stat();if(!stat.isFile()||stat.size>128)return;let text=(await handle.readFile("utf8")).trim();return/^(0|[1-9]\d*)$/.test(text)?text:void 0}finally{await handle.close()}}catch(cause){if(cause instanceof Error&&"code"in cause&&cause.code==="ENOENT")return"0";if(cause instanceof Error&&"code"in cause&&cause.code==="ELOOP")return;throw cause}}async recover(operation){await this.ensureDir();let through=this.failures;if(await operation(),through<=this.cleared)return this.revision();if(this.pending&&await this.pending,through<=this.cleared)return this.revision();this.pending=this.advance().then(revision=>(this.cleared=through,revision));try{return await this.pending}finally{this.pending=void 0}}async advance(){await this.ensureDir();let release=await acquireOwnershipSafeLock(join2(this.dir,"revision.lock")),temporary=join2(this.dir,`${randomUUID()}.tmp`);try{let next=String(BigInt(await this.readRevision()??"0")+1n),file=await open2(temporary,constants2.O_WRONLY|constants2.O_CREAT|constants2.O_EXCL|(constants2.O_NOFOLLOW??0),384);try{await file.writeFile(next),await file.sync()}finally{await file.close()}await rename(temporary,join2(this.dir,"revision"));let directory=await open2(this.dir,"r");try{await directory.sync()}finally{await directory.close()}return next}finally{try{await rm(temporary,{force:!0})}finally{await release()}}}};import{randomUUID as randomUUID2}from"node:crypto";import{lstat as lstat3,mkdir as mkdir2,rename as rename2,rm as rm2,rmdir,writeFile as writeFile2}from"node:fs/promises";import{dirname,join as join3}from"node:path";import{open as open3,readFile as readFile2,unlink,writeFile}from"node:fs/promises";var nodeCompactStorageIo={writeFile:(path,data)=>writeFile(path,data,{flag:"wx",mode:384}),readFile:async(path,range)=>{if(!range)return readFile2(path);let handle=await open3(path,"r");try{let{buffer,bytesRead}=await handle.read(Buffer.alloc(range.length),0,range.length,range.offset);return buffer.subarray(0,bytesRead)}finally{await handle.close()}},unlink:path=>unlink(path)};function describeCause(cause){try{return cause instanceof Error?cause.message:String(cause)}catch{return"unprintable failure cause"}}var CompactStorageReadError=class extends Error{constructor(operation,path,cause){super(`compact storage ${operation} failed for ${path}: ${describeCause(cause)}`,{cause}),this.name="CompactStorageReadError",this.operation=operation,this.path=path}};var MARKER=ROOT_MARKER,CompactSpoolRefusedError=class extends Error{constructor(reason,path,cause,cleanupFailure){let detail=cause===void 0?"":`: ${describeCause(cause)}`,kept=cleanupFailure===void 0?"":`; removing the directory failed: ${describeCause(cleanupFailure)}`;super(`compact spool directory refused (${reason}): ${path}${detail}${kept}`,{cause}),this.name="CompactSpoolRefusedError",this.reason=reason,this.path=path}};async function createSpoolDir(dir){await mkdir2(dirname(dir),{recursive:!0,mode:448});try{await mkdir2(dir,{mode:448})}catch(cause){throw cause.code==="EEXIST"?new CompactSpoolRefusedError("pre_existing",dir):cause}let token=randomUUID2(),temporary=join3(dir,`${MARKER}.${token}.tmp`);try{await writeFile2(temporary,JSON.stringify({kind:"scratch",token,owner:await currentRootOwner()}),{flag:"wx",mode:384}),await rename2(temporary,join3(dir,MARKER))}catch(cause){throw await abandonSpoolDir(dir,cause,temporary)}return token}async function abandonSpoolDir(dir,cause,temporary){try{return await rm2(temporary,{force:!0}),cause.code!=="EEXIST"&&await rm2(join3(dir,MARKER),{force:!0}),await rmdir(dir),new CompactSpoolRefusedError("marker_write_failed",dir,cause)}catch(cleanupFailure){return new CompactSpoolRefusedError("marker_write_failed",dir,cause,cleanupFailure)}}async function removeSpoolDir(dir,token){let owned=await lstat3(dir).catch(cause=>{if(cause.code!=="ENOENT")throw cause});if(owned===void 0)return;let refusal3=await refusalFor(dir,owned,token);if(refusal3)throw new CompactSpoolRefusedError(refusal3,dir);await rm2(dir,{recursive:!0,force:!0})}async function refusalFor(dir,owned,token){if(owned.isSymbolicLink())return"symlink";if(!owned.isDirectory())return"not_directory";let markerPath=join3(dir,MARKER),marker=await lstat3(markerPath).catch(()=>{});if(!marker?.isFile()||(await readRootMarker(dir))?.token!==token)return"marker_missing";let uid=process.getuid?.();if(uid!==void 0){if(owned.uid!==uid||marker.uid!==uid)return"foreign_owner";if(((owned.mode|marker.mode)&63)!==0)return"wide_mode"}}var RECLAIM_WORK_ALLOWANCE_BYTES=1024*1024,RECLAIM_RETRY_DELAYS_MS=[100,400,1600,6400,25600],FAILURE_HISTORY=32,FILE_PREFIX={spill_write:"leaf",value_write:"value",node_write:"node"},HALTING=new Set(["spill_write","value_write","node_write","spool_create"]),CompactSpoolStorage=class{assertReadable(){if(this.retired)throw new CompactReadError("retired")}beginRead(){this.assertReadable(),this.reads++,this.reading??=Promise.withResolvers();let done=!1;return()=>{done||(done=!0,--this.reads===0&&(this.reading?.resolve(),this.reading=void 0))}}constructor(dir,io,health=new RecoveryStorageHealth(recoveryAgentDir)){this.failures=[],this.nextFile=1,this.chain=Promise.resolve(),this.queued=0,this.spillQueued=!1,this.halted=!1,this.retired=!1,this.pendingIoCopyBytes=0,this.spillBytesWritten=0,this.reclaimDebtBytes=0,this.reads=0,this.dir=dir,this.io=io,this.health=health}async repair(){let revision=await this.health.recover(async()=>{let path=join4(dirname2(this.dir),`.senpi-repair-${randomUUID3()}`);try{let file=await open4(path,"wx",384);try{await file.writeFile("repair"),await file.sync()}finally{await file.close()}}finally{await rm3(path,{force:!0})}});return this.halted=!1,this.spoolToken===void 0&&(this.dirReady=void 0),this.scheduleSpill(),await this.idle(),revision}async idle(){for(;this.queued>0;)await this.chain}async retire(){this.retired=!0,await this.reading?.promise,await this.idle();let token=this.spoolToken;if(token!==void 0){try{await removeSpoolDir(this.dir,token)}catch(cause){throw this.fail("reclaim",this.dir,cause,0),cause}this.spoolToken=void 0,this.reclaimDebtBytes=0}}async readFile(path,bytes,operation,range){let done=this.beginRead();try{let result=await this.readCommittedFile(path,bytes,operation,range);return this.assertReadable(),result}finally{done()}}async readCommittedFile(path,bytes,operation,range){let data;try{data=await this.io.readFile(path,range)}catch(cause){throw this.readFailure(operation,path,cause)}if(data.byteLength!==bytes)throw this.readFailure(operation,path,new Error(`expected ${bytes} bytes, found ${data.byteLength}`));return data}async writeFile(data,operation,retainedInMemoryBytes){let path=await this.ensureDir(retainedInMemoryBytes);if(path===void 0)return;let file=join4(path,`${FILE_PREFIX[operation]??"page"}-${this.nextFile++}.bin`);this.pendingIoCopyBytes+=data.byteLength;try{return this.health.needsRecovery?await this.health.recover(()=>this.io.writeFile(file,data)):await this.io.writeFile(file,data),this.spillBytesWritten+=data.byteLength,file}catch(cause){try{this.fail(operation,file,cause,retainedInMemoryBytes)}finally{this.discard(file,data.byteLength)}return}finally{this.pendingIoCopyBytes-=data.byteLength}}discard(path,bytes){this.retired||(this.reclaimDebtBytes+=bytes,this.enqueue("reclaim",()=>this.reclaim(path,bytes,0)))}async reclaim(path,bytes,attempt){try{await this.io.unlink(path)}catch(cause){if(cause.code!=="ENOENT"){this.fail("reclaim",path,cause,0);let delay=RECLAIM_RETRY_DELAYS_MS[attempt];delay!==void 0&&setTimeout(()=>{this.retired||this.enqueue("reclaim",()=>this.reclaim(path,bytes,attempt+1))},delay).unref?.();return}}this.reclaimDebtBytes-=bytes,this.scheduleSpill()}get spillAllowed(){return!this.halted&&!this.retired}get spillStopped(){return this.halted||this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES}enqueue(operation,job){this.queued++,this.chain=this.chain.then(job).catch(cause=>{operation==="spill_write"&&(this.spillQueued=!1),!(this.retired&&cause instanceof CompactReadError&&cause.reason==="retired")&&this.fail(operation,this.dir,cause,0)}).finally(()=>{this.queued--})}ensureDir(retained){return this.dirReady??=createSpoolDir(this.dir).then(token=>(this.spoolToken=token,this.dir),cause=>{this.fail("spool_create",this.dir,cause,retained)}),this.dirReady}readFailure(operation,path,cause){return this.fail(operation,path,cause,0),new CompactStorageReadError(operation,path,cause)}fail(operation,path,cause,retained){(HALTING.has(operation)||operation==="page_write")&&this.health.unavailable(),HALTING.has(operation)&&(this.halted=!0),this.record({operation,path,cause:describeCause(cause),retainedInMemoryBytes:retained})}record(failure){this.failures.push(failure),this.failures.length>FAILURE_HISTORY&&this.failures.shift()}};var COMPACT_SEGMENT_BYTES=65536,CompactSegmentStorage=class extends CompactSpoolStorage{async writeSegment(texts,operation){let data=Buffer.from(texts.join(""),"utf16le"),path=await this.writeFile(data,operation,data.byteLength);if(path!==void 0)return{path,bytes:data.byteLength,operation,live:new Map,liveBytes:0,readers:0,rewritten:!1}}segmentRuns(entries){let runs=[],bytes=0;for(let[entry,size]of entries){let run=runs.at(-1);run&&bytes+size<=COMPACT_SEGMENT_BYTES?(run.push(entry),bytes+=size):(runs.push([entry]),bytes=size)}return runs}async writeSegments(texts,operation){let placements=[],written=[],complete=!1;try{for(let run of this.segmentRuns(texts.map((text,n)=>[n,text.length*2]))){let segment=await this.writeSegment(run.map(n=>texts[n]),operation);if(!segment)return;written.push(segment);let offset=0;for(let n of run)placements[n]=[segment,offset],offset+=texts[n].length*2}return complete=!0,placements}finally{if(!complete)for(let stray of written)this.discard(stray.path,stray.bytes)}}place(segment,id,offset,bytes){let slot={segment,offset,bytes};return segment.live.set(id,slot),segment.liveBytes+=bytes,slot}leave(id,slot){let segment=slot.segment;segment.live.delete(id),segment.liveBytes-=slot.bytes,this.settle(segment)}async readSlot(slot){let{segment,offset,bytes}=slot;segment.readers++;try{return await this.readFile(segment.path,bytes,"leaf_read",{offset,length:bytes})}finally{segment.readers--,this.settle(segment)}}settle(segment){segment.live.size?!segment.rewritten&&segment.liveBytes*2<segment.bytes&&(segment.rewritten=!0,this.enqueue("reclaim",()=>this.rewrite(segment))):segment.readers||this.discard(segment.path,segment.bytes)}async rewrite(segment){if(!this.spillAllowed||!segment.live.size)return;segment.readers++;let next,copied=0;try{let moving=[...segment.live].sort(([,a],[,b])=>a.offset-b.offset),texts=[];for(let n=0;n<moving.length;){let start=moving[n][1].offset,end=start,run=[];for(;n<moving.length&&moving[n][1].offset===end;n++)run.push(moving[n][1]),end+=moving[n][1].bytes;let data=await this.readFile(segment.path,end-start,"leaf_read",{offset:start,length:end-start});this.pendingIoCopyBytes+=data.byteLength,copied+=data.byteLength;for(let slot of run)texts.push(data.toString("utf16le",slot.offset-start,slot.offset-start+slot.bytes))}next=await this.writeSegment(texts,segment.operation);let offset=0;for(let[id,slot]of moving)next&&segment.live.delete(id)&&(segment.liveBytes-=slot.bytes,next.live.set(id,slot),next.liveBytes+=slot.bytes,slot.segment=next,slot.offset=offset),offset+=slot.bytes}catch(error){if(!(error instanceof CompactReadError&&error.reason==="retired"))throw error}finally{this.pendingIoCopyBytes-=copied,segment.readers--,this.settle(segment),next&&this.settle(next)}}};var CompactCommitDependencies=class{constructor(store,ready){this.pending=new Map,this.dependants=new Map,this.store=store,store.subscribeCommitted(id=>{let keys=this.dependants.get(id);this.dependants.delete(id);for(let key of keys??[]){let pending=this.pending.get(key);pending?.delete(id),pending?.size===0&&(this.pending.delete(key),ready(key))}})}get size(){return this.pending.size}has(key){return this.pending.has(key)}set(key,refs){this.delete(key);let pending=new Set(refs.filter(id=>!this.store.isCommitted(id)));if(pending.size!==0){this.pending.set(key,pending);for(let id of pending){let keys=this.dependants.get(id)??new Set;keys.add(key),this.dependants.set(id,keys)}}}delete(key){for(let id of this.pending.get(key)??[]){let keys=this.dependants.get(id);keys?.delete(key),keys?.size===0&&this.dependants.delete(id)}this.pending.delete(key)}};var CompactTextRoots=class{constructor(store){this.nodes=new Map,this.next=-1,this.store=store,this.pending=new CompactCommitDependencies(store,id=>store.committed(id))}get residentNodes(){return this.nodes.size}own(refs){if(refs.length===0)return 0;if(refs.length===1){let[ref]=refs;return this.store.adjust(ref,1,0),ref}let middle=Math.floor(refs.length/2),left=this.own(refs.slice(0,middle)),right=this.own(refs.slice(middle));if(left===0)return right;if(right===0)return left;let root=this.join(left,right);return this.store.adjust(left,-1,0),this.store.adjust(right,-1,0),root}units(id){return id===0?0:id>0?this.store.leafUnits(id):this.node(id).units}isCommitted(id){return this.nodes.has(id)&&!this.pending.has(id)}append(root,text,structured=!1){this.units(root);let leaf2=this.store.createLeaf(text,structured);if(root===0)return leaf2;let result=this.appendLeaf(root,leaf2);return this.store.adjust(root,-1,0),this.store.adjust(leaf2,-1,0),result}adjust(id,live,pins){let work=[[id,live,pins]];for(let next=work.pop();next;next=work.pop()){let[id2,live2,pins2]=next;if(id2>=0){this.store.adjust(id2,live2,pins2);continue}let node=this.node(id2),beforeLive=+(node.live>0),beforePin=+(node.live===0&&node.pins>0);if(node.live+live2<0||node.pins+pins2<0)throw new CompactReadError("ownership");node.live+=live2,node.pins+=pins2;let liveChange=+(node.live>0)-beforeLive,pinChange=+(node.live===0&&node.pins>0)-beforePin;(liveChange||pinChange)&&work.push([node.right,liveChange,pinChange],[node.left,liveChange,pinChange]),node.live===0&&node.pins===0&&(this.pending.delete(id2),this.nodes.delete(id2))}}async read(root,tail,offset,units,maxLeaves=2,valid=()=>this.store.assertReadable()){this.store.assertReadable(),valid();let length=this.units(root);if(!Number.isSafeInteger(offset)||!Number.isSafeInteger(units)||offset<0||units<0||offset+units>length+tail.length)throw new CompactReadError("range");if(units>COMPACT_LEAF_CODE_UNITS)throw new CompactReadError("size_limit");if(!Number.isSafeInteger(maxLeaves)||maxLeaves<1||maxLeaves>2)throw new CompactReadError("count_limit");let selected=[],visit=(id,start,end)=>{if(!(start>=end||id===0))if(id>0){if(selected.length===maxLeaves)throw new CompactReadError("count_limit");selected.push({id,offset:start,units:end-start})}else{let node=this.node(id),leftUnits=this.units(node.left);visit(node.left,start,Math.min(end,leftUnits)),visit(node.right,Math.max(0,start-leftUnits),end-leftUnits)}};visit(root,offset,Math.min(length,offset+units));let tailUnits=units===0?0:Math.max(0,offset+units-Math.max(offset,length));if(selected.length+ +(tailUnits>0)>maxLeaves)throw new CompactReadError("count_limit");this.store.adjust(root,0,1);let done=this.store.beginRead();try{let result="";for(let part of selected){let text=await this.store.readLeaf(part.id);valid(),result+=text.slice(part.offset,part.offset+part.units)}return valid(),result+tail.slice(Math.max(0,offset-length),Math.max(0,offset-length)+tailUnits)}finally{this.store.adjust(root,0,-1),done()}}node(id){let node=this.nodes.get(id);if(!node)throw new CompactReadError("ownership");return node}async*chunks(root,valid){if(valid(),root!==0)if(root>0){let text=await this.read(root,"",0,this.units(root),1,valid);valid(),yield text}else{let node=this.node(root);yield*this.chunks(node.left,valid),yield*this.chunks(node.right,valid)}}appendLeaf(root,leaf2){let node=this.nodes.get(root);if(!node||node.full)return this.join(root,leaf2);let right=this.appendLeaf(node.right,leaf2),result=this.join(node.left,right);return this.store.adjust(right,-1,0),result}height(id){return id>0?0:this.node(id).height}join(left,right){let id=this.next--;return this.nodes.set(id,{left,right,units:this.units(left)+this.units(right),height:1+Math.max(this.height(left),this.height(right)),full:this.height(left)===this.height(right)&&(this.nodes.get(left)?.full??!0)&&(this.nodes.get(right)?.full??!0),live:1,pins:0}),this.store.adjust(left,1,0),this.store.adjust(right,1,0),this.pending.set(id,[left,right]),id}};var COMPACT_LEAF_CODE_UNITS=32768,VALUE_FLUSH_BATCH=128,CompactWriteError=class extends Error{constructor(reason,limit){super(`compact write refused (${reason}${limit===void 0?"":`: depth above ${limit}`})`),this.name="CompactWriteError",this.reason=reason,this.limit=limit}},CompactContentStore=class extends CompactSegmentStorage{subscribeCommitted(listener){this.subscribers.add(listener)}committed(id){for(let listener of this.subscribers)listener(id)}leafUnits(id){let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.units}constructor(options){super(options.dir,options.io??nodeCompactStorageIo,options.health),this.leaves=new Map,this.ramLeaves=new Set,this.ramValues=new Set,this.valueQueued=!1,this.structuredBytes={resident:0,spilled:0,pinned:0},this.nextLeafId=1,this.residentPayloadBytes=0,this.pinnedOnlyBytes=0,this.spilledLiveBytes=0,this.subscribers=new Set,this.text=new CompactTextRoots(this),this.spillAboveBytes=options.spillAboveBytes??4*1024*1024,this.spillTargetBytes=options.spillTargetBytes??2*1024*1024}createLeaf(text,value=!1){if(this.assertReadable(),text.length>COMPACT_LEAF_CODE_UNITS)throw new CompactWriteError("size_limit");let id=this.nextLeafId++;return this.leaves.set(id,{text,units:text.length,value,live:1,pins:0,state:"ram"}),(value?this.ramValues:this.ramLeaves).add(id),value?this.structuredBytes.resident+=text.length*2:this.residentPayloadBytes+=text.length*2,this.scheduleSpill(),id}ownFile(path,bytes){let id=this.createLeaf("",!0),leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");return leaf2.file={path,bytes},id}adjust(id,live,pins){if(id===0)return;if(id<0)return this.text.adjust(id,live,pins);let leaf2=this.leaves.get(id);if(!leaf2||leaf2.live+live<0||leaf2.pins+pins<0)throw new CompactReadError("ownership");let pinnedOnly=leaf2.live===0&&leaf2.pins>0;if(leaf2.live+=live,leaf2.pins+=pins,pinnedOnly!==(leaf2.live===0&&leaf2.pins>0)){let bytes=(pinnedOnly?-2:2)*leaf2.units;leaf2.value?this.structuredBytes.pinned+=bytes:this.pinnedOnlyBytes+=bytes}if(!(leaf2.live>0||leaf2.pins>0)){if(this.leaves.delete(id),leaf2.file&&this.discard(leaf2.file.path,leaf2.file.bytes),(leaf2.value?this.ramValues:this.ramLeaves).delete(id),leaf2.state==="committed"&&leaf2.slot){leaf2.value?this.structuredBytes.spilled-=leaf2.units*2:this.spilledLiveBytes-=leaf2.units*2,this.leave(id,leaf2.slot);return}leaf2.value?this.structuredBytes.resident-=leaf2.units*2:this.residentPayloadBytes-=leaf2.units*2}}isCommitted(id){return id<=0?id===0||this.text.isCommitted(id):this.leaves.get(id)?.state==="committed"}async readLeaf(id){this.assertReadable();let leaf2=this.leaves.get(id);if(!leaf2)throw new CompactReadError("ownership");this.adjust(id,0,1);try{if(leaf2.text!==void 0)return leaf2.text;if(!leaf2.slot)throw new CompactReadError("ownership");return(await this.readSlot(leaf2.slot)).toString("utf16le")}finally{this.adjust(id,0,-1)}}status(){return{structuredBytes:{...this.structuredBytes},residentPayloadBytes:this.residentPayloadBytes,pendingIoCopyBytes:this.pendingIoCopyBytes,pinnedOnlyBytes:this.pinnedOnlyBytes,spilledLiveBytes:this.spilledLiveBytes,spillBytesWritten:this.spillBytesWritten,reclaimDebtBytes:this.reclaimDebtBytes,spillFailureRetainedBytes:this.spillStopped?Math.max(0,this.residentPayloadBytes-this.spillTargetBytes):0,spillHalted:this.spillStopped,failures:[...this.failures]}}scheduleSpill(){!this.valueQueued&&this.spillAllowed&&this.ramValues.size&&this.reclaimDebtBytes<=RECLAIM_WORK_ALLOWANCE_BYTES&&(this.valueQueued=!0,this.enqueue("value_write",async()=>{try{await this.flushValues()}finally{this.valueQueued=!1}this.scheduleSpill()})),!(this.spillQueued||!this.spillAllowed||this.residentPayloadBytes<=this.spillAboveBytes)&&(this.reclaimDebtBytes>RECLAIM_WORK_ALLOWANCE_BYTES||(this.spillQueued=!0,this.enqueue("spill_write",()=>this.spillNext())))}async spillNext(){let[id]=this.ramLeaves;id!==void 0&&await this.flushLeaf(id),this.spillQueued=!1,this.residentPayloadBytes>this.spillTargetBytes&&(this.spillQueued=this.spillAllowed&&this.ramLeaves.size>0,this.spillQueued&&this.enqueue("spill_write",()=>this.spillNext()))}async flushValues(){if(this.spillStopped)return;let batch=[];for(let id of this.ramValues)if(batch.push([id,this.leafUnits(id)*2]),batch.length===VALUE_FLUSH_BATCH)break;await this.flushLeaves(this.segmentRuns(batch)[0]??[])}flushLeaf(id){return this.flushLeaves([id])}async flushLeaves(ids,operation){if(!this.spillAllowed)return;let batch=[];for(let id of ids){let leaf2=this.leaves.get(id);leaf2?.state!=="ram"||leaf2.text===void 0||(leaf2.state="pending",(leaf2.value?this.ramValues:this.ramLeaves).delete(id),batch.push([id,leaf2,leaf2.text]))}if(!batch.length)return;let placements;try{let texts=batch.map(([,,text])=>text);placements=await this.writeSegments(texts,operation??(batch[0][1].value?"value_write":"spill_write"))}finally{for(let[id,leaf2]of placements?[]:batch)leaf2.state="ram",this.leaves.get(id)===leaf2&&(leaf2.value?this.ramValues:this.ramLeaves).add(id)}if(!placements)return;let placed=[];for(let[n,[id,leaf2]]of batch.entries()){let[segment,offset]=placements[n],bytes=leaf2.units*2;this.leaves.get(id)===leaf2&&!this.retired&&(leaf2.state="committed",leaf2.text=void 0,leaf2.slot=this.place(segment,id,offset,bytes),leaf2.value?(this.structuredBytes.resident-=bytes,this.structuredBytes.spilled+=bytes):(this.residentPayloadBytes-=bytes,this.spilledLiveBytes+=bytes),placed.push(id))}for(let segment of new Set(placements.map(([segment2])=>segment2)))this.settle(segment);for(let id of placed)this.committed(id)}};import{createHash}from"node:crypto";var BOUNDED_ID=/^[A-Za-z0-9][A-Za-z0-9:_-]*$/,CONTENT_DIGEST=/^[0-9a-f]{64}$/,CONTENT_REF=/^c-[0-9]{16}(?::[0-9]{3})*$/,BASE_REF=/^c-[0-9]{16}:base$/,RESERVED_STEP=/:base(?::|$)/,refused=reason=>({ok:!1,reason});function parseBoundedId(value){return value.length===0?refused("empty"):Buffer.byteLength(value)>128?refused("overlong"):BOUNDED_ID.test(value)?{ok:!0,value}:refused("forbidden_character")}function parseContentDigest(value){return value.length===0?refused("empty"):CONTENT_DIGEST.test(value)?{ok:!0,value}:refused("malformed")}function parseContentRef(value){let bounded=parseBoundedId(value);return bounded.ok?RESERVED_STEP.test(value)?refused("reserved"):CONTENT_REF.test(value)?(value.length-18)/4>8?refused("too_deep"):{ok:!0,value}:refused("malformed"):bounded}function parseBaseRef(value){let bounded=parseBoundedId(value);return bounded.ok?BASE_REF.test(value)?{ok:!0,value}:refused("malformed"):bounded}function parsePageRef(value){let base=parseBaseRef(value);if(base.ok)return{ok:!0,value:{kind:"base",ref:base.value}};let content=parseContentRef(value);return content.ok?{ok:!0,value:{kind:"catalog",ref:content.value}}:content}function protocolId(value){let parsed=parseBoundedId(value);if(!parsed.ok)throw new RangeError(`not a bounded protocol id (${parsed.reason}): ${value.length} chars`);return parsed.value}function fixed(value,digits,bound,what){if(!Number.isSafeInteger(value)||value<0||value>=bound)throw new RangeError(`${what} out of range: ${value}`);return String(value).padStart(digits,"0")}function minted(value){let parsed=parseContentRef(value);if(!parsed.ok)throw new RangeError(`catalog ref ${parsed.reason}`);return parsed.value}var catalogRootRef=counter=>minted(`c-${fixed(counter,16,10**16,"catalog counter")}`),childRef=(parent,index)=>minted(`${parent}:${fixed(index,3,128,"catalog child index")}`);function baseRef(root){let parsed=parseBaseRef(`${root}:base`);if(!parsed.ok)throw new RangeError(`base ref ${parsed.reason}`);return parsed.value}var refSteps=ref=>ref.split(":").slice(1).map(Number);var CATALOG_FORMAT="senpi-recovery-catalog",CATALOG_VERSION=1,CATALOG_ENCODING="utf16le",CATALOG_NODE_MAX_UNITS=COMPACT_LEAF_CODE_UNITS,storedBytes=text=>Buffer.from(text,CATALOG_ENCODING);function catalogDigester(domain,length){let tag=Buffer.from(`${CATALOG_FORMAT}/${CATALOG_VERSION}/${CATALOG_ENCODING}/${domain}`,"ascii"),prefix=Buffer.alloc(1+tag.length+8);prefix.writeUInt8(tag.length,0),tag.copy(prefix,1),prefix.writeBigUInt64BE(BigInt(length),1+tag.length);let hash=createHash("sha256").update(prefix),fed=0;return{update:bytes=>{fed+=bytes.length,hash.update(bytes)},finish:()=>{if(fed!==length)throw new RangeError(`catalog digest fed ${fed} of ${length} bytes`);let parsed=parseContentDigest(hash.digest("hex"));if(!parsed.ok)throw new RangeError("sha256 produced a malformed digest");return parsed.value}}}function catalogDigest(domain,bytes){let digester=catalogDigester(domain,bytes.length);return digester.update(bytes),digester.finish()}var HEAD=`{"format":"${CATALOG_FORMAT}","version":${CATALOG_VERSION},"entries":[`,TAIL="]}",encodeEntry=entry=>`{"kind":"${entry.kind}","id":"${entry.id}","length":${entry.length},"digest":"${entry.digest}"}`,CatalogNodeWriter=class{constructor(){this.parts=[],this.units=HEAD.length+TAIL.length}get count(){return this.parts.length}push(entry){if(!Number.isSafeInteger(entry.length)||entry.length<0)throw new RangeError("catalog entry length");let part=encodeEntry(entry),units=this.units+part.length+ +(this.parts.length>0);return this.parts.length===128||units>CATALOG_NODE_MAX_UNITS?!1:(this.parts.push(part),this.units=units,!0)}encode(){return`${HEAD}${this.parts.join(",")}${TAIL}`}},CatalogNodeSchema=external_exports.object({format:external_exports.literal(CATALOG_FORMAT),version:external_exports.literal(CATALOG_VERSION),entries:external_exports.array(external_exports.object({kind:external_exports.string(),id:external_exports.string(),length:external_exports.number().int().nonnegative(),digest:external_exports.string()}).strict()).max(128)}).strict();function decodeCatalogNode(text){let json;try{json=JSON.parse(text)}catch(cause){if(cause instanceof SyntaxError)return{ok:!1,reason:"schema"};throw cause}let parsed=CatalogNodeSchema.safeParse(json);if(!parsed.success)return{ok:!1,reason:"schema"};let entries=[];for(let raw of parsed.data.entries){let kind=parseBoundedId(raw.kind),id=parseBoundedId(raw.id),digest2=parseContentDigest(raw.digest);if(!kind.ok||!id.ok||!digest2.ok)return{ok:!1,reason:"schema"};entries.push({kind:kind.value,id:id.value,length:raw.length,digest:digest2.value})}return{ok:!0,entries}}var FRAGMENT_MAX_BYTES=131072,FRAGMENT_ENVELOPE_MAX_BYTES=Math.ceil(FRAGMENT_MAX_BYTES/3)*4,isIndex=value=>Number.isSafeInteger(value)&&value>=0;function assertRange(offset,length,total){if(!isIndex(offset)||!isIndex(length))throw new CompactReadError("range");if(length>FRAGMENT_MAX_BYTES)throw new CompactReadError("size_limit");if(offset+length>total)throw new CompactReadError("range")}function startAtOrBefore(starts,count,offset){let low=0,high=count-1;for(;low<high;){let middle=low+high+1>>1;(starts[middle]??Number.POSITIVE_INFINITY)<=offset?low=middle:high=middle-1}return low}var FrozenLeafBytes=class{constructor(digest2,leaves,starts,read){this.peakResidentLeaves=0,this.resident=0,this.length=starts[leaves.length]??0,this.digest=digest2,this.leaves=leaves,this.starts=starts,this.read=read}async range(offset,length,valid){assertRange(offset,length,this.length);let out=Buffer.allocUnsafe(length),written=0;for(let index=startAtOrBefore(this.starts,this.leaves.length,offset);written<length;index++){let leaf2=this.leaves[index],start=this.starts[index];if(leaf2===void 0||start===void 0)throw new CompactReadError("integrity");this.peakResidentLeaves=Math.max(this.peakResidentLeaves,++this.resident);try{let stored=storedBytes(await this.read(leaf2));valid?.();let from=Math.max(0,offset-start);written+=stored.copy(out,written,from,Math.min(stored.length,from+length-written))}finally{this.resident-=1}}return out}};async function openFrozenBytes(entry,leaves,read,valid,signal){let digester=catalogDigester("leaf",entry.length),starts=[0],fed=0;for(let leaf2 of leaves){if(signal?.aborted)throw new CompactReadError("aborted");let stored=storedBytes(await read(leaf2));if(valid(),fed+=stored.length,fed>entry.length)throw new CompactReadError("integrity");digester.update(stored),starts.push(fed)}if(fed!==entry.length||digester.finish()!==entry.digest)throw new CompactReadError("integrity");return new FrozenLeafBytes(entry.digest,leaves,starts,read)}async function producePage(bytes,offset,valid){if(!isIndex(offset)||offset>=bytes.length&&bytes.length>0)throw new CompactReadError("range");let length=Math.min(FRAGMENT_MAX_BYTES,bytes.length-offset),page=await bytes.range(offset,length,valid),next=offset+length;return{offset,length,bytes:page,digest:catalogDigest("fragment",page),next:next<bytes.length?next:null,complete:next===bytes.length}}var SKIPPED=new Set(["undefined","function","symbol"]),isRecord=value=>typeof value=="object"&&value!==null&&!Array.isArray(value);function jsonSize(value){let bytes=0,units=0;for(let piece of walk(value))bytes+=Buffer.byteLength(piece),units+=piece.length;return{bytes,units}}function*jsonChunks(value,size){let pending="";for(let piece of walk(value))for(pending+=piece;pending.length>=size;)yield pending.slice(0,size),pending=pending.slice(size);pending.length>0&&(yield pending)}function*walk(value){let stack=[],pending={value};for(;;){if(pending){let current=pending.value;if(pending=void 0,Array.isArray(current))yield"[",stack.push({entries:current,array:!0,index:0});else if(isRecord(current)){yield"{";let members=Object.entries(current).filter(([,child])=>!SKIPPED.has(typeof child));stack.push({entries:members,array:!1,index:0})}else yield JSON.stringify(current)??"null"}let frame=stack.at(-1);if(!frame)return;if(frame.index===frame.entries.length){stack.pop(),yield frame.array?"]":"}";continue}frame.index>0&&(yield",");let entry=frame.entries[frame.index++];if(frame.array)pending={value:entry};else{let[key,child]=entry;yield`${JSON.stringify(key)}:`,pending={value:child}}}}function stageRecord(staging,record,content){let kind=protocolId("event"),id=protocolId("record");if(typeof content=="string")return staging.stage(kind,id,content.slice(0,-1));let chunks2="chunks"in content?content.chunks:()=>jsonChunks(record,FRAGMENT_MAX_BYTES/2),units="units"in content?content.units:0;if("chunks"in content)for(let chunk of chunks2())units+=chunk.length;let transfer=staging.begin(kind,id,units*2);try{for(let chunk of chunks2())transfer.append(chunk);return transfer.commit()}catch(cause){throw transfer.abort(),cause}}function assertNever(value){throw new Error(`unexpected recovery failure: ${JSON.stringify(value)}`)}function refusalReason(failure){switch(failure.kind){case"storage_unavailable":return failure.kind;case"repair_needed":return failure.reason;default:return assertNever(failure)}}var recovered=value=>({ok:!0,value}),repairNeeded=reason=>({kind:"repair_needed",reason}),storageUnavailable=reason=>({kind:"storage_unavailable",reason}),RecoveryRefusedError=class extends Error{constructor(failure){super(`recovery refused (${failure.kind}: ${failure.reason})`),this.name="RecoveryRefusedError",this.failure=failure}};var TRANSFER_STAGING_MAX_BYTES=64*1024*1024,FRAGMENT_MAX_UNITS=FRAGMENT_MAX_BYTES/2,TransferStagingError=class extends Error{constructor(reason){super(`transfer staging refused (${reason})`),this.name="TransferStagingError",this.reason=reason}},StagedReadError=class extends Error{constructor(reason,options){super(`staged read refused (${reason})`,options),this.name="StagedReadError",this.reason=reason}},StagedTransfer=class{constructor(store,entry,settle){this.leaves=[],this.leafDigests=[],this.fed=0,this.open=!0,this.store=store,this.entry=entry,this.settle=settle,this.digester=catalogDigester("leaf",entry.length)}append(text){this.assertOpen();let bytes=text.length*2;bytes>FRAGMENT_MAX_BYTES&&this.refuse("fragment_over_limit"),this.fed+bytes>this.entry.length&&this.refuse("length_mismatch");try{for(let at=0;at<text.length;at+=COMPACT_LEAF_CODE_UNITS){let piece=text.slice(at,at+COMPACT_LEAF_CODE_UNITS);this.leaves.push(this.store.createLeaf(piece)),this.leafDigests.push(catalogDigest("leaf",storedBytes(piece)))}}catch(cause){throw this.abort(),cause}this.digester.update(storedBytes(text)),this.fed+=bytes}commit(){this.assertOpen(),this.fed!==this.entry.length&&this.refuse("length_mismatch"),this.open=!1;let content={ref:{variant:"staged",entry:{...this.entry,digest:this.digester.finish()}},leaves:[...this.leaves],leafDigests:[...this.leafDigests]};return this.settle(content),content}abort(){if(this.open){this.open=!1;for(let leaf2 of this.leaves)this.store.adjust(leaf2,-1,0);this.settle(void 0)}}assertOpen(){if(!this.open)throw new TransferStagingError("staging_closed")}refuse(reason){throw this.abort(),new TransferStagingError(reason)}},TransferStaging=class{constructor(store,maxBytes=TRANSFER_STAGING_MAX_BYTES){this.transfers=new Set,this.staged=new Map,this.reserved=0,this.closed=!1,this.store=store,this.maxBytes=maxBytes}get stagedBytes(){return this.reserved}get residentBytes(){return this.store.status().residentPayloadBytes}begin(kind,id,length){if(this.closed)throw new TransferStagingError("staging_closed");if(!Number.isSafeInteger(length)||length<0||length%2!==0)throw new TransferStagingError("length_mismatch");if(this.reserved+length>this.maxBytes)throw new TransferStagingError("staging_over_byte_limit");this.reserved+=length;let transfer=new StagedTransfer(this.store,{kind,id,length},content=>{this.transfers.delete(transfer),content?this.staged.set(content,length):this.reserved-=length});return this.transfers.add(transfer),transfer}stage(kind,id,text){let transfer=this.begin(kind,id,text.length*2);try{for(let at=0;at<text.length;at+=FRAGMENT_MAX_UNITS)transfer.append(text.slice(at,at+FRAGMENT_MAX_UNITS));return transfer.commit()}catch(cause){throw transfer.abort(),cause}}adopt(content){let bytes=this.staged.get(content);if(bytes===void 0)throw new CompactReadError("ownership");this.staged.delete(content),this.reserved-=bytes}release(content){let bytes=this.staged.get(content);bytes!==void 0&&(this.staged.delete(content),this.reserved-=bytes);for(let leaf2 of content.leaves)this.store.adjust(leaf2,-1,0)}abandon(content){this.staged.has(content)&&this.release(content)}pin(content,pins){for(let leaf2 of content.leaves)this.store.adjust(leaf2,0,pins)}open(content,valid=()=>{}){return openFrozenBytes(content.ref.entry,content.leaves,leaf2=>this.store.readLeaf(leaf2),valid)}async*chunks(content,valid=()=>{}){let length=0;for(let[index,leaf2]of content.leaves.entries()){let text;try{text=await this.store.readLeaf(leaf2)}catch(cause){throw cause instanceof CompactStorageReadError||cause instanceof CompactReadError?new StagedReadError("segment_missing",{cause}):cause}if(valid(),catalogDigest("leaf",storedBytes(text))!==content.leafDigests[index])throw new StagedReadError("segment_mismatch");length+=text.length*2,yield text}if(length!==content.ref.entry.length)throw new StagedReadError("segment_mismatch")}spill(content){for(let leaf2 of content.leaves)this.store.enqueue("spill_write",()=>this.store.flushLeaf(leaf2))}status(){return{...this.store.status(),stagedBytes:this.reserved,openTransfers:this.transfers.size}}idle(){return this.store.idle()}close(){this.closed=!0;for(let transfer of[...this.transfers])transfer.abort();for(let content of[...this.staged.keys()])this.release(content);return this.store.retire()}};var COMPACT_RECORD_MAX_BYTES=2*FRAGMENT_MAX_BYTES,PEER_EVENT_LEASES_MAX=32,RELEASED_LEASES_REMEMBERED=256,EVENT_RECORD_COMPONENT="record",EventLeases=class{constructor(peerLimit=PEER_EVENT_LEASES_MAX){this.peers=new Map,this.shared=new WeakMap,this.ended=new Set,this.refusals=new Map,this.open=0,this.minted=0,this.released=0,this.duplicates=0,this.abandoned=0,this.contentBytes=0,this.peerLimit=peerLimit}onLeaseEnd(listener){this.ended.add(listener)}mint(caller,at,record,content){let peer=this.peers.get(caller.socketEpoch)??{held:new Map,released:new Map};if(peer.held.size>=this.peerLimit)return this.refuse("lease_limit");let shared=this.stage(record,content);if(!shared)return this.refuse("storage_unavailable");let{entry}=shared.content.ref,lease=Object.freeze({kind:"event",id:protocolId(`event:${caller.socketEpoch}:${++this.minted}`),admissionId:caller.admissionId,...at,componentRef:EVENT_RECORD_COMPONENT,length:entry.length,digest:entry.digest});shared.holders+=1;let held={lease,sessionId:caller.sessionId,shared,admissions:new Set([caller.admissionId]),reads:new CompactReadLease(()=>this.dispose(peer,held))};return peer.held.set(lease.id,held),this.peers.set(caller.socketEpoch,peer),this.open+=1,{ok:!0,value:lease}}claim(caller,leaseId,admissionId){let held=this.peers.get(caller.socketEpoch)?.held.get(leaseId);return!held||held.sessionId!==caller.sessionId||!held.admissions.has(admissionId)?{ok:!1,failure:repairNeeded("unknown_token")}:recovered(held)}async page(held,componentRef,offset,signal){let staging=this.staging;if(componentRef!==EVENT_RECORD_COMPONENT||!staging)return{ok:!1,failure:storageUnavailable("range")};try{return staging.store.health.needsRecovery&&await staging.store.repair(),recovered(await held.reads.run(async()=>{held.shared.opened??=staging.open(held.shared.content);let bytes=await held.shared.opened;if(signal?.aborted)throw new CompactReadError("aborted");return producePage(bytes,offset,()=>held.reads.assert())}))}catch(cause){if(held.shared.opened=void 0,cause instanceof StagedReadError)return{ok:!1,failure:storageUnavailable("integrity")};if(!(cause instanceof CompactReadError))throw cause;return{ok:!1,failure:cause.reason==="released"?repairNeeded("released"):storageUnavailable(cause.reason)}}}release(caller,leaseId,admissionId){let peer=this.peers.get(caller.socketEpoch),receipt=(outcome,remaining)=>recovered({lease:{kind:"event",id:leaseId},outcome,remaining});if(!peer)return{ok:!1,failure:repairNeeded("unknown_token")};let held=peer.held.get(leaseId);if(held?.sessionId===caller.sessionId&&held.admissions.delete(admissionId))return this.remember(peer,held,admissionId),held.admissions.size>0?receipt("held",held.admissions.size):(this.released+=1,held.reads.release(),receipt("released",0));let done=peer.released.get(leaseId);return done?.sessionId===caller.sessionId&&done.admissions.has(admissionId)?(this.duplicates+=1,receipt("duplicate",held?.admissions.size??0)):{ok:!1,failure:repairNeeded("unknown_token")}}abandon(socketEpoch,leaseId){let held=this.peers.get(socketEpoch)?.held.get(leaseId);!held||!held.reads.release()||(this.abandoned+=1)}forgetAdmission(caller,admissionId){for(let held of this.peers.get(caller.socketEpoch)?.held.values()??[])held.sessionId!==caller.sessionId||!held.admissions.delete(admissionId)||held.admissions.size===0&&this.abandon(caller.socketEpoch,held.lease.id)}forgetPeer(socketEpoch){let peer=this.peers.get(socketEpoch);this.peers.delete(socketEpoch);for(let held of peer?.held.values()??[])held.reads.release()}status(){return{open:this.open,peers:this.peers.size,minted:this.minted,released:this.released,duplicates:this.duplicates,abandoned:this.abandoned,contentBytes:this.contentBytes,refused:Object.fromEntries(this.refusals)}}stage(record,content){let existing=this.shared.get(record);if(existing&&existing.holders>0)return existing;this.staging??=new TransferStaging(new CompactContentStore({dir:join5(tmpdir(),`senpi-event-leases-${randomUUID4()}`)}));try{let staged=stageRecord(this.staging,record,content);this.staging.adopt(staged);let shared={content:staged,holders:0};return this.contentBytes+=staged.ref.entry.length,this.shared.set(record,shared),shared}catch(cause){if(cause instanceof TransferStagingError||cause instanceof CompactWriteError||cause instanceof CompactReadError){process.stderr.write(`senpi rpc event lease: record not staged (${cause.message})
3
3
  `);return}throw cause}}remember(peer,held,admissionId){let admissions=new Set([...peer.released.get(held.lease.id)?.admissions??[],admissionId]);peer.released.set(held.lease.id,{sessionId:held.sessionId,admissions});for(let oldest of peer.released.keys()){if(peer.released.size<=RELEASED_LEASES_REMEMBERED)break;peer.released.delete(oldest)}}dispose(peer,held){peer.held.delete(held.lease.id),this.open-=1,held.shared.holders-=1,held.shared.holders===0&&this.staging&&(this.staging.release(held.shared.content),this.contentBytes-=held.shared.content.ref.entry.length);for(let listener of this.ended)listener(held.lease.id)}refuse(reason){return this.refusals.set(reason,(this.refusals.get(reason)??0)+1),{ok:!1,reason}}};var MESSAGE_KEY="message",COMPACT_DELTA_TYPES=new Set(["text_delta","thinking_delta","toolcall_delta"]);function compactDelta(value){if(value.type!=="message_update"||!Object.hasOwn(value,"message"))return;let event=value.assistantMessageEvent;if(typeof event!="object"||event===null)return;let{type,contentIndex,delta}=event;if(!(typeof type!="string"||!COMPACT_DELTA_TYPES.has(type)||typeof contentIndex!="number"||typeof delta!="string"))return{type,contentIndex,delta}}function demoteToDeltaOnly(value){let event=value.assistantMessageEvent;return{...value,message:null,assistantMessageEvent:{...event,partial:null}}}function toolUpdateKey(value){return value.type==="tool_execution_update"&&typeof value.toolCallId=="string"?`tool:${value.toolCallId}`:void 0}import{AsyncLocalStorage}from"node:async_hooks";var requests=new AsyncLocalStorage;function captureAdmissionReply(){let scope=requests.getStore();return scope&&{id:scope.command.id,admissionId:scope.command.admissionId,peer:scope.peer}}function withAdmissionReply(scope,action){return scope===void 0?action():requests.run({command:scope,peer:scope.peer},action)}function withAdmissionRequest(command,peer,action){return compactUpdatesEnabled()?requests.run({command,peer},action):action()}function replyAdmission(id,peer,routes){let request=requests.getStore();if(!request||request.command.id!==id||request.peer!==peer)return null;let admissionId=request.command.admissionId;return admissionId===void 0?void 0:routes.find(route=>route===admissionId)??null}var BaselineBarrier=class{constructor(cursor,live){this.cancelled=!1,this.ended=!1,this.cursor=cursor,this.live=live}get active(){return!this.cancelled&&!this.ended&&this.live()}cancel(){this.cancelled=!0,this.end()}end(){this.ended||(this.ended=!0,this.cursor.release())}async deliver(write,head){try{if(!this.active)return;let line=await this.cursor.next();for(head!==void 0&&this.active&&await write(head);line!==void 0&&this.active;)await write(line),line=await this.cursor.next()}finally{this.end()}}};var blockedMsTotal=0;function recordLoopBlockedMs(driftMs){driftMs>0&&(blockedMsTotal+=driftMs)}function loopBlockedMark(){return blockedMsTotal}function loopBlockedMsSince(mark){return blockedMsTotal-mark}var SocketEventQueueStallError=class extends Error{constructor(pendingBytes,stallMs){super(`socket event queue stalled: peer did not drain ${pendingBytes} queued bytes within ${stallMs}ms`),this.name="SocketEventQueueStallError",this.pendingBytes=pendingBytes,this.stallMs=stallMs}},SocketEventQueueOverflowError=class extends Error{constructor(queuedBytes,incomingBytes,maxQueueBytes,incomingPreview){super(`socket event queue overflow: ${queuedBytes} queued + ${incomingBytes} incoming > ${maxQueueBytes} (incoming: ${incomingPreview})`),this.name="SocketEventQueueOverflowError",this.queuedBytes=queuedBytes,this.incomingBytes=incomingBytes,this.maxQueueBytes=maxQueueBytes,this.incomingPreview=incomingPreview}};function waitForDrainOrStall(peer,writtenBytes){return new Promise((resolve2,reject)=>{let timer,blockedMark=loopBlockedMark(),cleanup=()=>{clearTimeout(timer),peer.stopped.removeEventListener("abort",onStop)},onStop=()=>{cleanup(),resolve2()},onDeadline=()=>{let blockedMs=loopBlockedMsSince(blockedMark);if(blockedMs>0){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,Math.min(blockedMs,peer.stallMs));return}try{if(peer.shedAndPing()){blockedMark=loopBlockedMark(),timer=setTimeout(onDeadline,peer.stallMs);return}}catch(cause){cleanup(),reject(cause);return}let stall=new SocketEventQueueStallError(peer.queuedBytes()+writtenBytes,peer.stallMs);try{peer.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"stalled, resync required"})}
4
4
  `)}catch{}cleanup(),reject(stall)};timer=setTimeout(onDeadline,peer.stallMs),peer.stopped.addEventListener("abort",onStop,{once:!0}),peer.sink.waitForBackpressure().then(()=>{cleanup(),resolve2()},cause=>{cleanup(),reject(cause)})})}var isBarrier=item=>"kind"in item,SocketEventQueue=class{constructor(){this.items=[],this.charged=0}get bytes(){return this.charged}get length(){return this.items.length}push(item){this.items.push(item),isBarrier(item)||(this.charged+=item.bytes)}shift(){let item=this.items.shift();return item!==void 0&&!isBarrier(item)&&(this.charged-=item.bytes),item}insertBefore(before,entry){let at=this.items.indexOf(before);at<0?this.items.push(entry):this.items.splice(at,0,entry),this.charged+=entry.bytes}supersede(key){let existing=this.items.find(item=>!isBarrier(item)&&item.key===key);existing===void 0||isBarrier(existing)||(existing.demotedLine!==void 0&&(this.charged-=existing.bytes,existing.line=existing.demotedLine,existing.bytes=Buffer.byteLength(existing.line),this.charged+=existing.bytes,existing.demotedLine=void 0,existing.onWritten?.(!1),existing.onWritten=void 0),existing.key=void 0)}retain(keep){let kept=[];for(let item of this.items)keep(item)?kept.push(item):isBarrier(item)?item.barrier.cancel():item.onWritten?.(!1);this.items=kept,this.charged=kept.reduce((bytes,item)=>isBarrier(item)?bytes:bytes+item.bytes,0)}clear(){for(let item of this.items)isBarrier(item)&&item.barrier.cancel();this.items.length=0,this.charged=0}};var SocketPeerShed=class{constructor(queue,mode){this.queue=queue,this.mode=mode}get isPending(){return this.pending!==void 0}get dropsRecords(){return this.pending!==void 0&&(this.mode==="drop"||this.pending.stale)}cut(reason,snapshot,live){this.queue.retain(item=>!isBarrier(item)&&item.reply);let cut=snapshot(reason);this.pending={kind:"recovery",reason,sessions:cut.sessions,barrier:new BaselineBarrier(cut,live),stale:!1},this.queue.push(this.pending)}supersede(){if(!this.pending||this.pending.stale)return;let recovery=this.pending;this.queue.retain(item=>isBarrier(item)?item===recovery:item.reply),recovery.barrier.cancel(),recovery.stale=!0}admitReply(entry){this.pending&&this.mode==="drop"?this.queue.insertBefore(this.pending,entry):this.queue.push(entry)}take(entry,snapshot,live){return entry.stale&&snapshot&&(entry.barrier=new BaselineBarrier(snapshot(entry.reason,entry.sessions),live)),this.pending===entry&&(this.pending=void 0),entry.barrier}clear(){this.pending=void 0}};var DEFAULT_QUEUE_BYTES=64*1024*1024,DEFAULT_STALL_MS=3e4,SocketEventSinkActor=class{constructor(sink,onFailure,maxQueueBytes=DEFAULT_QUEUE_BYTES,stallMs=DEFAULT_STALL_MS,shedMode="drop"){this.queue=new SocketEventQueue,this.closed=!1,this.recoveryEnabled=!1,this.frameBytes=0,this.stopped=new AbortController,this.sink=sink,this.onFailure=onFailure,this.maxQueueBytes=maxQueueBytes,this.shed=new SocketPeerShed(this.queue,shedMode),this.stallPeer={sink,stallMs,stopped:this.stopped.signal,queuedBytes:()=>this.queue.bytes,shedAndPing:()=>!this.recovery||!this.recoveryEnabled?!1:(this.cutOnce("stall"),this.recovery.ping(),!0)}}enableRecovery(snapshot){this.recoveryEnabled=!0,this.snapshot=snapshot,this.recovery??=new SocketPeerRecovery(line=>this.sink.writeRaw(line)),this.recovery.acknowledge()}disableRecovery(){this.recoveryEnabled=!1,this.recovery?.pending||(this.recovery=void 0)}installBaseline(cursor,live){if(this.closed||cursor.empty||this.shed.dropsRecords){cursor.release();return}this.queue.push({kind:"attach",barrier:new BaselineBarrier(cursor,live)}),this.drain()}enqueue(line,key,onWritten,demotedLine,reply=!1,held,current){if(this.closed)return;let bytes=Buffer.byteLength(line);if(this.shed.dropsRecords){reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1);return}if(key!==void 0&&this.queue.supersede(key),!this.fits(bytes)){if(this.recovery&&this.recoveryEnabled){this.shed.isPending?this.shed.supersede():this.cut("overflow"),reply?this.admitReply({line,bytes,onWritten,reply,current}):onWritten?.(!1),this.drain();return}this.failOverflow(bytes,line);return}this.queue.push({line,bytes,key,demotedLine,onWritten,reply,held:this.shed.isPending?held:void 0,current}),this.drain()}async flush(){for(;this.draining;)await this.draining;if(this.failure!==void 0)throw this.failure}waitForAcceptance(){return Promise.resolve()}close(){this.closed=!0,this.dropQueue(),this.stopped.abort()}fits(bytes){return this.queue.bytes+this.frameBytes+bytes<=this.maxQueueBytes}admitReply(entry){if(!this.fits(entry.bytes)){this.recovery?.loseReply(),entry.onWritten?.(!1);return}this.shed.admitReply(entry),this.drain()}failOverflow(bytes,line){let overflow=new SocketEventQueueOverflowError(this.queue.bytes+this.frameBytes,bytes,this.maxQueueBytes,line.slice(0,120));this.closed=!0,this.dropQueue();try{this.sink.writeRaw(`${JSON.stringify({type:"overflow",error:"overflow, resync required"})}
5
5
  `)}catch(cause){this.onFailure(cause)}this.onFailure(overflow)}dropQueue(){this.queue.clear(),this.attempt?.cancel(),this.shed.clear()}cutOnce(reason){this.recovery?.pending||this.cut(reason)}cut(reason){!this.recovery||!this.snapshot||(this.attempt?.cancel(),this.recovery.shed(reason),this.shed.cut(reason,this.snapshot,()=>!this.closed))}async write(line){this.sink.writeRaw(line),await waitForDrainOrStall(this.stallPeer,Buffer.byteLength(line))}async writeFrame(line){let bytes=Buffer.byteLength(line);if(!this.fits(bytes)){this.recovery&&this.recoveryEnabled?this.cutOnce("overflow"):this.failOverflow(bytes,line);return}this.frameBytes=bytes;try{await this.write(line)}finally{this.frameBytes=0}}async deliver(entry){if(entry.kind==="attach"){await this.stream(entry.barrier,line=>this.writeFrame(line));return}if(await waitForDrainOrStall(this.stallPeer,0),this.closed||!this.recovery)return;let barrier=this.shed.take(entry,this.snapshot,()=>!this.closed),gap=this.recovery.takeGap();this.recoveryEnabled||(this.recovery=void 0),await this.stream(barrier,line=>this.write(line),gap)}async stream(barrier,write,head){this.attempt=barrier;try{await barrier.deliver(write,head)}finally{barrier.end(),this.attempt===barrier&&(this.attempt=void 0)}}drain(){return this.draining?this.draining:(this.draining=(async()=>{try{for(;!this.closed&&this.queue.length>0;){let item=this.queue.shift();if(item===void 0)break;if(isBarrier(item)){try{await this.deliver(item)}finally{item.barrier.end()}continue}let written=(item.held?.()??!0)&&(item.current?.()??!0);written&&await this.write(item.line),item.onWritten?.(written)}}catch(cause){this.failure=cause,this.closed=!0,this.dropQueue(),this.onFailure(cause)}})().finally(()=>{this.draining=void 0,!this.closed&&this.queue.length>0&&this.drain()}),this.draining)}};var AdmissionRoutingActor=class extends SocketEventSinkActor{constructor(){super(...arguments),this.admissions=new Set,this.subscriptions=new Map,this.mirrorOwners=new Map,this.pendingMirrors=new Map,this.opened=new Map,this.retireAfterReply=new Map,this.terminal=new Map}close(){this.subscriptions.clear(),this.mirrorOwners.clear();for(let pending of this.pendingMirrors.values())pending.retire();this.pendingMirrors.clear(),this.admissions.clear(),this.opened.clear(),this.retireAfterReply.clear(),this.terminal.clear(),super.close()}remember(sessionId,checkpoints,socketEpoch){let stream=checkpoints.stream({socketEpoch,sessionId}),remembered=stream??this.terminal.get(sessionId),routes=remembered?.routes.filter(id=>this.admissions.has(id)||[...this.mirrorOwners.values()].includes(id))??[];return stream&&routes.length>0&&this.terminal.set(sessionId,{...stream,routes}),remembered?{...remembered,routes}:void 0}route(line,checkpoints,socketEpoch){if(this.admissions.size===0&&this.subscriptions.size===0&&this.mirrorOwners.size===0)return[line];let record=JSON.parse(line);if(typeof record.sessionId!="string"||record.admissionId!==void 0)return[line];if(typeof record.subscriptionId=="string"){let subscription=this.subscriptions.get(record.subscriptionId);return subscription===void 0?[line]:[serializeJsonLine({...record,admissionId:subscription,generation:0})]}let mirrors=record.type==="response"?[]:this.mirrorAdmissions?.(record.sessionId,String(record.type))??[],stream=this.remember(record.sessionId,checkpoints,socketEpoch),terminal2=record.type==="session_closed"||record.type==="session_parked",routes=[...new Set([...(stream?.routes??[]).filter(id=>this.admissions.has(id)||terminal2&&[...this.mirrorOwners.values()].includes(id)),...mirrors])];if(record.type==="response"&&typeof record.id=="string"){let admissionId=replyAdmission(record.id,this.peer,routes);return admissionId===null?[]:admissionId===void 0?[line]:[serializeJsonLine({...record,admissionId,generation:stream?.generation})]}return routes.length===0?[line]:routes.map(admissionId=>serializeJsonLine({...record,admissionId,generation:stream?.generation}))}deferRetire(id,retire){this.retireAfterReply.set(id,retire)}retireReplied(line){if(this.retireAfterReply.size===0)return;let record=JSON.parse(line);if(record.type!=="response"||typeof record.id!="string")return;let retire=this.retireAfterReply.get(record.id);this.retireAfterReply.delete(record.id),retire?.()}bind(checkpoints,socketEpoch,peer){this.peer=peer;let enqueue=super.enqueue.bind(this);this.enqueue=(line,key,written,demoted,reply,held)=>{let lines2=this.route(line,checkpoints,socketEpoch);if(this.retireReplied(line),lines2.length===0){written?.(!1);return}let replacements=demoted===void 0?void 0:this.route(demoted,checkpoints,socketEpoch),remaining=lines2.length,delivered=!1,receipt=ok=>{delivered||=ok,--remaining===0&&written?.(delivered)};for(let i=0;i<lines2.length;i++){let line2=lines2[i]??"",admissionId=Reflect.get(JSON.parse(line2),"admissionId"),pending=typeof admissionId=="string"?this.pendingMirrors.get(admissionId):void 0,deliver=()=>enqueue(lines2[i]??line2,key===void 0?void 0:`${key}:${i}`,receipt,replacements?.[i],reply,held);pending&&!reply?pending.enqueue(line2,deliver,()=>receipt(!1)):deliver()}}}};var CompactRequiredStreams=class{constructor(fanout,status){this.states=new WeakMap,this.fanout=fanout,this.status=status}sessions(peer){return this.status.requiredSessions(peer)}routes(peer,sessionId,type){let registered=this.fanout.get(peer),actor=registered?.actor;return!(actor instanceof AdmissionRoutingActor)||!registered?[]:[...new Set([...(this.fanout.checkpoints.stream({socketEpoch:registered.socketEpoch,sessionId})?.routes??[]).filter(id=>actor.admissions.has(id)),...this.status.mirrorAdmissions(peer,sessionId,type)])]}prepare(sessionId,record){let lane=this.fanout.acceptance.get(sessionId);if(!(!lane||lane.retired))for(let peer of this.fanout.connectionIds()){if(!this.fanout.connectionHas(peer,COMPACT_EVENTS_CAPABILITY))continue;let registered=this.fanout.get(peer),actor=registered?.actor;if(!(actor instanceof AdmissionRoutingActor)||!registered)continue;let routes=this.status.requiredAdmissions(peer,sessionId),caller={socketEpoch:registered.socketEpoch,sessionId};for(let admissionId of routes){if(this.fanout.checkpoints.stream(caller)?.routes.includes(admissionId))continue;let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId,routeKind:"mirror"},lane,!0);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);continue}}let stream=this.fanout.checkpoints.stream(caller);if(!stream?.routes.length)continue;let states=this.states.get(actor)??new Map;this.states.set(actor,states);let state=states.get(sessionId);if(state?.epoch!==lane.sessionEpoch&&(state={epoch:lane.sessionEpoch,dirty:!1},states.set(sessionId,state),state.seed=this.fanout.checkpoints.tokens().find(t=>t.admission.socketEpoch===caller.socketEpoch&&t.admission.sessionId===sessionId)),!record)continue;let type=String(Reflect.get(record,"type"));if(!(stream.routes.some(id=>actor.admissions.has(id))||this.status.mirrorAdmissions(peer,sessionId,type).length>0)){state.dirty=!0;continue}if(state.dirty){let frozen=this.fanout.checkpoints.freeze({...caller,peer,admissionId:stream.routes[0],routeKind:routes.length?"mirror":"ordinary"},lane);if(!frozen.ok){registered.close("checkpoint_unavailable",frozen.failure.reason);continue}state.seed=frozen.value.token,state.dirty=!1}}}takeSeed(peer,sessionId){let actor=this.fanout.get(peer)?.actor,state=actor instanceof AdmissionRoutingActor?this.states.get(actor)?.get(sessionId):void 0,seed=state?.seed;return state&&(state.seed=void 0),seed}forgetSession(sessionId){for(let peer of this.fanout.connectionIds()){let actor=this.fanout.get(peer)?.actor;actor instanceof AdmissionRoutingActor&&this.states.get(actor)?.delete(sessionId)}}};var LegacyRecordRefusals=class{constructor(){this.count=0}report(sessionId,refusal3){this.count+=1,process.stderr.write(`senpi rpc host: legacy record refused: ${refusal3.message} (session ${sessionId})