@code-yeongyu/senpi 2026.10.25-3 → 2026.10.26-1

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 (218) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/bundle/chunks/{anthropic-messages-WBASBTIW.js → anthropic-messages-M235FJQV.js} +3 -3
  3. package/dist/bundle/chunks/{args-B444OQBK.js → args-FBNJOJSR.js} +1 -1
  4. package/dist/bundle/chunks/azure-openai-responses-YQRTQ7H6.js +2 -0
  5. package/dist/bundle/chunks/bedrock-converse-stream.js +3 -3
  6. package/dist/bundle/chunks/{chunk-FFQOEC76.js → chunk-3A3XCLNH.js} +3 -3
  7. package/dist/bundle/chunks/{chunk-EHQXLHRB.js → chunk-3LPWILUZ.js} +2 -2
  8. package/dist/bundle/chunks/{chunk-3BTN337S.js → chunk-3WP5RFQR.js} +1 -1
  9. package/dist/bundle/chunks/{chunk-WLHNEUGD.js → chunk-5FQMNHXV.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-HVJI5T75.js → chunk-5KZH6EYQ.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-4P7WARQZ.js → chunk-5LWUUXMH.js} +1 -1
  12. package/dist/bundle/chunks/{chunk-ODTGC6YU.js → chunk-6U3TBFBA.js} +1 -1
  13. package/dist/bundle/chunks/chunk-6VWIMHMH.js +2 -0
  14. package/dist/bundle/chunks/{chunk-BWA4FVFW.js → chunk-7KOUQSBX.js} +2 -2
  15. package/dist/bundle/chunks/{chunk-7CNOCJCN.js → chunk-ADQAPDPV.js} +1 -1
  16. package/dist/bundle/chunks/{chunk-ITGYN22E.js → chunk-CDQPA4FP.js} +1 -1
  17. package/dist/bundle/chunks/{chunk-WDPQ6CZJ.js → chunk-DMFAVE5N.js} +1 -1
  18. package/dist/bundle/chunks/{chunk-XF3LJC3O.js → chunk-DYWIFF2Q.js} +1 -1
  19. package/dist/bundle/chunks/{chunk-YRF4I43T.js → chunk-EZP6AYW2.js} +37 -31
  20. package/dist/bundle/chunks/chunk-GQJYNFMO.js +2 -0
  21. package/dist/bundle/chunks/{chunk-O3Q2ET6W.js → chunk-GWGNVYPB.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-Z3UYNSVR.js → chunk-H4WJ4LY3.js} +1 -1
  23. package/dist/bundle/chunks/{chunk-UQNRW3VU.js → chunk-HWTD4QF3.js} +1 -1
  24. package/dist/bundle/chunks/{chunk-WD6WBYC5.js → chunk-I7QWTWVZ.js} +1 -1
  25. package/dist/bundle/chunks/{chunk-SWJXRC2I.js → chunk-J2YAYTB2.js} +1 -1
  26. package/dist/bundle/chunks/{chunk-TTU2RNVX.js → chunk-J5FCH7TI.js} +1 -1
  27. package/dist/bundle/chunks/chunk-JFQUWEN7.js +13 -0
  28. package/dist/bundle/chunks/{chunk-JA2R2ZSE.js → chunk-L2O6K3SJ.js} +1 -1
  29. package/dist/bundle/chunks/{chunk-4AOMNOGY.js → chunk-LO5MYLGF.js} +1 -1
  30. package/dist/bundle/chunks/{chunk-P3M2PF6K.js → chunk-MSHRIZGT.js} +8 -6
  31. package/dist/bundle/chunks/{chunk-T36LJ6MW.js → chunk-MY4ZD3EW.js} +1 -1
  32. package/dist/bundle/chunks/{chunk-UFJ2K7Q7.js → chunk-OQ3WDMB3.js} +1 -1
  33. package/dist/bundle/chunks/{chunk-7GZUFOM3.js → chunk-PH3JDRB2.js} +1 -1
  34. package/dist/bundle/chunks/{chunk-E6WYH3ZL.js → chunk-QREKAXKX.js} +7 -5
  35. package/dist/bundle/chunks/{chunk-MJ5NNWX4.js → chunk-QYFOHFPS.js} +1 -1
  36. package/dist/bundle/chunks/chunk-SOXQ42VS.js +2 -0
  37. package/dist/bundle/chunks/{chunk-FHXR4ZAC.js → chunk-UDM7VO6O.js} +1 -1
  38. package/dist/bundle/chunks/{chunk-OLCDIITS.js → chunk-UW6M3EXY.js} +1 -1
  39. package/dist/bundle/chunks/chunk-VICDRG3J.js +410 -0
  40. package/dist/bundle/chunks/chunk-VL7O5PO4.js +5 -0
  41. package/dist/bundle/chunks/chunk-XMJKZK5H.js +2 -0
  42. package/dist/bundle/chunks/{chunk-C5UFJ7B3.js → chunk-XMNPK472.js} +1 -1
  43. package/dist/bundle/chunks/{chunk-GSSD3R5X.js → chunk-XQ45JMGN.js} +1 -1
  44. package/dist/bundle/chunks/{client-WTYEICLH.js → chunk-Y3TMJV3J.js} +3 -3
  45. package/dist/bundle/chunks/{chunk-KXB5WIS5.js → chunk-Z6SAQ5O3.js} +1 -1
  46. package/dist/bundle/chunks/{chunk-CNL6QSUB.js → chunk-ZAUVY6ZC.js} +3 -3
  47. package/dist/bundle/chunks/{chunk-E4LBKOZG.js → chunk-ZLIVZQDY.js} +4 -4
  48. package/dist/bundle/chunks/{chunk-6AOVUTUR.js → chunk-ZXHLH4MW.js} +2 -2
  49. package/dist/bundle/chunks/cli-main-55EQA5PS.js +3 -0
  50. package/dist/bundle/chunks/client-LOS6GSEW.js +2 -0
  51. package/dist/bundle/chunks/{cloudflare-workers-ai-system-one-K5H6BJP3.js → cloudflare-workers-ai-system-one-ZJQGIIRC.js} +1 -1
  52. package/dist/bundle/chunks/cursor-agent.js +3 -3
  53. package/dist/bundle/chunks/devin-agent.js +3 -3
  54. package/dist/bundle/chunks/dispatch-C2IBP5VV.js +9 -0
  55. package/dist/bundle/chunks/google-generative-ai-5G4RIQA6.js +2 -0
  56. package/dist/bundle/chunks/google-vertex-ALD4P27O.js +2 -0
  57. package/dist/bundle/chunks/{help-fast-path-3Z26DQSV.js → help-fast-path-PEIKGCKZ.js} +1 -1
  58. package/dist/bundle/chunks/host-command-657VCQ34.js +2 -0
  59. package/dist/bundle/chunks/{host-lifecycle-ONQIMWMX.js → host-lifecycle-HX3EGRRW.js} +1 -1
  60. package/dist/bundle/chunks/host-lifecycle.js +2 -2
  61. package/dist/bundle/chunks/{host-session-command-J65ENSV5.js → host-session-command-OV5XDOJK.js} +1 -1
  62. package/dist/bundle/chunks/{host-socket-request-3CWE4265.js → host-socket-request-K4LCUOUD.js} +1 -1
  63. package/dist/bundle/chunks/interactive-mode-MLXSYK2H.js +2 -0
  64. package/dist/bundle/chunks/{mcp-presenter-bootstrap-XUSCQVRC.js → mcp-presenter-bootstrap-FOMKF4TU.js} +1 -1
  65. package/dist/bundle/chunks/{mistral-conversations-DH44NOYV.js → mistral-conversations-RAE4K2XY.js} +1 -1
  66. package/dist/bundle/chunks/{multi-session-host-YI2WZOET.js → multi-session-host-774MACJU.js} +5 -6
  67. package/dist/bundle/chunks/{openai-codex-responses-SERAFKAS.js → openai-codex-responses-3CW4R7TG.js} +1 -1
  68. package/dist/bundle/chunks/{openai-completions-BZB5O45A.js → openai-completions-5UIJXQUF.js} +1 -1
  69. package/dist/bundle/chunks/openai-responses-2BO44MRW.js +3 -0
  70. package/dist/bundle/chunks/{package-manager-cli-GHZPJMRF.js → package-manager-cli-MZHVCX2S.js} +1 -1
  71. package/dist/bundle/chunks/{pi-messages-VXATX45B.js → pi-messages-RF6GER4R.js} +2 -2
  72. package/dist/bundle/chunks/{role-JVSBNKGE.js → role-ETSFSDTS.js} +1 -1
  73. package/dist/bundle/chunks/rotation-stream-ZMQB4GPO.js +2 -0
  74. package/dist/bundle/chunks/rpc-mode-UJXOIZCW.js +2 -0
  75. package/dist/bundle/chunks/{rpc-monitor-source-FFEQS744.js → rpc-monitor-source-DRZXJHTL.js} +1 -1
  76. package/dist/bundle/chunks/{schedule-command-YWG6D6ZF.js → schedule-command-KA7LFFNK.js} +1 -1
  77. package/dist/bundle/chunks/session-control-endpoint-MFWXUR7Z.js +3 -0
  78. package/dist/bundle/chunks/session-picker-BP33NRSL.js +2 -0
  79. package/dist/bundle/chunks/session-worker.js +212 -203
  80. package/dist/bundle/chunks/{typesafe-system-one-P75WJ767.js → typesafe-system-one-GNNZ5O5U.js} +1 -1
  81. package/dist/bundle/cli.js +2 -2
  82. package/dist/bundle/host-supervisor.js +2 -2
  83. package/dist/bundle/index.js +1 -1
  84. package/dist/bundle/rpc-entry.js +1 -1
  85. package/dist/bundle/runtime-manifest.json +1 -1
  86. package/dist/cli/host-command-args.d.ts +1 -0
  87. package/dist/cli/host-command-args.js +5 -0
  88. package/dist/cli/host-command.js +7 -1
  89. package/dist/cli.js +21 -3
  90. package/dist/core/extensions/builtin/mcp/catalog-cache.d.ts +2 -1
  91. package/dist/core/extensions/builtin/mcp/catalog-cache.js +19 -6
  92. package/dist/core/extensions/builtin/mcp/catalog.d.ts +3 -2
  93. package/dist/core/extensions/builtin/mcp/catalog.js +20 -3
  94. package/dist/core/extensions/builtin/mcp/elicitation.js +2 -4
  95. package/dist/core/extensions/builtin/mcp/expose/call.d.ts +2 -1
  96. package/dist/core/extensions/builtin/mcp/expose/call.js +2 -1
  97. package/dist/core/extensions/builtin/mcp/expose/register.js +1 -1
  98. package/dist/core/extensions/builtin/mcp/expose/schema-compat.d.ts +2 -2
  99. package/dist/core/extensions/builtin/mcp/expose/schema-compat.js +11 -1
  100. package/dist/core/extensions/builtin/mcp/invocation.js +16 -2
  101. package/dist/core/extensions/builtin/mcp/modern/request.d.ts +1 -1
  102. package/dist/core/extensions/builtin/mcp/modern/request.js +1 -1
  103. package/dist/core/extensions/builtin/mcp/modern/sdk-bridge.js +18 -3
  104. package/dist/core/extensions/builtin/mcp/modern/stdio-probe.js +23 -0
  105. package/dist/core/extensions/builtin/mcp/modern/subscriptions.d.ts +14 -0
  106. package/dist/core/extensions/builtin/mcp/modern/subscriptions.js +226 -0
  107. package/dist/core/extensions/builtin/mcp/modern/tool-schema.d.ts +13 -0
  108. package/dist/core/extensions/builtin/mcp/modern/tool-schema.js +75 -0
  109. package/dist/core/extensions/builtin/mcp/modern/tools.d.ts +107 -0
  110. package/dist/core/extensions/builtin/mcp/modern/tools.js +53 -0
  111. package/dist/core/extensions/builtin/mcp/resources.js +4 -0
  112. package/dist/core/extensions/builtin/mcp/tool-client.d.ts +13 -0
  113. package/dist/core/extensions/builtin/mcp/tool-client.js +17 -0
  114. package/dist/core/extensions/builtin/mcp/tool-contracts.d.ts +19 -0
  115. package/dist/core/extensions/builtin/mcp/tool-contracts.js +2 -0
  116. package/dist/core/extensions/builtin/mcp/wrap.js +2 -2
  117. package/dist/core/extensions/builtin/permission-system/bash-command-segments.d.ts +37 -0
  118. package/dist/core/extensions/builtin/permission-system/bash-command-segments.js +899 -0
  119. package/dist/core/extensions/builtin/permission-system/parsers.d.ts +2 -0
  120. package/dist/core/extensions/builtin/permission-system/parsers.js +44 -10
  121. package/dist/core/session-control-actions.js +0 -2
  122. package/dist/modes/interactive/session-control-attach.d.ts +20 -0
  123. package/dist/modes/interactive/session-control-attach.js +13 -0
  124. package/dist/modes/interactive/session-control-commands.js +37 -10
  125. package/dist/modes/interactive/session-control-registry.d.ts +2 -1
  126. package/dist/modes/interactive/session-control-registry.js +3 -2
  127. package/dist/modes/interactive/session-control-rpc-commands.d.ts +4 -2
  128. package/dist/modes/interactive/session-control-rpc-commands.js +133 -4
  129. package/dist/modes/interactive/session-control-server.js +9 -3
  130. package/dist/modes/rpc/compact-content-store.d.ts +96 -0
  131. package/dist/modes/rpc/compact-content-store.js +269 -0
  132. package/dist/modes/rpc/compact-session-state.d.ts +111 -0
  133. package/dist/modes/rpc/compact-session-state.js +206 -0
  134. package/dist/modes/rpc/compact-spool-dir.d.ts +5 -0
  135. package/dist/modes/rpc/compact-spool-dir.js +61 -0
  136. package/dist/modes/rpc/compact-storage-io.d.ts +27 -0
  137. package/dist/modes/rpc/compact-storage-io.js +19 -0
  138. package/dist/modes/rpc/connection-handler.d.ts +2 -0
  139. package/dist/modes/rpc/connection-handler.js +45 -47
  140. package/dist/modes/rpc/connection-question-bridge.d.ts +2 -1
  141. package/dist/modes/rpc/connection-question-bridge.js +6 -2
  142. package/dist/modes/rpc/custom-capability.d.ts +6 -0
  143. package/dist/modes/rpc/custom-capability.js +6 -0
  144. package/dist/modes/rpc/extension-ui-response.d.ts +7 -2
  145. package/dist/modes/rpc/extension-ui-response.js +27 -7
  146. package/dist/modes/rpc/get-entries-command.d.ts +13 -0
  147. package/dist/modes/rpc/get-entries-command.js +61 -0
  148. package/dist/modes/rpc/get-entries-page.d.ts +22 -0
  149. package/dist/modes/rpc/get-entries-page.js +41 -2
  150. package/dist/modes/rpc/get-snapshot.d.ts +18 -0
  151. package/dist/modes/rpc/get-snapshot.js +43 -0
  152. package/dist/modes/rpc/host-capabilities.js +7 -1
  153. package/dist/modes/rpc/host-ensure-start.js +1 -0
  154. package/dist/modes/rpc/host-ensure-types.d.ts +2 -0
  155. package/dist/modes/rpc/host-ensure.js +1 -0
  156. package/dist/modes/rpc/host-handoff.d.ts +2 -0
  157. package/dist/modes/rpc/host-handover-request.d.ts +1 -1
  158. package/dist/modes/rpc/host-handover-request.js +4 -3
  159. package/dist/modes/rpc/host-handover-wire.js +6 -0
  160. package/dist/modes/rpc/host-idle-handover.d.ts +2 -0
  161. package/dist/modes/rpc/host-idle-handover.js +3 -1
  162. package/dist/modes/rpc/host-observe-request.d.ts +2 -1
  163. package/dist/modes/rpc/host-observe-request.js +5 -1
  164. package/dist/modes/rpc/host-runner.d.ts +1 -0
  165. package/dist/modes/rpc/host-runner.js +9 -7
  166. package/dist/modes/rpc/host-successor.js +4 -0
  167. package/dist/modes/rpc/json-normal-value.d.ts +6 -0
  168. package/dist/modes/rpc/json-normal-value.js +100 -0
  169. package/dist/modes/rpc/mcp-presenter-bootstrap.js +5 -0
  170. package/dist/modes/rpc/media-placeholders.d.ts +9 -3
  171. package/dist/modes/rpc/media-placeholders.js +12 -4
  172. package/dist/modes/rpc/rpc-host-command-types.d.ts +2 -0
  173. package/dist/modes/rpc/rpc-question-types.d.ts +1 -0
  174. package/dist/modes/rpc/rpc-read-response-types.d.ts +9 -0
  175. package/dist/modes/rpc/rpc-session-command-types.d.ts +14 -1
  176. package/dist/modes/rpc/rpc-session-state-types.d.ts +3 -0
  177. package/dist/modes/rpc/rpc-session-state.js +2 -0
  178. package/dist/modes/rpc/rpc-types.d.ts +1 -0
  179. package/dist/modes/rpc/session-attachment-gate.js +1 -0
  180. package/dist/modes/rpc/session-binding.js +21 -18
  181. package/dist/modes/rpc/session-command-activity.js +1 -0
  182. package/dist/modes/rpc/session-event-fanout.d.ts +1 -1
  183. package/dist/modes/rpc/session-event-fanout.js +17 -9
  184. package/dist/modes/rpc/session-event-writer.js +22 -5
  185. package/dist/modes/rpc/session-extension-ui-requests.d.ts +2 -1
  186. package/dist/modes/rpc/session-extension-ui-requests.js +15 -10
  187. package/dist/modes/rpc/session-held.js +1 -0
  188. package/dist/modes/rpc/session-status-stream.d.ts +2 -1
  189. package/dist/modes/rpc/session-status-stream.js +8 -2
  190. package/dist/modes/rpc/session-status-subscriptions.d.ts +2 -1
  191. package/dist/modes/rpc/session-status-subscriptions.js +4 -0
  192. package/dist/modes/rpc/session-worker.js +5 -2
  193. package/dist/modes/rpc/snapshot-types.d.ts +29 -0
  194. package/dist/modes/rpc/snapshot-types.js +2 -0
  195. package/dist/modes/rpc/ui-answer-ledger.d.ts +13 -0
  196. package/dist/modes/rpc/ui-answer-ledger.js +34 -0
  197. package/dist/senpi +21 -3
  198. package/docs/mcp.md +20 -0
  199. package/docs/rpc.md +87 -11
  200. package/package.json +7 -6
  201. package/dist/bundle/chunks/azure-openai-responses-7I45DI72.js +0 -2
  202. package/dist/bundle/chunks/chunk-3LNSLJ7N.js +0 -2
  203. package/dist/bundle/chunks/chunk-6O4SEW2W.js +0 -5
  204. package/dist/bundle/chunks/chunk-7W7OJDIY.js +0 -410
  205. package/dist/bundle/chunks/chunk-DMI55M2N.js +0 -2
  206. package/dist/bundle/chunks/chunk-H3HNMY2W.js +0 -13
  207. package/dist/bundle/chunks/chunk-MSQCTH6V.js +0 -2
  208. package/dist/bundle/chunks/cli-main-HEKFFB5S.js +0 -3
  209. package/dist/bundle/chunks/dispatch-NYAULNVW.js +0 -9
  210. package/dist/bundle/chunks/google-generative-ai-UM5Y7T6B.js +0 -2
  211. package/dist/bundle/chunks/google-vertex-OKU2VQHL.js +0 -2
  212. package/dist/bundle/chunks/host-command-Z3WPHJOW.js +0 -2
  213. package/dist/bundle/chunks/interactive-mode-DEPQC6TX.js +0 -2
  214. package/dist/bundle/chunks/openai-responses-TNHQ6SJS.js +0 -3
  215. package/dist/bundle/chunks/rotation-stream-ZPVCFOVD.js +0 -2
  216. package/dist/bundle/chunks/rpc-mode-ORHBGBBV.js +0 -2
  217. package/dist/bundle/chunks/session-control-endpoint-36HAQSQO.js +0 -3
  218. package/dist/bundle/chunks/session-picker-25H5KNYP.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{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{MISTRAL_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-GSSD3R5X.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-4P7WARQZ.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-6AOVUTUR.js";import{AssistantMessageEventStream}from"./chunk-DMI55M2N.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream,normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),preserveThinking=options?.promptMode==="reasoning"||options?.reasoningEffort!==void 0&&options.reasoningEffort!=="none",transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeMistralToolCallId(id),{preserveThinking}),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
2
+ import{getPiUserAgent}from"./chunk-QTG7MY2X.js";import{MISTRAL_RESERVED_BODY_KEYS,applyExtraBody,buildBaseOptions}from"./chunk-XQ45JMGN.js";import{getJsonSchemaToolParameters,resolveJsonSchemaStrictSampling,shortHash,transformMessages}from"./chunk-5LWUUXMH.js";import{sanitizeSurrogates}from"./chunk-WDTJ6JKE.js";import{parseStreamingJson}from"./chunk-3W47LTXQ.js";import{calculateCost,clampThinkingLevel,getCurrentTools,getSystemMessageText,renderSystemMessageUpdate,resolveTranscript}from"./chunk-ZXHLH4MW.js";import{AssistantMessageEventStream}from"./chunk-GQJYNFMO.js";import{headersToRecord}from"./chunk-PJ34QVL5.js";import"./chunk-IKOFCODM.js";var MISTRAL_TOOL_CALL_ID_LENGTH=9,MAX_MISTRAL_ERROR_BODY_CHARS=4e3,stream=(model,context,options)=>{let stream2=new AssistantMessageEventStream({captureBlocks:!0}),normalizedContext=resolveTranscript(context,model.compat?.supportsMidConvoSystemMessages);return(async()=>{let output=createOutput(model);try{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let normalizeMistralToolCallId=createMistralToolCallIdNormalizer(),preserveThinking=options?.promptMode==="reasoning"||options?.reasoningEffort!==void 0&&options.reasoningEffort!=="none",transformedMessages=transformMessages(normalizedContext.messages,model,id=>normalizeMistralToolCallId(id),{preserveThinking}),payload=buildChatPayload(model,normalizedContext,transformedMessages,options),nextPayload=await options?.onPayload?.(payload,model);nextPayload!==void 0&&(payload=nextPayload);let mistralStream=await requestMistralStream(model,payload,apiKey,options);if(stream2.push({type:"start",partial:output}),await consumeChatStream(model,output,stream2,mistralStream,options?.onProviderStreamEvent),options?.signal?.aborted)throw new Error("Request was aborted");if(output.stopReason==="pending")throw new Error("Mistral stream ended without a finish reason");if(output.stopReason==="aborted"||output.stopReason==="error")throw new Error(output.errorMessage||"An unknown error occurred");stream2.push({type:"done",reason:output.stopReason,message:output}),stream2.end()}catch(error){for(let block of output.content)delete block.partialArgs;output.stopReason=options?.signal?.aborted?"aborted":"error",output.errorMessage=formatMistralError(error),stream2.push({type:"error",reason:output.stopReason,error:output}),stream2.end()}})(),stream2},streamSimple=(model,context,options)=>{let apiKey=options?.apiKey;if(!apiKey)throw new Error(`No API key for provider: ${model.provider}`);let base={...buildBaseOptions(model,context,options,apiKey),toolChoice:options?.toolChoice},clampedReasoning=options?.reasoning?clampThinkingLevel(model,options.reasoning):void 0,reasoning=clampedReasoning==="off"?void 0:clampedReasoning,effortMap=model.reasoning?model.thinkingLevelMap:void 0,reasoningEffort=effortMap?reasoning?effortMap[reasoning]??"high":effortMap.off??void 0:void 0;return stream(model,context,{...base,promptMode:model.reasoning&&!effortMap&&reasoning?"reasoning":void 0,reasoningEffort})};function createOutput(model){return{role:"assistant",content:[],api:model.api,provider:model.provider,model:model.id,usage:{input:0,output:0,cacheRead:0,cacheWrite:0,totalTokens:0,cost:{input:0,output:0,cacheRead:0,cacheWrite:0,total:0}},stopReason:"pending",timestamp:Date.now()}}function createMistralToolCallIdNormalizer(){let idMap=new Map,reverseMap=new Map;return id=>{let existing=idMap.get(id);if(existing)return existing;let attempt=0;for(;;){let candidate=deriveMistralToolCallId(id,attempt),owner=reverseMap.get(candidate);if(!owner||owner===id)return idMap.set(id,candidate),reverseMap.set(candidate,id),candidate;attempt++}}}function deriveMistralToolCallId(id,attempt){let normalized=id.replace(/[^a-zA-Z0-9]/g,"");if(attempt===0&&normalized.length===MISTRAL_TOOL_CALL_ID_LENGTH)return normalized;let seedBase=normalized||id,seed=attempt===0?seedBase:`${seedBase}:${attempt}`;return shortHash(seed).replace(/[^a-zA-Z0-9]/g,"").slice(0,MISTRAL_TOOL_CALL_ID_LENGTH)}function formatMistralError(error){if(error instanceof Error){let httpError=error,statusCode=typeof httpError.statusCode=="number"?httpError.statusCode:void 0,bodyText=typeof httpError.body=="string"?httpError.body.trim():void 0;return statusCode!==void 0&&bodyText?`Mistral API error (${statusCode}): ${truncateErrorText(bodyText,MAX_MISTRAL_ERROR_BODY_CHARS)}`:statusCode!==void 0?`Mistral API error (${statusCode}): ${error.message}`:error.message}return safeJsonStringify(error)}function truncateErrorText(text,maxChars){return text.length<=maxChars?text:`${text.slice(0,maxChars)}... [truncated ${text.length-maxChars} chars]`}function safeJsonStringify(value){try{let serialized=JSON.stringify(value);return serialized===void 0?String(value):serialized}catch{return String(value)}}async function requestMistralStream(model,payload,apiKey,options){let baseUrl=new URL(model.baseUrl);baseUrl.pathname=`${baseUrl.pathname.replace(/\/+$/u,"")}/`;let url=new URL("v1/chat/completions",baseUrl),headers=buildMistralHeaders(model,apiKey,options),timeoutSignal=AbortSignal.timeout(options?.timeoutMs??6e4),signal=options?.signal?AbortSignal.any([options.signal,timeoutSignal]):timeoutSignal,response=await(options?.fetch??globalThis.fetch)(url,{method:"POST",headers,body:JSON.stringify(toMistralWirePayload(payload)),signal});if(await options?.onResponse?.({status:response.status,headers:headersToRecord(response.headers)},model),!response.ok){let body=await response.text();throw new MistralHttpError(response.status,body,response.statusText)}if(!response.body)throw new Error("Mistral response has no body");return readMistralEvents(response.body,signal)}var MistralHttpError=class extends Error{constructor(statusCode,body,statusText){super(statusText||`Request failed with status ${statusCode}`),this.name="MistralHttpError",this.statusCode=statusCode,this.body=body}};function buildMistralHeaders(model,apiKey,options){let headers=new Headers({"User-Agent":getPiUserAgent(),accept:"text/event-stream",authorization:`Bearer ${apiKey}`,"content-type":"application/json"});applyMistralHeaderOverrides(headers,model.headers),applyMistralHeaderOverrides(headers,options?.headers);let hasExplicitAffinity=hasMistralHeaderOverride(model.headers,"x-affinity")||hasMistralHeaderOverride(options?.headers,"x-affinity");return shouldUsePromptCaching(options)&&!hasExplicitAffinity&&headers.set("x-affinity",options.sessionId),headers}function applyMistralHeaderOverrides(headers,overrides){if(overrides)for(let[name,value]of Object.entries(overrides))value===null?headers.delete(name):headers.set(name,value)}function hasMistralHeaderOverride(overrides,target){return!!overrides&&Object.keys(overrides).some(name=>name.toLowerCase()===target)}function toMistralWirePayload(payload){let wirePayload={...payload};for(let[source,target]of[["topP","top_p"],["maxTokens","max_tokens"],["randomSeed","random_seed"],["responseFormat","response_format"],["toolChoice","tool_choice"],["presencePenalty","presence_penalty"],["frequencyPenalty","frequency_penalty"],["parallelToolCalls","parallel_tool_calls"],["reasoningEffort","reasoning_effort"],["promptMode","prompt_mode"],["promptCacheKey","prompt_cache_key"],["safePrompt","safe_prompt"]])remapMistralProperty(wirePayload,source,target);wirePayload.messages=payload.messages.map(message=>toMistralWireMessage(message));let responseFormat=wirePayload.response_format;if(isMistralRecord(responseFormat)){let wireResponseFormat={...responseFormat};remapMistralProperty(wireResponseFormat,"jsonSchema","json_schema");let jsonSchema=wireResponseFormat.json_schema;if(isMistralRecord(jsonSchema)){let wireJsonSchema={...jsonSchema};remapMistralProperty(wireJsonSchema,"schemaDefinition","schema"),wireResponseFormat.json_schema=wireJsonSchema}wirePayload.response_format=wireResponseFormat}return wirePayload}function toMistralWireMessage(message){let wireMessage={...message};return remapMistralProperty(wireMessage,"toolCalls","tool_calls"),remapMistralProperty(wireMessage,"toolCallId","tool_call_id"),Array.isArray(message.content)&&(wireMessage.content=message.content.map(chunk=>toMistralWireContentChunk(chunk))),wireMessage}function toMistralWireContentChunk(chunk){let wireChunk={...chunk};for(let[source,target]of[["imageUrl","image_url"],["documentUrl","document_url"],["documentName","document_name"],["fileId","file_id"],["referenceIds","reference_ids"],["inputAudio","input_audio"]])remapMistralProperty(wireChunk,source,target);return wireChunk}function remapMistralProperty(record,source,target){source in record&&(record[target]=record[source],delete record[source])}function isMistralRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var MISTRAL_STREAM_DONE=Symbol("mistral-stream-done");async function*readMistralEvents(body,signal){let reader=body.getReader(),decoder=new TextDecoder,buffer="",onAbort=()=>{reader.cancel().catch(()=>{})};signal.addEventListener("abort",onAbort,{once:!0});try{for(;;){if(signal.aborted)throw signal.reason;let{done,value}=await reader.read();if(signal.aborted)throw signal.reason;buffer+=done?decoder.decode():decoder.decode(value,{stream:!0});let boundary=findMistralEventBoundary(buffer);for(;boundary;){let event=parseMistralEvent(buffer.slice(0,boundary.index));if(buffer=buffer.slice(boundary.index+boundary.length),event===MISTRAL_STREAM_DONE)return;event&&(yield event),boundary=findMistralEventBoundary(buffer)}if(done)break}if(buffer.trim()){let event=parseMistralEvent(buffer);event!==MISTRAL_STREAM_DONE&&event&&(yield event)}}finally{signal.removeEventListener("abort",onAbort);try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function findMistralEventBoundary(buffer){let match=/\r\n\r\n|\r\n\r|\r\n\n|\r\r\n|\n\r\n|\r\r|\n\r|\n\n/u.exec(buffer);return match?.index===void 0?void 0:{index:match.index,length:match[0].length}}function parseMistralEvent(raw){let data=raw.split(/\r\n|\r|\n/u).filter(line=>line.startsWith("data:")).map(line=>line.slice(5).trimStart()).join(`
3
3
  `).trim();if(!data)return;if(data==="[DONE]")return MISTRAL_STREAM_DONE;let parsed=JSON.parse(data);if(!isMistralRecord(parsed)||!Array.isArray(parsed.choices))throw new Error("Invalid Mistral streaming event");return{data:parsed}}function buildChatPayload(model,context,messages,options){let payload={model:model.id,stream:!0,messages:toChatMessages(messages,model.input.includes("image"))},currentTools=getCurrentTools(context.messages);return currentTools.length>0&&(payload.tools=toFunctionTools(currentTools)),options?.temperature!==void 0&&(payload.temperature=options.temperature),options?.maxTokens!==void 0&&(payload.maxTokens=options.maxTokens),options?.toolChoice&&(payload.toolChoice=mapToolChoice(options.toolChoice)),options?.promptMode&&(payload.promptMode=options.promptMode),options?.reasoningEffort&&(payload.reasoningEffort=options.reasoningEffort),shouldUsePromptCaching(options)&&(payload.promptCacheKey=options.sessionId),applyExtraBody(payload,options?.extraBody,MISTRAL_RESERVED_BODY_KEYS),payload}function shouldUsePromptCaching(options){return options?.cacheRetention!=="none"&&!!options?.sessionId}function getMistralCachedPromptTokens(usage,promptTokens){let rawUsage=usage,rawCachedTokens=rawUsage.promptTokensDetails?.cachedTokens??rawUsage.prompt_tokens_details?.cached_tokens??rawUsage.promptTokenDetails?.cachedTokens??rawUsage.prompt_token_details?.cached_tokens??rawUsage.numCachedTokens??rawUsage.num_cached_tokens??0,cachedTokens=typeof rawCachedTokens=="number"&&Number.isFinite(rawCachedTokens)?rawCachedTokens:0;return Math.min(promptTokens,Math.max(0,cachedTokens))}async function consumeChatStream(model,output,stream2,mistralStream,onProviderStreamEvent){let currentBlock=null,blocks=output.content,blockIndex=()=>blocks.length-1,toolBlocksByKey=new Map,finishCurrentBlock=block=>{if(block){if(block.type==="text"){stream2.push({type:"text_end",contentIndex:blockIndex(),content:block.text,partial:output});return}block.type==="thinking"&&stream2.push({type:"thinking_end",contentIndex:blockIndex(),content:block.thinking,partial:output})}};for await(let event of mistralStream){let chunk=event.data;if(await onProviderStreamEvent?.(chunk,model),output.responseId||=chunk.id,chunk.usage){let promptTokens=chunk.usage.prompt_tokens||0,cachedPromptTokens=getMistralCachedPromptTokens(chunk.usage,promptTokens);output.usage.input=Math.max(0,promptTokens-cachedPromptTokens),output.usage.output=chunk.usage.completion_tokens||0,output.usage.cacheRead=cachedPromptTokens,output.usage.cacheWrite=0,output.usage.totalTokens=chunk.usage.total_tokens||output.usage.input+output.usage.output+output.usage.cacheRead+output.usage.cacheWrite,calculateCost(model,output.usage)}let choice=chunk.choices[0];if(!choice)continue;if(choice.finish_reason){output.rawStopReason=choice.finish_reason;let stopReasonResult=mapChatStopReason(choice.finish_reason);output.stopReason=stopReasonResult.stopReason,stopReasonResult.errorMessage&&(output.errorMessage=stopReasonResult.errorMessage)}let delta=choice.delta;if(delta.content!==null&&delta.content!==void 0){let contentItems=typeof delta.content=="string"?[delta.content]:delta.content;for(let item of contentItems){if(typeof item=="string"){let textDelta=sanitizeSurrogates(item);if(!textDelta)continue;currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output});continue}if(item.type==="thinking"){let deltaText=(item.thinking??[]).map(part=>part.text??"").filter(text=>text.length>0).join(""),thinkingDelta=sanitizeSurrogates(deltaText);if(!thinkingDelta)continue;currentBlock?.type!=="thinking"&&(finishCurrentBlock(currentBlock),currentBlock={type:"thinking",thinking:""},output.content.push(currentBlock),stream2.push({type:"thinking_start",contentIndex:blockIndex(),partial:output})),currentBlock.thinking+=thinkingDelta,stream2.push({type:"thinking_delta",contentIndex:blockIndex(),delta:thinkingDelta,partial:output});continue}if(item.type==="text"){let textDelta=sanitizeSurrogates(item.text??"");if(!textDelta)continue;currentBlock?.type!=="text"&&(finishCurrentBlock(currentBlock),currentBlock={type:"text",text:""},output.content.push(currentBlock),stream2.push({type:"text_start",contentIndex:blockIndex(),partial:output})),currentBlock.text+=textDelta,stream2.push({type:"text_delta",contentIndex:blockIndex(),delta:textDelta,partial:output})}}}let toolCalls=delta.tool_calls||[];for(let toolCall of toolCalls){currentBlock&&(finishCurrentBlock(currentBlock),currentBlock=null);let callId=toolCall.id&&toolCall.id!=="null"?toolCall.id:deriveMistralToolCallId(`toolcall:${toolCall.index??0}`,0),key=toolCall.index??callId,existingIndex=toolBlocksByKey.get(key),block;if(existingIndex!==void 0){let existing=output.content[existingIndex];existing?.type==="toolCall"&&(block=existing)}block||(block={type:"toolCall",id:callId,name:toolCall.function.name,arguments:{},partialArgs:""},output.content.push(block),toolBlocksByKey.set(key,output.content.length-1),stream2.push({type:"toolcall_start",contentIndex:output.content.length-1,partial:output}));let argsDelta=typeof toolCall.function.arguments=="string"?toolCall.function.arguments:JSON.stringify(toolCall.function.arguments||{});block.partialArgs=(block.partialArgs||"")+argsDelta,block.arguments=parseStreamingJson(block.partialArgs),stream2.push({type:"toolcall_delta",contentIndex:toolBlocksByKey.get(key),delta:argsDelta,partial:output})}}finishCurrentBlock(currentBlock);for(let index of toolBlocksByKey.values()){let block=output.content[index];if(block.type!=="toolCall")continue;let toolBlock=block;toolBlock.arguments=parseStreamingJson(toolBlock.partialArgs),delete toolBlock.partialArgs,stream2.push({type:"toolcall_end",contentIndex:index,toolCall:toolBlock,partial:output})}}function toFunctionTools(tools){return tools.map(tool=>{let strict=resolveJsonSchemaStrictSampling(tool,!0);return{type:"function",function:{name:tool.name,description:tool.description,parameters:stripSymbolKeys(getJsonSchemaToolParameters(tool,strict)),strict:strict??!1}}})}function stripSymbolKeys(value){if(Array.isArray(value))return value.map(item=>stripSymbolKeys(item));if(value&&typeof value=="object"){let result={};for(let[key,entry]of Object.entries(value))result[key]=stripSymbolKeys(entry);return result}return value}function appendUserMessage(result,content){let previous=result[result.length-1];if(previous?.role!=="user"){result.push({role:"user",content});return}let chunks=value=>typeof value=="string"?[{type:"text",text:value}]:value??[];previous.content=[...chunks(previous.content),...chunks(content)]}function toChatMessages(messages,supportsImages){let result=[];for(let[index,msg]of messages.entries()){if(msg.role==="configurationUpdate")continue;if(msg.role==="system"){let text=index===0?getSystemMessageText(msg):renderSystemMessageUpdate(msg);text.length>0&&result.push({role:"system",content:sanitizeSurrogates(text)});continue}if(msg.role==="user"){if(typeof msg.content=="string"){appendUserMessage(result,sanitizeSurrogates(msg.content));continue}let hadImages=msg.content.some(item=>item.type==="image"),content=msg.content.filter(item=>item.type==="text"||supportsImages).map(item=>item.type==="text"?{type:"text",text:sanitizeSurrogates(item.text)}:{type:"image_url",imageUrl:`data:${item.mimeType};base64,${item.data}`});if(content.length>0){appendUserMessage(result,content);continue}hadImages&&!supportsImages&&appendUserMessage(result,"(image omitted: model does not support images)");continue}if(msg.role==="assistant"){let contentParts=[],toolCalls=[];for(let block of msg.content){if(block.type==="text"){block.text.trim().length>0&&contentParts.push({type:"text",text:sanitizeSurrogates(block.text)});continue}if(block.type==="thinking"){block.thinking.trim().length>0&&contentParts.push({type:"thinking",thinking:[{type:"text",text:sanitizeSurrogates(block.thinking)}]});continue}block.type==="toolCall"&&toolCalls.push({id:block.id,type:"function",function:{name:block.name,arguments:JSON.stringify(block.arguments||{})},index:0})}let assistantMessage={role:"assistant",prefix:!1};contentParts.length>0&&(assistantMessage.content=contentParts),toolCalls.length>0&&(assistantMessage.toolCalls=toolCalls),(contentParts.length>0||toolCalls.length>0)&&result.push(assistantMessage);continue}let toolContent=[],textResult=msg.content.filter(part=>part.type==="text").map(part=>part.type==="text"?sanitizeSurrogates(part.text):"").join(`
4
4
  `),hasImages=msg.content.some(part=>part.type==="image"),toolText=buildToolResultText(textResult,hasImages,supportsImages,msg.isError);toolContent.push({type:"text",text:toolText});for(let part of msg.content)supportsImages&&part.type==="image"&&toolContent.push({type:"image_url",imageUrl:`data:${part.mimeType};base64,${part.data}`});result.push({role:"tool",toolCallId:msg.toolCallId,name:msg.toolName,content:toolContent})}return result}function buildToolResultText(text,hasImages,supportsImages,isError){let trimmed=text.trim(),errorPrefix=isError?"[tool error] ":"";return trimmed.length>0?`${errorPrefix}${trimmed}${hasImages&&!supportsImages?`
5
5
  [tool image omitted: model does not support images]`:""}`:hasImages?supportsImages?isError?"[tool error] (see attached image)":"(see attached image)":isError?"[tool error] (image omitted: model does not support images)":"(image omitted: model does not support images)":isError?"[tool error] (no tool output)":"(no tool output)"}function mapToolChoice(choice){if(choice)return choice==="auto"||choice==="none"||choice==="any"||choice==="required"?choice:{type:"function",function:{name:choice.function.name}}}function mapChatStopReason(reason){if(reason===null)return{stopReason:"stop"};switch(reason){case"stop":return{stopReason:"stop"};case"length":case"model_length":return{stopReason:"length"};case"tool_calls":return{stopReason:"toolUse"};case"error":return{stopReason:"error",errorMessage:"Provider stopped with: error"};default:return{stopReason:"error",errorMessage:`Provider stopped with: ${reason}`}}}export{stream,streamSimple};
@@ -1,8 +1,8 @@
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{getInternalHostBootstrap}from"./chunk-MYAENL22.js";import{SessionEventWriter,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,applyContextPatch,notAttachedRefusal,publishedSessionContext,recordLoopBlockedMs,registryStatusSource,socketSink}from"./chunk-6O4SEW2W.js";import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,CONNECTION_ROLE_FIXED,ConnectionRoles,EXTENSION_STATE_PAYLOAD,EXTENSION_STATE_PREFIX,HostMcpRegistry,MANIFEST_FILE,MOVE_BUNDLE_FORMAT,MoveBundleInvalidError,ProviderScope,SESSION_BUNDLE_PATH,STATE_ATTEMPT_FIELD,SessionPendingInputs,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,foreignSessionHolders,isMoveId,isPlainId,isSecurityNoticeState,movedStateDir,outgoingStateDir,parseMoveId,parsePermissionPresetName,parsePlainId,pathExists,prepareOutgoingState,readCodemodeKernelRows,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,roleConnection,runWithProviderScope,sealedOutgoingStateDir,sha256File,startHostChildReaper,subscriptionLimits,verifyBundle}from"./chunk-YRF4I43T.js";import"./chunk-ODTGC6YU.js";import{SessionHeldError,encodedSessionId,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-FHXR4ZAC.js";import"./chunk-7CNOCJCN.js";import{flushRawStdout,liveToolMediaScope,takeOverStdout,toolMediaPersister,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-FFQOEC76.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import{ClientAdmissions,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,answerEffectFromTranscript,beginEffect,buildRpcSessionState,drainSessionEffects,effectAnswer,installSessionEffectSink,isEffectBegin,latestSessionEffect,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-7W7OJDIY.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY}from"./chunk-GY5MR5KR.js";import"./chunk-EHQXLHRB.js";import{SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compareRepositoryIdentities,getDefaultSessionDir,headerSessionId,loadEntriesFromFileAsync,ownershipStep,readRepositoryIdentity,sessionOwnership}from"./chunk-XF3LJC3O.js";import{resolveMovedPath}from"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-H3HNMY2W.js";import{isRecord}from"./chunk-JPGT64RV.js";import"./chunk-UQNRW3VU.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-P3M2PF6K.js";import{ATTENDED_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DETACH_CONNECTION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,EVAL_CELLS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RESUME_SESSION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_STATUS_CAPABILITY,TOOL_BARRIER_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-HVJI5T75.js";import"./chunk-QMRJYMNH.js";import"./chunk-C5UFJ7B3.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-3LNSLJ7N.js";import"./chunk-MSQCTH6V.js";import"./chunk-4AOMNOGY.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import{lockWithLossHandling}from"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import{isHostOwnedToolRuntimeCapability,isSpawnedBy,toolRuntimeCapabilities}from"./chunk-WD6WBYC5.js";import"./chunk-26UBFF6N.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import"./chunk-JA2R2ZSE.js";import"./chunk-Z3UYNSVR.js";import{presenterBootstrapStream}from"./chunk-KXB5WIS5.js";import{ClientOccupancy,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,consumeHostWatchdogEnv,loopLagErrorMs,prepareSocketPath,scrubHostWatchdogEnv}from"./chunk-CNL6QSUB.js";import{SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,holderGenerationEnded,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-SWJXRC2I.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createHostDaemonPaths,sessionDirectoryRemoved}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import{RpcPublicEndpoint}from"./chunk-O3Q2ET6W.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3BTN337S.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-TTU2RNVX.js";import"./chunk-FDL4CF6F.js";import{killTrackedDetachedChildren}from"./chunk-BWA4FVFW.js";import"./chunk-YU4AYH4C.js";import"./chunk-E6WYH3ZL.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-E4LBKOZG.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-T36LJ6MW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-4P7WARQZ.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-6AOVUTUR.js";import"./chunk-45SZOLCU.js";import"./chunk-DMI55M2N.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-WLHNEUGD.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,shieldSocketDuringClose,socketEntryReplaced,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_SECRET_FILE_ENV,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import{processStartTimeMs}from"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{createServer as createServer2}from"node:net";import{mkdtemp,rm as rm6}from"node:fs/promises";import{tmpdir}from"node:os";import{basename as basename2,dirname as dirname3,join as join7}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.endpoint=hooks.endpoint,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord2(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);if(typeof request=="string")return beginHandoverResponse(parsed.id,request);let detail2=request.agentDir===void 0||this.endpoint===void 0?void 0:await agentDirMismatch(this.endpoint.socket,request.agentDir,this.endpoint.agentDir);return beginHandoverResponse(parsed.id,detail2===void 0?await this.handover.begin(request):{kind:"refused",reason:"foreign_agent_dir",detail:detail2})}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HandoffAnnouncement=class{begin(superseded,identity,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity,successor:replaced?{socket:publicSocket}:null}),cause=>{log(`handoff announcement failed: ${String(cause)}`)}),this.record}deliverLate(stream,arrivedBeforeDrain){let record=this.record;return!arrivedBeforeDrain||record===void 0?!1:(record.then(announced=>announced===void 0?stream.destroy():stream.end(`${JSON.stringify(announced)}
2
+ import{getInternalHostBootstrap}from"./chunk-MYAENL22.js";import{SessionEventWriter,answerSetSessionContext,answerSubscribeSessions,answerUnsubscribeSessions,applyContextPatch,notAttachedRefusal,publishedSessionContext,recordLoopBlockedMs,registryStatusSource,socketSink}from"./chunk-VL7O5PO4.js";import{ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,AgentSessionRuntime,EXTENSION_STATE_PAYLOAD,EXTENSION_STATE_PREFIX,HostMcpRegistry,MANIFEST_FILE,MOVE_BUNDLE_FORMAT,MoveBundleInvalidError,ProviderScope,SESSION_BUNDLE_PATH,STATE_ATTEMPT_FIELD,SessionPendingInputs,bindToProviderScope,createAgentSessionRuntime,createRpcConnectionHandler,createWebViewBroker,foreignSessionHolders,isMoveId,isPlainId,isSecurityNoticeState,movedStateDir,outgoingStateDir,parseMoveId,parsePermissionPresetName,parsePlainId,pathExists,prepareOutgoingState,readCodemodeKernelRows,readMainThreadHeapBytes,readManifest,readRecordedRepositoryIdentity,readSessionCwd,rebindSessionFile,runWithProviderScope,sealedOutgoingStateDir,sha256File,startHostChildReaper,subscriptionLimits,verifyBundle}from"./chunk-EZP6AYW2.js";import"./chunk-6U3TBFBA.js";import{SessionHeldError,encodedSessionId,liveSessionHolders,readProcessStartMs,serializeByKey,withSessionMoveLock}from"./chunk-UDM7VO6O.js";import"./chunk-ADQAPDPV.js";import{flushRawStdout,liveToolMediaScope,takeOverStdout,toolMediaPersister,waitForRawStdoutBackpressure,writeRawStdout}from"./chunk-3A3XCLNH.js";import"./chunk-DXJJP6RP.js";import"./chunk-GXY5JEI5.js";import{CONNECTION_ROLE_FIXED,ClientAdmissions,ConnectionRoles,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,EMPTY_SESSION_CONTEXT,EffectLedger,answerEffectFromTranscript,beginEffect,buildRpcSessionState,drainSessionEffects,effectAnswer,installSessionEffectSink,isEffectBegin,latestSessionEffect,roleConnection,rpcCommandShapeError,sessionAutoTitleError,sessionBrowserEngineError,sessionContextError,sessionKindError,sessionPromptSurfaceError,sessionRetryFallbackError}from"./chunk-VICDRG3J.js";import{RPC_ERROR_ATTACHED,RPC_ERROR_HOST_DRAINING,RPC_ERROR_INVALID_LAUNCH_PROFILE,RPC_ERROR_INVALID_PATH,RPC_ERROR_INVALID_RELEASE_REASON,RPC_ERROR_INVALID_SESSION_CONTEXT,RPC_ERROR_INVALID_SESSION_KIND,RPC_ERROR_MISSING_SESSION_ID,RPC_ERROR_OPEN_FAILED,RPC_ERROR_OWNER_CHANGED,RPC_ERROR_RELEASE_FAILED,RPC_ERROR_RELEASE_UNSUPPORTED,RPC_ERROR_SESSION_BUSY,RPC_ERROR_SESSION_CLOSING,RPC_ERROR_SESSION_HELD,RPC_ERROR_TURN_ACTIVE,RPC_ERROR_UNKNOWN_SESSION,RPC_ERROR_WARM_FAILED,STEER_WHEN_IDLE_CAPABILITY,USER_ACTIVITY_CAPABILITY}from"./chunk-GY5MR5KR.js";import"./chunk-3LPWILUZ.js";import{SESSION_MOVED,SESSION_MOVED_IN,SESSION_RECLAIMED,SESSION_RELEASED,SessionManager,SessionMovedAwayError,assertValidSessionId,compareRepositoryIdentities,getDefaultSessionDir,headerSessionId,loadEntriesFromFileAsync,ownershipStep,readRepositoryIdentity,sessionOwnership}from"./chunk-DYWIFF2Q.js";import{resolveMovedPath}from"./chunk-CNPDUC4D.js";import"./chunk-MLVIYDHK.js";import"./chunk-Y3TMJV3J.js";import"./chunk-JFQUWEN7.js";import{isRecord}from"./chunk-JPGT64RV.js";import"./chunk-HWTD4QF3.js";import{BEGIN_HANDOVER_COMMAND,EXPECTED_RUNTIME_BUILD_ID_ENV,HostIdleHandover,agentDirMismatch,beginHandoverResponse,handoverRefusal,isHandoffBusy,isHostIdle,parseBeginHandover,performIdleHandover,readDrainVerdicts,runAsHostGenerationProcess,withHostIdentity}from"./chunk-MSHRIZGT.js";import{ATTENDED_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,AUTO_TITLE_SESSIONS_CAPABILITY,BROWSER_ENGINE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,DETACH_CONNECTION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,ENTRIES_TAIL_CAPABILITY,EVAL_CELLS_CAPABILITY,GENERATION_HANDOFF_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,OBSERVE_READS_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,RESUME_SESSION_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,RUNTIME_IDENTITY_HANDOVER_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_HELD_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_STATUS_CAPABILITY,TOOL_BARRIER_CAPABILITY,WARM_CAPABILITY,computeRuntimeBuildId,hostGeneration,hostInstanceId,parseClientCapabilities,protocolIdentity}from"./chunk-5KZH6EYQ.js";import"./chunk-QMRJYMNH.js";import"./chunk-XMNPK472.js";import"./chunk-TIVW4P37.js";import"./chunk-H4QOEVS5.js";import"./chunk-SOXQ42VS.js";import"./chunk-XMJKZK5H.js";import"./chunk-6VWIMHMH.js";import"./chunk-LO5MYLGF.js";import"./chunk-KLAX467B.js";import"./chunk-JFFS72FL.js";import{lockWithLossHandling}from"./chunk-ORXZXUMC.js";import"./chunk-GZVCRV7I.js";import"./chunk-KUPQO7MC.js";import"./chunk-SOMFLLPD.js";import{isHostOwnedToolRuntimeCapability,isSpawnedBy,toolRuntimeCapabilities}from"./chunk-I7QWTWVZ.js";import"./chunk-26UBFF6N.js";import{readOwnFootprint}from"./chunk-MTQQ2VQH.js";import"./chunk-L2O6K3SJ.js";import"./chunk-H4WJ4LY3.js";import{presenterBootstrapStream}from"./chunk-Z6SAQ5O3.js";import{ClientOccupancy,PublicRpcConnection,acceptInternalConnection,armHostWatchdog,consumeHostWatchdogEnv,loopLagErrorMs,prepareSocketPath,scrubHostWatchdogEnv}from"./chunk-ZAUVY6ZC.js";import{SESSION_PATH_RETRY_AFTER_MS,createEndpointReservations,holderGenerationEnded,hostChildDrainRequestFile,ownGenerationDir,parseIdleExitMs,watchDrainRequest,writeHeartbeat,writeStallEvidence}from"./chunk-J2YAYTB2.js";import{HOST_DAEMON_DIR_ENV,canonicalSessionPath,createHostDaemonPaths,sessionDirectoryRemoved}from"./chunk-4WZRVZNX.js";import"./chunk-U3VOXCGP.js";import{RpcPublicEndpoint}from"./chunk-GWGNVYPB.js";import{MAX_RPC_LINE_CHARACTERS,attachJsonlLineReader}from"./chunk-YI7SPFDN.js";import"./chunk-HB35RBP4.js";import{FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS,FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS,isLockError}from"./chunk-Z6WGAK7W.js";import"./chunk-DLAY7CIU.js";import"./chunk-3WP5RFQR.js";import"./chunk-QXREUA5F.js";import"./chunk-RUGYFYH7.js";import"./chunk-OEFCY46F.js";import"./chunk-KRNXUTZJ.js";import"./chunk-TAV6QZFM.js";import"./chunk-PELNNWGO.js";import"./chunk-J5FCH7TI.js";import"./chunk-FDL4CF6F.js";import{killTrackedDetachedChildren}from"./chunk-7KOUQSBX.js";import"./chunk-YU4AYH4C.js";import"./chunk-QREKAXKX.js";import"./chunk-COH5F7QV.js";import"./chunk-RFB5CBW7.js";import"./chunk-2VZJTDUX.js";import"./chunk-ZLIVZQDY.js";import"./chunk-GVSBCJFI.js";import"./chunk-WASCMT6Y.js";import"./chunk-MY4ZD3EW.js";import"./chunk-QGJLZ6BI.js";import"./chunk-WHPDEDCC.js";import"./chunk-AA2L2RHH.js";import"./chunk-HK46JMSC.js";import"./chunk-5LWUUXMH.js";import"./chunk-WDTJ6JKE.js";import"./chunk-5ROMKDLK.js";import"./chunk-3W47LTXQ.js";import"./chunk-ZXHLH4MW.js";import"./chunk-45SZOLCU.js";import"./chunk-GQJYNFMO.js";import"./chunk-PJ34QVL5.js";import"./chunk-BMX2U22F.js";import"./chunk-YU2P3CAR.js";import"./chunk-5FQMNHXV.js";import"./chunk-ZOFZRJSL.js";import"./chunk-2SOVDETB.js";import"./chunk-V3CK2AVC.js";import{PUBLIC_SOCKET_IDENTITY_FILE,readSocketIdentityFile,shieldSocketDuringClose,socketEntryReplaced,statSocketIdentity,unlinkOwnedSocket,waitForSocketIdentityFile}from"./chunk-VRDU425E.js";import{SOCKET_SECRET_FILE_ENV,authenticateSocket,ensureSocketSecret,resolveSocketTransportAddress,socketSecretPath}from"./chunk-ZGAB7WQA.js";import{VERSION,envValue,isBunBinary,normalizePath,resolvePath}from"./chunk-7YO7VQZW.js";import"./chunk-ATQFN5HI.js";import"./chunk-MIENF2YK.js";import"./chunk-OXNWERO4.js";import{ownProcessStartedAtMs}from"./chunk-QN2BHP3M.js";import"./chunk-NTK2MHJ5.js";import{processStartTimeMs}from"./chunk-O5RYI3IW.js";import"./chunk-IKOFCODM.js";import{createServer as createServer2}from"node:net";import{mkdtemp,rm as rm6}from"node:fs/promises";import{tmpdir}from"node:os";import{basename as basename2,dirname as dirname3,join as join7}from"node:path";var HostCoreGate=class{constructor(registry,route,hooks){this.inFlight=new Map,this.answering=new Set,this.route=route,this.runtimeBuildId=hooks.runtimeBuildId,this.endpoint=hooks.endpoint,this.handover=hooks.handover===void 0?void 0:new HostIdleHandover({...hooks.handover,isIdle:()=>isHostIdle(registry,this.inFlight)})}async intercept(parsed,deliver){if(!isRecord2(parsed)||parsed.type!==BEGIN_HANDOVER_COMMAND)return!1;let answering=this.answerBegin(parsed).then(deliver);this.answering.add(answering);try{await answering}finally{this.answering.delete(answering)}return!0}async answerBegin(parsed){if(this.handover===void 0)return beginHandoverResponse(parsed.id,{kind:"refused",reason:"handover_unsupported"});let request=parseBeginHandover(parsed);if(typeof request=="string")return beginHandoverResponse(parsed.id,request);let detail2=request.agentDir===void 0||this.endpoint===void 0?void 0:await agentDirMismatch(this.endpoint.socket,request.agentDir,this.endpoint.agentDir);return beginHandoverResponse(parsed.id,detail2===void 0?await this.handover.begin(request):{kind:"refused",reason:"foreign_agent_dir",detail:detail2})}async answered(){for(;this.answering.size>0;)await Promise.allSettled([...this.answering])}async dispatch(command){let pending=this.handover?.view();if(pending!==void 0&&this.handover?.admits(command.type)===!1)return handoverRefusal(command,pending);let key="sessionId"in command?command.sessionId:void 0;this.inFlight.set(key,(this.inFlight.get(key)??0)+1);let response;try{response=await this.route(command)}finally{let remaining=(this.inFlight.get(key)??1)-1;remaining>0?this.inFlight.set(key,remaining):this.inFlight.delete(key),this.handover?.observe()}return response===void 0?void 0:withHostIdentity(response,this.runtimeBuildId,this.handover?.view())}};function isRecord2(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}var HandoffAnnouncement=class{begin(superseded,identity,publicSocket,log){return this.record=superseded.then(replaced=>({type:"host_superseded",...identity,successor:replaced?{socket:publicSocket}:null}),cause=>{log(`handoff announcement failed: ${String(cause)}`)}),this.record}deliverLate(stream,arrivedBeforeDrain){let record=this.record;return!arrivedBeforeDrain||record===void 0?!1:(record.then(announced=>announced===void 0?stream.destroy():stream.end(`${JSON.stringify(announced)}
3
3
  `)),!0)}};import{existsSync as existsSync4}from"node:fs";import{createHash}from"node:crypto";import{existsSync,renameSync}from"node:fs";import{mkdir,readdir,readFile,rm,writeFile}from"node:fs/promises";import{join}from"node:path";var recordDir=daemonDir=>join(daemonDir,"handover-parked"),entryFile=(daemonDir,sessionPath)=>join(recordDir(daemonDir),`${createHash("sha256").update(sessionPath,"utf8").digest("hex").slice(0,16)}.json`),mutationChain=Promise.resolve();function enqueueMutation(mutation){let next=mutationChain.then(mutation,mutation);return mutationChain=next.catch(()=>{}),next}function isEntry(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;let record=value;return typeof record.sessionPath=="string"&&typeof record.retainOnDisconnect=="boolean"&&(record.durableSessionId===void 0||typeof record.durableSessionId=="string")&&(record.cwd===void 0||typeof record.cwd=="string")&&(record.parkedBy===void 0||typeof record.parkedBy=="string")&&(record.thinkingLevel===void 0||typeof record.thinkingLevel=="string")&&(record.permissionPreset===void 0||typeof record.permissionPreset=="string"&&parsePermissionPresetName(record.permissionPreset)!==void 0)&&sessionPromptSurfaceError(record.promptSurface)===void 0&&sessionBrowserEngineError(record.browserEngine)===void 0&&sessionKindError(record.sessionKind)===void 0&&sessionContextError(record.sessionContext)===void 0&&(record.contextOverlay===void 0||!("refusal"in applyContextPatch(void 0,record.contextOverlay)))&&sessionAutoTitleError(record.autoTitle)===void 0&&sessionRetryFallbackError(record.retryFallback)===void 0&&(record.model===void 0||typeof record.model=="object"&&record.model!==null&&typeof record.model.provider=="string"&&typeof record.model.modelId=="string")}async function writeEntryFile(daemonDir,entry){await mkdir(recordDir(daemonDir),{recursive:!0,mode:448});let file=entryFile(daemonDir,entry.sessionPath),tmp=`${file}.${process.pid}.${Math.random().toString(16).slice(2,10)}.tmp`;await writeFile(tmp,`${JSON.stringify(entry,null,2)}
4
4
  `,{mode:384}),renameSync(tmp,file)}function recordHandoverParkedSession(daemonDir,entry){return enqueueMutation(()=>writeEntryFile(daemonDir,entry))}async function readHandoverParkedSessions(daemonDir){let names;try{names=(await readdir(recordDir(daemonDir))).filter(name=>name.endsWith(".json"))}catch{return[]}let entries=[];for(let name of names){let file=join(recordDir(daemonDir),name);try{let parsed=JSON.parse(await readFile(file,"utf8"));isEntry(parsed)&&entries.push(parsed)}catch(cause){cause instanceof SyntaxError&&(process.stderr.write(`senpi rpc handover-parked entry ${name} is corrupt; dropping it
5
- `),await rm(file,{force:!0}))}}return entries}function clearHandoverParkedSession(daemonDir,sessionPath){return enqueueMutation(()=>rm(entryFile(daemonDir,sessionPath),{force:!0}))}function dropHandoverParkedSessionIfFileGone(daemonDir,sessionPath){return existsSync(sessionPath)?Promise.resolve():clearHandoverParkedSession(daemonDir,sessionPath)}import{isAbsolute as isAbsolute2}from"node:path";import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code2){return{id:command.id,type:"response",command:"warm",success:!1,error:code2}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}var observations=new Set(["get_state","get_effect_status","get_pending_inputs","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_session_stats","resolve_path","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_commands","get_loaded_surfaces","get_media","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek"]);function refreshesSessionActivity(command){return!observations.has(command)}var RpcSessionRegistryError=class extends Error{constructor(code2,reason,detail2){super(code2==="open_failed"&&reason?`${code2}: ${reason}`:code2),this.code=code2,this.name="RpcSessionRegistryError",detail2&&(this.detail=detail2)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.holderEndpoint?{holderEndpoint:Object.freeze({...profile.holderEndpoint})}:{},...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{},...profile.retryFallback?{retryFallback:Object.freeze({modelFallback:profile.retryFallback.modelFallback,fallbackChains:Object.freeze(Object.fromEntries(Object.entries(profile.retryFallback.fallbackChains).map(([key,entries])=>[key,Object.freeze([...entries])])))})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}function attachLiveSession(entry,now,markAttached){if(entry?.state!=="open")throw new RpcSessionRegistryError("unknown_session");let wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;return entry.attachments++,entry.detachedAt=void 0,entry.lastCommandAt=now,markAttached(),wasParked&&entry.runtime&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed"))),entry}function markPathAttached(entry,claims){entry?.reservationKey&&claims?.setAttached(entry.reservationKey,!0)}function beginPendingClaim(pending,sessionPath){let settled=Promise.withResolvers();return pending.set(sessionPath,settled.promise),()=>{pending.get(sessionPath)===settled.promise&&pending.delete(sessionPath),settled.resolve()}}async function takeCrossGenerationClaim(reservations,pending,pathReservations,sessionPath){let settle=beginPendingClaim(pending,sessionPath),holder;try{holder=await pathReservations.claim(sessionPath)}catch(cause){throw reservations.delete(sessionPath),settle(),cause}if(holder===void 0)return settle;throw reservations.delete(sessionPath),settle(),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}async function settlePendingClaim(pending,sessionPath,graceMs){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),graceMs)});try{for(let claim=pending.get(sessionPath);claim!==void 0;claim=pending.get(sessionPath))if(await Promise.race([claim.then(()=>"settled"),late])==="late")throw new RpcSessionRegistryError("session_path_in_use","another open of this path is still taking its claim",{reason:"claim_in_progress",retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}finally{clearTimeout(timer)}}function syncRuntimeMetadata(entries,reservations,pathReservations){for(let entry of entries){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(reservations.delete(entry.reservationKey),pathReservations?.release(entry.reservationKey)),currentKey&&(reservations.add(currentKey),pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}async function settleClosingReservation(entries,sessionPath,closeGraceMs){let closing=[...entries].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve2=>{deadline=setTimeout(resolve2,closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}function assertRequestedModelResolved(profile,diagnostics){let requested=profile.creationModel;if(requested===void 0)return;let unresolved=diagnostics.find(diagnostic=>diagnostic.code==="model_unresolved");if(unresolved!==void 0)throw new RpcSessionRegistryError("open_failed",`model_unavailable: ${unresolved.message}`,{reason:"model_unavailable",requestedModel:`${requested.provider}/${requested.modelId}`})}var DEFAULT_OPEN_IN_PROGRESS_WAIT_MS=45e3,OPEN_IN_PROGRESS_WAIT_RETRY_MS=2e3;function openInProgressWaitMs(){let override=Number(process.env.SENPI_OPEN_IN_PROGRESS_WAIT_MS);return Number.isFinite(override)&&override>0?override:DEFAULT_OPEN_IN_PROGRESS_WAIT_MS}var OpenInProgressWaitError=class extends Error{};function openingOwner(sessionPath){return{instanceId:hostInstanceId(),pid:process.pid,processStartTime:null,sessionPath,attached:!0,current:!0}}function waitWithDeadline(openCompletion,waitMs){let timer;return Promise.race([openCompletion,new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new OpenInProgressWaitError),waitMs)})]).finally(()=>{timer!==void 0&&clearTimeout(timer)})}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing){let inFlight=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="opening");if(inFlight?.[1].openCompletion!==void 0){try{await waitWithDeadline(inFlight[1].openCompletion,openInProgressWaitMs())}catch(cause){throw cause instanceof OpenInProgressWaitError?new RpcSessionRegistryError("session_path_in_use","the session is still opening",{reason:"open_in_progress",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS,owner:openingOwner(sessionPath)}):new RpcSessionRegistryError("session_path_in_use","the in-flight open failed",{reason:"open_failed",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}return attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now)}throw new RpcSessionRegistryError("session_path_in_use","the session is still being released",{reason:"path_still_held",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}let[handle2,entry]=existing,wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;if(entry.attachments+=1,entry.detachedAt=void 0,pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),!entry.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface:profile.promptSurface}),entry.runtime?.setPromptSurface(profile.promptSurface)),profile.browserEngine!==void 0&&profile.browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine:profile.browserEngine}),entry.runtime?.setBrowserEngine(profile.browserEngine)),profile.permissionPreset!==void 0&&(entry.profile=frozenProfile({...entry.profile,permissionPreset:profile.permissionPreset}),entry.runtime?.setPermissionPreset(profile.permissionPreset)),entry.lastCommandAt=now,wasParked&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed")),await entry.lifecycleMutex),{sessionId:handle2,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,attached:!0}}import{existsSync as existsSync2}from"node:fs";function resolveMovedProfile(requested){let profile={...requested,cwd:resolveMovedPath(requested.cwd),...requested.sessionPath?{sessionPath:resolveMovedPath(requested.sessionPath)}:{}};if(profile.sessionPath!==requested.sessionPath&&profile.sessionPath&&!existsSync2(profile.sessionPath))throw new RpcSessionRegistryError("open_failed",`moved session file does not exist: ${profile.sessionPath}`);return profile}import{existsSync as existsSync3}from"node:fs";function createEntrySwitchSession(entry,createRuntime,syncRuntimeMetadata2){return(sessionPath,options)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath,options);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),ClientAdmissions.sealQueuedOnReplace(replacement),EffectLedger.sealOnReplace(replacement),runtime.releaseSessionHold(),entry.runtime=replacement,syncRuntimeMetadata2(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation}}function buildOpeningEntry(input){let{profile,sessionPath,requestedDurableId,options}=input,isResume=sessionPath!==void 0&&existsSync3(sessionPath),sessionStartEvent=isResume||profile.attended===!1?{type:"session_start",reason:isResume?"resume":"startup",...profile.attended===!1?{attended:!1}:{}}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,settleOpen,openCompletion=new Promise((resolve2,reject)=>{settleOpen={resolve:resolve2,reject}});openCompletion.catch(()=>{});let entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:input.now,lifecycleMutex:Promise.resolve(),openCompletion};return entry.switchSession=createEntrySwitchSession(entry,input.createRuntime,input.sync),requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),{entry,storedProfile,runtimeProfile,sessionStartEvent,settleOpen}}function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle2,cause){process.stderr.write(`senpi rpc session ${handle2} teardown failed: ${String(cause)}
5
+ `),await rm(file,{force:!0}))}}return entries}function clearHandoverParkedSession(daemonDir,sessionPath){return enqueueMutation(()=>rm(entryFile(daemonDir,sessionPath),{force:!0}))}function dropHandoverParkedSessionIfFileGone(daemonDir,sessionPath){return existsSync(sessionPath)?Promise.resolve():clearHandoverParkedSession(daemonDir,sessionPath)}import{isAbsolute as isAbsolute2}from"node:path";import{access}from"node:fs/promises";import{isAbsolute}from"node:path";var MAX_WARM_PROFILES=64;function profileKey(profile){let context=Object.entries(profile.sessionContext??{}).sort(([a],[b])=>a<b?-1:a>b?1:0);return JSON.stringify([profile.cwd,profile.sessionKind??"interactive",context])}var HostWarmer=class{constructor(load){this.warm=new Set,this.loading=new Map,this.load=load}async run(profile){let key=profileKey(profile);if(this.warm.has(key))return"already_warm";let pending=this.loading.get(key);return pending===void 0&&(pending=this.loadOnce(key,profile),this.loading.set(key,pending)),await pending,"warmed"}async loadOnce(key,profile){try{if(await this.load(profile),this.warm.add(key),this.warm.size>MAX_WARM_PROFILES){let oldest=this.warm.values().next().value;oldest!==void 0&&this.warm.delete(oldest)}}finally{this.loading.delete(key)}}};function createRegistryWarm(prepare,host){let warmer=new HostWarmer(async profile=>{await access(profile.cwd);let launchProfile={cwd:profile.cwd,...profile.sessionKind!==void 0?{sessionKind:profile.sessionKind}:{},...profile.sessionContext!==void 0?{sessionContext:Object.freeze({...profile.sessionContext})}:{}},scope=new ProviderScope;try{await runWithProviderScope(scope,()=>prepare({cwd:profile.cwd,agentDir:host.agentDir,launchProfile:Object.freeze(launchProfile),...host.mcpRegistry!==void 0?{mcpRegistry:host.mcpRegistry}:{}}))}finally{scope.close()}});return profile=>warmer.run(profile)}function refusal(command,code2){return{id:command.id,type:"response",command:"warm",success:!1,error:code2}}async function answerWarm(command,host){if(host.draining)return refusal(command,"host_draining");let kindError=sessionKindError(command.kind);if(kindError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return refusal(command,`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);if(host.warm===void 0)return{id:command.id,type:"response",command:"warm",success:!0,data:{state:"unsupported"}};let sessionContext=host.hostContext?{...command.context,...host.hostContext}:command.context,cwd=command.cwd??host.cwd;if(!isAbsolute(cwd))return refusal(command,RPC_ERROR_INVALID_PATH);try{let state=await host.warm({cwd,...command.kind!==void 0?{sessionKind:command.kind}:{},...sessionContext!==void 0?{sessionContext}:{}});return{id:command.id,type:"response",command:"warm",success:!0,data:{state}}}catch(cause){return refusal(command,`${RPC_ERROR_WARM_FAILED}: ${cause instanceof Error?cause.message:String(cause)}`)}}var observations=new Set(["get_state","get_snapshot","get_effect_status","get_pending_inputs","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_session_stats","resolve_path","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_commands","get_loaded_surfaces","get_media","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek"]);function refreshesSessionActivity(command){return!observations.has(command)}var RpcSessionRegistryError=class extends Error{constructor(code2,reason,detail2){super(code2==="open_failed"&&reason?`${code2}: ${reason}`:code2),this.code=code2,this.name="RpcSessionRegistryError",detail2&&(this.detail=detail2)}};function frozenProfile(profile){return Object.freeze({...profile,...profile.holderEndpoint?{holderEndpoint:Object.freeze({...profile.holderEndpoint})}:{},...profile.creationModel?{creationModel:Object.freeze({...profile.creationModel})}:{},...profile.sessionContext?{sessionContext:Object.freeze({...profile.sessionContext})}:{},...profile.retryFallback?{retryFallback:Object.freeze({modelFallback:profile.retryFallback.modelFallback,fallbackChains:Object.freeze(Object.fromEntries(Object.entries(profile.retryFallback.fallbackChains).map(([key,entries])=>[key,Object.freeze([...entries])])))})}:{}})}function sessionIdentity(profile){return{kind:profile.sessionKind??"interactive",context:profile.sessionContext??EMPTY_SESSION_CONTEXT}}function attachLiveSession(entry,now,markAttached){if(entry?.state!=="open")throw new RpcSessionRegistryError("unknown_session");let wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;return entry.attachments++,entry.detachedAt=void 0,entry.lastCommandAt=now,markAttached(),wasParked&&entry.runtime&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed"))),entry}function markPathAttached(entry,claims){entry?.reservationKey&&claims?.setAttached(entry.reservationKey,!0)}function beginPendingClaim(pending,sessionPath){let settled=Promise.withResolvers();return pending.set(sessionPath,settled.promise),()=>{pending.get(sessionPath)===settled.promise&&pending.delete(sessionPath),settled.resolve()}}async function takeCrossGenerationClaim(reservations,pending,pathReservations,sessionPath){let settle=beginPendingClaim(pending,sessionPath),holder;try{holder=await pathReservations.claim(sessionPath)}catch(cause){throw reservations.delete(sessionPath),settle(),cause}if(holder===void 0)return settle;throw reservations.delete(sessionPath),settle(),new RpcSessionRegistryError("session_path_in_use",void 0,{owner:holder,retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}async function settlePendingClaim(pending,sessionPath,graceMs){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),graceMs)});try{for(let claim=pending.get(sessionPath);claim!==void 0;claim=pending.get(sessionPath))if(await Promise.race([claim.then(()=>"settled"),late])==="late")throw new RpcSessionRegistryError("session_path_in_use","another open of this path is still taking its claim",{reason:"claim_in_progress",retry_after_ms:SESSION_PATH_RETRY_AFTER_MS})}finally{clearTimeout(timer)}}function syncRuntimeMetadata(entries,reservations,pathReservations){for(let entry of entries){let manager=entry.runtime?.session.sessionManager;if(!manager)continue;let currentPath=manager.getSessionFile(),currentKey=currentPath?canonicalSessionPath(currentPath):void 0;(currentPath!==entry.sessionPath||currentKey!==entry.reservationKey)&&(entry.reservationKey&&(reservations.delete(entry.reservationKey),pathReservations?.release(entry.reservationKey)),currentKey&&(reservations.add(currentKey),pathReservations?.claim(currentKey,entry.attachments>0)),entry.reservationKey=currentKey,entry.sessionPath=currentPath),entry.durableSessionId=manager.getSessionId(),entry.cwd=manager.getCwd()}}async function settleClosingReservation(entries,sessionPath,closeGraceMs){let closing=[...entries].find(entry=>entry.reservationKey===sessionPath&&entry.state==="closing");if(!closing?.closeCompletion)return;let deadline;try{await Promise.race([closing.closeCompletion,new Promise(resolve2=>{deadline=setTimeout(resolve2,closeGraceMs)})])}finally{deadline&&clearTimeout(deadline)}}function assertRequestedModelResolved(profile,diagnostics){let requested=profile.creationModel;if(requested===void 0)return;let unresolved=diagnostics.find(diagnostic=>diagnostic.code==="model_unresolved");if(unresolved!==void 0)throw new RpcSessionRegistryError("open_failed",`model_unavailable: ${unresolved.message}`,{reason:"model_unavailable",requestedModel:`${requested.provider}/${requested.modelId}`})}var DEFAULT_OPEN_IN_PROGRESS_WAIT_MS=45e3,OPEN_IN_PROGRESS_WAIT_RETRY_MS=2e3;function openInProgressWaitMs(){let override=Number(process.env.SENPI_OPEN_IN_PROGRESS_WAIT_MS);return Number.isFinite(override)&&override>0?override:DEFAULT_OPEN_IN_PROGRESS_WAIT_MS}var OpenInProgressWaitError=class extends Error{};function openingOwner(sessionPath){return{instanceId:hostInstanceId(),pid:process.pid,processStartTime:null,sessionPath,attached:!0,current:!0}}function waitWithDeadline(openCompletion,waitMs){let timer;return Promise.race([openCompletion,new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(new OpenInProgressWaitError),waitMs)})]).finally(()=>{timer!==void 0&&clearTimeout(timer)})}async function attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now){let existing=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="open");if(!existing){let inFlight=[...entries].find(([,entry2])=>entry2.reservationKey===sessionPath&&entry2.state==="opening");if(inFlight?.[1].openCompletion!==void 0){try{await waitWithDeadline(inFlight[1].openCompletion,openInProgressWaitMs())}catch(cause){throw cause instanceof OpenInProgressWaitError?new RpcSessionRegistryError("session_path_in_use","the session is still opening",{reason:"open_in_progress",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS,owner:openingOwner(sessionPath)}):new RpcSessionRegistryError("session_path_in_use","the in-flight open failed",{reason:"open_failed",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}return attachToOpenSession(entries,sessionPath,profile,options,pathReservations,now)}throw new RpcSessionRegistryError("session_path_in_use","the session is still being released",{reason:"path_still_held",retry_after_ms:OPEN_IN_PROGRESS_WAIT_RETRY_MS})}let[handle2,entry]=existing,wasParked=entry.retainOnDisconnect===!0&&entry.attachments===0;if(entry.attachments+=1,entry.detachedAt=void 0,pathReservations?.setAttached(sessionPath,!0),options?.retainOnDisconnect&&(entry.retainOnDisconnect=!0),!entry.durableSessionId)throw new RpcSessionRegistryError("session_path_in_use");return profile.promptSurface!==void 0&&profile.promptSurface!==entry.profile.promptSurface&&(entry.profile=frozenProfile({...entry.profile,promptSurface:profile.promptSurface}),entry.runtime?.setPromptSurface(profile.promptSurface)),profile.browserEngine!==void 0&&profile.browserEngine!==entry.profile.browserEngine&&(entry.profile=frozenProfile({...entry.profile,browserEngine:profile.browserEngine}),entry.runtime?.setBrowserEngine(profile.browserEngine)),profile.permissionPreset!==void 0&&(entry.profile=frozenProfile({...entry.profile,permissionPreset:profile.permissionPreset}),entry.runtime?.setPermissionPreset(profile.permissionPreset)),entry.lastCommandAt=now,wasParked&&(entry.lifecycleMutex=entry.lifecycleMutex.then(()=>entry.runtime?.emitAttachmentEvent("session_resumed")),await entry.lifecycleMutex),{sessionId:handle2,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,attached:!0}}import{existsSync as existsSync2}from"node:fs";function resolveMovedProfile(requested){let profile={...requested,cwd:resolveMovedPath(requested.cwd),...requested.sessionPath?{sessionPath:resolveMovedPath(requested.sessionPath)}:{}};if(profile.sessionPath!==requested.sessionPath&&profile.sessionPath&&!existsSync2(profile.sessionPath))throw new RpcSessionRegistryError("open_failed",`moved session file does not exist: ${profile.sessionPath}`);return profile}import{existsSync as existsSync3}from"node:fs";function createEntrySwitchSession(entry,createRuntime,syncRuntimeMetadata2){return(sessionPath,options)=>{let operation=entry.lifecycleMutex.then(async()=>{if(entry.state!=="open"||!entry.runtime)throw new RpcSessionRegistryError("unknown_session");let runtime=entry.runtime,cwdOverride=options?.cwdOverride,cwdChanged=cwdOverride!==void 0&&runtime.session.sessionManager.getCwd()!==cwdOverride,result=await runtime.switchSession(sessionPath,options);if(result.cancelled||!cwdChanged)return result;let replacement=new AgentSessionRuntime(runtime.session,runtime.services,createRuntime,[...runtime.diagnostics],runtime.modelFallbackMessage,runtime.launchProfile);return replacement.setRebindSession(entry.rebindSession),ClientAdmissions.sealQueuedOnReplace(replacement),EffectLedger.sealOnReplace(replacement),runtime.releaseSessionHold(),entry.runtime=replacement,syncRuntimeMetadata2(),result});return entry.lifecycleMutex=operation.then(()=>{},()=>{}),operation}}function buildOpeningEntry(input){let{profile,sessionPath,requestedDurableId,options}=input,isResume=sessionPath!==void 0&&existsSync3(sessionPath),sessionStartEvent=isResume||profile.attended===!1?{type:"session_start",reason:isResume?"resume":"startup",...profile.attended===!1?{attended:!1}:{}}:void 0,storedProfile=frozenProfile({...profile,...sessionPath?{sessionPath}:{}}),runtimeProfile=isResume?frozenProfile({...storedProfile,creationModel:void 0,initialThinkingLevel:void 0}):storedProfile,settleOpen,openCompletion=new Promise((resolve2,reject)=>{settleOpen={resolve:resolve2,reject}});openCompletion.catch(()=>{});let entry={state:"opening",scope:new ProviderScope,profile:storedProfile,...sessionIdentity(storedProfile),sessionPath,reservationKey:sessionPath,cwd:storedProfile.cwd,attachments:1,retainOnDisconnect:options?.retainOnDisconnect===!0,lastCommandAt:input.now,lifecycleMutex:Promise.resolve(),openCompletion};return entry.switchSession=createEntrySwitchSession(entry,input.createRuntime,input.sync),requestedDurableId!==void 0&&(entry.durableSessionId=requestedDurableId),{entry,storedProfile,runtimeProfile,sessionStartEvent,settleOpen}}function sessionIsWriting(entry){return entry.worker?.busy===!0||entry.runtime?.session.isSessionBusy===!0}function reportDetachedFailure(handle2,cause){process.stderr.write(`senpi rpc session ${handle2} teardown failed: ${String(cause)}
6
6
  `)}function beginSessionClose(host,handle2,onRole,options){let entry=host.get(handle2);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing")return onRole?.(!1),entry;if(entry.state!=="open")throw new RpcSessionRegistryError("unknown_session");return entry.attachments-=1,entry.attachments>0?entry:options?.detach&&entry.retainOnDisconnect?(entry.attachments=0,entry.detachedAt??=host.now(),entry.reservationKey&&!sessionIsWriting(entry)&&host.markDetached(entry.reservationKey),entry):(entry.state="closing",onRole?.(!0),entry.closeCompletion=new Promise(resolve2=>{entry.closeResolve=resolve2}),entry)}async function releaseWithinGrace(host,handle2,key){let timer,late=new Promise(resolve2=>{timer=setTimeout(()=>resolve2("late"),host.closeGraceMs)}),removal=host.releaseReservation(key).then(()=>"removed",cause=>(reportDetachedFailure(handle2,cause),"failed")),outcome=await Promise.race([removal,late]);clearTimeout(timer),outcome==="late"&&reportDetachedFailure(handle2,new Error(`session path reservation was not removed within ${host.closeGraceMs} ms; closing anyway`))}function closeSession(host,handle2){return beginSessionClose(host,handle2).state!=="closing"?Promise.resolve():closeMarkedSession(host,handle2)}function closeMarkedSession(host,handle2){host.sync();let entry=host.get(handle2);if(entry?.state!=="closing")throw new RpcSessionRegistryError("unknown_session");let completion=entry.closeCompletion;if(!completion)return Promise.resolve();if(entry.closeStarted)return completion;entry.closeStarted=!0;let previousLifecycle=entry.lifecycleMutex,releaseTimer,released=!1,disposePromise,scopeClosed=!1,disposeOnce=()=>disposePromise||(disposePromise=Promise.resolve(entry.runtime?.dispose()),disposePromise),closeScopeOnce=async()=>{scopeClosed||(scopeClosed=!0,await disposeOnce().catch(()=>{}),await entry.scope.close?.())},release=async()=>{released||(released=!0,releaseTimer&&clearTimeout(releaseTimer),entry.reservationKey&&await releaseWithinGrace(host,handle2,entry.reservationKey),entry.state="closed",host.delete(handle2))},graceful=(async()=>{await previousLifecycle;try{await entry.runtime?.session.abort()}catch(cause){reportDetachedFailure(handle2,cause)}try{await entry.runtime?.session.waitForIdle()}catch(cause){reportDetachedFailure(handle2,cause)}try{await disposeOnce()}catch(cause){reportDetachedFailure(handle2,cause)}try{await closeScopeOnce()}catch(cause){reportDetachedFailure(handle2,cause)}})(),settled=!1,finish=async()=>{settled||(settled=!0,await release(),entry.closeResolve?.())};return releaseTimer=setTimeout(()=>{disposeOnce().catch(cause=>reportDetachedFailure(handle2,cause)),closeScopeOnce().catch(cause=>reportDetachedFailure(handle2,cause)),graceful.catch(cause=>reportDetachedFailure(handle2,cause)),finish()},host.closeGraceMs),graceful.then(finish,cause=>(reportDetachedFailure(handle2,cause),finish())),completion}async function openRegistrySession(host,requested,options){host.validateProfile(requested);let profile=resolveMovedProfile(requested);host.syncRuntimeMetadata();let sessionPath=profile.sessionPath?canonicalSessionPath(profile.sessionPath):void 0,requestedDurableId=profile.durableSessionId;if(requestedDurableId!==void 0){for(let entry2 of host.entries.values())if(entry2.state!=="closed"&&entry2.durableSessionId===requestedDurableId&&!(sessionPath!==void 0&&entry2.reservationKey===sessionPath))throw new RpcSessionRegistryError("session_id_in_use")}if(sessionPath){await settleClosingReservation(host.entries.values(),sessionPath,host.closeGraceMs);let deadline=Date.now()+host.closeGraceMs;for(;host.pendingClaims.has(sessionPath);)await settlePendingClaim(host.pendingClaims,sessionPath,Math.max(0,deadline-Date.now()))}if(sessionPath&&host.reservations.has(sessionPath))return attachToOpenSession(host.entries,sessionPath,profile,options,host.options.pathReservations,host.now());if(options?.attachOnly)throw new RpcSessionRegistryError("session_not_held",void 0,{reason:"session_not_held",action:"rediscover_holder"});let claimSettled;sessionPath&&(host.reservations.add(sessionPath),host.options.pathReservations&&(claimSettled=await takeCrossGenerationClaim(host.reservations,host.pendingClaims,host.options.pathReservations,sessionPath)));let handle2=host.nextHandle(),opening;try{opening=buildOpeningEntry({profile,sessionPath,requestedDurableId,options,now:host.now(),createRuntime:host.options.createRuntime,sync:()=>host.syncRuntimeMetadata()})}catch(cause){try{sessionPath&&(host.reservations.delete(sessionPath),await host.options.pathReservations?.release(sessionPath))}catch(releaseCause){process.stderr.write(`senpi rpc open of ${sessionPath} could not release its claim: ${String(releaseCause)}
7
7
  `)}finally{claimSettled?.()}throw cause}let{entry,storedProfile,runtimeProfile,sessionStartEvent,settleOpen}=opening;host.entries.set(handle2,entry),claimSettled?.(),host.options.onSizeChange?.(host.entries.size);try{let newSessionOptions={...requestedDurableId!==void 0?{id:requestedDurableId}:{},...storedProfile.spawnedBy?{spawnedBy:storedProfile.spawnedBy}:{}},manager=sessionPath?host.options.sessionFileLoad==="blocking"?SessionManager.open(sessionPath,void 0,storedProfile.cwd,newSessionOptions):await SessionManager.openAsync(sessionPath,void 0,storedProfile.cwd,newSessionOptions,host.options.createSlicer?.()):SessionManager.create(storedProfile.cwd,void 0,newSessionOptions);return entry.runtime=await runWithProviderScope(entry.scope,()=>createAgentSessionRuntime(host.options.createRuntime,{cwd:manager.getCwd(),agentDir:host.options.agentDir,sessionManager:manager,sessionStartEvent,launchProfile:runtimeProfile})),assertRequestedModelResolved(runtimeProfile,entry.runtime.diagnostics),ClientAdmissions.sealQueuedOnReplace(entry.runtime),EffectLedger.sealOnReplace(entry.runtime),entry.durableSessionId=manager.getSessionId(),entry.sessionPath??=manager.getSessionFile(),entry.state="open",settleOpen.resolve(),{sessionId:handle2,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath}}catch(error2){try{await entry.runtime?.dispose()}catch{}finally{try{await entry.scope.close?.()}finally{host.entries.delete(handle2),host.options.onSizeChange?.(host.entries.size),sessionPath&&await releaseWithinGrace(host.teardownHost,handle2,sessionPath)}}if(error2 instanceof RpcSessionRegistryError)throw settleOpen.reject(error2),error2;let wrapped=new RpcSessionRegistryError("open_failed",error2 instanceof Error?error2.message:void 0);throw settleOpen.reject(wrapped),wrapped}}var RpcSessionRegistry=class{get agentDir(){return this.options.agentDir}constructor(options){this.entries=new Map,this.reservations=new Set,this.pendingClaims=new Map,this.nextHandle=0,options.createRuntime.prepare&&(this.warm=createRegistryWarm(options.createRuntime.prepare,{agentDir:options.agentDir,...options.mcpRegistry!==void 0?{mcpRegistry:options.mcpRegistry}:{}})),this.options=options.mcpRegistry===void 0?options:{...options,createRuntime:runtimeOptions=>options.createRuntime({...runtimeOptions,mcpRegistry:options.mcpRegistry})},this.now=options.now??Date.now,this.closeGraceMs=options.closeGraceMs??1e4,this.teardownHost={closeGraceMs:this.closeGraceMs,get:handle2=>this.entries.get(handle2),delete:handle2=>{let deleted=this.entries.delete(handle2);return this.options.onSizeChange?.(this.entries.size),deleted},releaseReservation:async key=>{await this.options.pathReservations?.release(key),this.reservations.delete(key)},markDetached:key=>this.options.pathReservations?.setAttached(key,!1),now:()=>this.now(),sync:()=>this.syncRuntimeMetadata()}}get size(){return this.entries.size}holderPids(observedStarts){return this.options.pathReservations?.holderPids?.(observedStarts)??Promise.resolve([])}openSession(requested,options){return openRegistrySession({entries:this.entries,reservations:this.reservations,pendingClaims:this.pendingClaims,options:this.options,teardownHost:this.teardownHost,closeGraceMs:this.closeGraceMs,now:this.now,nextHandle:()=>`rpc-${++this.nextHandle}`,validateProfile:profile=>this.validateProfile(profile),syncRuntimeMetadata:()=>this.syncRuntimeMetadata()},requested,options)}peek(handle2){return this.entries.get(handle2)}attachSession(handle2){let entry=this.entries.get(handle2);return attachLiveSession(entry,this.now(),()=>markPathAttached(entry,this.options.pathReservations))}getForCommand(handle2,command){let entry=this.entries.get(handle2);if(!entry)throw new RpcSessionRegistryError("unknown_session");if(entry.state==="closing"&&!["abort","abort_bash","extension_ui_response","extension_ui_progress","host_response"].includes(command))throw new RpcSessionRegistryError("session_closing");if(entry.state!=="open"&&entry.state!=="closing")throw new RpcSessionRegistryError("unknown_session");return(entry.attachments>0||refreshesSessionActivity(command))&&(entry.lastCommandAt=this.now()),entry}beginClose(handle2,onRole,options){return beginSessionClose(this.teardownHost,handle2,onRole,options)}async close(handle2){return closeSession(this.teardownHost,handle2)}async closeMarked(handle2){return closeMarkedSession(this.teardownHost,handle2)}list(){this.syncRuntimeMetadata();let now=this.now();return[...this.entries].map(([sessionId,entry])=>({sessionId,durableSessionId:entry.durableSessionId,sessionPath:entry.sessionPath,cwd:entry.cwd,name:entry.runtime?.session.sessionManager.getSessionName(),kind:entry.kind,context:publishedSessionContext(entry.context,entry.contextOverlay),attachments:Math.max(0,entry.attachments),status:entry.state==="quarantined"?"closing":entry.state,idleMs:Math.max(0,now-entry.lastCommandAt),tool_child:entry.runtime?.session.toolChildRow()??{state:"none"}}))}syncRuntimeMetadata(){syncRuntimeMetadata(this.entries.values(),this.reservations,this.options.pathReservations)}validateProfile(profile){if(!isAbsolute2(profile.cwd)||profile.sessionPath!==void 0&&!isAbsolute2(profile.sessionPath))throw new RpcSessionRegistryError("invalid_path");if(profile.durableSessionId!==void 0)try{assertValidSessionId(profile.durableSessionId)}catch(cause){throw new RpcSessionRegistryError("invalid_session_id",String(cause))}}};var HANDOVER_PARKED_REOPEN_BUDGET_MS=12e4,HANDOVER_PARKED_REOPEN_POLL_MS=250,HANDOVER_PARKED_REOPEN_MAX_ATTEMPTS=8,HANDOVER_PARKED_REOPEN_QUIET_STREAK=8;async function reopenHandoverParkedSessions(open2,agentDir,socket,holder){let daemonDir=createHostDaemonPaths({socket,agentDir}).dir,deadline=Date.now()+HANDOVER_PARKED_REOPEN_BUDGET_MS,reopenAttempts=new Map,heldPolls=new Map,emptyStreak=0,sawAnyPark=!1;for(;;){if(holder?.shouldReopen!==void 0&&!holder.shouldReopen())return;let parked=await inheritedParks(daemonDir,holder);for(let entry of parked)sawAnyPark=!0,await reopenOne(daemonDir,open2,entry,reopenAttempts,heldPolls,holder);let remaining=(await inheritedParks(daemonDir,holder)).length;if(holder?.shouldReopen!==void 0&&!holder.shouldReopen()||(emptyStreak=remaining===0?emptyStreak+1:0,sawAnyPark&&emptyStreak>=HANDOVER_PARKED_REOPEN_QUIET_STREAK)||Date.now()>=deadline)return;await new Promise(resolve2=>setTimeout(resolve2,HANDOVER_PARKED_REOPEN_POLL_MS))}}async function inheritedParks(daemonDir,holder){return(await readHandoverParkedSessions(daemonDir)).filter(entry=>entry.parkedBy===void 0||entry.parkedBy!==holder?.hostInstance)}async function reopenOne(daemonDir,open2,entry,attempts,heldPolls,holder){let taskStatus=entry.contextOverlay&&Object.hasOwn(entry.contextOverlay,"task_status")?entry.contextOverlay.task_status:entry.sessionContext?.task_status;if(typeof taskStatus=="string"&&["completed","cancelled","error","failed","lost","interrupted"].includes(taskStatus)){await clearHandoverParkedSession(daemonDir,entry.sessionPath),process.stderr.write(`senpi rpc successor dropped a terminal parked session (${taskStatus}): ${entry.sessionPath}
8
8
  `);return}if(await dropHandoverParkedSessionIfFileGone(daemonDir,entry.sessionPath),!existsSync4(entry.sessionPath)){process.stderr.write(`senpi rpc successor dropped a parked session whose file is gone: ${entry.sessionPath}
@@ -20,10 +20,9 @@ import{getInternalHostBootstrap}from"./chunk-MYAENL22.js";import{SessionEventWri
20
20
  `)}host.bindings.delete(sessionId);try{await host.registry.closeMarked(sessionId)}catch(cause){process.stderr.write(`senpi rpc close for session ${sessionId} failed: ${String(cause)}
21
21
  `)}await host.registry.peek(sessionId)?.closeCompletion,terminal?.()}finally{finalization.resolve(),host.finalizations.delete(sessionId)}}function createFinalization(){let resolveFinalization;return{promise:new Promise(resolve2=>{resolveFinalization=resolve2}),resolve:()=>resolveFinalization?.()}}async function tearDownReleased(host,sessionId,sessionPath){let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return!1;let binding2=host.bindings.get(sessionId);return binding2?.cancelPendingExtensionUiRequests?.(),forgetSessionOwnership(host,sessionId),claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.releaseSession(sessionId,sessionPath)):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId),!0}async function tearDownUnloaded(host,sessionId,sessionPath){let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});if(!claim)return!1;let binding2=host.bindings.get(sessionId);return binding2?.cancelPendingExtensionUiRequests?.(),forgetSessionOwnership(host,sessionId),claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.parkSession(sessionId,sessionPath,"unloaded")):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId),!0}async function dispose(host){host.stopLimitBroadcast(),host.drainExitRequested=!0,stopSweep(host),host.drainTimer!==void 0&&clearInterval(host.drainTimer),await Promise.all([...host.bindings.entries()].map(async([sessionId,binding2])=>{let claim=tryClaimClose(host,sessionId,{drainAttachments:!0});claim&&(claim.finalizer?await finalizeClose(host,sessionId,binding2,()=>host.writer.closeSession(sessionId,{type:"response",command:"close_session",success:!0,data:{}},"host_shutdown")):await host.finalizations.get(sessionId)?.promise,host.writer.forgetSession(sessionId))})),host.bindings.clear(),host.uninstallEffectSink?.(),host.uninstallEffectSink=void 0}function relocationConnection(host,sessionId){return host.attachOrder.connections(sessionId).find(connection=>host.sessionsByConnection.get(connection)?.has(sessionId)===!0&&host.writer.getConnectionCapabilities(connection)?.includes(SESSION_RELOCATION_CAPABILITY)===!0)}function connectionLeft(host,sessionId,connection){host.attachOrder.detached(sessionId,connection),host.bindings.get(sessionId)?.connectionDetached?.(connection)}async function releaseDisconnectAttachment(host,sessionId){let live=host.registry.peek(sessionId),endsSession=live?.retainOnDisconnect!==!0&&(live?.attachments??0)<=1,session=live?.state==="open"?live.runtime?.session:void 0;if(endsSession&&live?.state==="open"&&live.worker?.snapshot?.streaming){let unsubscribe=live.worker.subscribeSettled(()=>{unsubscribe(),releaseOwnedSession(host,sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred worker release ${sessionId} failed: ${String(cause)}
22
22
  `)})});return!0}if(endsSession&&session?.isStreaming){let released=!1,unsubscribe=session.subscribe(event=>{event.type!=="agent_settled"&&event.type!=="agent_idle"||released||(released=!0,unsubscribe(),releaseOwnedSession(host,sessionId).catch(cause=>{process.stderr.write(`senpi rpc deferred release for session ${sessionId} failed: ${String(cause)}
23
- `)}))});return!0}return await releaseOwnedSession(host,sessionId),!1}function recordAttachment(host,owner,sessionId){host.writer.attachConnectionToSession(owner,sessionId);let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(sessionId,(owned.get(sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(sessionId,owner)}async function releaseConnection(host,connectionId){host.releasedConnections.add(connectionId),host.writer.clearConnectionCapabilities(connectionId),host.connectionRoles.release(connectionId);for(let sessionId of host.sessionsByConnection.get(connectionId)?.keys()??[])host.writer.detachConnectionFromSession(connectionId,sessionId),connectionLeft(host,sessionId,connectionId);host.writer.hasConnection(connectionId)||host.pendingCapabilities.delete(connectionId);let opens=host.opensByConnection.get(connectionId),owned=host.sessionsByConnection.get(connectionId);if(host.sessionsByConnection.delete(connectionId),host.draining)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...owned?.keys()??[]];if(owned===void 0)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[];let deferred=new Set;return await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++)await releaseDisconnectAttachment(host,sessionId)&&deferred.add(sessionId)})),opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...deferred]}async function releaseOwnedSession(host,sessionId){let live=host.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=tryClaimClose(host,sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){host.writer.status.publish(sessionId,"detach","client"),parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await host.finalizations.get(sessionId)?.promise;return}let binding2=host.bindings.get(sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,sessionId,binding2)}function releaseOwnerAttachment(host,owner,sessionId){let owned=host.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?(host.writer.detachConnectionFromSession(owner,sessionId),owned.delete(sessionId),connectionLeft(host,sessionId,owner)):owned.set(sessionId,count-1),owned.size===0&&host.sessionsByConnection.delete(owner))}function forgetSessionOwnership(host,sessionId){host.attachOrder.forgetSession(sessionId);for(let[connection,owned]of host.sessionsByConnection)owned.delete(sessionId),owned.size===0&&host.sessionsByConnection.delete(connection)}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecords=chunk=>{for(let line of chunk.split(`
24
- `)){if(!line)continue;let record=JSON.parse(line);toolSpans.observe(record),writer.enqueue(sessionId,record)}},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),droppedAfterClose=!1,handler=await runWithProviderScope(entry.scope,async()=>{let writeInScope=bindToProviderScope(enqueueRecords),taggedSink={writeRaw:chunk=>{if(entry.scope.state==="closed"){droppedAfterClose||process.stderr.write(`senpi rpc host: dropped a record for closed session ${sessionId} at ${new Date().toISOString()}
25
- `),droppedAfterClose=!0;return}writeInScope(chunk)},waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,eventFlushScheduler:flush=>flush(),publishLoadedSurfacesChanged:(previous,digest)=>{entry.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options,workerSecurityBridge:writer.workerSecurityBridge,grantDialogSettled:id=>writer.settleGrantDialog(sessionId,id),bindSecurityPresentation:(session,ui)=>writer.bindSecurityPresentations(sessionId,session.sessionId,session.securityNotices,ui),bindMcpForms:(session,ui)=>writer.bindMcpForms(sessionId,session.sessionId,ui,()=>session.admitHumanAnswer()),clientInfo:options.clientInfo===void 0?void 0:{...options.clientInfo,hasCapability:(connection,capability)=>writer.getConnectionCapabilities(connection)?.includes(capability)===!0}})});return await handler.ready,{handle:command=>writer.handleMcpForm(command)?Promise.resolve():runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),connectionDetached:connectionId=>runWithProviderScope(entry.scope,()=>handler.connectionDetached(connectionId)),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}var SessionAttachOrder=class{constructor(){this.next=0,this.order=new Map}attached(sessionId,connection){let connections=this.order.get(sessionId)??new Map;connections.has(connection)||connections.set(connection,this.next++),this.order.set(sessionId,connections)}detached(sessionId,connection){let connections=this.order.get(sessionId);connections?.delete(connection),connections?.size===0&&this.order.delete(sessionId)}forgetSession(sessionId){this.order.delete(sessionId)}connections(sessionId){return[...(this.order.get(sessionId)??new Map).entries()].sort((left,right)=>left[1]-right[1]).map(([connection])=>connection)}};var RouterContext=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.attachOrder=new SessionAttachOrder,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.connectionRoles=new ConnectionRoles,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.releaseTeardown=(sessionId,sessionPath)=>tearDownReleased(this,sessionId,sessionPath),this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>routingIdOf(this,session)!==void 0,flush:(session,statuses)=>{let sessionId=routingIdOf(this,session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>sweepIdleSessions(this),tickMs),this.sweepTimer.unref?.()}}};import{execFile}from"node:child_process";var READ_ONLY_OR_CONTROL=new Set(["get_state","get_effect_status","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_session_stats","resolve_path","get_fork_messages","get_entries","get_tree","get_last_assistant_text","get_messages","get_media","get_commands","get_loaded_surfaces","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek","eval_cells.stop","export_html","export_jsonl","abort","interrupt","abort_compaction","abort_branch_summary","abort_retry","abort_bash","clear_queue","check_reload_veto","cleanup_bash_output","set_client_info","extension_ui_response","extension_ui_progress","host_response"]);function readProcessStarts(){let windows=process.platform==="win32",command=windows?"powershell.exe":"ps",args=windows?["-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }']:["-axo","pid=,lstart="];return new Promise(resolve2=>{execFile(command,args,{timeout:windows?5e3:1e3,maxBuffer:4*1024*1024,windowsHide:!0,...windows?{}:{env:{...process.env,LC_ALL:"C",LANG:"C"}}},(error2,stdout)=>{if(error2)return resolve2(void 0);let starts=new Map;for(let line of stdout.split(`
26
- `)){let row=/^\s*(\d+)\s+(.+)$/.exec(line);if(!row)continue;let start=processStartTimeMs(row[2]);start!==void 0&&starts.set(Number(row[1]),start)}resolve2(starts)})})}function sessionHeldCheck(resolveDaemonPids){let daemonPids,processStarts,pidStarts=new Map,observedStarts=new Map;return async(sessionFile,sessionId)=>{let holders=await foreignSessionHolders(sessionFile,sessionId,{holderEnded:generation=>holderGenerationEnded(generation),readProcessStartMs:pid=>{let probe=pidStarts.get(pid);return probe||(probe=(async()=>{process.platform!=="linux"&&(processStarts??=readProcessStarts());let start=(await processStarts)?.get(pid)??await readProcessStartMs(pid);return observedStarts.set(pid,start),start})(),pidStarts.set(pid,probe)),probe}});if(holders.length===0)return;daemonPids??=resolveDaemonPids?.(observedStarts)??Promise.resolve([]);let family=await daemonPids,foreign=holders.filter(holder=>!family.includes(holder.pid));if(foreign.length>0)throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD,void 0,{holders:foreign.map(({pid,cwd,host_socket,host_instance})=>({pid,...cwd===void 0?{}:{cwd},...host_socket===void 0?{}:{host_socket},...host_instance===void 0?{}:{host_instance}}))})}}async function dispatchSessionBinding(command,entry,binding2,acknowledgePrompt2,daemonPids){if(!binding2)throw new RpcSessionRegistryError("unknown_session");if(!READ_ONLY_OR_CONTROL.has(command.type)){let assertSessionNotHeld=sessionHeldCheck(daemonPids),state=entry.worker?.snapshot?.state;await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),"sessionPath"in command&&await assertSessionNotHeld(command.sessionPath)}command.type==="prompt"&&acknowledgePrompt2(),await binding2.handle(command)}function invalidSpawnedBy(command){let ancestry=command.spawnedBy;return ancestry!==void 0&&!isSpawnedBy(ancestry)}function validatedOpenProfile(host,command,options){let defaults=options?.defaults===!1?void 0:host.defaults,instanceId=host.defaults.hostContext?.host_instance??hostInstanceId();if(command.expectedHostInstance!==void 0){if(typeof command.expectedHostInstance!="string"||command.expectedHostInstance.trim()==="")return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: expectedHostInstance must be a non-empty string`,{reason:"invalid_expected_host_instance",action:"supply_host_instance"});if(command.expectedHostInstance!==instanceId)return error(command.id,"open_session",RPC_ERROR_OWNER_CHANGED,{reason:"host_instance_mismatch",action:"rediscover_holder",expectedHostInstance:command.expectedHostInstance,hostInstance:instanceId})}let kindError=sessionKindError(command.kind);if(command.attended!==void 0&&command.attended!==!1)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: attended must be false or omitted`);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let promptSurfaceError=sessionPromptSurfaceError(command.promptSurface);if(promptSurfaceError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${promptSurfaceError}`);let browserEngineError=sessionBrowserEngineError(command.browserEngine);if(browserEngineError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${browserEngineError}`);if(!command.provider!=!command.modelId)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: provider and modelId must be given together`);let retryFallbackError=sessionRetryFallbackError(command.retryFallback);return retryFallbackError?error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${retryFallbackError}`):{cwd:command.cwd??host.defaults.cwd,...command.attended===!1?{attended:!1}:{},sessionPath:command.sessionPath,holderEndpoint:{host_instance:instanceId,...process.env[HOST_DAEMON_DIR_ENV]?{host_daemon_dir:process.env[HOST_DAEMON_DIR_ENV]}:{},...host.defaults.hostContext?.host_socket===void 0?{}:{host_socket:host.defaults.hostContext.host_socket}},permissionPreset:command.permissionPreset??defaults?.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:defaults?.creationModel,initialThinkingLevel:command.thinkingLevel??defaults?.initialThinkingLevel,sessionKind:command.kind,sessionContext:host.defaults.hostContext?{...command.context,...host.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{},...command.promptSurface!==void 0?{promptSurface:command.promptSurface}:{},...command.browserEngine!==void 0?{browserEngine:command.browserEngine}:{},...command.retryFallback!==void 0?{retryFallback:command.retryFallback}:{}}}function openWithBarrier(host,command){let owner=host.writer.currentConnection();if(owner===void 0)return open(host,command);let resolveBarrier,barrier=new Promise(resolve2=>{resolveBarrier=resolve2}),opens=host.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of host.opensByConnection.values())inFlight+=pending.size;opens.add(barrier),host.opensByConnection.set(owner,opens),command.id!==void 0&&host.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight});let opened=open(host,command,owner);if(command.sessionPath!==void 0&&host.handoverParkedDir!==void 0){let dir=host.handoverParkedDir,sessionPath=command.sessionPath;opened.then(response=>{response===void 0&&clearHandoverParkedSession(dir,sessionPath).catch(()=>{})},()=>{})}return opened.finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&host.opensByConnection.delete(owner)})}function reopenParked(host,entry){return open(host,{...parkedOpenCommand(entry),attended:!1},void 0,{reply:!1,defaults:!1,contextOverlay:entry.contextOverlay})}async function open(host,command,owner,options){let profile=validatedOpenProfile(host,command,options);if("type"in profile)return profile;let opened,assertSessionNotHeld=sessionHeldCheck(observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));try{if(await assertSessionNotHeld(command.sessionPath),invalidSpawnedBy(command))return error(command.id,"open_session","invalid_spawned_by");let ancestry=command.spawnedBy;opened=await host.registry.openSession(ancestry?{...profile,spawnedBy:ancestry}:profile,{retainOnDisconnect:command.retain_on_disconnect===!0,attachOnly:command.expectedHostInstance!==void 0});let openedSession=opened;if(host.writer.isSessionSealed(openedSession.sessionId))return await releaseOwnedSession(host,openedSession.sessionId),opened=void 0,error(command.id,"open_session","session_output_overflow",{sessionId:openedSession.sessionId,sessionPath:openedSession.sessionPath,action:"unload_and_reopen"});let entry=host.registry.getForCommand(openedSession.sessionId,"open_session");!opened.attached&&options?.contextOverlay!==void 0&&(entry.contextOverlay=options.contextOverlay);let state=entry.worker?.snapshot?.state;if(await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),host.writer.setSessionKind(openedSession.sessionId,entry.kind),host.writer.setSessionMedia(openedSession.sessionId,toolMediaPersister(()=>liveToolMediaScope(entry))),owner!==void 0&&(host.writer.hasRegisteredConnectionCapabilities(owner)||host.writer.setConnectionCapabilities(owner,host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]),host.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(openedSession.sessionId,owner)}if(!host.bindings.has(openedSession.sessionId)){host.bindings.set(openedSession.sessionId,await host.createBinding(openedSession.sessionId,entry,host.writer,()=>{close(host,{type:"close_session",sessionId:openedSession.sessionId})},{...host.connectionOptions,capabilities:owner!==void 0?host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]:host.connectionOptions?.capabilities,connectionRoles:host.connectionRoles,clientInfo:{setCapabilities:(connectionId,capabilities)=>{connectionId!==void 0&&(host.writer.setConnectionCapabilities(connectionId,capabilities),host.pendingCapabilities.set(connectionId,[...capabilities]))},connectionId:()=>host.writer.currentConnection(),relocationConnection:()=>relocationConnection(host,openedSession.sessionId),deliverTo:(connection,deliver)=>host.writer.withConnection(connection,deliver)}})),entry.worker&&(entry.worker.bindingReady=!0);let settled=()=>{host.draining&&queueMicrotask(()=>sweepDrain(host))};typeof entry.worker?.subscribeSettled=="function"?entry.worker.subscribeSettled(settled):typeof entry.runtime?.session.subscribe=="function"&&entry.runtime.session.subscribe(event=>{(event.type==="agent_settled"||event.type==="agent_idle")&&settled()}),entry.worker&&entry.worker.exited.then(async()=>{await host.finalizations.get(openedSession.sessionId)?.promise,host.bindings.delete(openedSession.sessionId),forgetSessionOwnership(host,openedSession.sessionId),host.writer.forgetSession(openedSession.sessionId)})}opened.attached?host.writer.status.publish(openedSession.sessionId,"attach","client"):(host.writer.publishSessionOpened({type:"session_opened",sessionId:openedSession.sessionId,durableSessionId:openedSession.durableSessionId,...openedSession.sessionPath!==void 0?{sessionPath:openedSession.sessionPath}:{},kind:entry.kind,cwd:entry.cwd,context:entry.context}),host.writer.status.publish(openedSession.sessionId,"open","client")),!host.draining&&owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,openedSession.sessionId),await releaseOwnedSession(host,openedSession.sessionId));let replyState=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!replyState)throw new Error("Session state was not created");options?.reply!==!1&&host.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state:replyState,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened){if(!opened.attached){let entry=host.registry.peek(opened.sessionId);(entry?.runtime!==void 0||entry?.worker!==void 0)&&host.writer.sealRolledBackOpen(opened.sessionId,entry.sessionPath)}try{opened.attached?await releaseOwnedSession(host,opened.sessionId):await host.registry.close(opened.sessionId)}catch{}host.writer.forgetSession(opened.sessionId)}return error(command.id,"open_session",code(cause),detail(cause))}}async function detachConnection(command,connectionId,release){if(connectionId===void 0)return{id:command.id,type:"response",command:"detach_connection",success:!1,error:"detach_connection needs a socket connection"};let deferred=await release(connectionId);return{id:command.id,type:"response",command:"detach_connection",success:!0,data:{deferred:[...deferred]}}}var MOVE_SESSION_CAPABILITY="move_session",MOVE_SESSION_REVOKE_CAPABILITY="move_session_revoke",RPC_ERROR_INVALID_MOVE_REQUEST="invalid_move_request",RPC_ERROR_SESSION_OPEN_HERE="session_open_here",RPC_ERROR_MOVE_NOT_RELEASED="move_not_released",RPC_ERROR_MOVE_FAILED="move_failed";var UNLOAD_SESSION_CAPABILITY="unload_session",SUBSCRIPTION_LIMITS_CAPABILITY="subscription_limits",RESOLVE_PATH_CAPABILITY="resolve_path";function multiSessionHostCapabilities(options){return[...new Set(["multi_session",...options.mcpPresenters?["mcp_form_presenter_v1"]:[],"session_lifecycle","expected_host_instance","attach_session","release_attachment","release_caller_aware","reclaim_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,SUBSCRIPTION_LIMITS_CAPABILITY,RESOLVE_PATH_CAPABILITY,STEER_WHEN_IDLE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,TOOL_BARRIER_CAPABILITY,USER_ACTIVITY_CAPABILITY,SESSION_HELD_CAPABILITY,RESUME_SESSION_CAPABILITY,ATTENDED_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,DETACH_CONNECTION_CAPABILITY,UNLOAD_SESSION_CAPABILITY,MOVE_SESSION_CAPABILITY,MOVE_SESSION_REVOKE_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,BROWSER_ENGINE_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,...options.warm?[WARM_CAPABILITY]:[],...toolRuntimeCapabilities(options.toolRuntime),...options.negotiated.filter(capability=>capability!=="mcp_form_presenter_v1"&&!isHostOwnedToolRuntimeCapability(capability))])]}function identityMatches(host,entry,durableSessionId,expectedHostInstance){let durable=entry.runtime?.session.sessionId??entry.worker?.snapshot?.state.sessionId??entry.durableSessionId;return typeof durableSessionId=="string"&&durableSessionId.length>0&&durableSessionId===durable&&(expectedHostInstance===void 0||expectedHostInstance===(host.defaults.hostContext?.host_instance??hostInstanceId()))}function hostStopping(host){return host.draining||host.drainExitRequested}function drainingRefusal(host,command){if(hostStopping(host))return error(command.id,command.type,"session_busy_lifecycle",{reason:"host_draining"})}function attach(host,owner,sessionId){if(!host.registry.attachSession)throw new Error("live attachment is unavailable");host.registry.attachSession(sessionId),recordAttachment(host,owner,sessionId),host.writer.status.publish(sessionId,"attach","client")}function attachSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;let entry=host.registry.peek(command.sessionId);if(entry?.state!=="open"||!host.bindings.has(command.sessionId))return error(command.id,command.type,"unknown_session",{});if(!identityMatches(host,entry,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});try{return attach(host,owner,command.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{sessionId:command.sessionId,attached:!0}}}catch(cause){return error(command.id,command.type,code(cause),detail(cause)??{})}}async function releaseAttachment(host,command){let owner=host.writer.currentConnection();if(owner===void 0||!host.sessionsByConnection.get(owner)?.has(command.sessionId))return error(command.id,command.type,"session_not_attached",{reason:"not_attached"});releaseOwnerAttachment(host,owner,command.sessionId);let deferred=!hostStopping(host)&&await releaseDisconnectAttachment(host,command.sessionId);return{id:command.id,type:"response",command:command.type,success:!0,data:{deferred}}}async function reclaimSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;if(typeof command.sessionPath!="string"||command.sessionPath.length===0)return error(command.id,command.type,"unknown_session",{});let key=canonicalSessionPath(command.sessionPath),row=host.registry.list().find(candidate=>candidate.sessionPath!==void 0&&canonicalSessionPath(candidate.sessionPath)===key),entry=row&&host.registry.peek(row.sessionId);if(!row||!entry)return error(command.id,command.type,"unknown_session",{});if(entry.state!=="open"||!host.bindings.has(row.sessionId))return error(command.id,command.type,"session_busy_lifecycle",{});if(typeof command.expectedHostInstance!="string"||!identityMatches(host,entry,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});let own=host.sessionsByConnection.get(owner)?.get(row.sessionId)??0,elsewhere=Math.max(0,entry.attachments-own);if(elsewhere>0)return error(command.id,command.type,"attached_elsewhere",{attachments:elsewhere});attach(host,owner,row.sessionId);let claim=claimClose(host,row.sessionId,{drainAttachments:!0});if(host.sessionsByConnection.get(owner)?.delete(row.sessionId),host.sessionsByConnection.get(owner)?.size===0&&host.sessionsByConnection.delete(owner),connectionLeft(host,row.sessionId,owner),host.handoverParkedDir!==void 0&&entry.sessionPath!==void 0&&await clearHandoverParkedSession(host.handoverParkedDir,entry.sessionPath).catch(()=>{}),claim.finalizer){let binding2=host.bindings.get(row.sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,row.sessionId,binding2,()=>host.writer.sealLifecycle(row.sessionId,{type:"session_closed",sessionId:row.sessionId,reason:"client_close"},!0))}return host.writer.detachConnectionFromSession(owner,row.sessionId),host.writer.forgetSession(row.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{reclaimed:!0,sessionId:row.sessionId}}}var ATTACH_GATE_EXEMPT=new Set(["get_protocol_info","list_sessions","subscribe_sessions","unsubscribe_sessions","get_subscription_limits","warm","detach_connection","open_session","attach_session","reclaim_session","get_effect_status","get_state","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_media","get_commands","get_loaded_surfaces","get_available_models","get_available_thinking_levels","get_fast_mode","get_session_stats","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_auth_providers","get_provider_accounts","resolve_path","memory_report","eval_cells.list","eval_cells.peek","check_reload_veto"]);function logSafe(value){return JSON.stringify(value).slice(1,-1)}function attachmentGate(host,command){let owner=host.writer.currentConnection();if(!(owner===void 0||ATTACH_GATE_EXEMPT.has(command.type))&&!(!("sessionId"in command)||command.sessionId===void 0)&&!(command.type==="close_session"||command.type==="set_session_context"||command.type==="release_attachment")&&!host.sessionsByConnection.get(owner)?.has(command.sessionId)){if(process.env.SENPI_RPC_REQUIRE_ATTACH==="1")return error(command.id,command.type,"session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session { sessionId, durableSessionId } or open_session { sessionPath }"});process.stderr.write(`senpi rpc host: ${command.type} on ${logSafe(command.sessionId)} from a connection not attached to it (refused from the next release)
23
+ `)}))});return!0}return await releaseOwnedSession(host,sessionId),!1}function recordAttachment(host,owner,sessionId){host.writer.attachConnectionToSession(owner,sessionId);let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(sessionId,(owned.get(sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(sessionId,owner)}async function releaseConnection(host,connectionId){host.releasedConnections.add(connectionId),host.writer.clearConnectionCapabilities(connectionId),host.connectionRoles.release(connectionId);for(let sessionId of host.sessionsByConnection.get(connectionId)?.keys()??[])host.writer.detachConnectionFromSession(connectionId,sessionId),connectionLeft(host,sessionId,connectionId);host.writer.hasConnection(connectionId)||host.pendingCapabilities.delete(connectionId);let opens=host.opensByConnection.get(connectionId),owned=host.sessionsByConnection.get(connectionId);if(host.sessionsByConnection.delete(connectionId),host.draining)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...owned?.keys()??[]];if(owned===void 0)return opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[];let deferred=new Set;return await Promise.all([...owned].map(async([sessionId,count])=>{for(let attachment=0;attachment<count;attachment++)await releaseDisconnectAttachment(host,sessionId)&&deferred.add(sessionId)})),opens&&await Promise.all([...opens]),host.releasedConnections.delete(connectionId),[...deferred]}async function releaseOwnedSession(host,sessionId){let live=host.registry.peek(sessionId),parks=live?.state==="open"&&live.retainOnDisconnect===!0&&live.attachments===1,claim=tryClaimClose(host,sessionId,{drainAttachments:!1,detach:!0});if(!claim)return;if(!claim.finalizer){host.writer.status.publish(sessionId,"detach","client"),parks&&live.runtime&&(live.lifecycleMutex=live.lifecycleMutex.then(()=>live.runtime?.emitAttachmentEvent("session_parked")),await live.lifecycleMutex),await host.finalizations.get(sessionId)?.promise;return}let binding2=host.bindings.get(sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,sessionId,binding2)}function releaseOwnerAttachment(host,owner,sessionId){let owned=host.sessionsByConnection.get(owner),count=owned?.get(sessionId);!owned||count===void 0||(count===1?(host.writer.detachConnectionFromSession(owner,sessionId),owned.delete(sessionId),connectionLeft(host,sessionId,owner)):owned.set(sessionId,count-1),owned.size===0&&host.sessionsByConnection.delete(owner))}function forgetSessionOwnership(host,sessionId){host.attachOrder.forgetSession(sessionId);for(let[connection,owned]of host.sessionsByConnection)owned.delete(sessionId),owned.size===0&&host.sessionsByConnection.delete(connection)}async function createRpcSessionBinding(sessionId,entry,writer,requestClose,options={}){if(entry.worker)return entry.worker.bind(sessionId,writer,requestClose,options);if(!entry.runtime)throw new Error("Session runtime was not created");let toolSpans=createToolAttributionSpans(sessionId),enqueueRecord=record=>{toolSpans.observe(record),writer.enqueue(sessionId,record)},runtimeHost=new Proxy({},{get(_target,property){if(property==="switchSession"&&entry.switchSession)return entry.switchSession;if(property==="setRebindSession")return callback=>{entry.rebindSession=callback,entry.runtime?.setRebindSession(callback)};let runtime=entry.runtime;if(!runtime)throw new Error("Session runtime was not created");let value=Reflect.get(runtime,property,runtime);return typeof value=="function"?value.bind(runtime):value}}),droppedAfterClose=!1,handler=await runWithProviderScope(entry.scope,async()=>{let writeInScope=bindToProviderScope(enqueueRecord),dropAfterClose=()=>{droppedAfterClose||process.stderr.write(`senpi rpc host: dropped a record for closed session ${sessionId} at ${new Date().toISOString()}
24
+ `),droppedAfterClose=!0},taggedSink={writeRecord:record=>{if(entry.scope.state==="closed")return dropAfterClose();writeInScope(record)},writeRaw:()=>{if(entry.scope.state==="closed")return dropAfterClose();throw new Error("Shared session bindings deliver records through writeRecord, never writeRaw")},waitForBackpressure:bindToProviderScope(async()=>{})};return createRpcConnectionHandler(runtimeHost,taggedSink,{sessionId,shutdownHandler:bindToProviderScope(requestClose),disposeRuntime:!1,publishLoadedSurfacesChanged:(previous,digest)=>{entry.scope.state!=="closed"&&writer.publishLoadedSurfacesChanged(sessionId,previous,digest)},...options,workerSecurityBridge:writer.workerSecurityBridge,grantDialogSettled:id=>writer.settleGrantDialog(sessionId,id),bindSecurityPresentation:(session,ui)=>writer.bindSecurityPresentations(sessionId,session.sessionId,session.securityNotices,ui),bindMcpForms:(session,ui)=>writer.bindMcpForms(sessionId,session.sessionId,ui,()=>session.admitHumanAnswer()),clientInfo:options.clientInfo===void 0?void 0:{...options.clientInfo,hasCapability:(connection,capability)=>writer.getConnectionCapabilities(connection)?.includes(capability)===!0}})});return await handler.ready,{handle:command=>writer.handleMcpForm(command)?Promise.resolve():runWithProviderScope(entry.scope,()=>handler.handleInputLine(JSON.stringify(command))),cancelPendingExtensionUiRequests:()=>runWithProviderScope(entry.scope,()=>handler.cancelPendingExtensionUiRequests()),pendingPrompts:()=>handler.pendingPrompts(),connectionDetached:connectionId=>runWithProviderScope(entry.scope,()=>handler.connectionDetached(connectionId)),dispose:()=>(toolSpans.closeAll(),runWithProviderScope(entry.scope,()=>handler.dispose()))}}var SessionAttachOrder=class{constructor(){this.next=0,this.order=new Map}attached(sessionId,connection){let connections=this.order.get(sessionId)??new Map;connections.has(connection)||connections.set(connection,this.next++),this.order.set(sessionId,connections)}detached(sessionId,connection){let connections=this.order.get(sessionId);connections?.delete(connection),connections?.size===0&&this.order.delete(sessionId)}forgetSession(sessionId){this.order.delete(sessionId)}connections(sessionId){return[...(this.order.get(sessionId)??new Map).entries()].sort((left,right)=>left[1]-right[1]).map(([connection])=>connection)}};var RouterContext=class{constructor(registry,writer,defaults,createBinding=createRpcSessionBinding,connectionOptions={},idle){if(this.bindings=new Map,this.sessionsByConnection=new Map,this.attachOrder=new SessionAttachOrder,this.opensByConnection=new Map,this.releasedConnections=new Set,this.pendingCapabilities=new Map,this.connectionRoles=new ConnectionRoles,this.finalizations=new Map,this.draining=!1,this.handoffParks=0,this.drainExitRequested=!1,this.handoffClosed=new Set,this.activeRequests=new Map,this.requestSettledListeners=new Map,this.memoryPressure=!1,this.releaseTeardown=(sessionId,sessionPath)=>tearDownReleased(this,sessionId,sessionPath),this.stopLimitBroadcast=subscriptionLimits.subscribe(limits=>writer.broadcastHostRecord({type:"subscription_limits",...limits})),this.registry=registry,this.writer=writer,this.defaults=defaults,this.createBinding=createBinding,this.connectionOptions=connectionOptions,this.idleNow=idle?.now??Date.now,this.idleEvictionMs=idle?.idleEvictionMs??Number.POSITIVE_INFINITY,this.emptyExitMs=idle?.emptyExitMs??Number.POSITIVE_INFINITY,this.onEmptyExit=idle?.onEmptyExit,this.onHandoffParked=idle?.onHandoffParked,this.handoverParkedDir=idle?.handoverParkedDir,this.canExitWhenEmpty=idle?.canExitWhenEmpty,writer.status.setSource(registryStatusSource(registry)),writer.status.setLastEffectProvider(sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session===void 0)return;let latest=latestSessionEffect(session);return latest===void 0?void 0:{effectId:latest.effectId,kind:latest.kind,state:latest.state}}),writer.afterRecord=sessionId=>{let session=this.registry.peek(sessionId)?.runtime?.session;if(session!==void 0)for(let status of drainSessionEffects(session))this.writer.status.publishEffect(sessionId,status)},this.uninstallEffectSink=installSessionEffectSink({owns:session=>routingIdOf(this,session)!==void 0,flush:(session,statuses)=>{let sessionId=routingIdOf(this,session);if(sessionId!==void 0)for(let status of statuses)this.writer.status.publishEffect(sessionId,status)}}),Number.isFinite(this.idleEvictionMs)||Number.isFinite(this.emptyExitMs)){let tickMs=Math.max(20,Math.min(5e3,Math.min(this.idleEvictionMs,this.emptyExitMs)/4));this.sweepTimer=setInterval(()=>sweepIdleSessions(this),tickMs),this.sweepTimer.unref?.()}}};import{execFile}from"node:child_process";var READ_ONLY_OR_CONTROL=new Set(["get_state","get_snapshot","get_effect_status","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_available_models","get_available_thinking_levels","get_model_thinking_level","get_fast_mode","get_session_stats","resolve_path","get_fork_messages","get_entries","get_tree","get_last_assistant_text","get_messages","get_media","get_commands","get_loaded_surfaces","get_auth_providers","get_provider_accounts","memory_report","eval_cells.list","eval_cells.peek","eval_cells.stop","export_html","export_jsonl","abort","interrupt","abort_compaction","abort_branch_summary","abort_retry","abort_bash","clear_queue","check_reload_veto","cleanup_bash_output","set_client_info","extension_ui_response","extension_ui_progress","host_response"]);function readProcessStarts(){let windows=process.platform==="win32",command=windows?"powershell.exe":"ps",args=windows?["-NoProfile","-NonInteractive","-Command",'Get-CimInstance Win32_Process -ErrorAction Stop | ForEach-Object { if ($null -ne $_.CreationDate) { "{0} {1}" -f $_.ProcessId, $_.CreationDate.ToUniversalTime().ToString("o") } }']:["-axo","pid=,lstart="];return new Promise(resolve2=>{execFile(command,args,{timeout:windows?5e3:1e3,maxBuffer:4*1024*1024,windowsHide:!0,...windows?{}:{env:{...process.env,LC_ALL:"C",LANG:"C"}}},(error2,stdout)=>{if(error2)return resolve2(void 0);let starts=new Map;for(let line of stdout.split(`
25
+ `)){let row=/^\s*(\d+)\s+(.+)$/.exec(line);if(!row)continue;let start=processStartTimeMs(row[2]);start!==void 0&&starts.set(Number(row[1]),start)}resolve2(starts)})})}function sessionHeldCheck(resolveDaemonPids){let daemonPids,processStarts,pidStarts=new Map,observedStarts=new Map;return async(sessionFile,sessionId)=>{let holders=await foreignSessionHolders(sessionFile,sessionId,{holderEnded:generation=>holderGenerationEnded(generation),readProcessStartMs:pid=>{let probe=pidStarts.get(pid);return probe||(probe=(async()=>{process.platform!=="linux"&&(processStarts??=readProcessStarts());let start=(await processStarts)?.get(pid)??await readProcessStartMs(pid);return observedStarts.set(pid,start),start})(),pidStarts.set(pid,probe)),probe}});if(holders.length===0)return;daemonPids??=resolveDaemonPids?.(observedStarts)??Promise.resolve([]);let family=await daemonPids,foreign=holders.filter(holder=>!family.includes(holder.pid));if(foreign.length>0)throw new RpcSessionRegistryError(RPC_ERROR_SESSION_HELD,void 0,{holders:foreign.map(({pid,cwd,host_socket,host_instance})=>({pid,...cwd===void 0?{}:{cwd},...host_socket===void 0?{}:{host_socket},...host_instance===void 0?{}:{host_instance}}))})}}async function dispatchSessionBinding(command,entry,binding2,acknowledgePrompt2,daemonPids){if(!binding2)throw new RpcSessionRegistryError("unknown_session");if(!READ_ONLY_OR_CONTROL.has(command.type)){let assertSessionNotHeld=sessionHeldCheck(daemonPids),state=entry.worker?.snapshot?.state;await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),"sessionPath"in command&&await assertSessionNotHeld(command.sessionPath)}command.type==="prompt"&&acknowledgePrompt2(),await binding2.handle(command)}function invalidSpawnedBy(command){let ancestry=command.spawnedBy;return ancestry!==void 0&&!isSpawnedBy(ancestry)}function validatedOpenProfile(host,command,options){let defaults=options?.defaults===!1?void 0:host.defaults,instanceId=host.defaults.hostContext?.host_instance??hostInstanceId();if(command.expectedHostInstance!==void 0){if(typeof command.expectedHostInstance!="string"||command.expectedHostInstance.trim()==="")return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: expectedHostInstance must be a non-empty string`,{reason:"invalid_expected_host_instance",action:"supply_host_instance"});if(command.expectedHostInstance!==instanceId)return error(command.id,"open_session",RPC_ERROR_OWNER_CHANGED,{reason:"host_instance_mismatch",action:"rediscover_holder",expectedHostInstance:command.expectedHostInstance,hostInstance:instanceId})}let kindError=sessionKindError(command.kind);if(command.attended!==void 0&&command.attended!==!1)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: attended must be false or omitted`);if(kindError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_KIND}: ${kindError}`);let contextError=sessionContextError(command.context);if(contextError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_SESSION_CONTEXT}: ${contextError}`);let autoTitleError=sessionAutoTitleError(command.auto_title);if(autoTitleError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${autoTitleError}`);let promptSurfaceError=sessionPromptSurfaceError(command.promptSurface);if(promptSurfaceError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${promptSurfaceError}`);let browserEngineError=sessionBrowserEngineError(command.browserEngine);if(browserEngineError)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${browserEngineError}`);if(!command.provider!=!command.modelId)return error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: provider and modelId must be given together`);let retryFallbackError=sessionRetryFallbackError(command.retryFallback);return retryFallbackError?error(command.id,"open_session",`${RPC_ERROR_INVALID_LAUNCH_PROFILE}: ${retryFallbackError}`):{cwd:command.cwd??host.defaults.cwd,...command.attended===!1?{attended:!1}:{},sessionPath:command.sessionPath,holderEndpoint:{host_instance:instanceId,...process.env[HOST_DAEMON_DIR_ENV]?{host_daemon_dir:process.env[HOST_DAEMON_DIR_ENV]}:{},...host.defaults.hostContext?.host_socket===void 0?{}:{host_socket:host.defaults.hostContext.host_socket}},permissionPreset:command.permissionPreset??defaults?.permissionPreset,creationModel:command.provider&&command.modelId?{provider:command.provider,modelId:command.modelId}:defaults?.creationModel,initialThinkingLevel:command.thinkingLevel??defaults?.initialThinkingLevel,sessionKind:command.kind,sessionContext:host.defaults.hostContext?{...command.context,...host.defaults.hostContext}:command.context,...command.durableSessionId!==void 0?{durableSessionId:command.durableSessionId}:{},...typeof command.auto_title=="boolean"?{autoTitle:command.auto_title}:{},...command.promptSurface!==void 0?{promptSurface:command.promptSurface}:{},...command.browserEngine!==void 0?{browserEngine:command.browserEngine}:{},...command.retryFallback!==void 0?{retryFallback:command.retryFallback}:{}}}function openWithBarrier(host,command){let owner=host.writer.currentConnection();if(owner===void 0)return open(host,command);let resolveBarrier,barrier=new Promise(resolve2=>{resolveBarrier=resolve2}),opens=host.opensByConnection.get(owner)??new Set,inFlight=0;for(let pending of host.opensByConnection.values())inFlight+=pending.size;opens.add(barrier),host.opensByConnection.set(owner,opens),command.id!==void 0&&host.writer.sendOpenQueued(owner,{type:"queued",for_request:command.id,position:inFlight+1,in_flight:inFlight});let opened=open(host,command,owner);if(command.sessionPath!==void 0&&host.handoverParkedDir!==void 0){let dir=host.handoverParkedDir,sessionPath=command.sessionPath;opened.then(response=>{response===void 0&&clearHandoverParkedSession(dir,sessionPath).catch(()=>{})},()=>{})}return opened.finally(()=>{resolveBarrier(),opens.delete(barrier),opens.size===0&&host.opensByConnection.delete(owner)})}function reopenParked(host,entry){return open(host,{...parkedOpenCommand(entry),attended:!1},void 0,{reply:!1,defaults:!1,contextOverlay:entry.contextOverlay})}async function open(host,command,owner,options){let profile=validatedOpenProfile(host,command,options);if("type"in profile)return profile;let opened,assertSessionNotHeld=sessionHeldCheck(observedStarts=>host.registry.holderPids?.(observedStarts)??Promise.resolve([]));try{if(await assertSessionNotHeld(command.sessionPath),invalidSpawnedBy(command))return error(command.id,"open_session","invalid_spawned_by");let ancestry=command.spawnedBy;opened=await host.registry.openSession(ancestry?{...profile,spawnedBy:ancestry}:profile,{retainOnDisconnect:command.retain_on_disconnect===!0,attachOnly:command.expectedHostInstance!==void 0});let openedSession=opened;if(host.writer.isSessionSealed(openedSession.sessionId))return await releaseOwnedSession(host,openedSession.sessionId),opened=void 0,error(command.id,"open_session","session_output_overflow",{sessionId:openedSession.sessionId,sessionPath:openedSession.sessionPath,action:"unload_and_reopen"});let entry=host.registry.getForCommand(openedSession.sessionId,"open_session");!opened.attached&&options?.contextOverlay!==void 0&&(entry.contextOverlay=options.contextOverlay);let state=entry.worker?.snapshot?.state;if(await assertSessionNotHeld(entry.runtime?.session.sessionFile??state?.sessionFile??entry.sessionPath,entry.runtime?.session.sessionId??state?.sessionId??entry.durableSessionId),host.writer.setSessionKind(openedSession.sessionId,entry.kind),host.writer.setSessionMedia(openedSession.sessionId,toolMediaPersister(()=>liveToolMediaScope(entry))),owner!==void 0&&(host.writer.hasRegisteredConnectionCapabilities(owner)||host.writer.setConnectionCapabilities(owner,host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]),host.writer.attachConnectionToSession(owner,openedSession.sessionId)),owner!==void 0){let owned=host.sessionsByConnection.get(owner)??new Map;owned.set(openedSession.sessionId,(owned.get(openedSession.sessionId)??0)+1),host.sessionsByConnection.set(owner,owned),host.attachOrder.attached(openedSession.sessionId,owner)}if(!host.bindings.has(openedSession.sessionId)){host.bindings.set(openedSession.sessionId,await host.createBinding(openedSession.sessionId,entry,host.writer,()=>{close(host,{type:"close_session",sessionId:openedSession.sessionId})},{...host.connectionOptions,capabilities:owner!==void 0?host.pendingCapabilities.get(owner)??host.connectionOptions?.capabilities??[]:host.connectionOptions?.capabilities,connectionRoles:host.connectionRoles,clientInfo:{setCapabilities:(connectionId,capabilities)=>{connectionId!==void 0&&(host.writer.setConnectionCapabilities(connectionId,capabilities),host.pendingCapabilities.set(connectionId,[...capabilities]))},connectionId:()=>host.writer.currentConnection(),relocationConnection:()=>relocationConnection(host,openedSession.sessionId),deliverTo:(connection,deliver)=>host.writer.withConnection(connection,deliver)}})),entry.worker&&(entry.worker.bindingReady=!0);let settled=()=>{host.draining&&queueMicrotask(()=>sweepDrain(host))};typeof entry.worker?.subscribeSettled=="function"?entry.worker.subscribeSettled(settled):typeof entry.runtime?.session.subscribe=="function"&&entry.runtime.session.subscribe(event=>{(event.type==="agent_settled"||event.type==="agent_idle")&&settled()}),entry.worker&&entry.worker.exited.then(async()=>{await host.finalizations.get(openedSession.sessionId)?.promise,host.bindings.delete(openedSession.sessionId),forgetSessionOwnership(host,openedSession.sessionId),host.writer.forgetSession(openedSession.sessionId)})}opened.attached?host.writer.status.publish(openedSession.sessionId,"attach","client"):(host.writer.publishSessionOpened({type:"session_opened",sessionId:openedSession.sessionId,durableSessionId:openedSession.durableSessionId,...openedSession.sessionPath!==void 0?{sessionPath:openedSession.sessionPath}:{},kind:entry.kind,cwd:entry.cwd,context:entry.context}),host.writer.status.publish(openedSession.sessionId,"open","client")),!host.draining&&owner!==void 0&&host.releasedConnections.has(owner)&&(releaseOwnerAttachment(host,owner,openedSession.sessionId),await releaseOwnedSession(host,openedSession.sessionId));let replyState=entry.worker?.snapshot?.state??(entry.runtime?buildRpcSessionState(entry.runtime.session):void 0);if(!replyState)throw new Error("Session state was not created");options?.reply!==!1&&host.writer.enqueue(opened.sessionId,{id:command.id,type:"response",command:"open_session",success:!0,data:{sessionId:opened.sessionId,state:replyState,...opened.attached?{attached:!0}:{}}});return}catch(cause){if(opened){if(!opened.attached){let entry=host.registry.peek(opened.sessionId);(entry?.runtime!==void 0||entry?.worker!==void 0)&&host.writer.sealRolledBackOpen(opened.sessionId,entry.sessionPath)}try{opened.attached?await releaseOwnedSession(host,opened.sessionId):await host.registry.close(opened.sessionId)}catch{}host.writer.forgetSession(opened.sessionId)}return error(command.id,"open_session",code(cause),detail(cause))}}async function detachConnection(command,connectionId,release){if(connectionId===void 0)return{id:command.id,type:"response",command:"detach_connection",success:!1,error:"detach_connection needs a socket connection"};let deferred=await release(connectionId);return{id:command.id,type:"response",command:"detach_connection",success:!0,data:{deferred:[...deferred]}}}var MOVE_SESSION_CAPABILITY="move_session",MOVE_SESSION_REVOKE_CAPABILITY="move_session_revoke",RPC_ERROR_INVALID_MOVE_REQUEST="invalid_move_request",RPC_ERROR_SESSION_OPEN_HERE="session_open_here",RPC_ERROR_MOVE_NOT_RELEASED="move_not_released",RPC_ERROR_MOVE_FAILED="move_failed";var UNLOAD_SESSION_CAPABILITY="unload_session",SUBSCRIPTION_LIMITS_CAPABILITY="subscription_limits",RESOLVE_PATH_CAPABILITY="resolve_path";function multiSessionHostCapabilities(options){return[...new Set(["multi_session","snapshot_cursor","ui_answer_ledger","dialog_observer",...options.mcpPresenters?["mcp_form_presenter_v1"]:[],"session_lifecycle","expected_host_instance","attach_session","release_attachment","release_caller_aware","reclaim_session",AUTO_TITLE_SESSIONS_CAPABILITY,MEDIA_PLACEHOLDERS_CAPABILITY,DURABLE_CLIENT_MESSAGE_ID_CAPABILITY,EFFECT_LEDGER_CAPABILITY,SUBSCRIPTION_LIMITS_CAPABILITY,RESOLVE_PATH_CAPABILITY,STEER_WHEN_IDLE_CAPABILITY,CONTINUE_FROM_LEAF_CAPABILITY,EVAL_CELLS_CAPABILITY,AUTH_KEY_VERIFY_CAPABILITY,QUEUED_MESSAGE_REVISION_CAPABILITY,TOOL_BARRIER_CAPABILITY,USER_ACTIVITY_CAPABILITY,SESSION_HELD_CAPABILITY,RESUME_SESSION_CAPABILITY,ATTENDED_CAPABILITY,OBSERVE_READS_CAPABILITY,ENTRIES_TAIL_CAPABILITY,RETAIN_ON_DISCONNECT_CAPABILITY,DETACH_CONNECTION_CAPABILITY,UNLOAD_SESSION_CAPABILITY,MOVE_SESSION_CAPABILITY,MOVE_SESSION_REVOKE_CAPABILITY,SESSION_RELOCATION_CAPABILITY,SESSION_CONTEXT_CAPABILITY,SESSION_KIND_CAPABILITY,SESSION_STATUS_CAPABILITY,AUTO_TITLE_PER_SESSION_CAPABILITY,DURABLE_SESSION_ID_CAPABILITY,MOVED_PATH_GUARD_CAPABILITY,PROMPT_SURFACE_CAPABILITY,PROMPT_SURFACE_CHAT_CAPABILITY,BROWSER_ENGINE_CAPABILITY,RETRY_FALLBACK_PROFILE_CAPABILITY,ACCEPT_EDITS_PERMISSION_PRESET_CAPABILITY,AUTO_PERMISSION_PRESET_CAPABILITY,...options.warm?[WARM_CAPABILITY]:[],...toolRuntimeCapabilities(options.toolRuntime),...options.negotiated.filter(capability=>capability!=="mcp_form_presenter_v1"&&!isHostOwnedToolRuntimeCapability(capability))])]}function identityMatches(host,entry,durableSessionId,expectedHostInstance){let durable=entry.runtime?.session.sessionId??entry.worker?.snapshot?.state.sessionId??entry.durableSessionId;return typeof durableSessionId=="string"&&durableSessionId.length>0&&durableSessionId===durable&&(expectedHostInstance===void 0||expectedHostInstance===(host.defaults.hostContext?.host_instance??hostInstanceId()))}function hostStopping(host){return host.draining||host.drainExitRequested}function drainingRefusal(host,command){if(hostStopping(host))return error(command.id,command.type,"session_busy_lifecycle",{reason:"host_draining"})}function attach(host,owner,sessionId){if(!host.registry.attachSession)throw new Error("live attachment is unavailable");host.registry.attachSession(sessionId),recordAttachment(host,owner,sessionId),host.writer.status.publish(sessionId,"attach","client")}function attachSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;let entry=host.registry.peek(command.sessionId);if(entry?.state!=="open"||!host.bindings.has(command.sessionId))return error(command.id,command.type,"unknown_session",{});if(!identityMatches(host,entry,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});try{return attach(host,owner,command.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{sessionId:command.sessionId,attached:!0}}}catch(cause){return error(command.id,command.type,code(cause),detail(cause)??{})}}async function releaseAttachment(host,command){let owner=host.writer.currentConnection();if(owner===void 0||!host.sessionsByConnection.get(owner)?.has(command.sessionId))return error(command.id,command.type,"session_not_attached",{reason:"not_attached"});releaseOwnerAttachment(host,owner,command.sessionId);let deferred=!hostStopping(host)&&await releaseDisconnectAttachment(host,command.sessionId);return{id:command.id,type:"response",command:command.type,success:!0,data:{deferred}}}async function reclaimSession(host,command){let draining=drainingRefusal(host,command);if(draining)return draining;if(typeof command.sessionPath!="string"||command.sessionPath.length===0)return error(command.id,command.type,"unknown_session",{});let key=canonicalSessionPath(command.sessionPath),row=host.registry.list().find(candidate=>candidate.sessionPath!==void 0&&canonicalSessionPath(candidate.sessionPath)===key),entry=row&&host.registry.peek(row.sessionId);if(!row||!entry)return error(command.id,command.type,"unknown_session",{});if(entry.state!=="open"||!host.bindings.has(row.sessionId))return error(command.id,command.type,"session_busy_lifecycle",{});if(typeof command.expectedHostInstance!="string"||!identityMatches(host,entry,command.durableSessionId,command.expectedHostInstance))return error(command.id,command.type,"session_identity_mismatch",{});let owner=host.writer.currentConnection();if(owner===void 0)return error(command.id,command.type,"session_not_attached",{reason:"no_connection"});let own=host.sessionsByConnection.get(owner)?.get(row.sessionId)??0,elsewhere=Math.max(0,entry.attachments-own);if(elsewhere>0)return error(command.id,command.type,"attached_elsewhere",{attachments:elsewhere});attach(host,owner,row.sessionId);let claim=claimClose(host,row.sessionId,{drainAttachments:!0});if(host.sessionsByConnection.get(owner)?.delete(row.sessionId),host.sessionsByConnection.get(owner)?.size===0&&host.sessionsByConnection.delete(owner),connectionLeft(host,row.sessionId,owner),host.handoverParkedDir!==void 0&&entry.sessionPath!==void 0&&await clearHandoverParkedSession(host.handoverParkedDir,entry.sessionPath).catch(()=>{}),claim.finalizer){let binding2=host.bindings.get(row.sessionId);binding2?.cancelPendingExtensionUiRequests?.(),await finalizeClose(host,row.sessionId,binding2,()=>host.writer.sealLifecycle(row.sessionId,{type:"session_closed",sessionId:row.sessionId,reason:"client_close"},!0))}return host.writer.detachConnectionFromSession(owner,row.sessionId),host.writer.forgetSession(row.sessionId),{id:command.id,type:"response",command:command.type,success:!0,data:{reclaimed:!0,sessionId:row.sessionId}}}var ATTACH_GATE_EXEMPT=new Set(["get_protocol_info","list_sessions","subscribe_sessions","unsubscribe_sessions","get_subscription_limits","warm","detach_connection","open_session","attach_session","reclaim_session","get_effect_status","get_state","get_snapshot","get_messages","get_entries","get_tree","get_fork_messages","get_last_assistant_text","get_media","get_commands","get_loaded_surfaces","get_available_models","get_available_thinking_levels","get_fast_mode","get_session_stats","get_pending_inputs","get_steering_messages","get_follow_up_messages","get_auth_providers","get_provider_accounts","resolve_path","memory_report","eval_cells.list","eval_cells.peek","check_reload_veto"]);function logSafe(value){return JSON.stringify(value).slice(1,-1)}function attachmentGate(host,command){let owner=host.writer.currentConnection();if(!(owner===void 0||ATTACH_GATE_EXEMPT.has(command.type))&&!(!("sessionId"in command)||command.sessionId===void 0)&&!(command.type==="close_session"||command.type==="set_session_context"||command.type==="release_attachment")&&!host.sessionsByConnection.get(owner)?.has(command.sessionId)){if(process.env.SENPI_RPC_REQUIRE_ATTACH==="1")return error(command.id,command.type,"session_not_attached",{reason:"this connection is not attached to that session",action:"attach first with attach_session { sessionId, durableSessionId } or open_session { sessionPath }"});process.stderr.write(`senpi rpc host: ${command.type} on ${logSafe(command.sessionId)} from a connection not attached to it (refused from the next release)
27
26
  `)}}import{isAbsolute as isAbsolute3,join as join5}from"node:path";import{copyFile,mkdir as mkdir2,readdir as readdir2,rename,rm as rm2,writeFile as writeFile2}from"node:fs/promises";import{basename,dirname,join as join2,posix,relative,sep}from"node:path";import{realpath}from"node:fs/promises";import{resolve}from"node:path";async function realSessionPath(path){let absolute=resolve(path);try{return await realpath(absolute)}catch{return absolute}}var lockKey=resolvedPath=>`session-move:${resolvedPath}`,pathChains=new Map;function orderedRealPath(path){let key=resolve(path),next=(pathChains.get(key)??Promise.resolve("")).then(()=>realSessionPath(path));return pathChains.set(key,next),next.then(()=>{pathChains.get(key)===next&&pathChains.delete(key)}),next}var moveLockKey=async sessionFile=>lockKey(await orderedRealPath(sessionFile));async function withSessionMoveLock2(sessionFile,step,guard){let path=await orderedRealPath(sessionFile);return serializeByKey(lockKey(path),async()=>{await guard?.();let sessionId=headerSessionId(await loadEntriesFromFileAsync(path));return sessionId===void 0?step():withSessionMoveLock(path,sessionId,step)})}function exportSessionForMove(options){return withSessionMoveLock2(options.sessionFile,async()=>(await options.lockedGuard?.(),writeMoveBundle(options)),options.guard)}var MovedStateMissingError=class extends Error{constructor(dir){super(`The extension state the move release staged is missing (${dir}); the session was not exported without it. Finish the move as declined to take the session back, then release it again.`),this.name="MovedStateMissingError"}};async function writeMoveBundle(options){let{sessionFile}=options,moveId=parseMoveId(options.moveId),entries=await loadEntriesFromFileAsync(sessionFile),sessionId=parsePlainId(headerSessionId(entries),"session id"),holders=await liveSessionHolders(sessionFile,sessionId);if(holders.length>0)throw new SessionHeldError(sessionFile,holders);let ownership=sessionOwnership(entries);if(!ownership.writable&&!(ownership.state==="moving"&&ownership.moveId===moveId))throw new SessionMovedAwayError(sessionFile,ownership);ownership.writable&&(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_RELEASED,{reason:"move",move_id:moveId,session_id:sessionId,target:options.target,released_at:new Date().toISOString()});let stateDir=typeof options.extensionStateDir=="function"?await options.extensionStateDir():options.extensionStateDir;if(stateDir!==void 0&&!await pathExists(stateDir))throw new MovedStateMissingError(stateDir);let staging=`${options.bundleDir}.partial-${process.pid}`;await rm2(staging,{recursive:!0,force:!0}),await mkdir2(join2(staging,dirname(SESSION_BUNDLE_PATH)),{recursive:!0}),await copyFile(sessionFile,join2(staging,SESSION_BUNDLE_PATH));let sidecars=await copySidecars(dirname(sessionFile),sessionId,staging),stateFiles=await copyExtensionState(stateDir,staging),manifest={format:MOVE_BUNDLE_FORMAT,moveId,sessionId,sessionFileName:basename(sessionFile),sourceCwd:await readSessionCwd(sessionFile)??"",repository:await readRecordedRepositoryIdentity(sessionFile),session:{path:SESSION_BUNDLE_PATH,sha256:await sha256File(join2(staging,SESSION_BUNDLE_PATH))},sidecars,droppedUserMessages:[...options.droppedUserMessages],payloads:stateFiles.length>0?[{kind:EXTENSION_STATE_PAYLOAD,files:stateFiles}]:[]};return await writeFile2(join2(staging,MANIFEST_FILE),`${JSON.stringify(manifest,null,1)}
28
27
  `),await rm2(options.bundleDir,{recursive:!0,force:!0}),await rename(staging,options.bundleDir),manifest}async function copySidecars(sessionDir,sessionId,staging){let sources=[],extensions=join2(sessionDir,"extensions"),sidecarName=`${encodedSessionId(sessionId)}.json`;if(await pathExists(extensions))for(let extension of await readdir2(extensions,{withFileTypes:!0})){let file=join2(extensions,extension.name,sidecarName);extension.isDirectory()&&await pathExists(file)&&sources.push(file)}sources.push(...await filesUnder(join2(sessionDir,"resident-blobs",sessionId)));let files=[];for(let source of sources){let path=bundlePath("files",sessionDir,source);await mkdir2(dirname(join2(staging,path)),{recursive:!0}),await copyFile(source,join2(staging,path)),files.push({path,sha256:await sha256File(join2(staging,path))})}return files}async function copyExtensionState(dir,staging){if(dir===void 0)return[];let files=[];for(let source of await filesUnder(dir)){let path=bundlePath("state",dir,source);await mkdir2(dirname(join2(staging,path)),{recursive:!0}),await copyFile(source,join2(staging,path)),files.push({path,sha256:await sha256File(join2(staging,path))})}return files}function bundlePath(prefix,from,source){return posix.join(prefix,...relative(from,source).split(sep))}async function filesUnder(dir){if(!await pathExists(dir))return[];let files=[];for(let entry of await readdir2(dir,{withFileTypes:!0})){let path=join2(dir,entry.name);files.push(...entry.isDirectory()?await filesUnder(path):[path])}return files}import{rm as rm3}from"node:fs/promises";var hook;function moveStep(step){hook?.(step)}async function requeueInput(sessionFile,moveId,texts){if(texts.length===0)return;let sessionManager=await SessionManager.openAsync(sessionFile),next=0,inputs=new SessionPendingInputs({sessionManager,nextQueuedId:()=>`move-${moveId}-${next++}`});for(let[index,text2]of texts.entries())await inputs.admit({clientMessageId:`move:${moveId}:${index}`,text:text2,mode:"followUp"},()=>{})}var MoveMismatchError=class extends Error{constructor(expected,found,what){super(`The answer is about move ${expected}, but ${what} belongs to move ${found}; nothing was changed. Finish each move with its own answer and bundle.`),this.code="move_mismatch",this.name="MoveMismatchError"}},MoveAlreadyMovedError=class extends Error{constructor(moveId){super(`The receiver revoked its copy for move ${moveId}, but this session file was already marked moved by an earlier accepted answer; nothing was changed and no copy is writable. Copy the session to a new thread to keep working from it.`),this.code="move_already_moved",this.name="MoveAlreadyMovedError"}};function finishMove(options){return withSessionMoveLock2(options.sessionFile,()=>settleMove(options),options.guard)}async function settleMove(options){let{sessionFile,bundleDir,moveId,answer:answer3}=options;if(await pathExists(bundleDir)){let bundled=(await readManifest(bundleDir)).moveId;if(bundled!==moveId)throw new MoveMismatchError(moveId,bundled,"the kept bundle")}let entries=await loadEntriesFromFileAsync(sessionFile),ownership=sessionOwnership(entries);if(ownership.writable){reclaimed(entries,moveId)&&await requeueDroppedInput(sessionFile,bundleDir),await discardMoveFiles(sessionFile,bundleDir,moveId);return}if(ownership.moveId!==moveId)throw new MoveMismatchError(moveId,ownership.moveId,"the session file");if(ownership.state==="moved"){if("revoked"in answer3)throw new MoveAlreadyMovedError(moveId);await discardMoveFiles(sessionFile,bundleDir,moveId);return}let sessionId=headerSessionId(entries)??"";switch(answer3.state){case"receiving":return;case"accepted":if("revoked"in answer3){await takeBack(sessionFile,bundleDir,{move_id:moveId,session_id:sessionId,reason:"revoked"});break}(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_MOVED,{move_id:moveId,session_id:sessionId,target:ownership.target,moved_at:new Date().toISOString()}),moveStep("finish:recorded");break;case"declined":case"failed":await takeBack(sessionFile,bundleDir,{move_id:moveId,session_id:sessionId,reason:answer3.state,detail:answer3.reason});break;default:{let unreachable=answer3;throw new Error(`Unknown move answer ${JSON.stringify(unreachable)}`)}}moveStep("finish:requeued"),await discardMoveFiles(sessionFile,bundleDir,moveId)}async function takeBack(sessionFile,bundleDir,data2){(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_RECLAIMED,{...data2,reclaimed_at:new Date().toISOString()}),moveStep("finish:recorded"),await requeueDroppedInput(sessionFile,bundleDir)}async function discardMoveFiles(sessionFile,bundleDir,moveId){await rm3(bundleDir,{recursive:!0,force:!0}),await rm3(outgoingStateDir(sessionFile,moveId),{recursive:!0,force:!0})}function reclaimed(entries,moveId){return entries.some(entry=>entry.type==="custom"&&entry.customType===SESSION_RECLAIMED&&entry.data?.move_id===moveId)}async function requeueDroppedInput(sessionFile,bundleDir){if(!await pathExists(bundleDir))return;let manifest=await readManifest(bundleDir);await requeueInput(sessionFile,manifest.moveId,manifest.droppedUserMessages)}import{copyFile as copyFile2,mkdir as mkdir4,readdir as readdir3,rm as rm4}from"node:fs/promises";import{dirname as dirname2,join as join4}from"node:path";import{mkdir as mkdir3,readFile as readFile2,rename as renameFile,writeFile as writeFile3}from"node:fs/promises";import{join as join3}from"node:path";function parseLanding(value){if(typeof value!="object"||value===null)return{};let{target,committing}=value;return{...typeof target=="string"?{target}:{},...committing===!0?{committing:!0}:{}}}function settledLanding(record,committing,outcome){if(record?.state==="receiving"&&committing)return outcome==="absent"?{state:"failed",reason:"import_failed"}:outcome==="revoked"?{state:"accepted",revoked:!0}:{state:"accepted"};if(record?.state==="accepted"&&!("revoked"in record)&&outcome==="revoked")return{state:"accepted",revoked:!0}}function landsAt(record,landing,target){return record?.state==="receiving"&&landing.committing!==!0&&landing.target===target}function landedElsewhere(record,landing){let stored=landing.target;return record?.state==="accepted"&&"revoked"in record?"it was revoked here and never lands again":record?.state==="receiving"&&landing.committing===!0?"an import of it stopped mid-commit, and a move lands once; only the file it landed is accepted":record?.state==="accepted"?"it already landed here once, and a move lands once (a deleted copy is gone; copy the session to a new thread instead)":record?.state==="receiving"&&stored===void 0?"an older version started receiving it and where it landed is unknown; only its already landed file is accepted":stored===void 0?void 0:`it lands only as ${stored}`}var LOCK_OPTIONS={realpath:!1,stale:1e4,update:2e3,retries:0},LOCK_WAIT_MS=15e3,MoveRecordUnlockedError=class extends Error{constructor(file){super(`Move record ${file} was written outside its lock; the write was refused.`),this.code="move_record_unlocked",this.name="MoveRecordUnlockedError"}},MoveRecordLocks=class{#held=new Map;async hold(file,fn){let held=await acquireMoveRecordLock(file);this.#held.set(file,held);try{return await fn()}finally{this.#held.delete(file),await held.release().catch(()=>{})}}assertHeld(file){let held=this.#held.get(file);if(held===void 0)throw new MoveRecordUnlockedError(file);held.assertHeld()}};async function acquireMoveRecordLock(file){let startedAt=Date.now();for(let attempt=0;;attempt+=1)try{return await lockWithLossHandling(file,{...LOCK_OPTIONS,lockfilePath:`${file}.lock`})}catch(error2){if(!isLockError(error2))throw error2;let waited=Date.now()-startedAt;if(waited>=LOCK_WAIT_MS)throw new Error(`Move record ${file} stayed locked for ${waited}ms`,{cause:error2});let delay2=Math.min(FILE_STORAGE_LOCK_RETRY_MIN_DELAY_MS*2**attempt,FILE_STORAGE_LOCK_RETRY_MAX_DELAY_MS);await new Promise(resolve2=>setTimeout(resolve2,delay2))}}var READY_TTL_MS=10*6e4,FINAL_STATES=["accepted","declined","failed"],MoveFencedError=class extends Error{constructor(moveId,record,detail2){super(`Move ${moveId} can no longer be imported here: ${detail2??`it was already answered (${record?.state??"no record"})`}.`),this.code="move_fenced",this.name="MoveFencedError",this.record=record}},DECLINE_REASONS=["no_record","expired","cancelled","chunk_without_ready","repository"],FAIL_REASONS=["bundle_invalid","import_failed"];function parseMoveStatus(value){let record=parseRecord(value);return record?.state==="ready"?void 0:record}function parseRecord(value){if(typeof value!="object"||value===null)return;let{state,reason}=value;if(state==="accepted"&&value.revoked===!0)return{state,revoked:!0};if(state==="receiving")return{state};if(state==="accepted")return{state};let{expiresAt}=value;if(state==="ready"&&typeof expiresAt=="string"&&!Number.isNaN(Date.parse(expiresAt)))return{state,expiresAt};let decline=DECLINE_REASONS.find(known=>known===reason);if(state==="declined"&&decline!==void 0)return{state,reason:decline};let fail2=FAIL_REASONS.find(known=>known===reason);if(state==="failed"&&fail2!==void 0)return{state,reason:fail2}}var MoveLedger=class{#locks=new MoveRecordLocks;constructor(dir,options={}){this.dir=dir,this.now=options.now??Date.now}prepare(moveId){return this.locked(moveId,async()=>{let record=await this.current(moveId);if(record===void 0){let ready={state:"ready",expiresAt:new Date(this.now()+READY_TTL_MS).toISOString()};return await this.write(moveId,ready),ready}if(record.state==="ready"||record.state==="receiving"||record.state==="accepted")return record;throw new MoveFencedError(moveId,record)})}beginReceive(moveId,target){return this.locked(moveId,async()=>{let record=await this.current(moveId),landing=await this.landing(moveId);if(record?.state==="ready"){await this.write(moveId,{state:"receiving"},{target});return}if(landsAt(record,landing,target))return;if(record?.state==="receiving"||record?.state==="accepted")throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));if(record!==void 0)throw new MoveFencedError(moveId,record);let declined={state:"declined",reason:"chunk_without_ready"};throw await this.write(moveId,declined),new MoveFencedError(moveId,declined)})}expire(moveId){return this.locked(moveId,()=>this.current(moveId))}answerStatus(moveId,here){return this.locked(moveId,async()=>{let record=await this.reconcile(moveId,await this.current(moveId),here.landed);if(here.revoked===!0)return{state:"accepted",revoked:!0};if(record?.state==="accepted")return record;if(here.movedIn)return{state:"accepted"};if(record?.state==="ready")return{state:"receiving"};if(record!==void 0)return record;let declined={state:"declined",reason:"no_record"};return await this.write(moveId,declined),declined})}decline(moveId,reason){return this.settle(moveId,{state:"declined",reason},["receiving"])}fail(moveId,reason,options={}){return this.locked(moveId,async()=>await options.unlessLanded?.()?this.current(moveId):this.settleLocked(moveId,{state:"failed",reason},[]))}commit(moveId,target,rename2,prepare){return this.locked(moveId,async()=>{let record=await this.read(moveId),landing=await this.landing(moveId);if(!landsAt(record,landing,target))throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));await prepare?.(),await this.write(moveId,{state:"receiving"},{target,committing:!0}),moveStep("import:stamped");let result=await rename2();return moveStep("import:renamed"),await this.write(moveId,{state:"accepted"},{target}),result})}confirmLanded(moveId,target,revoked){return this.locked(moveId,async()=>{let record=await this.read(moveId),landing=await this.landing(moveId);if(!(record===void 0||record.state==="receiving"||record.state==="accepted")||landing.target!==void 0&&landing.target!==target)throw new MoveFencedError(moveId,record,landedElsewhere(record,landing));let marked=record?.state==="accepted"&&"revoked"in record;record?.state==="accepted"&&(marked||!revoked)||await this.write(moveId,revoked?{state:"accepted",revoked:!0}:{state:"accepted"},{target})})}async reconcile(moveId,record,landed){let{target,committing}=await this.landing(moveId);if(landed===void 0||target===void 0)return record;let next=settledLanding(record,committing===!0,await landed(target));return next===void 0?record:(await this.write(moveId,next,{target}),next)}markRevoked(moveId){return this.locked(moveId,async()=>{let record=await this.read(moveId);if(record!==void 0&&record.state!=="receiving"&&record.state!=="accepted"||record?.state==="accepted"&&"revoked"in record)return;let{target}=await this.landing(moveId);await this.write(moveId,{state:"accepted",revoked:!0},target===void 0?{}:{target})})}settle(moveId,next,keeps){return this.locked(moveId,()=>this.settleLocked(moveId,next,keeps))}async settleLocked(moveId,next,keeps){let record=await this.current(moveId);return record!==void 0&&(FINAL_STATES.includes(record.state)||keeps.includes(record.state))||record!==void 0&&(await this.landing(moveId)).committing===!0?record:(await this.write(moveId,next),next)}async current(moveId){let record=await this.read(moveId);if(record?.state!=="ready"||this.now()<Date.parse(record.expiresAt))return record;let expired={state:"declined",reason:"expired"};return await this.write(moveId,expired),expired}path(moveId){return join3(this.dir,`${parseMoveId(moveId)}.json`)}async raw(moveId){try{return JSON.parse(await readFile2(this.path(moveId),"utf8"))}catch(error2){if(error2.code==="ENOENT")return;throw error2}}async read(moveId){let value=await this.raw(moveId);if(value===void 0)return;let record=parseRecord(value);if(record===void 0)throw new Error(`Move record ${this.path(moveId)} is not a move record`);return record}async landing(moveId){return parseLanding(await this.raw(moveId))}async write(moveId,record,landing={}){let file=this.path(moveId),temp=`${file}.${process.pid}.tmp`;this.#locks.assertHeld(file),await writeFile3(temp,`${JSON.stringify({...record,...landing,at:new Date().toISOString()})}
29
28
  `),this.#locks.assertHeld(file),await renameFile(temp,file)}locked(moveId,fn){let file=this.path(moveId);return serializeByKey(file,async()=>(await mkdir3(this.dir,{recursive:!0}),this.#locks.hold(file,fn)))}};var RevokeMismatchError=class extends Error{constructor(moveId){super(`This session file is not the copy this device imported for move ${moveId}; nothing was changed. Revoke only the copy that move brought in, with that move's id.`),this.code="move_mismatch",this.name="RevokeMismatchError"}},REVOKED="revoked";function revokeImportedMove(options){return withSessionMoveLock2(options.sessionFile,async()=>{await seal(options.sessionFile,options.moveId),moveStep("revoke:sealed"),await options.ledger.markRevoked(options.moveId),moveStep("revoke:marked")},options.guard)}async function seal(sessionFile,moveId){let entries=await loadEntriesFromFileAsync(sessionFile),sessionId=headerSessionId(entries),ownership={writable:!0},latest;for(let entry of entries){let step=ownershipStep(ownership,entry,sessionId);step.kind==="apply"&&(ownership=step.next,latest=entry)}let ofThisMove=latest!==void 0&&data(latest,"move_id")===moveId;if(!(ofThisMove&&latest?.customType===SESSION_MOVED&&data(latest,"reason")===REVOKED)){if(!(ownership.writable&&ofThisMove&&latest?.customType===SESSION_MOVED_IN))throw new RevokeMismatchError(moveId);(await SessionManager.openAsync(sessionFile)).appendCustomEntry(SESSION_MOVED,{move_id:moveId,session_id:sessionId??"",target:data(latest,"from")??"",reason:REVOKED,moved_at:new Date().toISOString()})}}function data(entry,key){if(typeof entry.data!="object"||entry.data===null)return;let value=entry.data[key];return typeof value=="string"?value:void 0}var MoveRefusedError=class extends Error{constructor(targetCwd,sourceCwd){super(`${targetCwd} is not the same repository the session was recorded in (${sourceCwd}). Pick a checkout of the same repository, or copy the session into this folder instead.`),this.name="MoveRefusedError",this.code="move_repository_mismatch"}},MoveTargetOccupiedError=class extends Error{constructor(target){super(`A session that can still be written already sits at ${target}; the moved session was not imported over it. Close or move that session first, then send it again.`),this.code="move_target_occupied",this.name="MoveTargetOccupiedError"}},movedInFor=async(file,moveId)=>(await loadEntriesFromFileAsync(file)).some(entry=>entry.type==="custom"&&entry.customType===SESSION_MOVED_IN&&entry.data?.move_id===moveId);async function importOutcome(file,moveId){let outcome="absent";for(let entry of await loadEntriesFromFileAsync(file)){if(entry.type!=="custom")continue;let data2=entry.data;data2?.move_id===moveId&&(entry.customType===SESSION_MOVED_IN?outcome="moved_in":outcome==="moved_in"&&entry.customType===SESSION_MOVED&&data2.reason===REVOKED&&(outcome="revoked"))}return outcome}var StatusPathMismatchError=class extends Error{constructor(moveId,sessionFile){super(`${sessionFile} is not the copy this device imported for move ${moveId}; nothing was answered. Pass the session_path import returned for this move, or leave sessionPath out to answer from this device's record.`),this.code="move_mismatch",this.name="StatusPathMismatchError"}};async function answerMoveStatus(ledger,moveId,sessionFile){let landed=async target=>await pathExists(target)?importOutcome(target,moveId):"absent";return sessionFile===void 0||!await pathExists(sessionFile)?ledger.answerStatus(moveId,{movedIn:!1,landed}):serializeByKey(await moveLockKey(sessionFile),async()=>{let outcome=await importOutcome(sessionFile,moveId);if(outcome==="absent")throw new StatusPathMismatchError(moveId,sessionFile);return ledger.answerStatus(moveId,{movedIn:!0,revoked:outcome==="revoked",landed})})}async function importMovedSession(options){let manifest=await readManifest(options.bundleDir),targetCwd=resolvePath(options.targetCwd),sessionDir=options.sessionDir?normalizePath(options.sessionDir):getDefaultSessionDir(targetCwd),target=join4(sessionDir,manifest.sessionFileName),landed=async()=>await pathExists(target)&&await movedInFor(target,manifest.moveId);if(await landed())return await options.ledger.confirmLanded(manifest.moveId,target,await importOutcome(target,manifest.moveId)==="revoked"),{sessionFile:target};try{await verifyBundle(options.bundleDir,manifest)}catch(error2){throw error2 instanceof MoveBundleInvalidError&&await options.ledger.fail(manifest.moveId,"bundle_invalid",{unlessLanded:landed}),error2}let read=options.readIdentity??readRepositoryIdentity;if(compareRepositoryIdentities(manifest.repository,await read(targetCwd))!=="same")throw await landed()||await options.ledger.decline(manifest.moveId,"repository"),new MoveRefusedError(targetCwd,manifest.sourceCwd);await options.ledger.beginReceive(manifest.moveId,target),moveStep("import:received");let staging=join4(sessionDir,".move-staging",encodeURIComponent(manifest.moveId));try{let staged=await stage(options.bundleDir,manifest,staging,options.from??""),sessionFile=await options.ledger.commit(manifest.moveId,target,()=>rebindSessionFile(staged,targetCwd,sessionDir),async()=>{await replacePredecessor(target,manifest.sessionId,sessionDir),await placeExtensionState(staging,manifest,movedStateDir(target,manifest.moveId))});return moveStep("import:accepted"),await rm4(staging,{recursive:!0,force:!0}),{sessionFile}}catch(error2){throw error2 instanceof MoveFencedError||await options.ledger.fail(manifest.moveId,error2 instanceof MoveBundleInvalidError?"bundle_invalid":"import_failed",{unlessLanded:landed}),error2}}async function replacePredecessor(target,sessionId,sessionDir){if(!await pathExists(target))return;let entries=await loadEntriesFromFileAsync(target);if(headerSessionId(entries)!==sessionId||sessionOwnership(entries).writable)throw new MoveTargetOccupiedError(target);let extensions=join4(sessionDir,"extensions");if(await pathExists(extensions))for(let extension of await readdir3(extensions,{withFileTypes:!0}))extension.isDirectory()&&await rm4(join4(extensions,extension.name,`${encodedSessionId(sessionId)}.json`),{force:!0});await rm4(join4(sessionDir,"resident-blobs",sessionId),{recursive:!0,force:!0}),await rm4(target,{force:!0})}var STAGED_PAYLOADS=".payloads",extensionStateFiles=manifest=>manifest.payloads.filter(payload=>payload.kind===EXTENSION_STATE_PAYLOAD).flatMap(p=>p.files);async function stagePayloads(bundleDir,manifest,staging){for(let file of manifest.payloads.flatMap(payload=>payload.files)){let to=join4(staging,STAGED_PAYLOADS,file.path);if(await mkdir4(dirname2(to),{recursive:!0}),await copyFile2(join4(bundleDir,file.path),to),await sha256File(to)!==file.sha256)throw new MoveBundleInvalidError(`${file.path} changed in transit`)}}async function placeExtensionState(staging,manifest,dir){let files=extensionStateFiles(manifest);if(files.length!==0){await rm4(dir,{recursive:!0,force:!0});for(let file of files){let to=join4(dir,file.path.slice(EXTENSION_STATE_PREFIX.length));await mkdir4(dirname2(to),{recursive:!0}),await copyFile2(join4(staging,STAGED_PAYLOADS,file.path),to)}}}async function stage(bundleDir,manifest,staging,from){let file=join4(staging,manifest.sessionFileName);if(!(await pathExists(file)&&await movedInFor(file,manifest.moveId))){await rm4(staging,{recursive:!0,force:!0});for(let item of[manifest.session,...manifest.sidecars]){let to=item===manifest.session?file:join4(staging,item.path.replace(/^files\//,""));await mkdir4(dirname2(to),{recursive:!0}),await copyFile2(join4(bundleDir,item.path),to)}await stagePayloads(bundleDir,manifest,staging),(await SessionManager.openAsync(file,staging)).appendCustomEntry(SESSION_MOVED_IN,{move_id:manifest.moveId,session_id:manifest.sessionId,from,bundle_sha256:manifest.session.sha256,moved_in_at:new Date().toISOString()})}return await requeueInput(file,manifest.moveId,manifest.droppedUserMessages),file}var CORE_CODES=new Set(["move_fenced","move_bundle_invalid","move_repository_mismatch","move_target_occupied","move_mismatch","move_already_moved","session_moved_away"]),RENAMED_CODES={ESESSIONHELD:"session_held"};function plainMoveId(value){try{return parseMoveId(value)}catch{return}}var text=value=>typeof value=="string"&&value.trim()!=="";function parse(raw){let{op}=raw;if(op==="import"){if(!text(raw.bundleDir)||!text(raw.cwd)||!isAbsolute3(raw.bundleDir)||!isAbsolute3(raw.cwd))return"import needs bundleDir and cwd as absolute paths.";let from=typeof raw.from=="string"?raw.from:void 0;return raw.from!==void 0&&from===void 0?"from must be a string.":{op,bundleDir:raw.bundleDir,cwd:raw.cwd,from:from??""}}let id=plainMoveId(raw.moveId);if(id===void 0)return"moveId must be a plain id: a letter or digit, then letters, digits, '.', '_' or '-', at most 128 characters.";switch(op){case"prepare":case"cancel":return{op,moveId:id};case"status":{let sessionPath=text(raw.sessionPath)?raw.sessionPath:void 0;return raw.sessionPath!==void 0&&sessionPath===void 0?"sessionPath must be a non-empty string.":{op,moveId:id,sessionPath}}case"export":{let dropped=raw.droppedUserMessages??[];return!text(raw.sessionPath)||!text(raw.target)?"export needs sessionPath and target.":!Array.isArray(dropped)||!dropped.every(item=>typeof item=="string")?"droppedUserMessages must be the dropped.user_messages strings release_session returned.":{op,sessionPath:raw.sessionPath,moveId:id,target:raw.target,dropped}}case"finish":{let answer3=parseMoveStatus(raw.answer);return!text(raw.sessionPath)||answer3===void 0?"finish needs sessionPath and the receiver's answer from status (receiving, accepted, declined or failed).":{op,sessionPath:raw.sessionPath,moveId:id,answer:answer3}}case"revoke":return text(raw.sessionPath)?{op,sessionPath:raw.sessionPath,moveId:id}:"revoke needs sessionPath, the copy this host imported for the move.";default:return'op must be one of "prepare", "cancel", "status", "export", "import", "finish" or "revoke".'}}var wireRecord=record=>record.state==="ready"?{state:"ready",expires_at:record.expiresAt}:record;async function moveSession(port,command){let raw={...command},parsed=parse(raw);if(typeof parsed=="string")return refusal2(command.id,RPC_ERROR_INVALID_MOVE_REQUEST,parsed);let root=join5(port.agentDir,"session-moves"),ledger=new MoveLedger(join5(root,"ledger")),outgoing=moveId=>join5(root,"outgoing",moveId);try{return answer(command.id,await run(parsed,port,ledger,outgoing))}catch(cause){if(cause instanceof MoveRefusal)return refusal2(command.id,cause.code,cause.message);let code2=typeof cause=="object"&&cause!==null&&"code"in cause?cause.code:void 0,detail2=cause instanceof Error?cause.message:String(cause);return refusal2(command.id,typeof code2=="string"?RENAMED_CODES[code2]??(CORE_CODES.has(code2)?code2:RPC_ERROR_MOVE_FAILED):RPC_ERROR_MOVE_FAILED,detail2)}}async function run(parsed,port,ledger,outgoing){switch(parsed.op){case"prepare":return wireRecord(await ledger.prepare(parsed.moveId));case"cancel":return wireRecord(await ledger.decline(parsed.moveId,"cancelled"));case"status":return answerMoveStatus(ledger,parsed.moveId,parsed.sessionPath);case"export":{let sessionFile=await orderedRealPath(parsed.sessionPath),bundleDir=outgoing(parsed.moveId),manifest=await exportSessionForMove({sessionFile,moveId:parsed.moveId,target:parsed.target,droppedUserMessages:parsed.dropped,bundleDir,extensionStateDir:()=>sealedOutgoingStateDir(sessionFile,parsed.moveId),guard:async()=>{await refuseOpenHere(port,sessionFile,"This session is open on this host. Release it with release_session reason move and this moveId first."),await refuseUnlessSealedFor(sessionFile,parsed.moveId)},lockedGuard:()=>refuseUnlessSealedFor(sessionFile,parsed.moveId)});return{move_id:manifest.moveId,session_id:manifest.sessionId,bundle_dir:bundleDir,files:1+manifest.sidecars.length}}case"import":{let cwd=resolvePath(parsed.cwd),sessionDir=getDefaultSessionDir(cwd,port.agentDir),{sessionFile}=await importMovedSession({bundleDir:normalizePath(parsed.bundleDir),targetCwd:cwd,ledger,sessionDir,from:parsed.from}),sessionId=headerSessionId(await loadEntriesFromFileAsync(sessionFile));if(sessionId===void 0)throw new Error(`The imported session at ${sessionFile} has no id in its header.`);return{session_id:sessionId,session_path:sessionFile}}case"finish":{let sessionFile=await orderedRealPath(parsed.sessionPath);return await finishMove({sessionFile,bundleDir:outgoing(parsed.moveId),moveId:parsed.moveId,answer:parsed.answer,guard:()=>refuseOpenHere(port,sessionFile,"This session is open on this host, so its runtime would not see the move end. Close it here, then finish the move.")}),ownershipOf(sessionFile)}case"revoke":{let sessionFile=await orderedRealPath(parsed.sessionPath);return await revokeImportedMove({sessionFile,moveId:parsed.moveId,ledger,guard:()=>refuseOpenHere(port,sessionFile,"This session is open on this host, so its runtime would not see the revoke. Close it here, then revoke the move.")}),ownershipOf(sessionFile)}}}async function ownershipOf(sessionFile){let ownership=sessionOwnership(await loadEntriesFromFileAsync(sessionFile));return{ownership:ownership.writable?"writable":ownership.state}}var MoveRefusal=class extends Error{constructor(code2,detail2){super(detail2),this.name="MoveRefusal",this.code=code2}};async function refuseUnlessSealedFor(sessionFile,moveId){let ownership=sessionOwnership(await loadEntriesFromFileAsync(sessionFile));if(ownership.writable||ownership.state!=="moving"||ownership.moveId!==moveId)throw new MoveRefusal(RPC_ERROR_MOVE_NOT_RELEASED,"This session file is not sealed for this move. Release it with release_session reason move and this moveId first; that also hands back its queued input.")}async function refuseOpenHere(port,sessionFile,detail2){if((await Promise.all(port.hostedPaths().map(path=>realSessionPath(path)))).includes(sessionFile))throw new MoveRefusal(RPC_ERROR_SESSION_OPEN_HERE,detail2)}function answer(id,data2){return"refuse"in data2?refusal2(id,data2.refuse,data2.detail):{id,type:"response",command:"move_session",success:!0,data:data2}}function refusal2(id,code2,detail2){return{id,type:"response",command:"move_session",success:!1,error:code2,errorCode:code2,errorData:{detail:detail2}}}import{rm as rm5}from"node:fs/promises";var NOTHING_DROPPED={deliveries:[],user_messages:[]};function takeQueuedInput(session){let admittedBefore=session.externalAdmission.list().pending,cleared=session.clearQueue({abortWillFollow:!0}),stillAdmitted=new Set(session.externalAdmission.list().pending);return{deliveries:admittedBefore.filter(deliveryId=>!stillAdmitted.has(deliveryId)),user_messages:cleared.ordered.map(queued=>queued.text)}}async function abortAndSettle(port,sessionId,session){session.abortBash();let stopStarts=session.subscribe(event=>{event.type==="agent_start"&&session.abort()}),deadline,expired=new Promise(resolve2=>{deadline=setTimeout(resolve2,1e4)});try{await Promise.race([Promise.allSettled([session.abort().then(()=>session.waitForIdle()),port.otherRequestsSettled(sessionId),...port.pendingPrompts(sessionId)]),expired])}finally{clearTimeout(deadline),stopStarts()}}var SESSION_RELEASED_ENTRY_TYPE="session_released",RELEASED_ADMISSION_CLOSED="release_session handed this session to another runtime; deliver there instead (admission is closed here)",RELEASE_QUEUED_HINT="queued user input is still owed a turn; release with interrupt: true to take it out and receive it in dropped.user_messages";async function releaseSession(port,command){let validMove=command.reason==="move"&&isMoveId(command.moveId);if(command.reason!=="takeover"&&!validMove)return refusal3(command.id,RPC_ERROR_INVALID_RELEASE_REASON);if(port.draining())return refusal3(command.id,RPC_ERROR_HOST_DRAINING);let first=releasable(port,command,void 0);if(!("session"in first))return first;if(command.reason==="move"&&!isPlainId(first.session.sessionManager.getSessionId()))return refusal3(command.id,RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"session_id_not_plain"});let busy=busySignals(port,command.sessionId,first.session),interrupted=busy.length>0;if(interrupted&&command.interrupt!==!0)return refusal3(command.id,busyCode(busy),{attachments:first.attachments,...busyData(busy)});let admission=first.session.externalAdmission,dropped=NOTHING_DROPPED,answer3,stagedState,sealed=!1;try{interrupted&&(admission.close(RELEASED_ADMISSION_CLOSED),dropped=takeQueuedInput(first.session),await abortAndSettle(port,command.sessionId,first.session),await first.session.whenQueueClearRecorded());let manager=first.session.sessionManager;if(manager.isTranscriptFlushed()||await manager.persistHeaderNow(),command.reason==="move"){let moveId=parseMoveId(command.moveId);stagedState=await prepareOutgoingState(first.sessionPath,moveId);let[failed]=await first.session.extensionRunner.emitSessionMove({type:"session_move_export",moveId,dir:stagedState.dir});if(failed!==void 0)throw new Error(`${failed.extensionPath} could not write its state for the move: ${failed.error}`)}return answer3=await claimAndRelease(port,command,interrupted,dropped,stagedState?.attempt,()=>{sealed=!0}),answer3}catch(cause){return cause instanceof SessionMovedAwayError?(answer3=refusal3(command.id,cause.code,{detail:cause.message,...interrupted?{interrupted:!0,dropped}:{}}),answer3):(answer3=refusal3(command.id,RPC_ERROR_RELEASE_FAILED,{detail:cause instanceof Error?cause.message:String(cause),...interrupted?{interrupted:!0,dropped}:{}}),answer3)}finally{answer3?.success!==!0&&(admission.reopen(),stagedState!==void 0&&!sealed&&await rm5(stagedState.dir,{recursive:!0,force:!0}))}}async function claimAndRelease(port,command,interrupted,dropped,stateAttempt,onSealed){let taken=interrupted?{interrupted:!0,dropped}:void 0,ready=releasable(port,command,taken);if(!("session"in ready))return ready;let stillBusy=busySignals(port,command.sessionId,ready.session);if(stillBusy.length>0)return refusal3(command.id,busyCode(stillBusy),{attachments:ready.attachments,...busyData(stillBusy),interrupted,...taken});let admission=ready.session.externalAdmission;admission.close(RELEASED_ADMISSION_CLOSED);try{ready.session.sessionManager.appendCustomEntry(SESSION_RELEASED_ENTRY_TYPE,{reason:command.reason,...command.reason==="move"?{move_id:command.moveId,...stateAttempt===void 0?{}:{[STATE_ATTEMPT_FIELD]:stateAttempt},target:command.target??"",session_id:ready.session.sessionManager.getSessionId()}:{},interrupted,attachments:ready.attachments,host_instance:port.hostInstance??null,released_at:new Date().toISOString()})}catch(cause){throw admission.reopen(),cause}return onSealed(),await port.tearDown(command.sessionId,ready.sessionPath)?{id:command.id,type:"response",command:"release_session",success:!0,data:{released:!0,session_path:ready.sessionPath,attachments:ready.attachments,dropped}}:refusal3(command.id,RPC_ERROR_SESSION_CLOSING,taken)}function busySignals(port,sessionId,session){let activity=session.activitySnapshot,signals=[];return activity.isStreaming&&signals.push("turn"),port.pendingPrompts(sessionId).length>0&&signals.push("prompt"),session.pendingMessageCount>0&&signals.push("queued"),session.externalAdmission.list().pending.length>0&&signals.push("delivery"),activity.isBashRunning&&signals.push("bash"),activity.isCompacting&&signals.push("compaction"),activity.hasSessionWork&&signals.push("session_work"),signals.length===0&&isHandoffBusy(activity)&&signals.push("activity"),port.otherRequests(sessionId)>0&&signals.push("request"),signals}function busyData(signals){return signals.includes("queued")?{busy:signals,retry_with:{interrupt:!0},hint:RELEASE_QUEUED_HINT}:{busy:signals}}function busyCode(signals){return signals.some(signal=>signal==="turn"||signal==="prompt"||signal==="queued"||signal==="delivery")?RPC_ERROR_TURN_ACTIVE:RPC_ERROR_SESSION_BUSY}function releasable(port,command,taken){let refuse=(code2,data2)=>refusal3(command.id,code2,data2||taken?{...data2,...taken}:void 0),entry;try{entry=port.lookup(command.sessionId)}catch(cause){return refuse(port.code(cause))}if(entry.state!=="open")return refuse(RPC_ERROR_SESSION_CLOSING);let session=entry.runtime?.session;if(session===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"worker_runtime"});let sessionPath=entry.sessionPath??session.sessionFile;if(sessionPath===void 0)return refuse(RPC_ERROR_RELEASE_UNSUPPORTED,{detail:"no_session_file"});let elsewhere=port.otherAttachments(command.sessionId);return elsewhere>0&&command.force!==!0?refuse(RPC_ERROR_ATTACHED,{attachments:elsewhere}):{session,sessionPath,attachments:entry.attachments}}function refusal3(id,code2,data2){return{id,type:"response",command:"release_session",success:!1,error:code2,...data2&&{errorCode:code2,errorData:data2}}}function sessionMemory(host,sessionId){let view=host.hostMemoryView;if(view===void 0)return{main_heap_bytes:0,kernel_heap_bytes:0,kernel_count:0};let kernels=view.kernels().filter(kernel=>kernel.sessionId===sessionId),kernelHeapBytes=0;for(let kernel of kernels)kernelHeapBytes+=kernel.liveBytes;return{main_heap_bytes:view.mainHeapBytes(),kernel_heap_bytes:kernelHeapBytes,kernel_count:kernels.length}}function acknowledgePrompt(host,id,sessionId){let connection=host.writer.currentConnection();if(id===void 0||connection===void 0)return;let inFlight=Math.max(0,(host.activeRequests.get(sessionId)??1)-1);host.writer.sendOpenQueued(connection,{type:"queued",for_request:id,position:inFlight+1,in_flight:inFlight})}function otherRequestsSettled(host,sessionId){return new Promise(resolve2=>{let listeners=host.requestSettledListeners.get(sessionId)??new Set,check=()=>{(host.activeRequests.get(sessionId)??0)>1||(listeners.delete(check),listeners.size===0&&host.requestSettledListeners.delete(sessionId),resolve2())};listeners.add(check),host.requestSettledListeners.set(sessionId,listeners),check()})}var CHILD_TASK_SOURCE=/^senpi-task/,ACTIONS={extension_work:"let the named work finish, or unload with force: true (it is stopped, not resumed on reopen)",turn_active:"wait for the turn to end, or unload with interrupt: true to stop it first",work_pending:"wait for the work to finish, or unload with interrupt: true",children_live:'wait for the child tasks, or unload with children: "detach" to leave them running',attached:"ask the other clients to detach, or unload with force: true (they receive session_parked)"};async function unloadSession(port,command){if(port.draining())return answer2(command,refused({reason:"host_draining",detail:"this host is draining and parks every session itself"}));let first=loaded(port,command.sessionId);if("reason"in first)return answer2(command,refused(first));let{effectId}=command;if(effectId!==void 0){let begun=await beginEffect({session:first.session,by:port.by,sessionId:command.sessionId},"unload",{...command,effectId});if(!isEffectBegin(begun))return begun;if("replay"in begun)return answer2(command,{outcome:begun.replay.state==="failed"?"refused":"unloaded",...refusalFields(begun.replay.outcome),...effectAnswer(begun.replay,command.sessionId,!0)})}let blocked=blockers(port,command,first.session,first.durableSessionId),standing=blocked.find(refusal4=>!interruptible(refusal4)||command.interrupt!==!0);return standing!==void 0?fail(command,first.session,standing):(blocked.length>0&&await abortAndSettle(port,command.sessionId,first.session),claimAndUnload(port,command))}async function claimAndUnload(port,command){let ready=loaded(port,command.sessionId);if("reason"in ready)return answer2(command,refused(ready));let stillBlocked=blockers(port,command,ready.session,ready.durableSessionId);if(stillBlocked.length>0)return fail(command,ready.session,stillBlocked[0]);command.clearQueue===!0&&(ClientAdmissions.clearQueuedFor(ready.session),ready.session.clearQueue());let effect=command.effectId===void 0?void 0:EffectLedger.forSession(ready.session).transition(command.effectId,"done",{disposition:"unloaded"});return await port.tearDown(command.sessionId,ready.sessionPath)?answer2(command,{outcome:"unloaded",sessionPath:ready.sessionPath,...effect===void 0?{}:effectAnswer(effect,command.sessionId)}):answer2(command,{outcome:"refused",reason:"session_closing",detail:"another close of this session finished first"})}function interruptible(refusal4){return refusal4.reason==="turn_active"||refusal4.reason==="work_pending"}function blockers(port,command,session,durableSessionId){let found=[],activity=session.activitySnapshot,running=[activity.isStreaming&&"an agent run",port.pendingPrompts(command.sessionId).length>0&&"a prompt about to start",activity.isCompacting&&"compaction",activity.hasSessionWork&&"session work"].filter(label=>typeof label=="string");running.length>0&&found.push({reason:"turn_active",detail:running.join(", "),action:ACTIONS.turn_active});let pending=[activity.isBashRunning&&"a bash command",session.externalAdmission.list().pending.length>0&&"an admitted delivery not yet written",port.otherRequests(command.sessionId)>0&&"another request for this session"].filter(label=>typeof label=="string");pending.length>0&&found.push({reason:"work_pending",detail:pending.join(", "),action:ACTIONS.work_pending});let sources=session.activeWakeSources,childSources=sources.filter(source=>CHILD_TASK_SOURCE.test(source)),otherSources=sources.filter(source=>!CHILD_TASK_SOURCE.test(source));otherSources.length>0&&command.force!==!0&&found.push({reason:"extension_work",detail:`work published by ${otherSources.join(", ")}`,action:ACTIONS.extension_work});let childSessions=port.openChildSessions(durableSessionId);if(command.children!=="detach"&&(childSources.length>0||childSessions>0)){let what=childSessions>0?`${childSessions} child session(s) open on this host`:"child tasks still working";found.push({reason:"children_live",detail:what,action:ACTIONS.children_live})}let others=port.otherAttachments(command.sessionId);return others>0&&command.force!==!0&&found.push({reason:"attached",detail:`${others} other client(s) attached`,action:ACTIONS.attached}),found}function loaded(port,sessionId){let entry;try{entry=port.lookup(sessionId)}catch(cause){return{reason:"unsupported",detail:port.code(cause)}}if(entry.state!=="open")return{reason:"session_closing",detail:"the session is already closing"};let session=entry.runtime?.session;if(session===void 0)return{reason:"unsupported",detail:"a worker isolate owns this session's runtime"};let sessionPath=entry.sessionPath??session.sessionFile;return sessionPath===void 0?{reason:"unsupported",detail:"the session has no file to reopen it by",action:"send a prompt first so the session is written, or close it instead"}:{session,sessionPath,durableSessionId:session.sessionManager.getSessionId()}}function fail(command,session,refusal4){if(command.effectId===void 0)return answer2(command,refused(refusal4));let status=EffectLedger.forSession(session).transition(command.effectId,"failed",{outcome:{kind:"refused",reason:refusal4.reason,detail:refusal4.detail,...refusal4.action===void 0?{}:{action:refusal4.action}}});return answer2(command,{...refused(refusal4),...effectAnswer(status,command.sessionId)})}function refusalFields(outcome){return outcome?.reason===void 0?{}:{reason:outcome.reason,...outcome.detail===void 0?{}:{detail:outcome.detail},...outcome.action===void 0?{}:{action:outcome.action}}}function refused(refusal4){return{outcome:"refused",reason:refusal4.reason,detail:refusal4.detail,...refusal4.action===void 0?{}:{action:refusal4.action}}}function answer2(command,data2){return{id:command.id,type:"response",command:"unload_session",success:!0,data:data2}}function handle(host,command){let refusal4=attachmentGate(host,command);if(refusal4)return Promise.resolve(refusal4);let sessionId="sessionId"in command?command.sessionId:void 0;return host.draining&&sessionId!==void 0&&host.handoffClosed.has(sessionId)?Promise.resolve(void 0):host.draining&&command.type==="open_session"?Promise.resolve(error(command.id,command.type,"host_draining")):command.type==="warm"?answerWarm(command,{draining:host.draining,warm:host.registry.warm,cwd:host.defaults.cwd,hostContext:host.defaults.hostContext}):(host.activeRequests.set(sessionId,(host.activeRequests.get(sessionId)??0)+1),runWithSessionAttribution({sessionId},()=>dispatch(host,command)).finally(()=>{let remaining=(host.activeRequests.get(sessionId)??1)-1;if(remaining>0?host.activeRequests.set(sessionId,remaining):host.activeRequests.delete(sessionId),sessionId!==void 0)for(let listener of host.requestSettledListeners.get(sessionId)??[])listener();host.draining&&sweepDrain(host)}))}function otherAttachments(host,caller,sessionId){let own=caller===void 0?0:host.sessionsByConnection.get(caller)?.get(sessionId)??0;return Math.max(0,(host.registry.peek(sessionId)?.attachments??0)-own)}async function dispatch(host,command){if(command.type==="get_protocol_info"){let capabilities=multiSessionHostCapabilities({warm:host.registry.warm!==void 0,toolRuntime:host.defaults.toolRuntime??"in-process",negotiated:host.connectionOptions?.capabilities??[],mcpPresenters:host.writer.mcpPresenters!==void 0});return{id:command.id,type:"response",command:"get_protocol_info",success:!0,data:{protocolVersion:1,serverVersion:VERSION,capabilities,mode:"multi",...protocolIdentity(host.defaults.agentDir),memory_pressure:host.memoryPressure}}}if(command.type==="get_subscription_limits")return{id:command.id,type:"response",command:"get_subscription_limits",success:!0,data:{accounts:subscriptionLimits.snapshot()}};if(command.type==="list_sessions"){let withMemory=host.registry.list().map(row=>({...row,memory:sessionMemory(host,row.sessionId)})),sessions=command.include_workers===!0?withMemory:withMemory.filter(row=>row.kind!=="worker").map(({context:_context,...row})=>row);return{id:command.id,type:"response",command:"list_sessions",success:!0,data:{sessions}}}if(command.type==="detach_connection")return detachConnection(command,host.writer.currentConnection(),id=>releaseConnection(host,id));if(command.type==="open_session")return openWithBarrier(host,command);if(command.type==="attach_session")return attachSession(host,command);if(command.type==="release_attachment")return releaseAttachment(host,command);if(command.type==="reclaim_session")return reclaimSession(host,command);if(command.type==="close_session")return close(host,command);if(command.type==="release_session")return releaseSession({draining:()=>host.draining,hostInstance:host.defaults.hostContext?.host_instance,otherAttachments:sessionId2=>otherAttachments(host,host.writer.currentConnection(),sessionId2),lookup:sessionId2=>host.registry.getForCommand(sessionId2,"release_session"),code:cause=>code(cause),otherRequests:sessionId2=>Math.max(0,(host.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>otherRequestsSettled(host,sessionId2),pendingPrompts:sessionId2=>host.bindings.get(sessionId2)?.pendingPrompts?.()??[],tearDown:(sessionId2,sessionPath)=>host.releaseTeardown(sessionId2,sessionPath)},command);if(command.type==="move_session"){let agentDir=host.registry.agentDir;return agentDir===void 0?error(command.id,command.type,"move_unsupported: this host keeps no agent directory to move sessions in"):moveSession({agentDir,hostedPaths:()=>host.registry.list().flatMap(row=>row.sessionPath===void 0?[]:[row.sessionPath])},command)}if(command.type==="unload_session"){let caller=host.writer.currentConnection();return unloadSession({draining:()=>host.draining,by:{connectionId:caller??"host"},lookup:sessionId2=>host.registry.getForCommand(sessionId2,"unload_session"),code:cause=>code(cause),otherRequests:sessionId2=>Math.max(0,(host.activeRequests.get(sessionId2)??1)-1),otherRequestsSettled:sessionId2=>otherRequestsSettled(host,sessionId2),pendingPrompts:sessionId2=>host.bindings.get(sessionId2)?.pendingPrompts?.()??[],otherAttachments:sessionId2=>otherAttachments(host,caller,sessionId2),openChildSessions:durableSessionId=>host.registry.list().filter(row=>row.durableSessionId!==durableSessionId&&(row.context?.parent_session_id===durableSessionId||row.context?.root_session_id===durableSessionId)).length,tearDown:(sessionId2,sessionPath)=>tearDownUnloaded(host,sessionId2,sessionPath)},command)}if(command.type==="set_client_info"&&!command.sessionId){let connection=host.writer.currentConnection();return command.capabilities!==void 0&&!host.connectionRoles.declare(roleConnection(connection),command.capabilities)?{id:command.id,type:"response",command:"set_client_info",success:!1,error:CONNECTION_ROLE_FIXED}:(connection!==void 0&&(host.pendingCapabilities.set(connection,command.capabilities??[]),host.writer.setConnectionCapabilities(connection,command.capabilities??[])),{id:command.id,type:"response",command:"set_client_info",success:!0})}if(command.type==="subscribe_sessions"){let connection=host.writer.currentConnection(),{answer:answer3,activate}=answerSubscribeSessions(command,connection,host.writer.status);if(activate!==void 0&&connection!==void 0){(async()=>{await host.writer.enqueueControl(answer3,connection),await new Promise(resolve2=>queueMicrotask(resolve2));try{host.writer.hasConnection(connection)?host.writer.status.activate(activate):host.writer.status.unsubscribe(connection,activate)}catch(cause){process.stderr.write(`senpi rpc subscription activation failed: ${String(cause)}