@code-yeongyu/senpi 2026.9.19-2 → 2026.9.20

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 (171) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/bundle/chunks/{app-server-command-QBJ4GPN7.js → app-server-command-B35FQUTE.js} +1 -1
  3. package/dist/bundle/chunks/{bun-extension-importer-JQZRPNJH.js → bun-extension-importer-HHH4TV4B.js} +3 -3
  4. package/dist/bundle/chunks/{chunk-YRN3PCTM.js → chunk-DQZB4GVV.js} +4 -4
  5. package/dist/bundle/chunks/{chunk-EHSDTQ6I.js → chunk-E5R67F7G.js} +37 -37
  6. package/dist/bundle/chunks/{chunk-5E5TLB76.js → chunk-TWGC3TBR.js} +2 -2
  7. package/dist/bundle/chunks/{chunk-RLRLQRI2.js → chunk-V2ZB62DG.js} +1 -1
  8. package/dist/bundle/chunks/{chunk-3FRTRCR6.js → chunk-YXQG2SUX.js} +2 -2
  9. package/dist/bundle/chunks/{chunk-PLZK7ABD.js → chunk-Z4LHCTJ6.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-3Q4WGKFA.js → chunk-ZMFHNH6U.js} +1 -1
  11. package/dist/bundle/chunks/{cli-main-MLJ2H637.js → cli-main-USVT7JMN.js} +1 -1
  12. package/dist/bundle/chunks/{interactive-host-runtime-AITXUDCT.js → interactive-host-runtime-ELBAZ4LN.js} +1 -1
  13. package/dist/bundle/chunks/{interactive-mode-7C75IXNF.js → interactive-mode-R6225BKI.js} +1 -1
  14. package/dist/bundle/chunks/{list-tips-KTDNGQUK.js → list-tips-Z7T2ACVU.js} +1 -1
  15. package/dist/bundle/chunks/{multi-session-host-2YCJKQOL.js → multi-session-host-QNEBJW2P.js} +3 -3
  16. package/dist/bundle/chunks/{package-manager-cli-4ANSELYT.js → package-manager-cli-4MVJ3JSE.js} +1 -1
  17. package/dist/bundle/chunks/{rpc-mode-OPFQIWFP.js → rpc-mode-CXVDRIBU.js} +1 -1
  18. package/dist/bundle/chunks/{session-picker-DXCITGLS.js → session-picker-6N666KQZ.js} +1 -1
  19. package/dist/bundle/chunks/session-worker.js +66 -66
  20. package/dist/bundle/cli.js +1 -1
  21. package/dist/bundle/index.js +1 -1
  22. package/dist/bundle/rpc-entry.js +1 -1
  23. package/dist/core/agent-session-services.d.ts.map +1 -1
  24. package/dist/core/agent-session-services.js +14 -1
  25. package/dist/core/agent-session-services.js.map +1 -1
  26. package/dist/core/agent-session.d.ts +45 -0
  27. package/dist/core/agent-session.d.ts.map +1 -1
  28. package/dist/core/agent-session.js +233 -11
  29. package/dist/core/agent-session.js.map +1 -1
  30. package/dist/core/extensions/builtin/ask-user/extension.d.ts.map +1 -1
  31. package/dist/core/extensions/builtin/ask-user/extension.js +16 -5
  32. package/dist/core/extensions/builtin/ask-user/extension.js.map +1 -1
  33. package/dist/core/extensions/builtin/ask-user/format.d.ts +5 -0
  34. package/dist/core/extensions/builtin/ask-user/format.d.ts.map +1 -1
  35. package/dist/core/extensions/builtin/ask-user/format.js +4 -0
  36. package/dist/core/extensions/builtin/ask-user/format.js.map +1 -1
  37. package/dist/core/extensions/builtin/ask-user/notify.d.ts +2 -0
  38. package/dist/core/extensions/builtin/ask-user/notify.d.ts.map +1 -1
  39. package/dist/core/extensions/builtin/ask-user/notify.js +2 -0
  40. package/dist/core/extensions/builtin/ask-user/notify.js.map +1 -1
  41. package/dist/core/extensions/builtin/ask-user/registry.d.ts +15 -2
  42. package/dist/core/extensions/builtin/ask-user/registry.d.ts.map +1 -1
  43. package/dist/core/extensions/builtin/ask-user/registry.js +13 -0
  44. package/dist/core/extensions/builtin/ask-user/registry.js.map +1 -1
  45. package/dist/core/extensions/builtin/ask-user/render.d.ts +6 -0
  46. package/dist/core/extensions/builtin/ask-user/render.d.ts.map +1 -1
  47. package/dist/core/extensions/builtin/ask-user/render.js +9 -0
  48. package/dist/core/extensions/builtin/ask-user/render.js.map +1 -1
  49. package/dist/core/extensions/builtin/ask-user/resume.d.ts.map +1 -1
  50. package/dist/core/extensions/builtin/ask-user/resume.js +59 -24
  51. package/dist/core/extensions/builtin/ask-user/resume.js.map +1 -1
  52. package/dist/core/extensions/builtin/ask-user/tool.d.ts +1 -1
  53. package/dist/core/extensions/builtin/ask-user/tool.d.ts.map +1 -1
  54. package/dist/core/extensions/builtin/ask-user/tool.js +98 -17
  55. package/dist/core/extensions/builtin/ask-user/tool.js.map +1 -1
  56. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts +18 -0
  57. package/dist/core/extensions/builtin/compaction/model-usability-budget.d.ts.map +1 -1
  58. package/dist/core/extensions/builtin/compaction/model-usability-budget.js +16 -8
  59. package/dist/core/extensions/builtin/compaction/model-usability-budget.js.map +1 -1
  60. package/dist/core/extensions/builtin/compaction/switch-admission.d.ts +23 -0
  61. package/dist/core/extensions/builtin/compaction/switch-admission.d.ts.map +1 -0
  62. package/dist/core/extensions/builtin/compaction/switch-admission.js +19 -0
  63. package/dist/core/extensions/builtin/compaction/switch-admission.js.map +1 -0
  64. package/dist/core/extensions/builtin/goal/index.d.ts.map +1 -1
  65. package/dist/core/extensions/builtin/goal/index.js +10 -0
  66. package/dist/core/extensions/builtin/goal/index.js.map +1 -1
  67. package/dist/core/extensions/bun-extension-commonjs.d.ts +1 -1
  68. package/dist/core/extensions/bun-extension-commonjs.d.ts.map +1 -1
  69. package/dist/core/extensions/bun-extension-commonjs.js +3 -3
  70. package/dist/core/extensions/bun-extension-commonjs.js.map +1 -1
  71. package/dist/core/extensions/bun-extension-importer.d.ts.map +1 -1
  72. package/dist/core/extensions/bun-extension-importer.js +4 -1
  73. package/dist/core/extensions/bun-extension-importer.js.map +1 -1
  74. package/dist/core/extensions/bun-extension-registry.d.ts.map +1 -1
  75. package/dist/core/extensions/bun-extension-registry.js +5 -9
  76. package/dist/core/extensions/bun-extension-registry.js.map +1 -1
  77. package/dist/core/resolved-paths-memo.d.ts +31 -0
  78. package/dist/core/resolved-paths-memo.d.ts.map +1 -0
  79. package/dist/core/resolved-paths-memo.js +57 -0
  80. package/dist/core/resolved-paths-memo.js.map +1 -0
  81. package/dist/core/resource-loader.d.ts +4 -1
  82. package/dist/core/resource-loader.d.ts.map +1 -1
  83. package/dist/core/resource-loader.js +25 -12
  84. package/dist/core/resource-loader.js.map +1 -1
  85. package/dist/core/retry-fallback/settings.d.ts +10 -2
  86. package/dist/core/retry-fallback/settings.d.ts.map +1 -1
  87. package/dist/core/retry-fallback/settings.js +28 -6
  88. package/dist/core/retry-fallback/settings.js.map +1 -1
  89. package/dist/core/skill-discovery.d.ts.map +1 -1
  90. package/dist/core/skill-discovery.js +11 -1
  91. package/dist/core/skill-discovery.js.map +1 -1
  92. package/dist/main.d.ts +10 -0
  93. package/dist/main.d.ts.map +1 -1
  94. package/dist/main.js +19 -2
  95. package/dist/main.js.map +1 -1
  96. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts +2 -5
  97. package/dist/modes/interactive/components/ask-user-answer-chip.d.ts.map +1 -1
  98. package/dist/modes/interactive/components/ask-user-answer-chip.js +1 -4
  99. package/dist/modes/interactive/components/ask-user-answer-chip.js.map +1 -1
  100. package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
  101. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  102. package/dist/modes/interactive/components/assistant-message.js +8 -0
  103. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  104. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts +1 -0
  105. package/dist/modes/interactive/components/assistant-render-descriptors.d.ts.map +1 -1
  106. package/dist/modes/interactive/components/assistant-render-descriptors.js +4 -0
  107. package/dist/modes/interactive/components/assistant-render-descriptors.js.map +1 -1
  108. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  109. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  110. package/dist/modes/interactive/components/status-indicator.js +15 -2
  111. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  112. package/dist/modes/interactive/interactive-mode.d.ts +2 -0
  113. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  114. package/dist/modes/interactive/interactive-mode.js +81 -6
  115. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  116. package/dist/modes/interactive/provider-error-presentation.d.ts +18 -0
  117. package/dist/modes/interactive/provider-error-presentation.d.ts.map +1 -0
  118. package/dist/modes/interactive/provider-error-presentation.js +100 -0
  119. package/dist/modes/interactive/provider-error-presentation.js.map +1 -0
  120. package/dist/modes/rpc/rpc-types.d.ts +18 -0
  121. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  122. package/dist/modes/rpc/rpc-types.js.map +1 -1
  123. package/dist/modes/rpc/session-command-router.d.ts.map +1 -1
  124. package/dist/modes/rpc/session-command-router.js +14 -0
  125. package/dist/modes/rpc/session-command-router.js.map +1 -1
  126. package/dist/modes/rpc/session-event-writer.d.ts +9 -1
  127. package/dist/modes/rpc/session-event-writer.d.ts.map +1 -1
  128. package/dist/modes/rpc/session-event-writer.js +21 -0
  129. package/dist/modes/rpc/session-event-writer.js.map +1 -1
  130. package/dist/modes/rpc/session-registry.d.ts.map +1 -1
  131. package/dist/modes/rpc/session-registry.js +9 -2
  132. package/dist/modes/rpc/session-registry.js.map +1 -1
  133. package/dist/modes/rpc/session-worker-requests.d.ts +10 -1
  134. package/dist/modes/rpc/session-worker-requests.d.ts.map +1 -1
  135. package/dist/modes/rpc/session-worker-requests.js +8 -2
  136. package/dist/modes/rpc/session-worker-requests.js.map +1 -1
  137. package/dist/modes/rpc/session-worker-requests.test.d.ts +2 -0
  138. package/dist/modes/rpc/session-worker-requests.test.d.ts.map +1 -0
  139. package/dist/modes/rpc/session-worker-requests.test.js +44 -0
  140. package/dist/modes/rpc/session-worker-requests.test.js.map +1 -0
  141. package/docs/rpc.md +7 -0
  142. package/docs/settings.md +1 -1
  143. package/node_modules/@code-yeongyu/senpi-codemode/CHANGELOG.md +12 -0
  144. package/node_modules/@code-yeongyu/senpi-codemode/package.json +4 -4
  145. package/node_modules/@earendil-works/pi-agent-core/package.json +3 -3
  146. package/node_modules/@earendil-works/pi-ai/dist/providers/data/.manifest.json +1 -1
  147. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode-go.json +1 -1
  148. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opencode.json +1 -1
  149. package/node_modules/@earendil-works/pi-ai/dist/providers/data/opengateway.json +1 -1
  150. package/node_modules/@earendil-works/pi-ai/dist/providers/data/openrouter.json +1 -1
  151. package/node_modules/@earendil-works/pi-ai/dist/providers/data/vercel-ai-gateway.json +1 -1
  152. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai-coding-cn.json +1 -1
  153. package/node_modules/@earendil-works/pi-ai/dist/providers/data/zai.json +1 -1
  154. package/node_modules/@earendil-works/pi-ai/package.json +2 -2
  155. package/node_modules/@earendil-works/pi-pty/package.json +1 -1
  156. package/node_modules/@earendil-works/pi-telemetry/package.json +1 -1
  157. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.d.ts.map +1 -1
  158. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.js +26 -3
  159. package/node_modules/@earendil-works/pi-tui/dist/native-module-path.js.map +1 -1
  160. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.d.ts.map +1 -1
  161. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js +13 -6
  162. package/node_modules/@earendil-works/pi-tui/dist/tui-alt-screen.js.map +1 -1
  163. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.d.ts.map +1 -1
  164. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js +11 -3
  165. package/node_modules/@earendil-works/pi-tui/dist/tui-main-screen.js.map +1 -1
  166. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts +15 -2
  167. package/node_modules/@earendil-works/pi-tui/dist/tui.d.ts.map +1 -1
  168. package/node_modules/@earendil-works/pi-tui/dist/tui.js +45 -2
  169. package/node_modules/@earendil-works/pi-tui/dist/tui.js.map +1 -1
  170. package/node_modules/@earendil-works/pi-tui/package.json +1 -1
  171. package/package.json +8 -8
@@ -1 +1 @@
1
- {"version":3,"file":"session-event-writer.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-writer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAQ1D,OAAO,EACN,yBAAyB,EACzB,kBAAkB,GAElB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,yBAAyB,EAAqC,MAAM,2BAA2B,CAAC;AAEzG,qFAAqF;AACrF,MAAM,YAAY,GAAG,CAAC,MAAuC,EAAiB,EAAE,CAC/E,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AAEhG,0FAA0F;AAC1F,MAAM,YAAY,GAAG,CAAC,MAAuC,EAAiB,EAAE,CAC/E,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,iBAAiB,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;AA0BrF,MAAM,CAAC,MAAM,4BAA4B,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAC7D,MAAM,CAAC,MAAM,8BAA8B,GAAG,IAAI,CAAC;AAEnD,MAAM,WAAW,GAAG,SAAS,CAAC;AAC9B,MAAM,mBAAmB,GAAG,IAAI,GAAG,CAAmB,CAAC,YAAY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KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,SAAS,EAAE,EAAE,CAAC;YACtC,KAAK,IAAI,IAAI,GAAG,KAAK,CAAC,IAAI,EAAE,IAAI,EAAE,IAAI,GAAG,IAAI,CAAC,IAAI;gBAAE,IAAI,CAAC,MAAM,EAAE,CAAC,KAAK,CAAC,CAAC;QAC1E,CAAC;IACF,CAAC;IAEO,CAAC,SAAS;QACjB,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QAC5B,MAAM,IAAI,CAAC,YAAY,CAAC;IACzB,CAAC;CACD","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { SessionKind } from \"../../core/extensions/types.ts\";\nimport { MEDIA_PLACEHOLDERS_CAPABILITY } from \"./custom-capability.ts\";\nimport { serializeJsonLine } from \"./jsonl.ts\";\nimport { omitInlineMedia } from \"./media-placeholders.ts\";\nimport type {\n\tRpcHostMemoryPressureEvent,\n\tRpcHostStalledEvent,\n\tRpcSessionClosedEvent,\n\tRpcSessionClosedReason,\n\tRpcSessionParkedEvent,\n} from \"./rpc-types.ts\";\nimport {\n\tRENDERED_COMPONENT_RECORD,\n\tSessionEventFanout,\n\ttype SessionEventWriterConnection,\n} from \"./session-event-fanout.ts\";\nimport type { SocketEventSinkActor } from \"./socket-event-fanout.ts\";\n\nexport { RENDERED_COMPONENT_RECORD, type SessionEventWriterConnection } from \"./session-event-fanout.ts\";\n\n/** Await every actor's drain; a failed actor is a cut peer, not a writer failure. */\nconst settleActors = (actors: readonly SocketEventSinkActor[]): Promise<void> =>\n\tPromise.all(actors.map((actor) => actor.flush().catch(() => undefined))).then(() => undefined);\n\n/** Await every actor's ACCEPTANCE of what it was given; never the peer's kernel drain. */\nconst acceptActors = (actors: readonly SocketEventSinkActor[]): Promise<void> =>\n\tPromise.all(actors.map((actor) => actor.waitForAcceptance())).then(() => undefined);\n\ntype RawWriter = (chunk: string) => void;\ntype BackpressureWaiter = () => Promise<void>;\ntype FlushScheduler = (flush: () => Promise<void>) => void;\ntype RpcRecord = Record<string, unknown>;\ntype CompactDeltaType = \"text_delta\" | \"thinking_delta\" | \"toolcall_delta\";\n\ntype QueueNode = {\n\tvalue: RpcRecord;\n\tkey?: string;\n\tprevious?: QueueNode;\n\tnext?: QueueNode;\n\tresolve?: () => void;\n\treject?: (cause: unknown) => void;\n};\n\ntype RecordQueue = {\n\tsessionId?: string;\n\ttargetId?: string;\n\thead?: QueueNode;\n\ttail?: QueueNode;\n\tlatestByKey: Map<string, QueueNode>;\n\tready: boolean;\n};\n\nexport const MAX_SHARED_STDIO_QUEUE_BYTES = 64 * 1024 * 1024;\nexport const MAX_SHARED_STDIO_QUEUE_RECORDS = 4096;\n\nconst MESSAGE_KEY = \"message\";\nconst COMPACT_DELTA_TYPES = new Set<CompactDeltaType>([\"text_delta\", \"thinking_delta\", \"toolcall_delta\"]);\n\nfunction compactDelta(value: RpcRecord): { type: CompactDeltaType; contentIndex: number; delta: string } | undefined {\n\tif (value.type !== \"message_update\" || !Object.hasOwn(value, \"message\")) return undefined;\n\tconst event = value.assistantMessageEvent;\n\tif (typeof event !== \"object\" || event === null) return undefined;\n\tconst typedEvent = event as Record<string, unknown>;\n\tif (\n\t\ttypeof typedEvent.type !== \"string\" ||\n\t\t!COMPACT_DELTA_TYPES.has(typedEvent.type as CompactDeltaType) ||\n\t\ttypeof typedEvent.contentIndex !== \"number\" ||\n\t\ttypeof typedEvent.delta !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\ttype: typedEvent.type as CompactDeltaType,\n\t\tcontentIndex: typedEvent.contentIndex,\n\t\tdelta: typedEvent.delta,\n\t};\n}\n\n/** The delta-only form of a compact message_update: cumulative snapshot fields blanked, delta kept. */\nfunction demoteToDeltaOnly(value: RpcRecord): RpcRecord {\n\tconst event = value.assistantMessageEvent as Record<string, unknown>;\n\treturn { ...value, message: null, assistantMessageEvent: { ...event, partial: null } };\n}\n\nfunction toolUpdateKey(value: RpcRecord): string | undefined {\n\treturn value.type === \"tool_execution_update\" && typeof value.toolCallId === \"string\"\n\t\t? `tool:${value.toolCallId}`\n\t\t: undefined;\n}\n\n/**\n * Process-wide stdout scheduler for multi-session RPC mode.\n *\n * Each queue contains complete structured JSONL records for one routing handle.\n * Draining takes one record per queue in round-robin order and waits for stdout\n * backpressure before selecting the next one. A record is deliberately written\n * by itself: coalescing records from different sessions would obscure the\n * scheduling boundary and violate D9.\n */\nexport class SessionEventWriter {\n\tprivate readonly queues = new Map<string, RecordQueue>();\n\tprivate readonly fanout = new SessionEventFanout();\n\tprivate readonly connectionContext = new AsyncLocalStorage<string>();\n\tprivate readonly controlQueue: RecordQueue = { latestByKey: new Map(), ready: false };\n\tprivate readonly readyQueues: RecordQueue[] = [];\n\tprivate readonly sealedSessions = new Set<string>();\n\t/** Sessions whose lifecycle records stay on their attached connections (`kind: \"worker\"`). */\n\tprivate readonly workerSessions = new Set<string>();\n\tprivate readonly writeRaw: RawWriter;\n\tprivate readonly waitForBackpressure?: BackpressureWaiter;\n\tprivate readonly scheduleFlush: FlushScheduler;\n\tprivate flushScheduled = false;\n\tprivate drainPromise?: Promise<void>;\n\tprivate inFlight?: { queue: RecordQueue; node: QueueNode };\n\tprivate failure?: unknown;\n\tprivate controlOverflowReported = false;\n\tprivate closeOverflowReported = false;\n\tprivate readonly closeOverflowActors = new WeakSet<SocketEventSinkActor>();\n\tprivate reservedCloseRecords = 0;\n\tprivate reservedCloseBytes = 0;\n\n\tget pendingCloseRecordCount(): number {\n\t\treturn this.reservedCloseRecords;\n\t}\n\n\tget pendingCloseByteLength(): number {\n\t\treturn this.reservedCloseBytes;\n\t}\n\n\tconstructor(writeRaw: RawWriter, scheduleFlush?: FlushScheduler);\n\tconstructor(writeRaw: RawWriter, waitForBackpressure: BackpressureWaiter, scheduleFlush?: FlushScheduler);\n\tconstructor(\n\t\twriteRaw: RawWriter,\n\t\twaitOrSchedule?: BackpressureWaiter | FlushScheduler,\n\t\tscheduleFlush?: FlushScheduler,\n\t) {\n\t\tthis.writeRaw = writeRaw;\n\t\tif (waitOrSchedule && scheduleFlush === undefined && waitOrSchedule.length > 0) {\n\t\t\tthis.scheduleFlush = waitOrSchedule as FlushScheduler;\n\t\t} else {\n\t\t\tthis.waitForBackpressure = waitOrSchedule as BackpressureWaiter | undefined;\n\t\t\tthis.scheduleFlush = scheduleFlush ?? ((flush) => queueMicrotask(() => void flush()));\n\t\t}\n\t}\n\n\tget bufferedRecordCount(): number {\n\t\tlet count = this.inFlight ? 1 : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tget bufferedByteLength(): number {\n\t\tlet bytes = this.inFlight ? Buffer.byteLength(serializeJsonLine(this.inFlight.node.value)) : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) {\n\t\t\t\tbytes += Buffer.byteLength(serializeJsonLine(node.value));\n\t\t\t}\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tregisterConnection(\n\t\tid: string,\n\t\tconnection: SessionEventWriterConnection,\n\t\toptions: { readonly maxQueueBytes?: number; readonly stallMs?: number } = {},\n\t): void {\n\t\tthis.fanout.registerConnection(id, connection, options);\n\t}\n\n\tunregisterConnection(id: string): void {\n\t\tthis.fanout.unregisterConnection(id);\n\t}\n\n\tattachConnectionToSession(id: string, sessionId: string): void {\n\t\tthis.fanout.attachConnectionToSession(id, sessionId);\n\t}\n\n\tdetachConnectionFromSession(id: string, sessionId: string): void {\n\t\tthis.fanout.detachConnectionFromSession(id, sessionId);\n\t}\n\n\tsetConnectionCapabilities(id: string, capabilities: readonly string[]): void {\n\t\tthis.fanout.setConnectionCapabilities(id, capabilities);\n\t}\n\n\tclearConnectionCapabilities(id: string): void {\n\t\tthis.fanout.clearConnectionCapabilities(id);\n\t}\n\n\thasRegisteredConnectionCapabilities(id: string): boolean {\n\t\treturn this.fanout.hasRegisteredConnectionCapabilities(id);\n\t}\n\n\tgetConnectionCapabilities(id: string): readonly string[] | undefined {\n\t\treturn this.fanout.getConnectionCapabilities(id);\n\t}\n\n\thasCapableConnection(sessionId: string): boolean {\n\t\treturn this.fanout.hasCapableConnection(sessionId);\n\t}\n\n\t/**\n\t * Records a session's visibility class. A worker session is machine-driven work that\n\t * only its attached connections track, so its lifecycle records are delivered to them\n\t * instead of broadcast; an interactive session keeps the broadcast every client (the\n\t * desktop mirror, the supervisor's idle observer) relies on.\n\t */\n\tsetSessionKind(sessionId: string, kind: SessionKind): void {\n\t\tif (kind === \"worker\") this.workerSessions.add(sessionId);\n\t\telse this.workerSessions.delete(sessionId);\n\t}\n\n\t/** Execute a connection's command with its response destination in context. */\n\twithConnection<T>(id: string, task: () => T): T {\n\t\treturn this.connectionContext.run(id, task);\n\t}\n\n\t/** Connection id of the command currently being dispatched, when one owns it. */\n\tcurrentConnection(): string | undefined {\n\t\treturn this.connectionContext.getStore();\n\t}\n\n\t/** Queue a session record. Content events target connections attached to the session. */\n\tenqueue(sessionId: string, value: object): boolean {\n\t\tif (this.sealedSessions.has(sessionId)) return false;\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst record = value as RpcRecord;\n\t\tconst isTargeted =\n\t\t\trecord.type === \"response\" ||\n\t\t\trecord.type === \"bash_execution_update\" ||\n\t\t\t(record.type === \"extension_ui_request\" &&\n\t\t\t\t[\"select\", \"confirm\", \"input\", \"editor\"].includes(String(record.method)));\n\t\tconst tagged = { ...value, sessionId } as RpcRecord;\n\t\tconst { [RENDERED_COMPONENT_RECORD]: _rendered, ...wireTagged } = tagged;\n\t\tconst line = serializeJsonLine(wireTagged);\n\t\tif (this.fanout.isEmpty() && this.exceedsStdioCapacity(line)) {\n\t\t\tthis.closeSession(\n\t\t\t\tsessionId,\n\t\t\t\t{\n\t\t\t\t\ttype: \"response\",\n\t\t\t\t\tcommand: \"close_session\",\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: \"session_output_overflow, resync required\",\n\t\t\t\t},\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tconst targets = this.fanout.targets(\n\t\t\tsessionId,\n\t\t\ttargetId,\n\t\t\tisTargeted,\n\t\t\trecord[RENDERED_COMPONENT_RECORD] === true,\n\t\t\trecord.type,\n\t\t);\n\t\t// A record is only walked and re-serialized when a target asked for placeholders;\n\t\t// otherwise this is byte-for-byte today's path, with serializeJsonLine called once.\n\t\tconst hasPlaceholderTarget = targets.some((target) =>\n\t\t\tthis.fanout.connectionHas(target, MEDIA_PLACEHOLDERS_CAPABILITY),\n\t\t);\n\t\tconst redacted = hasPlaceholderTarget ? omitInlineMedia(wireTagged) : wireTagged;\n\t\tconst placeholderLine = redacted === wireTagged ? undefined : serializeJsonLine(redacted);\n\t\tif (!isTargeted) this.fanout.rememberSnapshot(sessionId, tagged, line, placeholderLine, wireTagged);\n\t\tfor (const target of targets) {\n\t\t\tif (target !== undefined && !this.fanout.get(target)) continue;\n\t\t\tconst registered = target === undefined ? undefined : this.fanout.get(target);\n\t\t\tconst wants =\n\t\t\t\tplaceholderLine !== undefined && this.fanout.connectionHas(target, MEDIA_PLACEHOLDERS_CAPABILITY);\n\t\t\tif (registered) {\n\t\t\t\tconst keyed = compactDelta(tagged) !== undefined && tagged.message !== null;\n\t\t\t\tregistered.actor.enqueue(\n\t\t\t\t\twants ? placeholderLine : line,\n\t\t\t\t\tkeyed ? MESSAGE_KEY : undefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\tkeyed ? serializeJsonLine(demoteToDeltaOnly(wireTagged)) : undefined,\n\t\t\t\t);\n\t\t\t} else this.appendSessionRecord(sessionId, wants ? (redacted as RpcRecord) : wireTagged, target);\n\t\t}\n\t\tthis.requestFlush();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Return worker credit once this session's destinations have ACCEPTED the record\n\t * into their bounded queues - never when the slowest peer's kernel has drained it.\n\t * A client that is merely busy would otherwise pace the producing worker into\n\t * session_worker_credit_timeout and force the dead-peer budget under\n\t * SESSION_WORKER_LIMITS.controlMs (#1774). Delivery stays bounded by each queue's\n\t * maxQueueBytes and its dead-peer cut. A destination that failed (byte overflow or\n\t * stall) was already cut and closed by the fanout's onFailure; it is a cut peer,\n\t * not a writer failure. The shared stdio lane keeps its stdout backpressure wait.\n\t */\n\twaitForSessionBackpressure(sessionId: string): Promise<void> {\n\t\tif (this.fanout.isEmpty()) return this.flush();\n\t\treturn acceptActors(this.sessionActors(sessionId));\n\t}\n\n\t/** Registered actors this session's records are delivered to, plus the caller's own. */\n\tprivate sessionActors(sessionId: string): SocketEventSinkActor[] {\n\t\tconst targets = new Set([\n\t\t\t...this.fanout.targets(sessionId, this.currentConnection(), false, false, undefined),\n\t\t\tthis.currentConnection(),\n\t\t]);\n\t\treturn [...targets].flatMap((target) => {\n\t\t\tconst registered = target === undefined ? undefined : this.fanout.get(target);\n\t\t\treturn registered ? [registered.actor] : [];\n\t\t});\n\t}\n\n\t/** Queue one untagged host-control response for the current connection. */\n\tenqueueControl(value: object): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) {\n\t\t\tregistered.actor.enqueue(serializeJsonLine(value));\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (this.exceedsStdioCapacity(serializeJsonLine(value))) {\n\t\t\tif (!this.controlOverflowReported) {\n\t\t\t\tthis.controlOverflowReported = true;\n\t\t\t\tthis.append(this.controlQueue, { type: \"overflow\", error: \"rpc_control_output_overflow, resync required\" });\n\t\t\t\tthis.markReady(this.controlQueue);\n\t\t\t\tthis.requestFlush();\n\t\t\t}\n\t\t\treturn Promise.reject(new Error(\"rpc_control_output_overflow, resync required\"));\n\t\t}\n\t\tconst queue = targetId === undefined ? this.controlQueue : this.connectionQueue(targetId);\n\t\tconst completion = new Promise<void>((resolve, reject) => {\n\t\t\tthis.append(queue, { ...value }, undefined, resolve, reject);\n\t\t});\n\t\tthis.markReady(queue);\n\t\tthis.requestFlush();\n\t\treturn completion;\n\t}\n\n\t/**\n\t * Queue one HOST-level lifecycle record for every registered connection, or the\n\t * shared stdio lane when none is registered. Unlike session records it is not tagged\n\t * with a routing handle by the writer: `host_stalled` carries the handle it blames,\n\t * and `host_memory_pressure` belongs to the process, not to a session.\n\t */\n\tbroadcastHostRecord(record: RpcHostStalledEvent | RpcHostMemoryPressureEvent): void {\n\t\t// Reconstruct so desktop `refresh-senpi-events.ts` sees literal `type:` sites in this file.\n\t\tlet wire: RpcRecord;\n\t\tswitch (record.type) {\n\t\t\tcase \"host_stalled\":\n\t\t\t\twire = {\n\t\t\t\t\ttype: \"host_stalled\",\n\t\t\t\t\tdriftMs: record.driftMs,\n\t\t\t\t\t...(record.sessionId !== undefined ? { sessionId: record.sessionId } : {}),\n\t\t\t\t\t...(record.tool !== undefined ? { tool: record.tool } : {}),\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"host_memory_pressure\":\n\t\t\t\twire = { type: \"host_memory_pressure\", rssMb: record.rssMb, sessions: record.sessions };\n\t\t\t\tbreak;\n\t\t\tdefault: {\n\t\t\t\tconst exhaustive: never = record;\n\t\t\t\tthrow new Error(`unexpected host record ${exhaustive}`);\n\t\t\t}\n\t\t}\n\t\tif (this.fanout.isEmpty()) {\n\t\t\tthis.append(this.controlQueue, wire);\n\t\t\tthis.markReady(this.controlQueue);\n\t\t} else this.fanout.broadcast(serializeJsonLine(wire));\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Prevent subsequent records for a session and append its terminal response.\n\t * Existing records retain FIFO order; this response is therefore that\n\t * session's final stdout record.\n\t */\n\tcloseSession(sessionId: string, response: object, reason?: RpcSessionClosedReason): void {\n\t\tif (this.sealedSessions.has(sessionId)) return;\n\t\tthis.sealedSessions.add(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\t// `reason` tells an attached client WHY the handle ended, so a park it can reopen by path is\n\t\t// not read as a session that is gone. Absent unless the caller names one; clients tolerate that.\n\t\tconst lifecycle: RpcSessionClosedEvent = { type: \"session_closed\", sessionId, ...(reason && { reason }) };\n\t\tif (this.fanout.isEmpty()) this.appendSessionRecord(sessionId, lifecycle);\n\t\telse if (this.workerSessions.has(sessionId))\n\t\t\tthis.fanout.deliverToSession(sessionId, serializeJsonLine(lifecycle));\n\t\telse this.fanout.broadcast(serializeJsonLine(lifecycle));\n\t\tconst taggedResponse = { ...response, sessionId };\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) registered.actor.enqueue(serializeJsonLine(taggedResponse));\n\t\telse this.appendSessionRecord(sessionId, taggedResponse, targetId);\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Seal a session the host PARKED and publish `session_parked`.\n\t *\n\t * Parking is the idle sweep putting a RETAINED session back on disk: the routing\n\t * handle ends exactly as a close ends it, but the session survives and reopens with\n\t * `open_session { sessionPath }`, so the record a client dispatches on must say so\n\t * instead of claiming the session ended. Delivery follows the `session_closed` rule -\n\t * a worker session's record reaches only its attached connections, an interactive\n\t * session's reaches every connection. No client asked for this teardown, so there is\n\t * no close response to answer.\n\t */\n\tparkSession(sessionId: string, sessionPath: string): void {\n\t\tif (this.sealedSessions.has(sessionId)) return;\n\t\tthis.sealedSessions.add(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t\tconst lifecycle: RpcSessionParkedEvent = { type: \"session_parked\", sessionId, sessionPath };\n\t\tif (this.fanout.isEmpty()) this.appendSessionRecord(sessionId, lifecycle);\n\t\telse if (this.workerSessions.has(sessionId))\n\t\t\tthis.fanout.deliverToSession(sessionId, serializeJsonLine(lifecycle));\n\t\telse this.fanout.broadcast(serializeJsonLine(lifecycle));\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Admit reply debt before routing can mutate attachments or await finalization.\n\t * Reserve the lifecycle as well: the claimant's role is not known yet. Rejected\n\t * closes do not wait, retain their ids, or create per-request stderr output.\n\t */\n\treserveCloseResponse(\n\t\tsessionId: string,\n\t\tresponse: object,\n\t\trecords = 2,\n\t): { release: () => void; complete: (terminal: boolean, reason?: RpcSessionClosedReason) => void } | undefined {\n\t\tconst bytes =\n\t\t\tBuffer.byteLength(serializeJsonLine({ ...response, sessionId })) +\n\t\t\t(records === 2\n\t\t\t\t? Buffer.byteLength(serializeJsonLine({ type: \"session_closed\", sessionId, reason: \"client_close\" }))\n\t\t\t\t: 0);\n\t\tif (\n\t\t\tthis.bufferedRecordCount + this.reservedCloseRecords + records > MAX_SHARED_STDIO_QUEUE_RECORDS ||\n\t\t\tthis.bufferedByteLength + this.reservedCloseBytes + bytes > MAX_SHARED_STDIO_QUEUE_BYTES\n\t\t) {\n\t\t\tconst overflow = {\n\t\t\t\ttype: \"overflow\",\n\t\t\t\tcommand: \"close_session\",\n\t\t\t\terror: \"rpc_close_output_overflow, resync required\",\n\t\t\t};\n\t\t\tconst targetId = this.currentConnection();\n\t\t\tif (targetId !== undefined) {\n\t\t\t\tconst actor = this.fanout.get(targetId)?.actor;\n\t\t\t\tif (actor && !this.closeOverflowActors.has(actor)) {\n\t\t\t\t\tthis.closeOverflowActors.add(actor);\n\t\t\t\t\t// One outstanding notice per sink, released only on consumption.\n\t\t\t\t\t// Actor identity isolates reconnects and does not retain dead sinks.\n\t\t\t\t\tactor.enqueue(serializeJsonLine(overflow), undefined, () => this.closeOverflowActors.delete(actor));\n\t\t\t\t}\n\t\t\t} else if (!this.closeOverflowReported) {\n\t\t\t\tthis.closeOverflowReported = true;\n\t\t\t\tthis.append(this.controlQueue, overflow);\n\t\t\t\tthis.markReady(this.controlQueue);\n\t\t\t\tthis.requestFlush();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.reservedCloseRecords += records;\n\t\tthis.reservedCloseBytes += bytes;\n\t\tlet active = true;\n\t\tconst release = () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\tthis.reservedCloseRecords -= records;\n\t\t\tthis.reservedCloseBytes -= bytes;\n\t\t};\n\t\treturn {\n\t\t\trelease,\n\t\t\tcomplete: (terminal, reason) => {\n\t\t\t\tif (!active) return;\n\t\t\t\trelease();\n\t\t\t\tif (terminal) this.closeSession(sessionId, response, reason);\n\t\t\t\telse this.appendClosedResponse(sessionId, response);\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Queue a joined close only after admitting its noncompactable reply. */\n\tenqueueClosedResponse(sessionId: string, response: object): void {\n\t\tthis.reserveCloseResponse(sessionId, response, 1)?.complete(false);\n\t}\n\n\tprivate appendClosedResponse(sessionId: string, response: object): void {\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst taggedResponse = { ...response, sessionId };\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) registered.actor.enqueue(serializeJsonLine(taggedResponse));\n\t\telse this.appendSessionRecord(sessionId, taggedResponse, targetId);\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Drops per-session bookkeeping for a handle whose runtime is fully disposed.\n\t * Routing handles are unique per process epoch, so nothing can legitimately\n\t * emit under this id again; without this every host-closed session would\n\t * leave a permanent sealed-handle (and snapshot) entry behind.\n\t */\n\tforgetSession(sessionId: string): void {\n\t\tthis.sealedSessions.delete(sessionId);\n\t\tthis.workerSessions.delete(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t}\n\n\t/** Drain every retained lane and the current in-flight record. */\n\tflush(): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tthis.flushScheduled = false;\n\t\tif (this.drainPromise) return this.drainPromise;\n\t\tif (this.readyQueues.length === 0) return settleActors([...this.fanout.values()].map(({ actor }) => actor));\n\t\tlet resolveDrain!: () => void;\n\t\tlet rejectDrain!: (cause: unknown) => void;\n\t\tconst drain = new Promise<void>((resolve, reject) => {\n\t\t\tresolveDrain = resolve;\n\t\t\trejectDrain = reject;\n\t\t});\n\t\tthis.drainPromise = drain;\n\t\tvoid this.drainUntilEmpty().then(resolveDrain, rejectDrain);\n\t\tvoid drain.then(\n\t\t\t() => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tif (this.readyQueues.length > 0) this.requestFlush();\n\t\t\t},\n\t\t\t(cause) => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tthis.fail(cause);\n\t\t\t},\n\t\t);\n\t\treturn drain;\n\t}\n\n\tprivate async drainUntilEmpty(): Promise<void> {\n\t\tdo {\n\t\t\tawait this.drainReadyQueues();\n\t\t} while (this.readyQueues.length > 0);\n\t\t// Per-connection failures are handled by the fanout (cut + close); only the\n\t\t// shared stdio lane may fail this writer.\n\t\tawait settleActors([...this.fanout.values()].map(({ actor }) => actor));\n\t\tthis.controlOverflowReported = false;\n\t\tif (this.reservedCloseRecords === 0) this.closeOverflowReported = false;\n\t}\n\n\tprivate async drainReadyQueues(): Promise<void> {\n\t\twhile (this.readyQueues.length > 0) {\n\t\t\tconst queue = this.readyQueues.shift()!;\n\t\t\tqueue.ready = false;\n\t\t\tconst node = queue.head;\n\t\t\tif (!node) continue;\n\n\t\t\tthis.unlink(queue, node);\n\t\t\tthis.inFlight = { queue, node };\n\t\t\ttry {\n\t\t\t\t// D9: exactly one complete record per raw write. The next lane is not\n\t\t\t\t// selected until this record has cleared stdout backpressure.\n\t\t\t\tconst connection = queue.targetId ? this.fanout.get(queue.targetId)?.connection : undefined;\n\t\t\t\tconst writeRaw = connection?.writeRaw ?? this.writeRaw;\n\t\t\t\tconst waitForBackpressure = connection?.waitForBackpressure ?? this.waitForBackpressure;\n\t\t\t\tif (!connection && queue.targetId) {\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t} else {\n\t\t\t\t\twriteRaw(serializeJsonLine(node.value));\n\t\t\t\t\tif (waitForBackpressure) await waitForBackpressure();\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t}\n\t\t\t} catch (cause) {\n\t\t\t\tnode.reject?.(cause);\n\t\t\t\tthrow cause;\n\t\t\t} finally {\n\t\t\t\tthis.inFlight = undefined;\n\t\t\t}\n\n\t\t\tif (queue.head) {\n\t\t\t\tthis.markReady(queue);\n\t\t\t} else if (queue.sessionId || queue.targetId) {\n\t\t\t\tfor (const [key, candidate] of this.queues) {\n\t\t\t\t\tif (candidate === queue) this.queues.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate exceedsStdioCapacity(line: string): boolean {\n\t\treturn (\n\t\t\tthis.bufferedRecordCount + this.reservedCloseRecords >= MAX_SHARED_STDIO_QUEUE_RECORDS ||\n\t\t\tthis.bufferedByteLength + this.reservedCloseBytes + Buffer.byteLength(line) > MAX_SHARED_STDIO_QUEUE_BYTES\n\t\t);\n\t}\n\n\tprivate connectionQueue(targetId: string): RecordQueue {\n\t\tconst key = `connection:${targetId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\t\treturn queue;\n\t}\n\n\tprivate appendSessionRecord(sessionId: string, value: RpcRecord, targetId?: string): void {\n\t\tconst key = `${targetId ?? \"default\"}:${sessionId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { sessionId, targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\n\t\tconst delta = compactDelta(value);\n\t\tif (delta) {\n\t\t\tconst previousFull = queue.latestByKey.get(MESSAGE_KEY);\n\t\t\tif (previousFull) this.demoteAndMerge(queue, previousFull);\n\t\t\tconst node = this.append(queue, value, MESSAGE_KEY);\n\t\t\tqueue.latestByKey.set(MESSAGE_KEY, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\tconst toolKey = toolUpdateKey(value);\n\t\tif (toolKey) {\n\t\t\tconst previous = queue.latestByKey.get(toolKey);\n\t\t\tif (previous) this.unlink(queue, previous);\n\t\t\tconst node = this.append(queue, value, toolKey);\n\t\t\tqueue.latestByKey.set(toolKey, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\t// All non-compactable records are ordering barriers. In particular this\n\t\t// includes delta-only/full non-delta message updates, protocol responses,\n\t\t// extension UI requests, errors, retries, lifecycle, and unknown records.\n\t\tqueue.latestByKey.clear();\n\t\tthis.append(queue, value);\n\t\tthis.markReady(queue);\n\t}\n\n\tprivate demoteAndMerge(queue: RecordQueue, node: QueueNode): void {\n\t\tnode.value = demoteToDeltaOnly(node.value);\n\t\tconst current = compactDelta(node.value);\n\t\tconst preceding = node.previous;\n\t\tconst previous = preceding ? compactDelta(preceding.value) : undefined;\n\t\tif (\n\t\t\tpreceding &&\n\t\t\tprevious &&\n\t\t\tcurrent &&\n\t\t\tpreceding.value.message === null &&\n\t\t\tprevious.type === current.type &&\n\t\t\tprevious.contentIndex === current.contentIndex\n\t\t) {\n\t\t\tconst precedingEvent = preceding.value.assistantMessageEvent as Record<string, unknown>;\n\t\t\tpreceding.value = {\n\t\t\t\t...preceding.value,\n\t\t\t\tassistantMessageEvent: { ...precedingEvent, delta: previous.delta + current.delta },\n\t\t\t};\n\t\t\tthis.unlink(queue, node);\n\t\t}\n\t}\n\n\tprivate append(\n\t\tqueue: RecordQueue,\n\t\tvalue: RpcRecord,\n\t\tkey?: string,\n\t\tresolve?: () => void,\n\t\treject?: (cause: unknown) => void,\n\t): QueueNode {\n\t\tconst node: QueueNode = { value, key, previous: queue.tail, resolve, reject };\n\t\tif (queue.tail) queue.tail.next = node;\n\t\telse queue.head = node;\n\t\tqueue.tail = node;\n\t\treturn node;\n\t}\n\n\tprivate unlink(queue: RecordQueue, node: QueueNode): void {\n\t\tif (node.previous) node.previous.next = node.next;\n\t\telse queue.head = node.next;\n\t\tif (node.next) node.next.previous = node.previous;\n\t\telse queue.tail = node.previous;\n\t\tif (node.key && queue.latestByKey.get(node.key) === node) queue.latestByKey.delete(node.key);\n\t\tnode.previous = undefined;\n\t\tnode.next = undefined;\n\t}\n\n\tprivate markReady(queue: RecordQueue): void {\n\t\tif (queue.ready || this.inFlight?.queue === queue || !queue.head) return;\n\t\tqueue.ready = true;\n\t\tthis.readyQueues.push(queue);\n\t}\n\n\tprivate requestFlush(): void {\n\t\tif (this.failure !== undefined || this.flushScheduled || this.drainPromise) return;\n\t\tthis.flushScheduled = true;\n\t\tthis.scheduleFlush(() => this.flush());\n\t}\n\n\tprivate fail(cause: unknown): void {\n\t\tif (this.failure !== undefined) return;\n\t\tthis.failure = cause;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) node.reject?.(cause);\n\t\t}\n\t}\n\n\tprivate *allQueues(): Iterable<RecordQueue> {\n\t\tyield* this.queues.values();\n\t\tyield this.controlQueue;\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-event-writer.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-event-writer.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAErD,OAAO,EAAE,6BAA6B,EAAE,MAAM,wBAAwB,CAAC;AACvE,OAAO,EAAE,iBAAiB,EAAE,MAAM,YAAY,CAAC;AAC/C,OAAO,EAAE,eAAe,EAAE,MAAM,yBAAyB,CAAC;AAS1D,OAAO,EACN,yBAAyB,EACzB,kBAAkB,GAElB,MAAM,2BAA2B,CAAC;AAGnC,OAAO,EAAE,yBAAyB,EAAqC,MAAM,2BAA2B,CAAC;AAEzG,qFAAqF;AACrF,MAAM,YAAY,GAAG,CAAC,MAAuC,EAAiB,EAAE,CAC/E,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,KAAK,EAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC,CAAC,CAAC,IAA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;IACF,CAAC;IAEO,CAAC,SAAS;QACjB,KAAK,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC;QAC5B,MAAM,IAAI,CAAC,YAAY,CAAC;IACzB,CAAC;CACD","sourcesContent":["import { AsyncLocalStorage } from \"node:async_hooks\";\nimport type { SessionKind } from \"../../core/extensions/types.ts\";\nimport { MEDIA_PLACEHOLDERS_CAPABILITY } from \"./custom-capability.ts\";\nimport { serializeJsonLine } from \"./jsonl.ts\";\nimport { omitInlineMedia } from \"./media-placeholders.ts\";\nimport type {\n\tRpcHostMemoryPressureEvent,\n\tRpcHostStalledEvent,\n\tRpcOpenQueuedEvent,\n\tRpcSessionClosedEvent,\n\tRpcSessionClosedReason,\n\tRpcSessionParkedEvent,\n} from \"./rpc-types.ts\";\nimport {\n\tRENDERED_COMPONENT_RECORD,\n\tSessionEventFanout,\n\ttype SessionEventWriterConnection,\n} from \"./session-event-fanout.ts\";\nimport type { SocketEventSinkActor } from \"./socket-event-fanout.ts\";\n\nexport { RENDERED_COMPONENT_RECORD, type SessionEventWriterConnection } from \"./session-event-fanout.ts\";\n\n/** Await every actor's drain; a failed actor is a cut peer, not a writer failure. */\nconst settleActors = (actors: readonly SocketEventSinkActor[]): Promise<void> =>\n\tPromise.all(actors.map((actor) => actor.flush().catch(() => undefined))).then(() => undefined);\n\n/** Await every actor's ACCEPTANCE of what it was given; never the peer's kernel drain. */\nconst acceptActors = (actors: readonly SocketEventSinkActor[]): Promise<void> =>\n\tPromise.all(actors.map((actor) => actor.waitForAcceptance())).then(() => undefined);\n\ntype RawWriter = (chunk: string) => void;\ntype BackpressureWaiter = () => Promise<void>;\ntype FlushScheduler = (flush: () => Promise<void>) => void;\ntype RpcRecord = Record<string, unknown>;\ntype CompactDeltaType = \"text_delta\" | \"thinking_delta\" | \"toolcall_delta\";\n\ntype QueueNode = {\n\tvalue: RpcRecord;\n\tkey?: string;\n\tprevious?: QueueNode;\n\tnext?: QueueNode;\n\tresolve?: () => void;\n\treject?: (cause: unknown) => void;\n};\n\ntype RecordQueue = {\n\tsessionId?: string;\n\ttargetId?: string;\n\thead?: QueueNode;\n\ttail?: QueueNode;\n\tlatestByKey: Map<string, QueueNode>;\n\tready: boolean;\n};\n\nexport const MAX_SHARED_STDIO_QUEUE_BYTES = 64 * 1024 * 1024;\nexport const MAX_SHARED_STDIO_QUEUE_RECORDS = 4096;\n\nconst MESSAGE_KEY = \"message\";\nconst COMPACT_DELTA_TYPES = new Set<CompactDeltaType>([\"text_delta\", \"thinking_delta\", \"toolcall_delta\"]);\n\nfunction compactDelta(value: RpcRecord): { type: CompactDeltaType; contentIndex: number; delta: string } | undefined {\n\tif (value.type !== \"message_update\" || !Object.hasOwn(value, \"message\")) return undefined;\n\tconst event = value.assistantMessageEvent;\n\tif (typeof event !== \"object\" || event === null) return undefined;\n\tconst typedEvent = event as Record<string, unknown>;\n\tif (\n\t\ttypeof typedEvent.type !== \"string\" ||\n\t\t!COMPACT_DELTA_TYPES.has(typedEvent.type as CompactDeltaType) ||\n\t\ttypeof typedEvent.contentIndex !== \"number\" ||\n\t\ttypeof typedEvent.delta !== \"string\"\n\t) {\n\t\treturn undefined;\n\t}\n\treturn {\n\t\ttype: typedEvent.type as CompactDeltaType,\n\t\tcontentIndex: typedEvent.contentIndex,\n\t\tdelta: typedEvent.delta,\n\t};\n}\n\n/** The delta-only form of a compact message_update: cumulative snapshot fields blanked, delta kept. */\nfunction demoteToDeltaOnly(value: RpcRecord): RpcRecord {\n\tconst event = value.assistantMessageEvent as Record<string, unknown>;\n\treturn { ...value, message: null, assistantMessageEvent: { ...event, partial: null } };\n}\n\nfunction toolUpdateKey(value: RpcRecord): string | undefined {\n\treturn value.type === \"tool_execution_update\" && typeof value.toolCallId === \"string\"\n\t\t? `tool:${value.toolCallId}`\n\t\t: undefined;\n}\n\n/**\n * Process-wide stdout scheduler for multi-session RPC mode.\n *\n * Each queue contains complete structured JSONL records for one routing handle.\n * Draining takes one record per queue in round-robin order and waits for stdout\n * backpressure before selecting the next one. A record is deliberately written\n * by itself: coalescing records from different sessions would obscure the\n * scheduling boundary and violate D9.\n */\nexport class SessionEventWriter {\n\tprivate readonly queues = new Map<string, RecordQueue>();\n\tprivate readonly fanout = new SessionEventFanout();\n\tprivate readonly connectionContext = new AsyncLocalStorage<string>();\n\tprivate readonly controlQueue: RecordQueue = { latestByKey: new Map(), ready: false };\n\tprivate readonly readyQueues: RecordQueue[] = [];\n\tprivate readonly sealedSessions = new Set<string>();\n\t/** Sessions whose lifecycle records stay on their attached connections (`kind: \"worker\"`). */\n\tprivate readonly workerSessions = new Set<string>();\n\tprivate readonly writeRaw: RawWriter;\n\tprivate readonly waitForBackpressure?: BackpressureWaiter;\n\tprivate readonly scheduleFlush: FlushScheduler;\n\tprivate flushScheduled = false;\n\tprivate drainPromise?: Promise<void>;\n\tprivate inFlight?: { queue: RecordQueue; node: QueueNode };\n\tprivate failure?: unknown;\n\tprivate controlOverflowReported = false;\n\tprivate closeOverflowReported = false;\n\tprivate readonly closeOverflowActors = new WeakSet<SocketEventSinkActor>();\n\tprivate reservedCloseRecords = 0;\n\tprivate reservedCloseBytes = 0;\n\n\tget pendingCloseRecordCount(): number {\n\t\treturn this.reservedCloseRecords;\n\t}\n\n\tget pendingCloseByteLength(): number {\n\t\treturn this.reservedCloseBytes;\n\t}\n\n\tconstructor(writeRaw: RawWriter, scheduleFlush?: FlushScheduler);\n\tconstructor(writeRaw: RawWriter, waitForBackpressure: BackpressureWaiter, scheduleFlush?: FlushScheduler);\n\tconstructor(\n\t\twriteRaw: RawWriter,\n\t\twaitOrSchedule?: BackpressureWaiter | FlushScheduler,\n\t\tscheduleFlush?: FlushScheduler,\n\t) {\n\t\tthis.writeRaw = writeRaw;\n\t\tif (waitOrSchedule && scheduleFlush === undefined && waitOrSchedule.length > 0) {\n\t\t\tthis.scheduleFlush = waitOrSchedule as FlushScheduler;\n\t\t} else {\n\t\t\tthis.waitForBackpressure = waitOrSchedule as BackpressureWaiter | undefined;\n\t\t\tthis.scheduleFlush = scheduleFlush ?? ((flush) => queueMicrotask(() => void flush()));\n\t\t}\n\t}\n\n\tget bufferedRecordCount(): number {\n\t\tlet count = this.inFlight ? 1 : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) count++;\n\t\t}\n\t\treturn count;\n\t}\n\n\tget bufferedByteLength(): number {\n\t\tlet bytes = this.inFlight ? Buffer.byteLength(serializeJsonLine(this.inFlight.node.value)) : 0;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) {\n\t\t\t\tbytes += Buffer.byteLength(serializeJsonLine(node.value));\n\t\t\t}\n\t\t}\n\t\treturn bytes;\n\t}\n\n\tregisterConnection(\n\t\tid: string,\n\t\tconnection: SessionEventWriterConnection,\n\t\toptions: { readonly maxQueueBytes?: number; readonly stallMs?: number } = {},\n\t): void {\n\t\tthis.fanout.registerConnection(id, connection, options);\n\t}\n\n\tunregisterConnection(id: string): void {\n\t\tthis.fanout.unregisterConnection(id);\n\t}\n\n\tattachConnectionToSession(id: string, sessionId: string): void {\n\t\tthis.fanout.attachConnectionToSession(id, sessionId);\n\t}\n\n\tdetachConnectionFromSession(id: string, sessionId: string): void {\n\t\tthis.fanout.detachConnectionFromSession(id, sessionId);\n\t}\n\n\tsetConnectionCapabilities(id: string, capabilities: readonly string[]): void {\n\t\tthis.fanout.setConnectionCapabilities(id, capabilities);\n\t}\n\n\tclearConnectionCapabilities(id: string): void {\n\t\tthis.fanout.clearConnectionCapabilities(id);\n\t}\n\n\thasRegisteredConnectionCapabilities(id: string): boolean {\n\t\treturn this.fanout.hasRegisteredConnectionCapabilities(id);\n\t}\n\n\tgetConnectionCapabilities(id: string): readonly string[] | undefined {\n\t\treturn this.fanout.getConnectionCapabilities(id);\n\t}\n\n\thasCapableConnection(sessionId: string): boolean {\n\t\treturn this.fanout.hasCapableConnection(sessionId);\n\t}\n\n\t/**\n\t * Records a session's visibility class. A worker session is machine-driven work that\n\t * only its attached connections track, so its lifecycle records are delivered to them\n\t * instead of broadcast; an interactive session keeps the broadcast every client (the\n\t * desktop mirror, the supervisor's idle observer) relies on.\n\t */\n\tsetSessionKind(sessionId: string, kind: SessionKind): void {\n\t\tif (kind === \"worker\") this.workerSessions.add(sessionId);\n\t\telse this.workerSessions.delete(sessionId);\n\t}\n\n\t/** Execute a connection's command with its response destination in context. */\n\twithConnection<T>(id: string, task: () => T): T {\n\t\treturn this.connectionContext.run(id, task);\n\t}\n\n\t/** Connection id of the command currently being dispatched, when one owns it. */\n\tcurrentConnection(): string | undefined {\n\t\treturn this.connectionContext.getStore();\n\t}\n\n\t/** Queue a session record. Content events target connections attached to the session. */\n\tenqueue(sessionId: string, value: object): boolean {\n\t\tif (this.sealedSessions.has(sessionId)) return false;\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst record = value as RpcRecord;\n\t\tconst isTargeted =\n\t\t\trecord.type === \"response\" ||\n\t\t\trecord.type === \"bash_execution_update\" ||\n\t\t\t(record.type === \"extension_ui_request\" &&\n\t\t\t\t[\"select\", \"confirm\", \"input\", \"editor\"].includes(String(record.method)));\n\t\tconst tagged = { ...value, sessionId } as RpcRecord;\n\t\tconst { [RENDERED_COMPONENT_RECORD]: _rendered, ...wireTagged } = tagged;\n\t\tconst line = serializeJsonLine(wireTagged);\n\t\tif (this.fanout.isEmpty() && this.exceedsStdioCapacity(line)) {\n\t\t\tthis.closeSession(\n\t\t\t\tsessionId,\n\t\t\t\t{\n\t\t\t\t\ttype: \"response\",\n\t\t\t\t\tcommand: \"close_session\",\n\t\t\t\t\tsuccess: false,\n\t\t\t\t\terror: \"session_output_overflow, resync required\",\n\t\t\t\t},\n\t\t\t\t\"error\",\n\t\t\t);\n\t\t\treturn false;\n\t\t}\n\t\tconst targets = this.fanout.targets(\n\t\t\tsessionId,\n\t\t\ttargetId,\n\t\t\tisTargeted,\n\t\t\trecord[RENDERED_COMPONENT_RECORD] === true,\n\t\t\trecord.type,\n\t\t);\n\t\t// A record is only walked and re-serialized when a target asked for placeholders;\n\t\t// otherwise this is byte-for-byte today's path, with serializeJsonLine called once.\n\t\tconst hasPlaceholderTarget = targets.some((target) =>\n\t\t\tthis.fanout.connectionHas(target, MEDIA_PLACEHOLDERS_CAPABILITY),\n\t\t);\n\t\tconst redacted = hasPlaceholderTarget ? omitInlineMedia(wireTagged) : wireTagged;\n\t\tconst placeholderLine = redacted === wireTagged ? undefined : serializeJsonLine(redacted);\n\t\tif (!isTargeted) this.fanout.rememberSnapshot(sessionId, tagged, line, placeholderLine, wireTagged);\n\t\tfor (const target of targets) {\n\t\t\tif (target !== undefined && !this.fanout.get(target)) continue;\n\t\t\tconst registered = target === undefined ? undefined : this.fanout.get(target);\n\t\t\tconst wants =\n\t\t\t\tplaceholderLine !== undefined && this.fanout.connectionHas(target, MEDIA_PLACEHOLDERS_CAPABILITY);\n\t\t\tif (registered) {\n\t\t\t\tconst keyed = compactDelta(tagged) !== undefined && tagged.message !== null;\n\t\t\t\tregistered.actor.enqueue(\n\t\t\t\t\twants ? placeholderLine : line,\n\t\t\t\t\tkeyed ? MESSAGE_KEY : undefined,\n\t\t\t\t\tundefined,\n\t\t\t\t\tkeyed ? serializeJsonLine(demoteToDeltaOnly(wireTagged)) : undefined,\n\t\t\t\t);\n\t\t\t} else this.appendSessionRecord(sessionId, wants ? (redacted as RpcRecord) : wireTagged, target);\n\t\t}\n\t\tthis.requestFlush();\n\t\treturn true;\n\t}\n\n\t/**\n\t * Return worker credit once this session's destinations have ACCEPTED the record\n\t * into their bounded queues - never when the slowest peer's kernel has drained it.\n\t * A client that is merely busy would otherwise pace the producing worker into\n\t * session_worker_credit_timeout and force the dead-peer budget under\n\t * SESSION_WORKER_LIMITS.controlMs (#1774). Delivery stays bounded by each queue's\n\t * maxQueueBytes and its dead-peer cut. A destination that failed (byte overflow or\n\t * stall) was already cut and closed by the fanout's onFailure; it is a cut peer,\n\t * not a writer failure. The shared stdio lane keeps its stdout backpressure wait.\n\t */\n\twaitForSessionBackpressure(sessionId: string): Promise<void> {\n\t\tif (this.fanout.isEmpty()) return this.flush();\n\t\treturn acceptActors(this.sessionActors(sessionId));\n\t}\n\n\t/** Registered actors this session's records are delivered to, plus the caller's own. */\n\tprivate sessionActors(sessionId: string): SocketEventSinkActor[] {\n\t\tconst targets = new Set([\n\t\t\t...this.fanout.targets(sessionId, this.currentConnection(), false, false, undefined),\n\t\t\tthis.currentConnection(),\n\t\t]);\n\t\treturn [...targets].flatMap((target) => {\n\t\t\tconst registered = target === undefined ? undefined : this.fanout.get(target);\n\t\t\treturn registered ? [registered.actor] : [];\n\t\t});\n\t}\n\n\t/** Queue one untagged host-control response for the current connection. */\n\tenqueueControl(value: object): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) {\n\t\t\tregistered.actor.enqueue(serializeJsonLine(value));\n\t\t\treturn Promise.resolve();\n\t\t}\n\t\tif (this.exceedsStdioCapacity(serializeJsonLine(value))) {\n\t\t\tif (!this.controlOverflowReported) {\n\t\t\t\tthis.controlOverflowReported = true;\n\t\t\t\tthis.append(this.controlQueue, { type: \"overflow\", error: \"rpc_control_output_overflow, resync required\" });\n\t\t\t\tthis.markReady(this.controlQueue);\n\t\t\t\tthis.requestFlush();\n\t\t\t}\n\t\t\treturn Promise.reject(new Error(\"rpc_control_output_overflow, resync required\"));\n\t\t}\n\t\tconst queue = targetId === undefined ? this.controlQueue : this.connectionQueue(targetId);\n\t\tconst completion = new Promise<void>((resolve, reject) => {\n\t\t\tthis.append(queue, { ...value }, undefined, resolve, reject);\n\t\t});\n\t\tthis.markReady(queue);\n\t\tthis.requestFlush();\n\t\treturn completion;\n\t}\n\n\t/**\n\t * Queue one HOST-level lifecycle record for every registered connection, or the\n\t * shared stdio lane when none is registered. Unlike session records it is not tagged\n\t * with a routing handle by the writer: `host_stalled` carries the handle it blames,\n\t * and `host_memory_pressure` belongs to the process, not to a session.\n\t */\n\t/**\n\t * Tell ONE opener where it sits in the open queue, before its open reaches the loop.\n\t *\n\t * Sent to the opening connection only: a queue position is about that caller's request, not\n\t * about the host. If the connection is gone the record is dropped rather than queued - a\n\t * position is worthless to a client that already left.\n\t */\n\tsendOpenQueued(connection: string, record: RpcOpenQueuedEvent): void {\n\t\t// Reconstruct so desktop `refresh-senpi-events.ts` sees a literal `type:` site in this file.\n\t\tconst wire: RpcRecord = {\n\t\t\ttype: \"queued\",\n\t\t\tfor_request: record.for_request,\n\t\t\tposition: record.position,\n\t\t\tin_flight: record.in_flight,\n\t\t};\n\t\tconst target = this.fanout.get(connection);\n\t\tif (target === undefined) return;\n\t\ttarget.actor.enqueue(serializeJsonLine(wire));\n\t\tthis.requestFlush();\n\t}\n\n\tbroadcastHostRecord(record: RpcHostStalledEvent | RpcHostMemoryPressureEvent): void {\n\t\t// Reconstruct so desktop `refresh-senpi-events.ts` sees literal `type:` sites in this file.\n\t\tlet wire: RpcRecord;\n\t\tswitch (record.type) {\n\t\t\tcase \"host_stalled\":\n\t\t\t\twire = {\n\t\t\t\t\ttype: \"host_stalled\",\n\t\t\t\t\tdriftMs: record.driftMs,\n\t\t\t\t\t...(record.sessionId !== undefined ? { sessionId: record.sessionId } : {}),\n\t\t\t\t\t...(record.tool !== undefined ? { tool: record.tool } : {}),\n\t\t\t\t};\n\t\t\t\tbreak;\n\t\t\tcase \"host_memory_pressure\":\n\t\t\t\twire = { type: \"host_memory_pressure\", rssMb: record.rssMb, sessions: record.sessions };\n\t\t\t\tbreak;\n\t\t\tdefault: {\n\t\t\t\tconst exhaustive: never = record;\n\t\t\t\tthrow new Error(`unexpected host record ${exhaustive}`);\n\t\t\t}\n\t\t}\n\t\tif (this.fanout.isEmpty()) {\n\t\t\tthis.append(this.controlQueue, wire);\n\t\t\tthis.markReady(this.controlQueue);\n\t\t} else this.fanout.broadcast(serializeJsonLine(wire));\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Prevent subsequent records for a session and append its terminal response.\n\t * Existing records retain FIFO order; this response is therefore that\n\t * session's final stdout record.\n\t */\n\tcloseSession(sessionId: string, response: object, reason?: RpcSessionClosedReason): void {\n\t\tif (this.sealedSessions.has(sessionId)) return;\n\t\tthis.sealedSessions.add(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t\tconst targetId = this.connectionContext.getStore();\n\t\t// `reason` tells an attached client WHY the handle ended, so a park it can reopen by path is\n\t\t// not read as a session that is gone. Absent unless the caller names one; clients tolerate that.\n\t\tconst lifecycle: RpcSessionClosedEvent = { type: \"session_closed\", sessionId, ...(reason && { reason }) };\n\t\tif (this.fanout.isEmpty()) this.appendSessionRecord(sessionId, lifecycle);\n\t\telse if (this.workerSessions.has(sessionId))\n\t\t\tthis.fanout.deliverToSession(sessionId, serializeJsonLine(lifecycle));\n\t\telse this.fanout.broadcast(serializeJsonLine(lifecycle));\n\t\tconst taggedResponse = { ...response, sessionId };\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) registered.actor.enqueue(serializeJsonLine(taggedResponse));\n\t\telse this.appendSessionRecord(sessionId, taggedResponse, targetId);\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Seal a session the host PARKED and publish `session_parked`.\n\t *\n\t * Parking is the idle sweep putting a RETAINED session back on disk: the routing\n\t * handle ends exactly as a close ends it, but the session survives and reopens with\n\t * `open_session { sessionPath }`, so the record a client dispatches on must say so\n\t * instead of claiming the session ended. Delivery follows the `session_closed` rule -\n\t * a worker session's record reaches only its attached connections, an interactive\n\t * session's reaches every connection. No client asked for this teardown, so there is\n\t * no close response to answer.\n\t */\n\tparkSession(sessionId: string, sessionPath: string): void {\n\t\tif (this.sealedSessions.has(sessionId)) return;\n\t\tthis.sealedSessions.add(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t\tconst lifecycle: RpcSessionParkedEvent = { type: \"session_parked\", sessionId, sessionPath };\n\t\tif (this.fanout.isEmpty()) this.appendSessionRecord(sessionId, lifecycle);\n\t\telse if (this.workerSessions.has(sessionId))\n\t\t\tthis.fanout.deliverToSession(sessionId, serializeJsonLine(lifecycle));\n\t\telse this.fanout.broadcast(serializeJsonLine(lifecycle));\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Admit reply debt before routing can mutate attachments or await finalization.\n\t * Reserve the lifecycle as well: the claimant's role is not known yet. Rejected\n\t * closes do not wait, retain their ids, or create per-request stderr output.\n\t */\n\treserveCloseResponse(\n\t\tsessionId: string,\n\t\tresponse: object,\n\t\trecords = 2,\n\t): { release: () => void; complete: (terminal: boolean, reason?: RpcSessionClosedReason) => void } | undefined {\n\t\tconst bytes =\n\t\t\tBuffer.byteLength(serializeJsonLine({ ...response, sessionId })) +\n\t\t\t(records === 2\n\t\t\t\t? Buffer.byteLength(serializeJsonLine({ type: \"session_closed\", sessionId, reason: \"client_close\" }))\n\t\t\t\t: 0);\n\t\tif (\n\t\t\tthis.bufferedRecordCount + this.reservedCloseRecords + records > MAX_SHARED_STDIO_QUEUE_RECORDS ||\n\t\t\tthis.bufferedByteLength + this.reservedCloseBytes + bytes > MAX_SHARED_STDIO_QUEUE_BYTES\n\t\t) {\n\t\t\tconst overflow = {\n\t\t\t\ttype: \"overflow\",\n\t\t\t\tcommand: \"close_session\",\n\t\t\t\terror: \"rpc_close_output_overflow, resync required\",\n\t\t\t};\n\t\t\tconst targetId = this.currentConnection();\n\t\t\tif (targetId !== undefined) {\n\t\t\t\tconst actor = this.fanout.get(targetId)?.actor;\n\t\t\t\tif (actor && !this.closeOverflowActors.has(actor)) {\n\t\t\t\t\tthis.closeOverflowActors.add(actor);\n\t\t\t\t\t// One outstanding notice per sink, released only on consumption.\n\t\t\t\t\t// Actor identity isolates reconnects and does not retain dead sinks.\n\t\t\t\t\tactor.enqueue(serializeJsonLine(overflow), undefined, () => this.closeOverflowActors.delete(actor));\n\t\t\t\t}\n\t\t\t} else if (!this.closeOverflowReported) {\n\t\t\t\tthis.closeOverflowReported = true;\n\t\t\t\tthis.append(this.controlQueue, overflow);\n\t\t\t\tthis.markReady(this.controlQueue);\n\t\t\t\tthis.requestFlush();\n\t\t\t}\n\t\t\treturn undefined;\n\t\t}\n\t\tthis.reservedCloseRecords += records;\n\t\tthis.reservedCloseBytes += bytes;\n\t\tlet active = true;\n\t\tconst release = () => {\n\t\t\tif (!active) return;\n\t\t\tactive = false;\n\t\t\tthis.reservedCloseRecords -= records;\n\t\t\tthis.reservedCloseBytes -= bytes;\n\t\t};\n\t\treturn {\n\t\t\trelease,\n\t\t\tcomplete: (terminal, reason) => {\n\t\t\t\tif (!active) return;\n\t\t\t\trelease();\n\t\t\t\tif (terminal) this.closeSession(sessionId, response, reason);\n\t\t\t\telse this.appendClosedResponse(sessionId, response);\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Queue a joined close only after admitting its noncompactable reply. */\n\tenqueueClosedResponse(sessionId: string, response: object): void {\n\t\tthis.reserveCloseResponse(sessionId, response, 1)?.complete(false);\n\t}\n\n\tprivate appendClosedResponse(sessionId: string, response: object): void {\n\t\tconst targetId = this.connectionContext.getStore();\n\t\tconst taggedResponse = { ...response, sessionId };\n\t\tconst registered = targetId === undefined ? undefined : this.fanout.get(targetId);\n\t\tif (registered) registered.actor.enqueue(serializeJsonLine(taggedResponse));\n\t\telse this.appendSessionRecord(sessionId, taggedResponse, targetId);\n\t\tthis.requestFlush();\n\t}\n\n\t/**\n\t * Drops per-session bookkeeping for a handle whose runtime is fully disposed.\n\t * Routing handles are unique per process epoch, so nothing can legitimately\n\t * emit under this id again; without this every host-closed session would\n\t * leave a permanent sealed-handle (and snapshot) entry behind.\n\t */\n\tforgetSession(sessionId: string): void {\n\t\tthis.sealedSessions.delete(sessionId);\n\t\tthis.workerSessions.delete(sessionId);\n\t\tthis.fanout.forgetSession(sessionId);\n\t}\n\n\t/** Drain every retained lane and the current in-flight record. */\n\tflush(): Promise<void> {\n\t\tif (this.failure !== undefined) return Promise.reject(this.failure);\n\t\tthis.flushScheduled = false;\n\t\tif (this.drainPromise) return this.drainPromise;\n\t\tif (this.readyQueues.length === 0) return settleActors([...this.fanout.values()].map(({ actor }) => actor));\n\t\tlet resolveDrain!: () => void;\n\t\tlet rejectDrain!: (cause: unknown) => void;\n\t\tconst drain = new Promise<void>((resolve, reject) => {\n\t\t\tresolveDrain = resolve;\n\t\t\trejectDrain = reject;\n\t\t});\n\t\tthis.drainPromise = drain;\n\t\tvoid this.drainUntilEmpty().then(resolveDrain, rejectDrain);\n\t\tvoid drain.then(\n\t\t\t() => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tif (this.readyQueues.length > 0) this.requestFlush();\n\t\t\t},\n\t\t\t(cause) => {\n\t\t\t\tif (this.drainPromise === drain) this.drainPromise = undefined;\n\t\t\t\tthis.fail(cause);\n\t\t\t},\n\t\t);\n\t\treturn drain;\n\t}\n\n\tprivate async drainUntilEmpty(): Promise<void> {\n\t\tdo {\n\t\t\tawait this.drainReadyQueues();\n\t\t} while (this.readyQueues.length > 0);\n\t\t// Per-connection failures are handled by the fanout (cut + close); only the\n\t\t// shared stdio lane may fail this writer.\n\t\tawait settleActors([...this.fanout.values()].map(({ actor }) => actor));\n\t\tthis.controlOverflowReported = false;\n\t\tif (this.reservedCloseRecords === 0) this.closeOverflowReported = false;\n\t}\n\n\tprivate async drainReadyQueues(): Promise<void> {\n\t\twhile (this.readyQueues.length > 0) {\n\t\t\tconst queue = this.readyQueues.shift()!;\n\t\t\tqueue.ready = false;\n\t\t\tconst node = queue.head;\n\t\t\tif (!node) continue;\n\n\t\t\tthis.unlink(queue, node);\n\t\t\tthis.inFlight = { queue, node };\n\t\t\ttry {\n\t\t\t\t// D9: exactly one complete record per raw write. The next lane is not\n\t\t\t\t// selected until this record has cleared stdout backpressure.\n\t\t\t\tconst connection = queue.targetId ? this.fanout.get(queue.targetId)?.connection : undefined;\n\t\t\t\tconst writeRaw = connection?.writeRaw ?? this.writeRaw;\n\t\t\t\tconst waitForBackpressure = connection?.waitForBackpressure ?? this.waitForBackpressure;\n\t\t\t\tif (!connection && queue.targetId) {\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t} else {\n\t\t\t\t\twriteRaw(serializeJsonLine(node.value));\n\t\t\t\t\tif (waitForBackpressure) await waitForBackpressure();\n\t\t\t\t\tnode.resolve?.();\n\t\t\t\t}\n\t\t\t} catch (cause) {\n\t\t\t\tnode.reject?.(cause);\n\t\t\t\tthrow cause;\n\t\t\t} finally {\n\t\t\t\tthis.inFlight = undefined;\n\t\t\t}\n\n\t\t\tif (queue.head) {\n\t\t\t\tthis.markReady(queue);\n\t\t\t} else if (queue.sessionId || queue.targetId) {\n\t\t\t\tfor (const [key, candidate] of this.queues) {\n\t\t\t\t\tif (candidate === queue) this.queues.delete(key);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate exceedsStdioCapacity(line: string): boolean {\n\t\treturn (\n\t\t\tthis.bufferedRecordCount + this.reservedCloseRecords >= MAX_SHARED_STDIO_QUEUE_RECORDS ||\n\t\t\tthis.bufferedByteLength + this.reservedCloseBytes + Buffer.byteLength(line) > MAX_SHARED_STDIO_QUEUE_BYTES\n\t\t);\n\t}\n\n\tprivate connectionQueue(targetId: string): RecordQueue {\n\t\tconst key = `connection:${targetId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\t\treturn queue;\n\t}\n\n\tprivate appendSessionRecord(sessionId: string, value: RpcRecord, targetId?: string): void {\n\t\tconst key = `${targetId ?? \"default\"}:${sessionId}`;\n\t\tlet queue = this.queues.get(key);\n\t\tif (!queue) {\n\t\t\tqueue = { sessionId, targetId, latestByKey: new Map(), ready: false };\n\t\t\tthis.queues.set(key, queue);\n\t\t}\n\n\t\tconst delta = compactDelta(value);\n\t\tif (delta) {\n\t\t\tconst previousFull = queue.latestByKey.get(MESSAGE_KEY);\n\t\t\tif (previousFull) this.demoteAndMerge(queue, previousFull);\n\t\t\tconst node = this.append(queue, value, MESSAGE_KEY);\n\t\t\tqueue.latestByKey.set(MESSAGE_KEY, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\tconst toolKey = toolUpdateKey(value);\n\t\tif (toolKey) {\n\t\t\tconst previous = queue.latestByKey.get(toolKey);\n\t\t\tif (previous) this.unlink(queue, previous);\n\t\t\tconst node = this.append(queue, value, toolKey);\n\t\t\tqueue.latestByKey.set(toolKey, node);\n\t\t\tthis.markReady(queue);\n\t\t\treturn;\n\t\t}\n\n\t\t// All non-compactable records are ordering barriers. In particular this\n\t\t// includes delta-only/full non-delta message updates, protocol responses,\n\t\t// extension UI requests, errors, retries, lifecycle, and unknown records.\n\t\tqueue.latestByKey.clear();\n\t\tthis.append(queue, value);\n\t\tthis.markReady(queue);\n\t}\n\n\tprivate demoteAndMerge(queue: RecordQueue, node: QueueNode): void {\n\t\tnode.value = demoteToDeltaOnly(node.value);\n\t\tconst current = compactDelta(node.value);\n\t\tconst preceding = node.previous;\n\t\tconst previous = preceding ? compactDelta(preceding.value) : undefined;\n\t\tif (\n\t\t\tpreceding &&\n\t\t\tprevious &&\n\t\t\tcurrent &&\n\t\t\tpreceding.value.message === null &&\n\t\t\tprevious.type === current.type &&\n\t\t\tprevious.contentIndex === current.contentIndex\n\t\t) {\n\t\t\tconst precedingEvent = preceding.value.assistantMessageEvent as Record<string, unknown>;\n\t\t\tpreceding.value = {\n\t\t\t\t...preceding.value,\n\t\t\t\tassistantMessageEvent: { ...precedingEvent, delta: previous.delta + current.delta },\n\t\t\t};\n\t\t\tthis.unlink(queue, node);\n\t\t}\n\t}\n\n\tprivate append(\n\t\tqueue: RecordQueue,\n\t\tvalue: RpcRecord,\n\t\tkey?: string,\n\t\tresolve?: () => void,\n\t\treject?: (cause: unknown) => void,\n\t): QueueNode {\n\t\tconst node: QueueNode = { value, key, previous: queue.tail, resolve, reject };\n\t\tif (queue.tail) queue.tail.next = node;\n\t\telse queue.head = node;\n\t\tqueue.tail = node;\n\t\treturn node;\n\t}\n\n\tprivate unlink(queue: RecordQueue, node: QueueNode): void {\n\t\tif (node.previous) node.previous.next = node.next;\n\t\telse queue.head = node.next;\n\t\tif (node.next) node.next.previous = node.previous;\n\t\telse queue.tail = node.previous;\n\t\tif (node.key && queue.latestByKey.get(node.key) === node) queue.latestByKey.delete(node.key);\n\t\tnode.previous = undefined;\n\t\tnode.next = undefined;\n\t}\n\n\tprivate markReady(queue: RecordQueue): void {\n\t\tif (queue.ready || this.inFlight?.queue === queue || !queue.head) return;\n\t\tqueue.ready = true;\n\t\tthis.readyQueues.push(queue);\n\t}\n\n\tprivate requestFlush(): void {\n\t\tif (this.failure !== undefined || this.flushScheduled || this.drainPromise) return;\n\t\tthis.flushScheduled = true;\n\t\tthis.scheduleFlush(() => this.flush());\n\t}\n\n\tprivate fail(cause: unknown): void {\n\t\tif (this.failure !== undefined) return;\n\t\tthis.failure = cause;\n\t\tfor (const queue of this.allQueues()) {\n\t\t\tfor (let node = queue.head; node; node = node.next) node.reject?.(cause);\n\t\t}\n\t}\n\n\tprivate *allQueues(): Iterable<RecordQueue> {\n\t\tyield* this.queues.values();\n\t\tyield this.controlQueue;\n\t}\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"session-registry.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-registry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,aAAa,EAAwB,MAAM,2CAA2C,CAAC;AAChG,OAAO,EACN,KAAK,yBAAyB,EAC9B,mBAAmB,EACnB,KAAK,gCAAgC,EAErC,MAAM,qCAAqC,CAAC;AAC7C,OAAO,KAAK,EAAE,cAAc,EAAE,WAAW,EAAqB,MAAM,gCAAgC,CAAC;AAGrG,OAAO,EAA+B,KAAK,uBAAuB,EAAE,MAAM,wBAAwB,CAAC;AAEnG,OAAO,KAAK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AAI,aAAa,EAAE,CActB;IAED,qEAAqE;IACrE,OAAO,CAAC,mBAAmB;IAoC3B,OAAO,CAAC,eAAe;CAKvB"}
@@ -302,12 +302,19 @@ export class RpcSessionRegistry {
302
302
  if (!manager)
303
303
  continue;
304
304
  const currentPath = manager.getSessionFile();
305
+ const currentKey = currentPath ? canonicalPath(currentPath) : undefined;
305
306
  // Preserve the originally canonicalized key while the runtime still points at
306
307
  // the same path. SessionManager may expose a symlink-resolved spelling after
307
308
  // opening a file that did not exist yet; treating that as replacement would
308
309
  // break ordinary attach-on-open aliases.
309
- if (currentPath !== entry.sessionPath) {
310
- const currentKey = currentPath ? canonicalPath(currentPath) : undefined;
310
+ //
311
+ // A moved path is not the only reason to reconcile: a session opened WITHOUT
312
+ // `sessionPath` lands its created file straight into `sessionPath` and never
313
+ // takes a reservation, so comparing paths alone leaves that file unclaimed
314
+ // forever and a later open of it builds a SECOND runtime over the same
315
+ // transcript. Reconcile whenever the canonical key we hold is not the key the
316
+ // runtime is actually writing.
317
+ if (currentPath !== entry.sessionPath || currentKey !== entry.reservationKey) {
311
318
  if (entry.reservationKey) {
312
319
  this.reservations.delete(entry.reservationKey);
313
320
  this.options.pathReservations?.release(entry.reservationKey);
@@ -1 +1 @@
1
- {"version":3,"file":"session-registry.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-registry.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AACnD,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,UAAU,EAAE,OAAO,EAAE,MAAM,WAAW,CAAC;AACnE,OAAO,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AAChG,OAAO,EAEN,mBAAmB,EAEnB,yBAAyB,GACzB,MAAM,qCAAqC,CAAC;AAE7C,OAAO,EAAE,qBAAqB,EAAE,MAAM,gCAAgC,CAAC;AACvE,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CA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AM,EAAE,CAAC;QAC9B,CAAC;IACF,CAAC;IAEO,eAAe,CAAC,OAAgC;QACvD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC;YACzG,MAAM,IAAI,uBAAuB,CAAC,cAAc,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;CACD","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport { ProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport {\n\ttype AgentSessionLaunchProfile,\n\tAgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\tcreateAgentSessionRuntime,\n} from \"../../core/agent-session-runtime.ts\";\nimport type { SessionContext, SessionKind, SessionStartEvent } from \"../../core/extensions/types.ts\";\nimport { EMPTY_SESSION_CONTEXT } from \"../../core/extensions/types.ts\";\nimport { SessionManager } from \"../../core/session-manager.ts\";\nimport { SESSION_PATH_RETRY_AFTER_MS, type SessionPathReservations } from \"./host-reservations.ts\";\nimport { beginSessionClose, closeMarkedSession, closeSession, type SessionTeardownHost } from \"./session-teardown.ts\";\nimport type { SessionWorkerClient } from \"./session-worker-client.ts\";\n\n/** The immutable flags selected when a routing session is opened. */\nexport interface RpcSessionLaunchProfile extends AgentSessionLaunchProfile {\n\tsessionPath?: string;\n}\n\nexport type SessionRuntime = AgentSessionRuntime;\nexport type RpcSessionState = \"opening\" | \"open\" | \"closing\" | \"quarantined\" | \"closed\";\n\nexport interface RpcSessionEntry {\n\tstate: RpcSessionState;\n\truntime?: SessionRuntime;\n\tworker?: SessionWorkerClient;\n\t/** Visibility class chosen by the open, frozen for the entry's life. */\n\treadonly kind: SessionKind;\n\t/** Frozen opaque labels the open attached; `{}` when it attached none. */\n\treadonly context: SessionContext;\n\t/** Resolves replacement against the runtime currently owned by this entry. */\n\tswitchSession?: SessionRuntime[\"switchSession\"];\n\t/** Rebind callback installed by the shared RPC connection handler. */\n\trebindSession?: Parameters<SessionRuntime[\"setRebindSession\"]>[0];\n\tscope: ProviderScope;\n\tprofile: Readonly<RpcSessionLaunchProfile>;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\t/** Canonical reservation key for path-opened sessions; matches the reservations set. */\n\treservationKey?: string;\n\t/** Key granted for the spelling this session was opened with; cleared once superseded. */\n\trequestedPathKey?: string;\n\t/** Current runtime cwd, which can change when a session is replaced. */\n\tcwd: string;\n\t/** Live attachments (open + later attaches). The runtime is disposed only when the last one closes. */\n\tattachments: number;\n\t/**\n\t * Opt-in retention: a dropped connection only DETACHES from this session. The\n\t * entry stays open at zero attachments (still listed, still running its turn,\n\t * still holding its path) until an explicit close_session or idle eviction.\n\t * Requested per `open_session`; an attach may turn it on, never off.\n\t */\n\tretainOnDisconnect?: boolean;\n\t/** Timestamp of the last routed command / observed activity; drives idle eviction. */\n\tlastCommandAt: number;\n\tlifecycleMutex: Promise<void>;\n\tcloseCompletion?: Promise<void>;\n\tcloseResolve?: () => void;\n\tcloseStarted?: boolean;\n}\n\nexport class RpcSessionRegistryError extends Error {\n\treadonly code:\n\t\t| \"unknown_session\"\n\t\t| \"session_closing\"\n\t\t| \"session_path_in_use\"\n\t\t| \"session_reservation_limit\"\n\t\t| \"invalid_path\"\n\t\t| \"open_failed\";\n\t/** Machine-readable context for the wire (`errorData`): who holds a path, when to retry. */\n\treadonly detail?: Readonly<Record<string, unknown>>;\n\n\tconstructor(code: RpcSessionRegistryError[\"code\"], reason?: string, detail?: Readonly<Record<string, unknown>>) {\n\t\tsuper(code === \"open_failed\" && reason ? `${code}: ${reason}` : code);\n\t\tthis.code = code;\n\t\tthis.name = \"RpcSessionRegistryError\";\n\t\tif (detail) this.detail = detail;\n\t}\n}\n\nexport interface RpcSessionRegistryOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n\t/** Injectable clock (defaults to Date.now) so idle bookkeeping is testable. */\n\tnow?: () => number;\n\t/** Maximum time to wait for graceful runtime teardown before forced release. */\n\tcloseGraceMs?: number;\n\t/**\n\t * Cross-GENERATION path claims. During a handoff two hosts are alive at once, and only a\n\t * claim outside either process can keep them off one JSONL. Absent for an embedded registry\n\t * that is the only host of its agent directory.\n\t */\n\tpathReservations?: SessionPathReservations;\n}\n\n/** Host-side lifecycle policy for one `open_session`, distinct from the session's launch profile. */\nexport interface RpcSessionOpenOptions {\n\t/** Keep the session alive when its last client disconnects (`open_session.retain_on_disconnect`). */\n\tretainOnDisconnect?: boolean;\n}\n\n/** One `list_sessions` row. `context` is published only to a listing that asked for workers. */\nexport interface RpcSessionRow {\n\tsessionId: string;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\tcwd: string;\n\tname?: string;\n\tstatus: Exclude<RpcSessionState, \"quarantined\">;\n\tattachments: number;\n\tkind: SessionKind;\n\tcontext: SessionContext;\n}\n\nexport interface OpenRpcSession {\n\tsessionId: string;\n\tdurableSessionId: string;\n\tsessionPath?: string;\n\t/** True when this open attached to an already-open session instead of creating one. */\n\tattached?: boolean;\n}\n\nfunction canonicalPath(path: string): string {\n\tconst absolutePath = resolve(path);\n\tif (existsSync(absolutePath)) return realpathSync(absolutePath);\n\treturn `${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`;\n}\n\n/** Freezes an open's launch inputs, including the nested objects a client supplied. */\nexport function frozenProfile(profile: RpcSessionLaunchProfile): Readonly<RpcSessionLaunchProfile> {\n\treturn Object.freeze({\n\t\t...profile,\n\t\t...(profile.creationModel ? { creationModel: Object.freeze({ ...profile.creationModel }) } : {}),\n\t\t...(profile.sessionContext ? { sessionContext: Object.freeze({ ...profile.sessionContext }) } : {}),\n\t});\n}\n\n/**\n * The visibility class and labels an entry keeps for its life, normalized once here so no\n * lifecycle, listing or delivery decision has to re-apply the defaults. Reads the already\n * frozen profile, so the entry and the runtime share one frozen context object.\n */\nexport function sessionIdentity(profile: Readonly<RpcSessionLaunchProfile>): {\n\treadonly kind: SessionKind;\n\treadonly context: SessionContext;\n} {\n\treturn { kind: profile.sessionKind ?? \"interactive\", context: profile.sessionContext ?? EMPTY_SESSION_CONTEXT };\n}\n\n/** Process-local lifecycle owner for multi-session RPC runtimes. */\nexport class RpcSessionRegistry {\n\tprivate readonly entries = new Map<string, RpcSessionEntry>();\n\tprivate readonly reservations = new Set<string>();\n\tprivate readonly teardownHost: SessionTeardownHost;\n\tprivate nextHandle = 0;\n\tprivate readonly options: RpcSessionRegistryOptions;\n\tprivate readonly now: () => number;\n\treadonly closeGraceMs: number;\n\n\tconstructor(options: RpcSessionRegistryOptions) {\n\t\tthis.options = options;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.closeGraceMs = options.closeGraceMs ?? 10_000;\n\t\tthis.teardownHost = {\n\t\t\tcloseGraceMs: this.closeGraceMs,\n\t\t\tget: (handle) => this.entries.get(handle),\n\t\t\tdelete: (handle) => this.entries.delete(handle),\n\t\t\treleaseReservation: (key) => {\n\t\t\t\tthis.reservations.delete(key);\n\t\t\t\tthis.options.pathReservations?.release(key);\n\t\t\t},\n\t\t\tsync: () => this.syncRuntimeMetadata(),\n\t\t};\n\t}\n\n\t/** Number of live entries, including ones still opening or closing. */\n\tget size(): number {\n\t\treturn this.entries.size;\n\t}\n\n\tasync openSession(profile: RpcSessionLaunchProfile, options?: RpcSessionOpenOptions): Promise<OpenRpcSession> {\n\t\tthis.validateProfile(profile);\n\t\tthis.syncRuntimeMetadata();\n\t\tconst sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;\n\t\tif (sessionPath) await this.settleClosingReservation(sessionPath);\n\t\tif (sessionPath && this.reservations.has(sessionPath)) {\n\t\t\t// Attach-on-open: a live session outlives individual client attachments, so a\n\t\t\t// resume (or a second surface) for an already-hosted path joins the existing\n\t\t\t// runtime instead of failing. An entry still opening keeps the exclusive\n\t\t\t// reservation and rejects as before.\n\t\t\tconst existing = [...this.entries].find(\n\t\t\t\t([, entry]) => entry.reservationKey === sessionPath && entry.state === \"open\",\n\t\t\t);\n\t\t\tif (!existing) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\tconst [handle, entry] = existing;\n\t\t\tentry.attachments += 1;\n\t\t\t// Retention is a property of the live session: any attach may ask for it, and\n\t\t\t// no attach may revoke it for the clients that already rely on it.\n\t\t\tif (options?.retainOnDisconnect) entry.retainOnDisconnect = true;\n\t\t\tif (!entry.durableSessionId) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\tentry.lastCommandAt = this.now();\n\t\t\treturn {\n\t\t\t\tsessionId: handle,\n\t\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\t\tsessionPath: entry.sessionPath,\n\t\t\t\tattached: true,\n\t\t\t};\n\t\t}\n\t\tif (sessionPath) {\n\t\t\t// Taken SYNCHRONOUSLY, before any await: a concurrent open for the same path must find the\n\t\t\t// reservation already held, not a window between the decision and the record of it.\n\t\t\tthis.reservations.add(sessionPath);\n\t\t\t// Another generation of this daemon may still be writing this file. Its claim is the only\n\t\t\t// thing this process can see across a handoff, and a live one means \"retry\", not \"gone\".\n\t\t\t// Only AWAIT when there is a cross-generation claim to take: `await undefined` still costs a\n\t\t\t// microtask, and an embedded registry (no second generation) must reach the \"opening\" entry\n\t\t\t// in the same tick a caller that raced it would look, exactly as it did before generations.\n\t\t\tconst holder = this.options.pathReservations\n\t\t\t\t? await this.options.pathReservations.claim(sessionPath)\n\t\t\t\t: undefined;\n\t\t\tif (holder) {\n\t\t\t\tthis.reservations.delete(sessionPath);\n\t\t\t\tthrow new RpcSessionRegistryError(\"session_path_in_use\", undefined, {\n\t\t\t\t\towner: holder,\n\t\t\t\t\tretry_after_ms: SESSION_PATH_RETRY_AFTER_MS,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):\n\t\t// Create-only launch semantics mirror classic startup flags. A resumed\n\t\t// session restores its persisted model and thinking level instead of being\n\t\t// overridden by the new open_session request.\n\t\tconst isResume = sessionPath !== undefined && existsSync(sessionPath);\n\t\t// Re-opening an existing session file is a resume, exactly like interactive\n\t\t// /resume (AgentSessionRuntime.switchSession). Without the event the session\n\t\t// starts with reason \"startup\" and every extension that only rebuilds state\n\t\t// on a resume - the ask-user dangling-question hook - stays unreachable from\n\t\t// the RPC restart path. A session created by this open stays \"startup\".\n\t\tconst sessionStartEvent: SessionStartEvent | undefined = isResume\n\t\t\t? { type: \"session_start\", reason: \"resume\" }\n\t\t\t: undefined;\n\t\tconst storedProfile = frozenProfile({ ...profile, ...(sessionPath ? { sessionPath } : {}) });\n\t\tconst runtimeProfile = isResume\n\t\t\t? frozenProfile({ ...storedProfile, creationModel: undefined, initialThinkingLevel: undefined })\n\t\t\t: storedProfile;\n\n\t\tconst handle = `rpc-${++this.nextHandle}`;\n\t\tconst entry: RpcSessionEntry = {\n\t\t\tstate: \"opening\",\n\t\t\tscope: new ProviderScope(),\n\t\t\tprofile: storedProfile,\n\t\t\t...sessionIdentity(storedProfile),\n\t\t\tsessionPath,\n\t\t\treservationKey: sessionPath,\n\t\t\tcwd: storedProfile.cwd,\n\t\t\tattachments: 1,\n\t\t\tretainOnDisconnect: options?.retainOnDisconnect === true,\n\t\t\tlastCommandAt: this.now(),\n\t\t\tlifecycleMutex: Promise.resolve(),\n\t\t};\n\t\tentry.switchSession = (sessionPath, options) => {\n\t\t\tconst operation = entry.lifecycleMutex.then(async () => {\n\t\t\t\tif (entry.state !== \"open\" || !entry.runtime) {\n\t\t\t\t\tthrow new RpcSessionRegistryError(\"unknown_session\");\n\t\t\t\t}\n\t\t\t\tconst runtime = entry.runtime;\n\t\t\t\tconst cwdOverride = options?.cwdOverride;\n\t\t\t\tconst cwdChanged = cwdOverride !== undefined && runtime.session.sessionManager.getCwd() !== cwdOverride;\n\t\t\t\tconst result = await runtime.switchSession(sessionPath, options);\n\t\t\t\tif (result.cancelled || !cwdChanged) return result;\n\n\t\t\t\t// A multi-session binding outlives an individual replacement. Keep the\n\t\t\t\t// entry's runtime object aligned with the replacement so every attached\n\t\t\t\t// client resolves getters and future commands against the new cwd-bound\n\t\t\t\t// runtime, not the object created during open_session.\n\t\t\t\tconst replacement = new AgentSessionRuntime(\n\t\t\t\t\truntime.session,\n\t\t\t\t\truntime.services,\n\t\t\t\t\tthis.options.createRuntime,\n\t\t\t\t\t[...runtime.diagnostics],\n\t\t\t\t\truntime.modelFallbackMessage,\n\t\t\t\t\truntime.launchProfile,\n\t\t\t\t);\n\t\t\t\treplacement.setRebindSession(entry.rebindSession);\n\t\t\t\tentry.runtime = replacement;\n\t\t\t\tthis.syncRuntimeMetadata();\n\t\t\t\treturn result;\n\t\t\t});\n\t\t\tentry.lifecycleMutex = operation.then(\n\t\t\t\t() => undefined,\n\t\t\t\t() => undefined,\n\t\t\t);\n\t\t\treturn operation;\n\t\t};\n\t\tthis.entries.set(handle, entry);\n\t\ttry {\n\t\t\tconst manager = sessionPath\n\t\t\t\t? SessionManager.open(sessionPath, undefined, storedProfile.cwd)\n\t\t\t\t: SessionManager.create(storedProfile.cwd);\n\t\t\tentry.runtime = await runWithProviderScope(entry.scope, () =>\n\t\t\t\tcreateAgentSessionRuntime(this.options.createRuntime, {\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tagentDir: this.options.agentDir,\n\t\t\t\t\tsessionManager: manager,\n\t\t\t\t\tsessionStartEvent,\n\t\t\t\t\tlaunchProfile: runtimeProfile,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.sessionPath ??= manager.getSessionFile();\n\t\t\tentry.state = \"open\";\n\t\t\treturn { sessionId: handle, durableSessionId: entry.durableSessionId, sessionPath: entry.sessionPath };\n\t\t} catch (error) {\n\t\t\t// Runtime construction may have started extensions, watchers, and provider\n\t\t\t// registrations before it rejects. Keep the reservation and entry private\n\t\t\t// until all of those resources have been torn down, then release them as\n\t\t\t// one rollback so the path can immediately be opened again.\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t} catch {\n\t\t\t\t// The original construction error remains the externally visible cause.\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait entry.scope.close?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.entries.delete(handle);\n\t\t\t\t\tif (sessionPath) {\n\t\t\t\t\t\tthis.reservations.delete(sessionPath);\n\t\t\t\t\t\tthis.options.pathReservations?.release(sessionPath);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error instanceof RpcSessionRegistryError) throw error;\n\t\t\tthrow new RpcSessionRegistryError(\"open_failed\", error instanceof Error ? error.message : undefined);\n\t\t}\n\t}\n\n\t/**\n\t * Waits out a teardown already in flight for this path before the open decides.\n\t *\n\t * A close FREES the path, but the entry keeps its reservation until its runtime is\n\t * disposed, so an open landing inside that window used to be refused with\n\t * `session_path_in_use` for a session that no longer exists - making \"reopen the\n\t * path I just closed\" a race against disposal latency, which no client can time.\n\t * The open now waits for the teardown it would have been refused by and then opens\n\t * the file fresh. Bounded by the same grace window that bounds the teardown itself\n\t * (`closeMarkedSession` force-releases at that deadline), so a wedged disposal\n\t * still ends in the ordinary refusal instead of an open that never answers.\n\t */\n\tprivate async settleClosingReservation(sessionPath: string): Promise<void> {\n\t\tconst closing = [...this.entries.values()].find(\n\t\t\t(entry) => entry.reservationKey === sessionPath && entry.state === \"closing\",\n\t\t);\n\t\tif (!closing?.closeCompletion) return;\n\t\tlet deadline: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tclosing.closeCompletion,\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\tdeadline = setTimeout(resolve, this.closeGraceMs);\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (deadline) clearTimeout(deadline);\n\t\t}\n\t}\n\n\t/**\n\t * Read-only lookup with no state transitions or attachment accounting.\n\t * Exists so lifecycle decisions (e.g. deferring a dropped connection's\n\t * release while a turn is still streaming) can inspect the live entry\n\t * without claiming it.\n\t */\n\tpeek(handle: string): RpcSessionEntry | undefined {\n\t\treturn this.entries.get(handle);\n\t}\n\n\tgetForCommand(handle: string, command: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (!entry) throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tif (\n\t\t\tentry.state === \"closing\" &&\n\t\t\t![\"abort\", \"abort_bash\", \"extension_ui_response\", \"extension_ui_progress\"].includes(command)\n\t\t) {\n\t\t\tthrow new RpcSessionRegistryError(\"session_closing\");\n\t\t}\n\t\tif (entry.state !== \"open\" && entry.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\t// Every routed command counts as activity for idle eviction. Lookups that\n\t\t// must not refresh idleness (sweeps, listing) use peek()/list() instead.\n\t\tentry.lastCommandAt = this.now();\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Starts a close synchronously and returns the live entry for routing decisions.\n\t * `detach` marks a client going away rather than the session ending, which a\n\t * retained entry answers by staying open at zero attachments.\n\t */\n\tbeginClose(handle: string, onRole?: (finalizer: boolean) => void, options?: { detach?: boolean }): RpcSessionEntry {\n\t\treturn beginSessionClose(this.teardownHost, handle, onRole, options);\n\t}\n\n\tasync close(handle: string): Promise<void> {\n\t\treturn closeSession(this.teardownHost, handle);\n\t}\n\n\t/** Completes a close previously made visible by beginClose(). */\n\tasync closeMarked(handle: string): Promise<void> {\n\t\treturn closeMarkedSession(this.teardownHost, handle);\n\t}\n\n\tlist(): RpcSessionRow[] {\n\t\tthis.syncRuntimeMetadata();\n\t\treturn [...this.entries].map(([sessionId, entry]) => ({\n\t\t\tsessionId,\n\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\tsessionPath: entry.sessionPath,\n\t\t\tcwd: entry.cwd,\n\t\t\tname: entry.runtime?.session.sessionManager.getSessionName(),\n\t\t\tkind: entry.kind,\n\t\t\tcontext: entry.context,\n\t\t\t// A closing entry has already released its last attachment; never publish that as negative.\n\t\t\tattachments: Math.max(0, entry.attachments),\n\t\t\tstatus: entry.state === \"quarantined\" ? \"closing\" : entry.state,\n\t\t}));\n\t}\n\n\t/** Reconcile path and durable identity after runtime replacement. */\n\tprivate syncRuntimeMetadata(): void {\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tconst manager = entry.runtime?.session.sessionManager;\n\t\t\tif (!manager) continue;\n\t\t\tconst currentPath = manager.getSessionFile();\n\t\t\t// Preserve the originally canonicalized key while the runtime still points at\n\t\t\t// the same path. SessionManager may expose a symlink-resolved spelling after\n\t\t\t// opening a file that did not exist yet; treating that as replacement would\n\t\t\t// break ordinary attach-on-open aliases.\n\t\t\tif (currentPath !== entry.sessionPath) {\n\t\t\t\tconst currentKey = currentPath ? canonicalPath(currentPath) : undefined;\n\t\t\t\tif (entry.reservationKey) {\n\t\t\t\t\tthis.reservations.delete(entry.reservationKey);\n\t\t\t\t\tthis.options.pathReservations?.release(entry.reservationKey);\n\t\t\t\t}\n\t\t\t\tif (currentKey) {\n\t\t\t\t\tthis.reservations.add(currentKey);\n\t\t\t\t\t// A replacement moved this session to another file; the claim follows it. A file a\n\t\t\t\t\t// live foreign generation holds is left alone by claim() itself.\n\t\t\t\t\tvoid this.options.pathReservations?.claim(currentKey);\n\t\t\t\t}\n\t\t\t\tentry.reservationKey = currentKey;\n\t\t\t\tentry.sessionPath = currentPath;\n\t\t\t}\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.cwd = manager.getCwd();\n\t\t}\n\t}\n\n\tprivate validateProfile(profile: RpcSessionLaunchProfile): void {\n\t\tif (!isAbsolute(profile.cwd) || (profile.sessionPath !== undefined && !isAbsolute(profile.sessionPath))) {\n\t\t\tthrow new RpcSessionRegistryError(\"invalid_path\");\n\t\t}\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-registry.js","sourceRoot":"","sources":["../../../src/mod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K,CAAC,cAAc,CAAC,CAAC;oBAC/C,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,OAAO,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;gBAC9D,CAAC;gBACD,IAAI,UAAU,EAAE,CAAC;oBAChB,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,UAAU,CAAC,CAAC;oBAClC,mFAAmF;oBACnF,iEAAiE;oBACjE,KAAK,IAAI,CAAC,OAAO,CAAC,gBAAgB,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;gBACvD,CAAC;gBACD,KAAK,CAAC,cAAc,GAAG,UAAU,CAAC;gBAClC,KAAK,CAAC,WAAW,GAAG,WAAW,CAAC;YACjC,CAAC;YACD,KAAK,CAAC,gBAAgB,GAAG,OAAO,CAAC,YAAY,EAAE,CAAC;YAChD,KAAK,CAAC,GAAG,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC;QAC9B,CAAC;IACF,CAAC;IAEO,eAAe,CAAC,OAAgC;QACvD,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,GAAG,CAAC,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,SAAS,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,EAAE,CAAC;YACzG,MAAM,IAAI,uBAAuB,CAAC,cAAc,CAAC,CAAC;QACnD,CAAC;IACF,CAAC;CACD","sourcesContent":["import { existsSync, realpathSync } from \"node:fs\";\nimport { basename, dirname, isAbsolute, resolve } from \"node:path\";\nimport { ProviderScope, runWithProviderScope } from \"@earendil-works/pi-ai/node/provider-scope\";\nimport {\n\ttype AgentSessionLaunchProfile,\n\tAgentSessionRuntime,\n\ttype CreateAgentSessionRuntimeFactory,\n\tcreateAgentSessionRuntime,\n} from \"../../core/agent-session-runtime.ts\";\nimport type { SessionContext, SessionKind, SessionStartEvent } from \"../../core/extensions/types.ts\";\nimport { EMPTY_SESSION_CONTEXT } from \"../../core/extensions/types.ts\";\nimport { SessionManager } from \"../../core/session-manager.ts\";\nimport { SESSION_PATH_RETRY_AFTER_MS, type SessionPathReservations } from \"./host-reservations.ts\";\nimport { beginSessionClose, closeMarkedSession, closeSession, type SessionTeardownHost } from \"./session-teardown.ts\";\nimport type { SessionWorkerClient } from \"./session-worker-client.ts\";\n\n/** The immutable flags selected when a routing session is opened. */\nexport interface RpcSessionLaunchProfile extends AgentSessionLaunchProfile {\n\tsessionPath?: string;\n}\n\nexport type SessionRuntime = AgentSessionRuntime;\nexport type RpcSessionState = \"opening\" | \"open\" | \"closing\" | \"quarantined\" | \"closed\";\n\nexport interface RpcSessionEntry {\n\tstate: RpcSessionState;\n\truntime?: SessionRuntime;\n\tworker?: SessionWorkerClient;\n\t/** Visibility class chosen by the open, frozen for the entry's life. */\n\treadonly kind: SessionKind;\n\t/** Frozen opaque labels the open attached; `{}` when it attached none. */\n\treadonly context: SessionContext;\n\t/** Resolves replacement against the runtime currently owned by this entry. */\n\tswitchSession?: SessionRuntime[\"switchSession\"];\n\t/** Rebind callback installed by the shared RPC connection handler. */\n\trebindSession?: Parameters<SessionRuntime[\"setRebindSession\"]>[0];\n\tscope: ProviderScope;\n\tprofile: Readonly<RpcSessionLaunchProfile>;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\t/** Canonical reservation key for path-opened sessions; matches the reservations set. */\n\treservationKey?: string;\n\t/** Key granted for the spelling this session was opened with; cleared once superseded. */\n\trequestedPathKey?: string;\n\t/** Current runtime cwd, which can change when a session is replaced. */\n\tcwd: string;\n\t/** Live attachments (open + later attaches). The runtime is disposed only when the last one closes. */\n\tattachments: number;\n\t/**\n\t * Opt-in retention: a dropped connection only DETACHES from this session. The\n\t * entry stays open at zero attachments (still listed, still running its turn,\n\t * still holding its path) until an explicit close_session or idle eviction.\n\t * Requested per `open_session`; an attach may turn it on, never off.\n\t */\n\tretainOnDisconnect?: boolean;\n\t/** Timestamp of the last routed command / observed activity; drives idle eviction. */\n\tlastCommandAt: number;\n\tlifecycleMutex: Promise<void>;\n\tcloseCompletion?: Promise<void>;\n\tcloseResolve?: () => void;\n\tcloseStarted?: boolean;\n}\n\nexport class RpcSessionRegistryError extends Error {\n\treadonly code:\n\t\t| \"unknown_session\"\n\t\t| \"session_closing\"\n\t\t| \"session_path_in_use\"\n\t\t| \"session_reservation_limit\"\n\t\t| \"invalid_path\"\n\t\t| \"open_failed\";\n\t/** Machine-readable context for the wire (`errorData`): who holds a path, when to retry. */\n\treadonly detail?: Readonly<Record<string, unknown>>;\n\n\tconstructor(code: RpcSessionRegistryError[\"code\"], reason?: string, detail?: Readonly<Record<string, unknown>>) {\n\t\tsuper(code === \"open_failed\" && reason ? `${code}: ${reason}` : code);\n\t\tthis.code = code;\n\t\tthis.name = \"RpcSessionRegistryError\";\n\t\tif (detail) this.detail = detail;\n\t}\n}\n\nexport interface RpcSessionRegistryOptions {\n\tagentDir: string;\n\tcreateRuntime: CreateAgentSessionRuntimeFactory;\n\t/** Injectable clock (defaults to Date.now) so idle bookkeeping is testable. */\n\tnow?: () => number;\n\t/** Maximum time to wait for graceful runtime teardown before forced release. */\n\tcloseGraceMs?: number;\n\t/**\n\t * Cross-GENERATION path claims. During a handoff two hosts are alive at once, and only a\n\t * claim outside either process can keep them off one JSONL. Absent for an embedded registry\n\t * that is the only host of its agent directory.\n\t */\n\tpathReservations?: SessionPathReservations;\n}\n\n/** Host-side lifecycle policy for one `open_session`, distinct from the session's launch profile. */\nexport interface RpcSessionOpenOptions {\n\t/** Keep the session alive when its last client disconnects (`open_session.retain_on_disconnect`). */\n\tretainOnDisconnect?: boolean;\n}\n\n/** One `list_sessions` row. `context` is published only to a listing that asked for workers. */\nexport interface RpcSessionRow {\n\tsessionId: string;\n\tdurableSessionId?: string;\n\tsessionPath?: string;\n\tcwd: string;\n\tname?: string;\n\tstatus: Exclude<RpcSessionState, \"quarantined\">;\n\tattachments: number;\n\tkind: SessionKind;\n\tcontext: SessionContext;\n}\n\nexport interface OpenRpcSession {\n\tsessionId: string;\n\tdurableSessionId: string;\n\tsessionPath?: string;\n\t/** True when this open attached to an already-open session instead of creating one. */\n\tattached?: boolean;\n}\n\nfunction canonicalPath(path: string): string {\n\tconst absolutePath = resolve(path);\n\tif (existsSync(absolutePath)) return realpathSync(absolutePath);\n\treturn `${realpathSync(dirname(absolutePath))}/${basename(absolutePath)}`;\n}\n\n/** Freezes an open's launch inputs, including the nested objects a client supplied. */\nexport function frozenProfile(profile: RpcSessionLaunchProfile): Readonly<RpcSessionLaunchProfile> {\n\treturn Object.freeze({\n\t\t...profile,\n\t\t...(profile.creationModel ? { creationModel: Object.freeze({ ...profile.creationModel }) } : {}),\n\t\t...(profile.sessionContext ? { sessionContext: Object.freeze({ ...profile.sessionContext }) } : {}),\n\t});\n}\n\n/**\n * The visibility class and labels an entry keeps for its life, normalized once here so no\n * lifecycle, listing or delivery decision has to re-apply the defaults. Reads the already\n * frozen profile, so the entry and the runtime share one frozen context object.\n */\nexport function sessionIdentity(profile: Readonly<RpcSessionLaunchProfile>): {\n\treadonly kind: SessionKind;\n\treadonly context: SessionContext;\n} {\n\treturn { kind: profile.sessionKind ?? \"interactive\", context: profile.sessionContext ?? EMPTY_SESSION_CONTEXT };\n}\n\n/** Process-local lifecycle owner for multi-session RPC runtimes. */\nexport class RpcSessionRegistry {\n\tprivate readonly entries = new Map<string, RpcSessionEntry>();\n\tprivate readonly reservations = new Set<string>();\n\tprivate readonly teardownHost: SessionTeardownHost;\n\tprivate nextHandle = 0;\n\tprivate readonly options: RpcSessionRegistryOptions;\n\tprivate readonly now: () => number;\n\treadonly closeGraceMs: number;\n\n\tconstructor(options: RpcSessionRegistryOptions) {\n\t\tthis.options = options;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.closeGraceMs = options.closeGraceMs ?? 10_000;\n\t\tthis.teardownHost = {\n\t\t\tcloseGraceMs: this.closeGraceMs,\n\t\t\tget: (handle) => this.entries.get(handle),\n\t\t\tdelete: (handle) => this.entries.delete(handle),\n\t\t\treleaseReservation: (key) => {\n\t\t\t\tthis.reservations.delete(key);\n\t\t\t\tthis.options.pathReservations?.release(key);\n\t\t\t},\n\t\t\tsync: () => this.syncRuntimeMetadata(),\n\t\t};\n\t}\n\n\t/** Number of live entries, including ones still opening or closing. */\n\tget size(): number {\n\t\treturn this.entries.size;\n\t}\n\n\tasync openSession(profile: RpcSessionLaunchProfile, options?: RpcSessionOpenOptions): Promise<OpenRpcSession> {\n\t\tthis.validateProfile(profile);\n\t\tthis.syncRuntimeMetadata();\n\t\tconst sessionPath = profile.sessionPath ? canonicalPath(profile.sessionPath) : undefined;\n\t\tif (sessionPath) await this.settleClosingReservation(sessionPath);\n\t\tif (sessionPath && this.reservations.has(sessionPath)) {\n\t\t\t// Attach-on-open: a live session outlives individual client attachments, so a\n\t\t\t// resume (or a second surface) for an already-hosted path joins the existing\n\t\t\t// runtime instead of failing. An entry still opening keeps the exclusive\n\t\t\t// reservation and rejects as before.\n\t\t\tconst existing = [...this.entries].find(\n\t\t\t\t([, entry]) => entry.reservationKey === sessionPath && entry.state === \"open\",\n\t\t\t);\n\t\t\tif (!existing) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\tconst [handle, entry] = existing;\n\t\t\tentry.attachments += 1;\n\t\t\t// Retention is a property of the live session: any attach may ask for it, and\n\t\t\t// no attach may revoke it for the clients that already rely on it.\n\t\t\tif (options?.retainOnDisconnect) entry.retainOnDisconnect = true;\n\t\t\tif (!entry.durableSessionId) throw new RpcSessionRegistryError(\"session_path_in_use\");\n\t\t\tentry.lastCommandAt = this.now();\n\t\t\treturn {\n\t\t\t\tsessionId: handle,\n\t\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\t\tsessionPath: entry.sessionPath,\n\t\t\t\tattached: true,\n\t\t\t};\n\t\t}\n\t\tif (sessionPath) {\n\t\t\t// Taken SYNCHRONOUSLY, before any await: a concurrent open for the same path must find the\n\t\t\t// reservation already held, not a window between the decision and the record of it.\n\t\t\tthis.reservations.add(sessionPath);\n\t\t\t// Another generation of this daemon may still be writing this file. Its claim is the only\n\t\t\t// thing this process can see across a handoff, and a live one means \"retry\", not \"gone\".\n\t\t\t// Only AWAIT when there is a cross-generation claim to take: `await undefined` still costs a\n\t\t\t// microtask, and an embedded registry (no second generation) must reach the \"opening\" entry\n\t\t\t// in the same tick a caller that raced it would look, exactly as it did before generations.\n\t\t\tconst holder = this.options.pathReservations\n\t\t\t\t? await this.options.pathReservations.claim(sessionPath)\n\t\t\t\t: undefined;\n\t\t\tif (holder) {\n\t\t\t\tthis.reservations.delete(sessionPath);\n\t\t\t\tthrow new RpcSessionRegistryError(\"session_path_in_use\", undefined, {\n\t\t\t\t\towner: holder,\n\t\t\t\t\tretry_after_ms: SESSION_PATH_RETRY_AFTER_MS,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\t// Resume vs create parity (D1 + omo SenpiSessionRuntime.ts:198-200):\n\t\t// Create-only launch semantics mirror classic startup flags. A resumed\n\t\t// session restores its persisted model and thinking level instead of being\n\t\t// overridden by the new open_session request.\n\t\tconst isResume = sessionPath !== undefined && existsSync(sessionPath);\n\t\t// Re-opening an existing session file is a resume, exactly like interactive\n\t\t// /resume (AgentSessionRuntime.switchSession). Without the event the session\n\t\t// starts with reason \"startup\" and every extension that only rebuilds state\n\t\t// on a resume - the ask-user dangling-question hook - stays unreachable from\n\t\t// the RPC restart path. A session created by this open stays \"startup\".\n\t\tconst sessionStartEvent: SessionStartEvent | undefined = isResume\n\t\t\t? { type: \"session_start\", reason: \"resume\" }\n\t\t\t: undefined;\n\t\tconst storedProfile = frozenProfile({ ...profile, ...(sessionPath ? { sessionPath } : {}) });\n\t\tconst runtimeProfile = isResume\n\t\t\t? frozenProfile({ ...storedProfile, creationModel: undefined, initialThinkingLevel: undefined })\n\t\t\t: storedProfile;\n\n\t\tconst handle = `rpc-${++this.nextHandle}`;\n\t\tconst entry: RpcSessionEntry = {\n\t\t\tstate: \"opening\",\n\t\t\tscope: new ProviderScope(),\n\t\t\tprofile: storedProfile,\n\t\t\t...sessionIdentity(storedProfile),\n\t\t\tsessionPath,\n\t\t\treservationKey: sessionPath,\n\t\t\tcwd: storedProfile.cwd,\n\t\t\tattachments: 1,\n\t\t\tretainOnDisconnect: options?.retainOnDisconnect === true,\n\t\t\tlastCommandAt: this.now(),\n\t\t\tlifecycleMutex: Promise.resolve(),\n\t\t};\n\t\tentry.switchSession = (sessionPath, options) => {\n\t\t\tconst operation = entry.lifecycleMutex.then(async () => {\n\t\t\t\tif (entry.state !== \"open\" || !entry.runtime) {\n\t\t\t\t\tthrow new RpcSessionRegistryError(\"unknown_session\");\n\t\t\t\t}\n\t\t\t\tconst runtime = entry.runtime;\n\t\t\t\tconst cwdOverride = options?.cwdOverride;\n\t\t\t\tconst cwdChanged = cwdOverride !== undefined && runtime.session.sessionManager.getCwd() !== cwdOverride;\n\t\t\t\tconst result = await runtime.switchSession(sessionPath, options);\n\t\t\t\tif (result.cancelled || !cwdChanged) return result;\n\n\t\t\t\t// A multi-session binding outlives an individual replacement. Keep the\n\t\t\t\t// entry's runtime object aligned with the replacement so every attached\n\t\t\t\t// client resolves getters and future commands against the new cwd-bound\n\t\t\t\t// runtime, not the object created during open_session.\n\t\t\t\tconst replacement = new AgentSessionRuntime(\n\t\t\t\t\truntime.session,\n\t\t\t\t\truntime.services,\n\t\t\t\t\tthis.options.createRuntime,\n\t\t\t\t\t[...runtime.diagnostics],\n\t\t\t\t\truntime.modelFallbackMessage,\n\t\t\t\t\truntime.launchProfile,\n\t\t\t\t);\n\t\t\t\treplacement.setRebindSession(entry.rebindSession);\n\t\t\t\tentry.runtime = replacement;\n\t\t\t\tthis.syncRuntimeMetadata();\n\t\t\t\treturn result;\n\t\t\t});\n\t\t\tentry.lifecycleMutex = operation.then(\n\t\t\t\t() => undefined,\n\t\t\t\t() => undefined,\n\t\t\t);\n\t\t\treturn operation;\n\t\t};\n\t\tthis.entries.set(handle, entry);\n\t\ttry {\n\t\t\tconst manager = sessionPath\n\t\t\t\t? SessionManager.open(sessionPath, undefined, storedProfile.cwd)\n\t\t\t\t: SessionManager.create(storedProfile.cwd);\n\t\t\tentry.runtime = await runWithProviderScope(entry.scope, () =>\n\t\t\t\tcreateAgentSessionRuntime(this.options.createRuntime, {\n\t\t\t\t\tcwd: manager.getCwd(),\n\t\t\t\t\tagentDir: this.options.agentDir,\n\t\t\t\t\tsessionManager: manager,\n\t\t\t\t\tsessionStartEvent,\n\t\t\t\t\tlaunchProfile: runtimeProfile,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.sessionPath ??= manager.getSessionFile();\n\t\t\tentry.state = \"open\";\n\t\t\treturn { sessionId: handle, durableSessionId: entry.durableSessionId, sessionPath: entry.sessionPath };\n\t\t} catch (error) {\n\t\t\t// Runtime construction may have started extensions, watchers, and provider\n\t\t\t// registrations before it rejects. Keep the reservation and entry private\n\t\t\t// until all of those resources have been torn down, then release them as\n\t\t\t// one rollback so the path can immediately be opened again.\n\t\t\ttry {\n\t\t\t\tawait entry.runtime?.dispose();\n\t\t\t} catch {\n\t\t\t\t// The original construction error remains the externally visible cause.\n\t\t\t} finally {\n\t\t\t\ttry {\n\t\t\t\t\tawait entry.scope.close?.();\n\t\t\t\t} finally {\n\t\t\t\t\tthis.entries.delete(handle);\n\t\t\t\t\tif (sessionPath) {\n\t\t\t\t\t\tthis.reservations.delete(sessionPath);\n\t\t\t\t\t\tthis.options.pathReservations?.release(sessionPath);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (error instanceof RpcSessionRegistryError) throw error;\n\t\t\tthrow new RpcSessionRegistryError(\"open_failed\", error instanceof Error ? error.message : undefined);\n\t\t}\n\t}\n\n\t/**\n\t * Waits out a teardown already in flight for this path before the open decides.\n\t *\n\t * A close FREES the path, but the entry keeps its reservation until its runtime is\n\t * disposed, so an open landing inside that window used to be refused with\n\t * `session_path_in_use` for a session that no longer exists - making \"reopen the\n\t * path I just closed\" a race against disposal latency, which no client can time.\n\t * The open now waits for the teardown it would have been refused by and then opens\n\t * the file fresh. Bounded by the same grace window that bounds the teardown itself\n\t * (`closeMarkedSession` force-releases at that deadline), so a wedged disposal\n\t * still ends in the ordinary refusal instead of an open that never answers.\n\t */\n\tprivate async settleClosingReservation(sessionPath: string): Promise<void> {\n\t\tconst closing = [...this.entries.values()].find(\n\t\t\t(entry) => entry.reservationKey === sessionPath && entry.state === \"closing\",\n\t\t);\n\t\tif (!closing?.closeCompletion) return;\n\t\tlet deadline: ReturnType<typeof setTimeout> | undefined;\n\t\ttry {\n\t\t\tawait Promise.race([\n\t\t\t\tclosing.closeCompletion,\n\t\t\t\tnew Promise<void>((resolve) => {\n\t\t\t\t\tdeadline = setTimeout(resolve, this.closeGraceMs);\n\t\t\t\t}),\n\t\t\t]);\n\t\t} finally {\n\t\t\tif (deadline) clearTimeout(deadline);\n\t\t}\n\t}\n\n\t/**\n\t * Read-only lookup with no state transitions or attachment accounting.\n\t * Exists so lifecycle decisions (e.g. deferring a dropped connection's\n\t * release while a turn is still streaming) can inspect the live entry\n\t * without claiming it.\n\t */\n\tpeek(handle: string): RpcSessionEntry | undefined {\n\t\treturn this.entries.get(handle);\n\t}\n\n\tgetForCommand(handle: string, command: string): RpcSessionEntry {\n\t\tconst entry = this.entries.get(handle);\n\t\tif (!entry) throw new RpcSessionRegistryError(\"unknown_session\");\n\t\tif (\n\t\t\tentry.state === \"closing\" &&\n\t\t\t![\"abort\", \"abort_bash\", \"extension_ui_response\", \"extension_ui_progress\"].includes(command)\n\t\t) {\n\t\t\tthrow new RpcSessionRegistryError(\"session_closing\");\n\t\t}\n\t\tif (entry.state !== \"open\" && entry.state !== \"closing\") throw new RpcSessionRegistryError(\"unknown_session\");\n\t\t// Every routed command counts as activity for idle eviction. Lookups that\n\t\t// must not refresh idleness (sweeps, listing) use peek()/list() instead.\n\t\tentry.lastCommandAt = this.now();\n\t\treturn entry;\n\t}\n\n\t/**\n\t * Starts a close synchronously and returns the live entry for routing decisions.\n\t * `detach` marks a client going away rather than the session ending, which a\n\t * retained entry answers by staying open at zero attachments.\n\t */\n\tbeginClose(handle: string, onRole?: (finalizer: boolean) => void, options?: { detach?: boolean }): RpcSessionEntry {\n\t\treturn beginSessionClose(this.teardownHost, handle, onRole, options);\n\t}\n\n\tasync close(handle: string): Promise<void> {\n\t\treturn closeSession(this.teardownHost, handle);\n\t}\n\n\t/** Completes a close previously made visible by beginClose(). */\n\tasync closeMarked(handle: string): Promise<void> {\n\t\treturn closeMarkedSession(this.teardownHost, handle);\n\t}\n\n\tlist(): RpcSessionRow[] {\n\t\tthis.syncRuntimeMetadata();\n\t\treturn [...this.entries].map(([sessionId, entry]) => ({\n\t\t\tsessionId,\n\t\t\tdurableSessionId: entry.durableSessionId,\n\t\t\tsessionPath: entry.sessionPath,\n\t\t\tcwd: entry.cwd,\n\t\t\tname: entry.runtime?.session.sessionManager.getSessionName(),\n\t\t\tkind: entry.kind,\n\t\t\tcontext: entry.context,\n\t\t\t// A closing entry has already released its last attachment; never publish that as negative.\n\t\t\tattachments: Math.max(0, entry.attachments),\n\t\t\tstatus: entry.state === \"quarantined\" ? \"closing\" : entry.state,\n\t\t}));\n\t}\n\n\t/** Reconcile path and durable identity after runtime replacement. */\n\tprivate syncRuntimeMetadata(): void {\n\t\tfor (const entry of this.entries.values()) {\n\t\t\tconst manager = entry.runtime?.session.sessionManager;\n\t\t\tif (!manager) continue;\n\t\t\tconst currentPath = manager.getSessionFile();\n\t\t\tconst currentKey = currentPath ? canonicalPath(currentPath) : undefined;\n\t\t\t// Preserve the originally canonicalized key while the runtime still points at\n\t\t\t// the same path. SessionManager may expose a symlink-resolved spelling after\n\t\t\t// opening a file that did not exist yet; treating that as replacement would\n\t\t\t// break ordinary attach-on-open aliases.\n\t\t\t//\n\t\t\t// A moved path is not the only reason to reconcile: a session opened WITHOUT\n\t\t\t// `sessionPath` lands its created file straight into `sessionPath` and never\n\t\t\t// takes a reservation, so comparing paths alone leaves that file unclaimed\n\t\t\t// forever and a later open of it builds a SECOND runtime over the same\n\t\t\t// transcript. Reconcile whenever the canonical key we hold is not the key the\n\t\t\t// runtime is actually writing.\n\t\t\tif (currentPath !== entry.sessionPath || currentKey !== entry.reservationKey) {\n\t\t\t\tif (entry.reservationKey) {\n\t\t\t\t\tthis.reservations.delete(entry.reservationKey);\n\t\t\t\t\tthis.options.pathReservations?.release(entry.reservationKey);\n\t\t\t\t}\n\t\t\t\tif (currentKey) {\n\t\t\t\t\tthis.reservations.add(currentKey);\n\t\t\t\t\t// A replacement moved this session to another file; the claim follows it. A file a\n\t\t\t\t\t// live foreign generation holds is left alone by claim() itself.\n\t\t\t\t\tvoid this.options.pathReservations?.claim(currentKey);\n\t\t\t\t}\n\t\t\t\tentry.reservationKey = currentKey;\n\t\t\t\tentry.sessionPath = currentPath;\n\t\t\t}\n\t\t\tentry.durableSessionId = manager.getSessionId();\n\t\t\tentry.cwd = manager.getCwd();\n\t\t}\n\t}\n\n\tprivate validateProfile(profile: RpcSessionLaunchProfile): void {\n\t\tif (!isAbsolute(profile.cwd) || (profile.sessionPath !== undefined && !isAbsolute(profile.sessionPath))) {\n\t\t\tthrow new RpcSessionRegistryError(\"invalid_path\");\n\t\t}\n\t}\n}\n"]}
@@ -11,10 +11,19 @@ export declare class SessionWorkerRequests {
11
11
  private readonly pending;
12
12
  private serial;
13
13
  private closed;
14
- private readonly openingDeadline;
14
+ /**
15
+ * Armed by the FIRST open message, never at construction. The open sequence (commit then
16
+ * bind) deliberately shares one budget - resetting it between them is what
17
+ * "does not reset the opening deadline between commit and bind" forbids - but a queue
18
+ * built long before its first open must not be charged for the wait, which is the
19
+ * silent instant timeout senpi#1719 reports on a loaded machine.
20
+ */
21
+ private openingDeadline;
15
22
  private readonly send;
16
23
  private readonly timeout;
17
24
  constructor(send: (message: Request) => void, timeout: () => void);
25
+ /** Remaining share of the open budget, armed on first use so idle time before it is free. */
26
+ private remainingOpenMs;
18
27
  get activeCount(): number;
19
28
  request(message: WorkerRequestInput): Promise<Reply>;
20
29
  receive(message: Reply): void;
@@ -1 +1 @@
1
- {"version":3,"file":"session-worker-requests.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-worker-requests.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,mBAAmB,EAExB,KAAK,mBAAmB,EACxB,MAAM,8BAA8B,CAAC;AAEtC,KAAK,OAAO,GAAG,OAAO,CAAC,mBAAmB,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AACjE,KAAK,KAAK,GAAG,OAAO,CAAC,mBAAmB,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAC/D,MAAM,MAAM,kBAAkB,GAAG,OAAO,SAAS,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,OAAO,GAAG,IAAI,CAAC,CAAC,EAAE,SAAS,CAAC,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC;AAEpH,8FAA8F;AAC9F,qBAAa,qBAAqB;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CASpB;IACJ,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB,OAAO,CAAC,QAAQ,CAAC,eAAe,CAA6C;IAC7E,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAa;IAErC,YAAY,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,EAAE,OAAO,EAAE,MAAM,IAAI,EAGhE;IAED,IAAI,WAAW,IAAI,MAAM,CAExB;IAED,OAAO,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,KAAK,CAAC,CAsCnD;IAED,OAAO,CAAC,OAAO,EAAE,KAAK,GAAG,IAAI,CAO5B;IAED,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAOxB;CACD"}
1
+ {"version":3,"file":"session-worker-requests.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-worker-requests.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,mBAAmB,EAExB,KAAK,mBAAmB,EACxB,MAAM,8BAA8B,CAAC;AAEtC,KAAK,OAAO,GAAG,OAAO,CAAC,mBAAmB,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AACjE,KAAK,KAAK,GAAG,OAAO,CAAC,mBAAmB,EAAE;IAAE,OAAO,EAAE,MAAM,CAAA;CAAE,CAAC,CAAC;AAC/D,MAAM,MAAM,kBAAkB,GAAG,OAAO,SAAS,MAAM,CAAC,GAAG,CAAC,CAAC,SAAS,OAAO,GAAG,IAAI,CAAC,CAAC,EAAE,SAAS,CAAC,GAAG,KAAK,CAAC,GAAG,KAAK,CAAC;AAEpH,8FAA8F;AAC9F,qBAAa,qBAAqB;IACjC,OAAO,CAAC,QAAQ,CAAC,OAAO,CASpB;IACJ,OAAO,CAAC,MAAM,CAAK;IACnB,OAAO,CAAC,MAAM,CAAS;IACvB;;;;;;OAMG;IACH,OAAO,CAAC,eAAe,CAAqB;IAC5C,OAAO,CAAC,QAAQ,CAAC,IAAI,CAA6B;IAClD,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAa;IAErC,YAAY,IAAI,EAAE,CAAC,OAAO,EAAE,OAAO,KAAK,IAAI,EAAE,OAAO,EAAE,MAAM,IAAI,EAGhE;IAED,6FAA6F;IAC7F,OAAO,CAAC,eAAe;IAMvB,IAAI,WAAW,IAAI,MAAM,CAExB;IAED,OAAO,CAAC,OAAO,EAAE,kBAAkB,GAAG,OAAO,CAAC,KAAK,CAAC,CAmCnD;IAED,OAAO,CAAC,OAAO,EAAE,KAAK,GAAG,IAAI,CAO5B;IAED,KAAK,CAAC,KAAK,EAAE,KAAK,GAAG,IAAI,CAOxB;CACD"}
@@ -5,10 +5,16 @@ export class SessionWorkerRequests {
5
5
  this.pending = new Map();
6
6
  this.serial = 0;
7
7
  this.closed = false;
8
- this.openingDeadline = Date.now() + SESSION_WORKER_LIMITS.openMs;
9
8
  this.send = send;
10
9
  this.timeout = timeout;
11
10
  }
11
+ /** Remaining share of the open budget, armed on first use so idle time before it is free. */
12
+ remainingOpenMs() {
13
+ const now = Date.now();
14
+ if (this.openingDeadline === undefined)
15
+ this.openingDeadline = now + SESSION_WORKER_LIMITS.openMs;
16
+ return Math.max(0, this.openingDeadline - now);
17
+ }
12
18
  get activeCount() {
13
19
  return this.pending.size;
14
20
  }
@@ -36,7 +42,7 @@ export class SessionWorkerRequests {
36
42
  return new Promise((resolve, reject) => {
37
43
  const timer = message.type === "command" && !control
38
44
  ? undefined
39
- : setTimeout(this.timeout, control ? SESSION_WORKER_LIMITS.controlMs : Math.max(0, this.openingDeadline - Date.now()));
45
+ : setTimeout(this.timeout, control ? SESSION_WORKER_LIMITS.controlMs : this.remainingOpenMs());
40
46
  this.pending.set(request, { resolve, reject, bytes, control, timer });
41
47
  try {
42
48
  this.send({ ...message, request });
@@ -1 +1 @@
1
- {"version":3,"file":"session-worker-requests.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-worker-requests.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,qBAAqB,GAErB,MAAM,8BAA8B,CAAC;AAMtC,8FAA8F;AAC9F,MAAM,OAAO,qBAAqB;IAiBjC,YAAY,IAAgC,EAAE,OAAmB;QAhBhD,YAAO,GAAG,IAAI,GAAG,EAS/B,CAAC;QACI,WAAM,GAAG,CAAC,CAAC;QACX,WAAM,GAAG,KAAK,CAAC;QACN,oBAAe,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,qBAAqB,CAAC,MAAM,CAAC;QAK5E,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAED,IAAI,WAAW;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC1B,CAAC;IAED,OAAO,CAAC,OAA2B;QAClC,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO,OAAO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CAAC,IAAI,KAAK,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC,CAAC;;YACpF,OAAO,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;IAED,KAAK,CAAC,KAAY;QACjB,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC;QACnB,KAAK,MAAM,OAAO,IAAI,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,EAAE,CAAC;YAC7C,YAAY,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;YAC5B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACD","sourcesContent":["import {\n\ttype HostToSessionWorker,\n\tSESSION_WORKER_LIMITS,\n\ttype SessionWorkerToHost,\n} from \"./session-worker-protocol.ts\";\n\ntype Request = Extract<HostToSessionWorker, { request: number }>;\ntype Reply = Extract<SessionWorkerToHost, { request: number }>;\nexport type WorkerRequestInput = Request extends infer T ? (T extends Request ? Omit<T, \"request\"> : never) : never;\n\n/** Bounded request debt, with separate admission for interrupt and extension-UI responses. */\nexport class SessionWorkerRequests {\n\tprivate readonly pending = new Map<\n\t\tnumber,\n\t\t{\n\t\t\tresolve: (reply: Reply) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\tbytes: number;\n\t\t\tcontrol: boolean;\n\t\t\ttimer?: ReturnType<typeof setTimeout>;\n\t\t}\n\t>();\n\tprivate serial = 0;\n\tprivate closed = false;\n\tprivate readonly openingDeadline = Date.now() + SESSION_WORKER_LIMITS.openMs;\n\tprivate readonly send: (message: Request) => void;\n\tprivate readonly timeout: () => void;\n\n\tconstructor(send: (message: Request) => void, timeout: () => void) {\n\t\tthis.send = send;\n\t\tthis.timeout = timeout;\n\t}\n\n\tget activeCount(): number {\n\t\treturn this.pending.size;\n\t}\n\n\trequest(message: WorkerRequestInput): Promise<Reply> {\n\t\tif (this.closed) return Promise.reject(new Error(\"session_closing\"));\n\t\tconst control =\n\t\t\tmessage.type === \"command\" &&\n\t\t\t\"type\" in message.command &&\n\t\t\ttypeof message.command.type === \"string\" &&\n\t\t\t[\"abort\", \"abort_bash\", \"extension_ui_response\", \"extension_ui_progress\"].includes(message.command.type);\n\t\tconst bytes = Buffer.byteLength(JSON.stringify(message));\n\t\tlet count = 0;\n\t\tlet pendingBytes = 0;\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tif (pending.control === control) {\n\t\t\t\tcount++;\n\t\t\t\tpendingBytes += pending.bytes;\n\t\t\t}\n\t\t}\n\t\tconst maxCount = control ? SESSION_WORKER_LIMITS.controlRequests : SESSION_WORKER_LIMITS.requests;\n\t\tconst maxBytes = control ? SESSION_WORKER_LIMITS.controlBytes : SESSION_WORKER_LIMITS.requestBytes;\n\t\tif (count >= maxCount || pendingBytes + bytes > maxBytes)\n\t\t\treturn Promise.reject(new Error(\"session_worker_request_limit\"));\n\t\tconst request = ++this.serial;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer =\n\t\t\t\tmessage.type === \"command\" && !control\n\t\t\t\t\t? undefined\n\t\t\t\t\t: setTimeout(\n\t\t\t\t\t\t\tthis.timeout,\n\t\t\t\t\t\t\tcontrol ? SESSION_WORKER_LIMITS.controlMs : Math.max(0, this.openingDeadline - Date.now()),\n\t\t\t\t\t\t);\n\t\t\tthis.pending.set(request, { resolve, reject, bytes, control, timer });\n\t\t\ttry {\n\t\t\t\tthis.send({ ...message, request });\n\t\t\t} catch (cause) {\n\t\t\t\tthis.pending.delete(request);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t\t}\n\t\t});\n\t}\n\n\treceive(message: Reply): void {\n\t\tconst pending = this.pending.get(message.request);\n\t\tif (!pending) return;\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(message.request);\n\t\tif (message.type === \"result\" && message.error) pending.reject(new Error(message.error));\n\t\telse pending.resolve(message);\n\t}\n\n\tclose(error: Error): void {\n\t\tthis.closed = true;\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t}\n}\n"]}
1
+ {"version":3,"file":"session-worker-requests.js","sourceRoot":"","sources":["../../../src/modes/rpc/session-worker-requests.ts"],"names":[],"mappings":"AAAA,OAAO,EAEN,qBAAqB,GAErB,MAAM,8BAA8B,CAAC;AAMtC,8FAA8F;AAC9F,MAAM,OAAO,qBAAqB;IAwBjC,YAAY,IAAgC,EAAE,OAAmB;QAvBhD,YAAO,GAAG,IAAI,GAAG,EAS/B,CAAC;QACI,WAAM,GAAG,CAAC,CAAC;QACX,WAAM,GAAG,KAAK,CAAC;QAatB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;IAED,6FAA6F;IACrF,eAAe;QACtB,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,IAAI,CAAC,eAAe,KAAK,SAAS;YAAE,IAAI,CAAC,eAAe,GAAG,GAAG,GAAG,qBAAqB,CAAC,MAAM,CAAC;QAClG,OAAO,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,eAAe,GAAG,GAAG,CAAC,CAAC;IAChD,CAAC;IAED,IAAI,WAAW;QACd,OAAO,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC;IAC1B,CAAC;IAED,OAAO,CAAC,OAA2B;QAClC,IAAI,IAAI,CAAC,MAAM;YAAE,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;QACrE,MAAM,OAAO,GACZ,OAAO,CAAC,IAAI,KAAK,SAAS;YAC1B,MAAM,IAAI,OAAO,CAAC,OAAO;YACzB,OAAO,OAAO,CAAC,OAAO,CAAC,IAAI,KAAK,QAAQ;YACxC,CAAC,O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O,CAAC,KAAK,CAAC,CAAC;YAC5B,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;QACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;CACD","sourcesContent":["import {\n\ttype HostToSessionWorker,\n\tSESSION_WORKER_LIMITS,\n\ttype SessionWorkerToHost,\n} from \"./session-worker-protocol.ts\";\n\ntype Request = Extract<HostToSessionWorker, { request: number }>;\ntype Reply = Extract<SessionWorkerToHost, { request: number }>;\nexport type WorkerRequestInput = Request extends infer T ? (T extends Request ? Omit<T, \"request\"> : never) : never;\n\n/** Bounded request debt, with separate admission for interrupt and extension-UI responses. */\nexport class SessionWorkerRequests {\n\tprivate readonly pending = new Map<\n\t\tnumber,\n\t\t{\n\t\t\tresolve: (reply: Reply) => void;\n\t\t\treject: (error: Error) => void;\n\t\t\tbytes: number;\n\t\t\tcontrol: boolean;\n\t\t\ttimer?: ReturnType<typeof setTimeout>;\n\t\t}\n\t>();\n\tprivate serial = 0;\n\tprivate closed = false;\n\t/**\n\t * Armed by the FIRST open message, never at construction. The open sequence (commit then\n\t * bind) deliberately shares one budget - resetting it between them is what\n\t * \"does not reset the opening deadline between commit and bind\" forbids - but a queue\n\t * built long before its first open must not be charged for the wait, which is the\n\t * silent instant timeout senpi#1719 reports on a loaded machine.\n\t */\n\tprivate openingDeadline: number | undefined;\n\tprivate readonly send: (message: Request) => void;\n\tprivate readonly timeout: () => void;\n\n\tconstructor(send: (message: Request) => void, timeout: () => void) {\n\t\tthis.send = send;\n\t\tthis.timeout = timeout;\n\t}\n\n\t/** Remaining share of the open budget, armed on first use so idle time before it is free. */\n\tprivate remainingOpenMs(): number {\n\t\tconst now = Date.now();\n\t\tif (this.openingDeadline === undefined) this.openingDeadline = now + SESSION_WORKER_LIMITS.openMs;\n\t\treturn Math.max(0, this.openingDeadline - now);\n\t}\n\n\tget activeCount(): number {\n\t\treturn this.pending.size;\n\t}\n\n\trequest(message: WorkerRequestInput): Promise<Reply> {\n\t\tif (this.closed) return Promise.reject(new Error(\"session_closing\"));\n\t\tconst control =\n\t\t\tmessage.type === \"command\" &&\n\t\t\t\"type\" in message.command &&\n\t\t\ttypeof message.command.type === \"string\" &&\n\t\t\t[\"abort\", \"abort_bash\", \"extension_ui_response\", \"extension_ui_progress\"].includes(message.command.type);\n\t\tconst bytes = Buffer.byteLength(JSON.stringify(message));\n\t\tlet count = 0;\n\t\tlet pendingBytes = 0;\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tif (pending.control === control) {\n\t\t\t\tcount++;\n\t\t\t\tpendingBytes += pending.bytes;\n\t\t\t}\n\t\t}\n\t\tconst maxCount = control ? SESSION_WORKER_LIMITS.controlRequests : SESSION_WORKER_LIMITS.requests;\n\t\tconst maxBytes = control ? SESSION_WORKER_LIMITS.controlBytes : SESSION_WORKER_LIMITS.requestBytes;\n\t\tif (count >= maxCount || pendingBytes + bytes > maxBytes)\n\t\t\treturn Promise.reject(new Error(\"session_worker_request_limit\"));\n\t\tconst request = ++this.serial;\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst timer =\n\t\t\t\tmessage.type === \"command\" && !control\n\t\t\t\t\t? undefined\n\t\t\t\t\t: setTimeout(this.timeout, control ? SESSION_WORKER_LIMITS.controlMs : this.remainingOpenMs());\n\t\t\tthis.pending.set(request, { resolve, reject, bytes, control, timer });\n\t\t\ttry {\n\t\t\t\tthis.send({ ...message, request });\n\t\t\t} catch (cause) {\n\t\t\t\tthis.pending.delete(request);\n\t\t\t\tclearTimeout(timer);\n\t\t\t\treject(cause instanceof Error ? cause : new Error(String(cause)));\n\t\t\t}\n\t\t});\n\t}\n\n\treceive(message: Reply): void {\n\t\tconst pending = this.pending.get(message.request);\n\t\tif (!pending) return;\n\t\tclearTimeout(pending.timer);\n\t\tthis.pending.delete(message.request);\n\t\tif (message.type === \"result\" && message.error) pending.reject(new Error(message.error));\n\t\telse pending.resolve(message);\n\t}\n\n\tclose(error: Error): void {\n\t\tthis.closed = true;\n\t\tfor (const pending of this.pending.values()) {\n\t\t\tclearTimeout(pending.timer);\n\t\t\tpending.reject(error);\n\t\t}\n\t\tthis.pending.clear();\n\t}\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=session-worker-requests.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"session-worker-requests.test.d.ts","sourceRoot":"","sources":["../../../src/modes/rpc/session-worker-requests.test.ts"],"names":[],"mappings":""}