openmeld 0.3.222 → 0.3.224

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 (177) hide show
  1. package/dist/{add-me-membership-Wc69O6rA.js → add-me-membership-CGISMRPF.js} +2 -2
  2. package/dist/{add-me-membership-Wc69O6rA.js.map → add-me-membership-CGISMRPF.js.map} +1 -1
  3. package/dist/{agents-B8zhQnGw.js → agents-CR7BebgO.js} +12 -12
  4. package/dist/{agents-B8zhQnGw.js.map → agents-CR7BebgO.js.map} +1 -1
  5. package/dist/{api-client-foundation-DTiFoGpI.js → api-client-foundation-CqbIn_de.js} +1 -1
  6. package/dist/{api-client-foundation-DnJ_JYli.js → api-client-foundation-DpVwrgh-.js} +3 -3
  7. package/dist/{api-client-foundation-DnJ_JYli.js.map → api-client-foundation-DpVwrgh-.js.map} +1 -1
  8. package/dist/auth-session-BJfKu74u.js +4 -0
  9. package/dist/{auth-session-nhS8jyux.js → auth-session-uEk_Tx6T.js} +8 -8
  10. package/dist/auth-session-uEk_Tx6T.js.map +1 -0
  11. package/dist/{base-url-CMBApK1J.js → base-url-DXrUiSMI.js} +1 -1
  12. package/dist/{base-url-D7uE_xTo.js → base-url-DvjOkKPs.js} +2 -2
  13. package/dist/{base-url-D7uE_xTo.js.map → base-url-DvjOkKPs.js.map} +1 -1
  14. package/dist/{channel-ggx0o_aG.js → channel-B2fD2_be.js} +4 -4
  15. package/dist/{channel-ggx0o_aG.js.map → channel-B2fD2_be.js.map} +1 -1
  16. package/dist/{cli-binary-manifest-DiUulkp0.js → cli-binary-manifest-CT5X05lk.js} +30 -4
  17. package/dist/cli-binary-manifest-CT5X05lk.js.map +1 -0
  18. package/dist/{command-Bz9x7V2T.js → command-CQ9XRwqf.js} +22 -165
  19. package/dist/command-CQ9XRwqf.js.map +1 -0
  20. package/dist/{computer-connection-M3N6plkj.js → computer-connection-Dm7iTnRK.js} +2 -2
  21. package/dist/{computer-connection-M3N6plkj.js.map → computer-connection-Dm7iTnRK.js.map} +1 -1
  22. package/dist/{computer-connection-review-DY5BK_27.js → computer-connection-review-RHAoddSS.js} +6 -6
  23. package/dist/{computer-connection-review-DY5BK_27.js.map → computer-connection-review-RHAoddSS.js.map} +1 -1
  24. package/dist/{computer-disconnect-DR1WDSPK.js → computer-disconnect-BWRsge_2.js} +10 -10
  25. package/dist/{computer-disconnect-DR1WDSPK.js.map → computer-disconnect-BWRsge_2.js.map} +1 -1
  26. package/dist/{computer-setup-continuation-2gs8z-nB.js → computer-setup-continuation-BOCRH0qq.js} +4 -4
  27. package/dist/{computer-setup-continuation-2gs8z-nB.js.map → computer-setup-continuation-BOCRH0qq.js.map} +1 -1
  28. package/dist/context-Bdh3nAzw.js +162 -0
  29. package/dist/context-Bdh3nAzw.js.map +1 -0
  30. package/dist/{control-plane-e3W6PD2M.js → control-plane-rTE2rHZ5.js} +2 -2
  31. package/dist/{control-plane-e3W6PD2M.js.map → control-plane-rTE2rHZ5.js.map} +1 -1
  32. package/dist/{daemon-device-id-DWO9_QW6.js → daemon-device-id-B1Af2Zmn.js} +344 -36
  33. package/dist/daemon-device-id-B1Af2Zmn.js.map +1 -0
  34. package/dist/{daemon-frame-transport-D2-tazuK.js → daemon-frame-transport-WiB73yhT.js} +519 -12
  35. package/dist/daemon-frame-transport-WiB73yhT.js.map +1 -0
  36. package/dist/{daemon-lifecycle-journal-DyKx1xzm.js → daemon-lifecycle-journal-CDZLWgMj.js} +11 -11
  37. package/dist/daemon-lifecycle-journal-CDZLWgMj.js.map +1 -0
  38. package/dist/{daemon-runtime-lease-BUr4qsLo.js → daemon-runtime-lease-1LMeZ6IS.js} +2 -2
  39. package/dist/{daemon-runtime-lease-BUr4qsLo.js.map → daemon-runtime-lease-1LMeZ6IS.js.map} +1 -1
  40. package/dist/{daemon-runtime-lease-C9X8xV_F.js → daemon-runtime-lease-Bz0ucJj3.js} +1 -1
  41. package/dist/{daemon-service-contract-BpOBMGX0.js → daemon-service-contract-GLmAxsq-.js} +4 -4
  42. package/dist/{daemon-service-contract-BpOBMGX0.js.map → daemon-service-contract-GLmAxsq-.js.map} +1 -1
  43. package/dist/{daemon-service-manager-HL4VKbIU.js → daemon-service-manager-C8RUCMDo.js} +9 -7
  44. package/dist/daemon-service-manager-C8RUCMDo.js.map +1 -0
  45. package/dist/{daemon-service-manager-B-QrDe5p.js → daemon-service-manager-CU-79a4z.js} +1 -1
  46. package/dist/{daemon-service-runtime-bKt0YjC7.js → daemon-service-runtime-CBJtgM4P.js} +397 -51
  47. package/dist/daemon-service-runtime-CBJtgM4P.js.map +1 -0
  48. package/dist/{daemon-service-update-coordinator-D8O1uTtu.js → daemon-service-update-coordinator-0LB_XGVZ.js} +48 -33
  49. package/dist/daemon-service-update-coordinator-0LB_XGVZ.js.map +1 -0
  50. package/dist/{daemon-state-B44aq2nm.js → daemon-state-Ca0WK5x0.js} +3 -3
  51. package/dist/{daemon-state-B44aq2nm.js.map → daemon-state-Ca0WK5x0.js.map} +1 -1
  52. package/dist/{dist-B07ziN_u.js → dist-BeJcIdCZ.js} +25 -17
  53. package/dist/dist-BeJcIdCZ.js.map +1 -0
  54. package/dist/dist-C32frPV2.js +4 -0
  55. package/dist/{dist-B2EauBG6.js → dist-YbTZ-Y-2.js} +16 -12
  56. package/dist/dist-YbTZ-Y-2.js.map +1 -0
  57. package/dist/{elapsed-time-Ooo4IC25.js → elapsed-time-q8lSPcfm.js} +6 -6
  58. package/dist/{elapsed-time-Ooo4IC25.js.map → elapsed-time-q8lSPcfm.js.map} +1 -1
  59. package/dist/{entry-DeIRMCiW.js → entry-CpS6tnIk.js} +12 -12
  60. package/dist/{entry-DeIRMCiW.js.map → entry-CpS6tnIk.js.map} +1 -1
  61. package/dist/{installation-inventory-DThnBEhV.js → installation-inventory-C5FsAvrf.js} +5 -5
  62. package/dist/{installation-inventory-DThnBEhV.js.map → installation-inventory-C5FsAvrf.js.map} +1 -1
  63. package/dist/{installer-D2bWZT88.js → installer-054NLJg6.js} +2 -2
  64. package/dist/{installer-D2bWZT88.js.map → installer-054NLJg6.js.map} +1 -1
  65. package/dist/io-DT66typ4.js +16 -0
  66. package/dist/io-DT66typ4.js.map +1 -0
  67. package/dist/{local-components-B6SCXZf9.js → local-components-DleLEzSU.js} +2 -1
  68. package/dist/local-components-DleLEzSU.js.map +1 -0
  69. package/dist/{lock-Bsl_ElWy.js → lock-iue1J2xy.js} +8 -5
  70. package/dist/lock-iue1J2xy.js.map +1 -0
  71. package/dist/{cli-space-api-CQtKu9Zt.js → meta-api-B1k3mwHN.js} +203 -19
  72. package/dist/meta-api-B1k3mwHN.js.map +1 -0
  73. package/dist/{openmeld-BQy0nMox.js → openmeld-BFO3sfC_.js} +93 -1027
  74. package/dist/openmeld-BFO3sfC_.js.map +1 -0
  75. package/dist/openmeld-dev.js +1 -1
  76. package/dist/{openmeld-environment-target-B6HqY0_a.js → openmeld-environment-target-BBn5Ko6p.js} +3 -3
  77. package/dist/{openmeld-environment-target-B6HqY0_a.js.map → openmeld-environment-target-BBn5Ko6p.js.map} +1 -1
  78. package/dist/{openmeld-maintenance-worker-BSODPHbn.js → openmeld-maintenance-worker-Ce4ehQ-c.js} +15 -14
  79. package/dist/openmeld-maintenance-worker-Ce4ehQ-c.js.map +1 -0
  80. package/dist/{openmeld-tools-update-join-BfY0GnDs.js → openmeld-tools-update-join-D24llJ9L.js} +4 -4
  81. package/dist/{openmeld-tools-update-join-BfY0GnDs.js.map → openmeld-tools-update-join-D24llJ9L.js.map} +1 -1
  82. package/dist/{openmeld-tools-update-process-frame-B-XB4dmO.js → openmeld-tools-update-process-frame-BtFKp70p.js} +2 -2
  83. package/dist/{openmeld-tools-update-process-frame-B-XB4dmO.js.map → openmeld-tools-update-process-frame-BtFKp70p.js.map} +1 -1
  84. package/dist/{openmeld-tools-update-process-frame-j-RXwFsK.js → openmeld-tools-update-process-frame-DbEZ3fEh.js} +1 -1
  85. package/dist/openmeld.js +9 -5
  86. package/dist/openmeld.js.map +1 -1
  87. package/dist/{prepare-provider-runtime-CWZcuMF6.js → prepare-provider-runtime-MB-BxOgt.js} +3342 -1327
  88. package/dist/prepare-provider-runtime-MB-BxOgt.js.map +1 -0
  89. package/dist/{prepare-session-executor-CkDxstsf.js → prepare-session-executor-zvSZ6jqy.js} +29 -28
  90. package/dist/prepare-session-executor-zvSZ6jqy.js.map +1 -0
  91. package/dist/{presenter-BcxiQyJg.js → presenter-MJ5YgsOT.js} +3 -13
  92. package/dist/presenter-MJ5YgsOT.js.map +1 -0
  93. package/dist/{process-channel-BQwtOlRc.js → process-channel-CgbduFCz.js} +2 -2
  94. package/dist/{process-channel-BQwtOlRc.js.map → process-channel-CgbduFCz.js.map} +1 -1
  95. package/dist/process-environment-BWSFeUu6.js +49 -0
  96. package/dist/process-environment-BWSFeUu6.js.map +1 -0
  97. package/dist/process-identity-BQLdaZdB.js +190 -0
  98. package/dist/process-identity-BQLdaZdB.js.map +1 -0
  99. package/dist/process-launch-B0pHlkV_.js +173 -0
  100. package/dist/process-launch-B0pHlkV_.js.map +1 -0
  101. package/dist/{published-production-safety-dp-fOmmB.js → published-production-safety-C40hKrBA.js} +2 -2
  102. package/dist/{published-production-safety-dp-fOmmB.js.map → published-production-safety-C40hKrBA.js.map} +1 -1
  103. package/dist/{runtime-BYaFkkLK.js → runtime-D6jItuQ-.js} +155 -702
  104. package/dist/runtime-D6jItuQ-.js.map +1 -0
  105. package/dist/{runtime-agent-controller-reporting-submission-BUUub9_1.js → runtime-agent-controller-reporting-submission-D9ysbi7R.js} +9 -9
  106. package/dist/{runtime-agent-controller-reporting-submission-BUUub9_1.js.map → runtime-agent-controller-reporting-submission-D9ysbi7R.js.map} +1 -1
  107. package/dist/{runtime-reporting-health-state-BgwfrH7f.js → runtime-reporting-health-state-DA-_vW-n.js} +2210 -60
  108. package/dist/runtime-reporting-health-state-DA-_vW-n.js.map +1 -0
  109. package/dist/{runtime-transport-Cc_RN-PL.js → runtime-transport-YIYHSJPn.js} +99 -14
  110. package/dist/runtime-transport-YIYHSJPn.js.map +1 -0
  111. package/dist/{service-CfO38_a-.js → service-Dz2MsvGr.js} +126 -550
  112. package/dist/service-Dz2MsvGr.js.map +1 -0
  113. package/dist/{service-account-admission-Dy2W3n3_.js → service-account-admission-BfdJ-kKR.js} +18 -10
  114. package/dist/service-account-admission-BfdJ-kKR.js.map +1 -0
  115. package/dist/{service-account-authorization-DKpIpxXo.js → service-account-authorization-DZbUOD29.js} +6 -6
  116. package/dist/{service-account-authorization-DKpIpxXo.js.map → service-account-authorization-DZbUOD29.js.map} +1 -1
  117. package/dist/{service-account-control-CCPQAZzn.js → service-account-control-DCMOKXDT.js} +16 -16
  118. package/dist/service-account-control-DCMOKXDT.js.map +1 -0
  119. package/dist/{service-control-capabilities-C9UHSMPz.js → service-control-capabilities-3_bdeHXu.js} +1 -1
  120. package/dist/{service-control-capabilities-xGylBNoH.js → service-control-capabilities-Bb738e_d.js} +19 -15
  121. package/dist/service-control-capabilities-Bb738e_d.js.map +1 -0
  122. package/dist/{service-control-carrier-capability-DDNyE5cB.js → service-control-carrier-capability-gMk5gMKU.js} +11 -4
  123. package/dist/service-control-carrier-capability-gMk5gMKU.js.map +1 -0
  124. package/dist/{state-CQG3k9eh.js → state-GxF_KAM1.js} +4 -4
  125. package/dist/{state-CQG3k9eh.js.map → state-GxF_KAM1.js.map} +1 -1
  126. package/dist/{upgrade-D5FxGbh1.js → upgrade-DfJwCD5H.js} +52 -32
  127. package/dist/upgrade-DfJwCD5H.js.map +1 -0
  128. package/dist/upgrade-DgmYWeNu.js +4 -0
  129. package/dist/windows/openmeld-windows-process.exe +0 -0
  130. package/dist/windows-artifact-DJ9DKjfc.js +16 -0
  131. package/dist/windows-artifact-DJ9DKjfc.js.map +1 -0
  132. package/dist/windows-task-command-COu_6Ke3.js +74 -0
  133. package/dist/windows-task-command-COu_6Ke3.js.map +1 -0
  134. package/dist/windows-task-entry-CtRpUbiK.js +50 -0
  135. package/dist/windows-task-entry-CtRpUbiK.js.map +1 -0
  136. package/dist/{windows-user-task-Bx2yYnOM.js → windows-user-task-B8NcRg_u.js} +1 -1
  137. package/dist/{windows-user-task-CRGbKggi.js → windows-user-task-Io5QuEVR.js} +108 -51
  138. package/dist/windows-user-task-Io5QuEVR.js.map +1 -0
  139. package/package.json +12 -12
  140. package/skills/openmeld-cli/playbooks/space-ops.md +9 -3
  141. package/skills/openmeld-cli/references/commands.md +0 -1
  142. package/dist/auth-session-D8dbMpaK.js +0 -4
  143. package/dist/auth-session-nhS8jyux.js.map +0 -1
  144. package/dist/cli-binary-manifest-DiUulkp0.js.map +0 -1
  145. package/dist/cli-space-api-CQtKu9Zt.js.map +0 -1
  146. package/dist/command-Bz9x7V2T.js.map +0 -1
  147. package/dist/context-l_31Mn4X.js +0 -473
  148. package/dist/context-l_31Mn4X.js.map +0 -1
  149. package/dist/daemon-device-id-DWO9_QW6.js.map +0 -1
  150. package/dist/daemon-frame-transport-D2-tazuK.js.map +0 -1
  151. package/dist/daemon-lifecycle-journal-DyKx1xzm.js.map +0 -1
  152. package/dist/daemon-service-manager-HL4VKbIU.js.map +0 -1
  153. package/dist/daemon-service-runtime-bKt0YjC7.js.map +0 -1
  154. package/dist/daemon-service-update-coordinator-D8O1uTtu.js.map +0 -1
  155. package/dist/dist-B07ziN_u.js.map +0 -1
  156. package/dist/dist-B2EauBG6.js.map +0 -1
  157. package/dist/dist-DhWI1iyi.js +0 -4
  158. package/dist/local-components-B6SCXZf9.js.map +0 -1
  159. package/dist/lock-Bsl_ElWy.js.map +0 -1
  160. package/dist/openmeld-BQy0nMox.js.map +0 -1
  161. package/dist/openmeld-maintenance-worker-BSODPHbn.js.map +0 -1
  162. package/dist/prepare-provider-runtime-CWZcuMF6.js.map +0 -1
  163. package/dist/prepare-session-executor-CkDxstsf.js.map +0 -1
  164. package/dist/presenter-BcxiQyJg.js.map +0 -1
  165. package/dist/process-identity-CNus0e6E.js +0 -146
  166. package/dist/process-identity-CNus0e6E.js.map +0 -1
  167. package/dist/runtime-BYaFkkLK.js.map +0 -1
  168. package/dist/runtime-reporting-health-state-BgwfrH7f.js.map +0 -1
  169. package/dist/runtime-transport-Cc_RN-PL.js.map +0 -1
  170. package/dist/service-CfO38_a-.js.map +0 -1
  171. package/dist/service-account-admission-Dy2W3n3_.js.map +0 -1
  172. package/dist/service-account-control-CCPQAZzn.js.map +0 -1
  173. package/dist/service-control-capabilities-xGylBNoH.js.map +0 -1
  174. package/dist/service-control-carrier-capability-DDNyE5cB.js.map +0 -1
  175. package/dist/upgrade-D5FxGbh1.js.map +0 -1
  176. package/dist/upgrade-DhFEu0k6.js +0 -4
  177. package/dist/windows-user-task-CRGbKggi.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"command-CQ9XRwqf.js","names":["MAX_TEXT_LENGTH","MENTION_ALIAS_MAX_LENGTH","MENTION_ALIAS_TOKEN_REGEX","parseAgentControllerRef","normalizeOptionalText","toErrorMessage","normalizeOptionalText","toErrorMessage","sanitizeSingleLineText","normalizeOptionalText","parseAgentControllerRef","normalizeOptionalText","normalizeOptionalText","resolveGatewayHost","SPACE_ID_HEX_REGEX","normalizeOptionalString","isValidSpaceId","HTTP_ERROR_MESSAGE_REGEX","safeJsonParse","toErrorMessage","normalizeOptionalText","readHttpErrorField","normalizeOptionalString","parseHttpErrorMessage","readHttpErrorField","safeJsonParse","toErrorMessage","MENTION_ALIAS_TOKEN_REGEX","normalizeOptionalString","normalizeOptionalString","normalizeOptionalString","normalizeOptionalString","fetchSpaceCursor","parseProtocolEnvelope","parseProtocolIncoming","parseProtocolServerErrorFrame","normalizeOptionalText","sanitizeSingleLineText","readObjectField","readStringField","resolveSignalTextMeta","readSignalMetaText","assertUnreachable","isSignalEnvelope","REPLYING_STATUS_SYSTEM_LABEL","REPLYING_STATUS_AGENT_LABEL","PREVIEW_MAX_VISIBLE_CHARS","PREVIEW_MIN_VISIBLE_CHARS","PREVIEW_ELLIPSIS","truncatePreviewHead","resolveSignalTextMetaFromEnvelope","resolveSignalClientMessageId","countRenderedTerminalRows","isSignalEnvelope","isSignalEnvelope","renderTranscriptBlock","measureVisibleWidth","isSignalEnvelope","MENTION_ALIAS_TOKEN_REGEX","record","assertUnreachable","wrapText","toErrorMessage","isMessageSemanticSignal","#input","#listeners","#bufferedLiveEvents","#pendingSentMessages","#started","#ws","#stopRequested","safeJsonParse","#maybeEmitSendFailed","#handleLiveEvent","#emitConnectionClosed","#emit","#startReplayAndDrain","#forceTerminateTimer","#rememberPendingSentMessage","#bufferLiveEventsUntilReplayComplete","#historyLoadedReason","#drainBufferedLiveEvents","#emitSignalReceived","#replayFinished","#maybeEmitSendConfirmed","#closeEventDispatched","REPLYING_STATUS_PROMPT_GAP_LINES","CHAT_GROUP_DIVIDER_MARGIN","CHAT_GROUP_DIVIDER_MIN_WIDTH","CHAT_GROUP_DIVIDER_MAX_WIDTH","CHAT_GROUP_DIVIDER_CHAR","CHAT_GROUP_DIVIDER_SIDE_GAP_LINES","#composePromptPrefix","#onLine","#onClose","#readline","#composerVisible","#resolvePrompt","#latestViewState","#renderNewTranscriptItems","#syncOverlayLine","#refreshPrompt","#clearInteractiveOverlay","#lastRenderedTranscriptCount","#emitTranscriptItem","#hasPrintedTextLine","#lastPrintedTextLineGroupKey","#emitTextGroupDivider","buildChatGroupDividerLine","#nextDividerGapPlacement","#clearVisibleOverlayLine","#visibleOverlayLine","#visibleOverlayLineRows","#countPromptDisplayRows","#resolvePromptCursorRows","resolveTerminalColumns","clampNumber","#tui","#activity","#tick","#activityBaseSetAtMs","#syncTimer","#timer","#resolveElapsedDeltaSeconds","#onMentionSelected","#getMembersSnapshot","#getRecentMentionProfileIds","#getSlashSuggestions","#getMentionSuggestions","#mentionPickerState","#resetRelationSelectionOnNextSync","#container","#helperText","#leadingBlankLines","#placeholderText","#showPlaceholder","#summarySegments","#visible","clampNumber","#chrome","#getMaxPanelRows","#onClose","#panel","#syncText","#lastRenderWidth","#scrollOffset","#onActiveItemChange","#onQueryChange","clampNumber","#text","#blocks","#transcriptBlockPanel","#blocks","#text","#visible","#chrome","#getMaxPanelRows","#onClose","#blocks","#syncText","#pendingBlockUpdate","#lastRenderWidth","#buildViewportState","#scrollOffset","#isFollowingLatest","#hasNewUpdatesBelow","#normalizeRenderState","#readRenderState","#buildOverlayRenderResult","#resolveNextHasNewUpdatesBelow","#isSameRenderState","#lastRenderedRowCount","#buildOverlaySections","#buildViewportRuntimeFooter","#buildOverlayRuntimeFooter","#buildLatestBlockRowRange","#buildBodyRows","#buildFooterLines","#submittedMentions","#authoredText","#authoredMentions","#input","#terminal","#tui","#root","#sessionDocumentPanel","#composerActivityStrip","#composerPanel","#statusBar","#updateAuthoredText","#latestViewState","#syncingEditorText","#started","#applyViewState","#removeInputListener","#handleInput","#requestUiRender","#composerVisible","#syncStatusBar","#syncEditorText","#syncOverlay","#overlayHandle","#requestHardResetRender","#overlayPanel","#overlayKind","#clearCtrlCExitConfirmation","#resolveStatusBarText","#ctrlCExitDeadlineMs","#handleCtrlCInput","#handleCtrlDInput","#isTranscriptReaderOpen","#closeTranscriptReader","#openTranscriptReader","#handleReadonlyInput","#shouldConfirmCtrlCExitNow","#armCtrlCExitConfirmation","#clearCtrlCExitConfirmationTimer","#ctrlCExitTimeout","#syncTranscriptReader","#createOverlayPanel","#resolveOverlayLayout","#resolveCenteredOverlayLayout","resolveGatewayHost","toErrorMessage","countRenderedTerminalRows","resolveSignalClientMessageId","safeJsonParse","parseHttpErrorMessage","readHttpErrorField","resolveSignalTextMetaFromEnvelope","toErrorMessage","password","passwordPrompt","toErrorMessage","normalizeOptionalString","safeJsonParse","readHttpErrorField","parseHttpErrorMessage","passwordPrompt","fetchSpaceCursor"],"sources":["../../../packages/schemas/dist/schemas/http/space-cursor.js","../src/local-service/reporting/local-agent-controller-report-resolution.ts","../src/system/action-participation-planner.ts","../src/system/assistant-binding-support-code.ts","../src/system/ensure-agent-profile-runtime-binding.ts","../src/profile/create-flow.ts","../src/space/send-input.ts","../src/ui/brand.ts","../src/ui/profile-label-color.ts","../src/profile/agent-setup-flow.ts","../src/ui/controller-display.ts","../src/system/reply-readiness-guidance.ts","../src/system/local-agent-readiness-preparation.ts","../src/space/agent-overview.ts","../src/config/account-space-index-api.ts","../src/config/profile-space-history-api.ts","../src/system/formal-agent-binding-backstop.ts","../src/system/local-participation-orchestrator.ts","../src/ui/space-access-prompt-card.ts","../src/ui/space-create-password-prompt.ts","../src/space/command-context.ts","../src/space/http-failure.ts","../src/space/command-http-errors.ts","../src/space/command-input-normalizers.ts","../src/space/space-display-projection.ts","../src/space/command-known-space-projection.ts","../src/space/command-member-recovery.ts","../src/space/command-selection-prompts.ts","../src/space/command-target-resolution.ts","../src/space/command-output-handled.ts","../src/space/command-send-history-leaves.ts","../src/protocol/wire.ts","../src/space/access-presentation.ts","../src/space/agent-output-contract.ts","../src/space/mention-label-state.ts","../src/space/openmeld-system-profile.ts","../src/space/read-projection/human-message-read-display.ts","../src/space/reply-cue-preview.ts","../src/ui/positive-accent.ts","../src/ui/public-space-warning.ts","../src/ui/space-mention-highlight.ts","../src/ui/output.ts","../src/space/addressing-preflight.ts","../src/space/quit-command.ts","../src/space/compose-input.ts","../src/space/composer/slash-command-registry.ts","../src/space/composer/composer-controller.ts","../src/space/composer-submission-adapter.ts","../src/space/connect-catchup.ts","../src/space/connect-dispatch-activity.ts","../src/space/session-profile.ts","../src/space/transcript/membership-notice.ts","../src/space/transcript/transcript-owner-enrichment.ts","../src/space/transcript/transcript-reply-ref.ts","../src/space/transcript/transcript-item-builder.ts","../src/space/read-projection/human-reply-workflow-transcript-display.ts","../src/space/transcript/system-notice-importance.ts","../src/space/transcript/transcript-render.ts","../src/space/connect-history-transcript-bootstrap.ts","../src/space/connect-session-meta.ts","../src/space/pending-outbound-confirmation.ts","../src/space/pending-outbound-status.ts","../src/space/human-send-state.ts","../src/space/interactive-text-submit.ts","../src/space/join-read-model-seed.ts","../src/space/view/space-storage-usage-text.ts","../src/space/panel/space-panel-content.ts","../src/ui/text-input-cursor.ts","../src/space/panel/space-panel-definition.ts","../src/space/panel/space-panel-display.ts","../src/space/preflight.ts","../src/space/read-projection/formal-message-read-output.ts","../src/space/runtime/space-session-runtime.ts","../src/space/shell/interactive-shell-kind.ts","../src/space/shell/legacy-interactive-space-shell.ts","../src/space/panel/build-space-panel-view-state.ts","../src/space/readonly-session-shortcuts.ts","../src/space/view/build-composer-activity-view-state.ts","../src/space/view/build-space-summary-view-state.ts","../src/space/view/build-space-session-view-state.ts","../src/space/shell/pi-tui/mount-pi-tui-session-shell.ts","../src/space/shell/pi-tui/theme.ts","../src/space/shell/pi-tui/components/composer-activity-strip.ts","../src/space/shell/pi-tui/mention-autocomplete-select-list.ts","../src/space/shell/pi-tui/pi-tui-composer-autocomplete-provider.ts","../src/space/shell/pi-tui/space-composer-editor.ts","../src/space/shell/pi-tui/components/render-space-summary-lines.ts","../src/space/shell/pi-tui/components/composer-panel.ts","../src/space/shell/pi-tui/components/readonly-viewport.ts","../src/space/shell/pi-tui/components/readonly-overlay-surface.ts","../src/space/shell/pi-tui/components/overlay-host.ts","../src/space/shell/pi-tui/components/render-session-header-lines.ts","../src/space/shell/pi-tui/components/transcript-block-panel.ts","../src/space/shell/pi-tui/components/session-document-panel.ts","../src/space/shell/pi-tui/components/status-bar.ts","../src/space/shell/pi-tui/components/transcript-reader-overlay.ts","../src/space/shell/pi-tui/pi-tui-interactive-space-shell.ts","../src/space/space-meta-upsert-input.ts","../src/space/state/space-screen-state.ts","../src/space/state/space-screen-store.ts","../src/space/connect.ts","../src/space/read-projection/space-read-projection-context.ts","../src/space/read-signals-output.ts","../src/space/shell/pi-tui/run-readonly-pi-tui-session.ts","../src/space/history.ts","../src/space/password-flow.ts","../src/space/join-access-bootstrap.ts","../src/space/join-connect-handoff.ts","../src/space/join-progress.ts","../src/space/join-entry.ts","../src/space/space-add-members-ui.ts","../src/space/join-membership-bootstrap.ts","../src/space/join-role-alias-bootstrap.ts","../src/space/members-mutations.ts","../src/space/send.ts","../src/space/command.ts"],"sourcesContent":["import { MAX_TEXT_LENGTH } from \"../protocol/constants.js\";\nimport * as z$1 from \"zod/v4\";\n//#region src/schemas/http/space-cursor.ts\nconst patchCursorLastSeenTsSchema = z$1.number().int().finite().min(0);\nconst patchCursorStringSchema = z$1.string().transform((value) => value.trim());\nconst patchCursorRoleSchema = patchCursorStringSchema.refine((value) => value.length <= MAX_TEXT_LENGTH, { message: \"Role too long\" });\nconst MENTION_ALIAS_MAX_LENGTH = 128;\nconst MENTION_ALIAS_TOKEN_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nconst patchCursorMentionAliasSchema = patchCursorStringSchema.refine((value) => value.length <= MENTION_ALIAS_MAX_LENGTH, { message: \"MentionAlias too long\" }).refine((value) => value.length === 0 || MENTION_ALIAS_TOKEN_REGEX.test(value), { message: \"Invalid mentionAlias\" });\nconst patchSpaceCursorBodySchema = z$1.strictObject({\n\tlastSeenTs: patchCursorLastSeenTsSchema.optional(),\n\trole: patchCursorRoleSchema.optional(),\n\tmentionAlias: patchCursorMentionAliasSchema.optional()\n});\nconst SPACE_CURSOR_PATCH_REQUIRED_MESSAGE = \"Expected lastSeenTs, role or mentionAlias\";\nconst SPACE_CURSOR_STRING_PATCH_FIELDS = [\"role\", \"mentionAlias\"];\nconst SPACE_CURSOR_PATCH_FIELDS = /* @__PURE__ */ new Set([\"lastSeenTs\", ...SPACE_CURSOR_STRING_PATCH_FIELDS]);\nfunction readNormalizedLastSeenTs(patch) {\n\tif (!Object.hasOwn(patch, \"lastSeenTs\")) return { ok: true };\n\tconst rawLastSeenTs = patch.lastSeenTs;\n\tif (rawLastSeenTs === void 0) return { ok: true };\n\tif (typeof rawLastSeenTs !== \"number\") return {\n\t\tok: false,\n\t\tmessage: \"Invalid lastSeenTs\"\n\t};\n\tif (!Number.isFinite(rawLastSeenTs)) return { ok: true };\n\treturn {\n\t\tok: true,\n\t\tvalue: Math.max(0, Math.trunc(rawLastSeenTs))\n\t};\n}\nfunction readNormalizedStringPatchField(patch, field) {\n\tif (!Object.hasOwn(patch, field)) return { ok: true };\n\tconst rawValue = patch[field];\n\tif (rawValue === void 0) return { ok: true };\n\tif (typeof rawValue !== \"string\") return {\n\t\tok: false,\n\t\tmessage: `Invalid ${field}`\n\t};\n\treturn {\n\t\tok: true,\n\t\tvalue: rawValue\n\t};\n}\nfunction normalizeSpaceCursorPatch(input) {\n\tif (!input || typeof input !== \"object\") return {\n\t\tok: false,\n\t\tmessage: \"Invalid JSON\"\n\t};\n\tconst rawPatch = input;\n\tconst unknownField = Object.keys(rawPatch).find((field) => !SPACE_CURSOR_PATCH_FIELDS.has(field));\n\tif (unknownField) return {\n\t\tok: false,\n\t\tmessage: `Unrecognized key: \"${unknownField}\"`\n\t};\n\tconst patch = {};\n\tconst lastSeenTs = readNormalizedLastSeenTs(rawPatch);\n\tif (!lastSeenTs.ok) return lastSeenTs;\n\tif (lastSeenTs.value !== void 0) patch.lastSeenTs = lastSeenTs.value;\n\tfor (const field of SPACE_CURSOR_STRING_PATCH_FIELDS) {\n\t\tconst fieldValue = readNormalizedStringPatchField(rawPatch, field);\n\t\tif (!fieldValue.ok) return fieldValue;\n\t\tif (fieldValue.value !== void 0) patch[field] = fieldValue.value;\n\t}\n\tif (Object.keys(patch).length === 0) return {\n\t\tok: false,\n\t\tmessage: SPACE_CURSOR_PATCH_REQUIRED_MESSAGE\n\t};\n\tconst parsed = patchSpaceCursorBodySchema.safeParse(patch);\n\tif (!parsed.success) return {\n\t\tok: false,\n\t\tmessage: parsed.error.issues[0]?.message ?? \"Invalid cursor patch\"\n\t};\n\treturn {\n\t\tok: true,\n\t\tvalue: parsed.data\n\t};\n}\n//#endregion\nexport { normalizeSpaceCursorPatch, patchCursorLastSeenTsSchema, patchCursorStringSchema, patchSpaceCursorBodySchema };\n\n//# sourceMappingURL=space-cursor.js.map","import { parseAgentControllerRef } from \"@openmeld/agent-runtime\";\nimport {\n collectLocalAgentControllerInventory,\n type LocalAgentControllerInventoryItem,\n resolveLocalAgentControllerReportDecision,\n} from \"../inventory/agent-controller-inventory\";\nimport type { RuntimeAgentControllerReportInput } from \"./runtime-agent-controller-reporting-submission\";\n\nexport async function resolveLocalAgentControllerReportInput(input: {\n agentControllerRef: string;\n controllerInventory?: readonly LocalAgentControllerInventoryItem[];\n diagnosticProfileId?: string;\n requireEnabled: boolean;\n}): Promise<RuntimeAgentControllerReportInput> {\n const parsedRef = parseAgentControllerRef(input.agentControllerRef);\n const agentControllerRef = parsedRef?.ref ?? input.agentControllerRef.trim();\n if (!parsedRef) {\n return buildReportInput({\n agentControllerRef,\n diagnosticProfileId: input.diagnosticProfileId,\n localParticipationState: \"needs_agent_prepare\",\n reasonCodes: [\"runtime.reporting.agent_controller_ref_invalid\"],\n });\n }\n\n if (parsedRef.kind !== \"builtin\") {\n return buildReportInput({\n agentControllerRef,\n diagnosticProfileId: input.diagnosticProfileId,\n localParticipationState: \"ready\",\n reasonCodes: [],\n });\n }\n\n const controllerInventory =\n input.controllerInventory ??\n (\n await collectLocalAgentControllerInventory({\n includeControllerInterface: true,\n })\n ).capabilities;\n const capability =\n controllerInventory.find(\n (currentCapability) =>\n currentCapability.agentControllerRef === agentControllerRef\n ) ?? null;\n if (!capability) {\n return buildReportInput({\n agentControllerRef,\n diagnosticProfileId: input.diagnosticProfileId,\n localParticipationState: \"needs_agent_prepare\",\n reasonCodes: [\"local_agent_preparation.not_found\"],\n });\n }\n\n const decision = resolveLocalAgentControllerReportDecision(capability, {\n requireEnabled: input.requireEnabled,\n });\n return buildReportInput({\n agentControllerInterface: capability.agentControllerInterface,\n agentControllerRef,\n diagnosticProfileId: input.diagnosticProfileId,\n localParticipationState: decision.localParticipationState,\n reasonCodes: decision.reasonCodes,\n });\n}\n\nfunction buildReportInput(\n input: RuntimeAgentControllerReportInput\n): RuntimeAgentControllerReportInput {\n return {\n agentControllerRef: input.agentControllerRef,\n ...(input.agentControllerInterface\n ? { agentControllerInterface: input.agentControllerInterface }\n : {}),\n ...(input.diagnosticProfileId\n ? { diagnosticProfileId: input.diagnosticProfileId }\n : {}),\n localParticipationState: input.localParticipationState,\n reasonCodes: input.reasonCodes,\n };\n}\n","import type { AgentTargetState } from \"../agents/registry\";\nimport type { ServiceParticipationReadiness } from \"./service-participation-readiness\";\n\nexport type ActionParticipationIntent =\n | \"start\"\n | \"space_join\"\n | \"space_create_join\"\n | \"space_add_members\";\n\nexport type LocalParticipationState =\n | \"not_needed\"\n | \"membership_only\"\n | \"needs_agent_prepare\"\n | \"needs_openmeld_service\"\n | \"ready\";\n\nexport type LocalParticipationRootCause =\n | \"human_only\"\n | \"profile_unbound\"\n | \"controller_disabled\"\n | \"target_not_selectable\"\n | \"target_needs_repair\"\n | \"workspace_not_ready\"\n | \"daemon_service_not_ready\"\n | \"daemon_service_drifted\"\n | \"unknown\";\n\nexport type ActionParticipationCandidate = {\n profileId: string;\n profileName: string;\n profileKind: \"human\" | \"agent\";\n localTargetSelectable?: boolean | null;\n localTargetLaunchStatus?: AgentTargetState[\"launchStatus\"] | null;\n localParticipationReadiness?: ServiceParticipationReadiness | null;\n localParticipationReasonCodes?: readonly string[];\n};\n\nexport type LocalParticipationAssessment = {\n profileId: string;\n profileName: string;\n profileKind: \"human\" | \"agent\";\n membershipAllowed: boolean;\n localParticipationState: LocalParticipationState;\n rootCause: LocalParticipationRootCause;\n reasonCodes: string[];\n};\n\nexport type ActionParticipationPlan = {\n intent: ActionParticipationIntent;\n assessments: LocalParticipationAssessment[];\n shouldOfferServiceGate: boolean;\n hasAgentPreparationWork: boolean;\n hasReadyLocalAgentParticipation: boolean;\n explicitLocalAgentCount: number;\n};\n\nexport type LocalParticipationOrchestratorOutcome =\n | { status: \"continued\" }\n | { status: \"recheck_required\" }\n | { status: \"cancelled\" };\n\nconst OPENMELD_SERVICE_REASON_CODES: ReadonlySet<string> = new Set([\n \"service.not_installed\",\n \"service.not_running\",\n \"service.drifted\",\n \"dispatch.storage_not_ready\",\n \"service.gateway_chain_unhealthy\",\n \"agent_execution.route_missing\",\n \"agent_execution.route_offline\",\n \"agent_execution.route_unavailable\",\n \"route.offline\",\n \"route.not_registered\",\n \"route.unavailable\",\n] as const);\n\nconst PROFILE_CONNECTION_REASON_CODES: ReadonlySet<string> = new Set([\n \"profile.unbound\",\n \"controller.binding.disabled\",\n \"agent_profile_binding.missing\",\n \"agent_profile_binding.command_eligible\",\n \"agent_profile_binding.owner_mismatch\",\n \"agent_profile_binding.runtime_mismatch\",\n \"agent_profile_binding.capability_mismatch\",\n \"claim_eligibility.binding_capability_mismatch\",\n \"claim_eligibility.binding_owner_mismatch\",\n \"claim_eligibility.binding_runtime_mismatch\",\n \"claim_eligibility.owner_mismatch\",\n \"claim_eligibility.openmeld_service_runtime_id_mismatch\",\n \"local_service.identity_mismatch\",\n] as const);\n\nconst AGENT_PREPARE_REASON_CODES: ReadonlySet<string> = new Set([\n \"controller.registry.disabled\",\n \"controller.launch.choice_required\",\n \"controller.launch.needs_repair\",\n \"workspace.missing\",\n \"workspace.invalid\",\n \"projection.missing\",\n \"runtime.adapter.unsupported\",\n \"controller.bootstrap.failed\",\n \"controller.gateway.unhealthy\",\n] as const);\n\nexport function planActionParticipation(input: {\n intent: ActionParticipationIntent;\n candidates: readonly ActionParticipationCandidate[];\n}): ActionParticipationPlan {\n const assessments = input.candidates.map((candidate) =>\n assessActionParticipationCandidate(candidate)\n );\n\n return {\n intent: input.intent,\n assessments,\n shouldOfferServiceGate: assessments.some(\n (assessment) =>\n assessment.localParticipationState === \"needs_openmeld_service\"\n ),\n hasAgentPreparationWork: assessments.some(\n (assessment) =>\n assessment.localParticipationState === \"needs_agent_prepare\"\n ),\n hasReadyLocalAgentParticipation: assessments.some(\n (assessment) => assessment.localParticipationState === \"ready\"\n ),\n explicitLocalAgentCount: assessments.filter(\n (assessment) => assessment.profileKind === \"agent\"\n ).length,\n };\n}\n\nexport function assessActionParticipationCandidate(\n candidate: ActionParticipationCandidate\n): LocalParticipationAssessment {\n const reasonCodes = normalizeReasonCodes(\n candidate.localParticipationReasonCodes\n );\n\n if (candidate.profileKind !== \"agent\") {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"not_needed\",\n rootCause: \"human_only\",\n reasonCodes,\n };\n }\n\n if (candidate.localTargetSelectable === false) {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"needs_agent_prepare\",\n rootCause: \"target_not_selectable\",\n reasonCodes,\n };\n }\n\n if (candidate.localTargetLaunchStatus === \"needs_repair\") {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"needs_agent_prepare\",\n rootCause: \"target_needs_repair\",\n reasonCodes,\n };\n }\n\n if (\n reasonCodes.some((reasonCode) => AGENT_PREPARE_REASON_CODES.has(reasonCode))\n ) {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"needs_agent_prepare\",\n rootCause: resolveAgentPrepareRootCause(reasonCodes),\n reasonCodes,\n };\n }\n\n if (\n candidate.localParticipationReadiness === \"not_installed\" ||\n candidate.localParticipationReadiness === \"not_running\" ||\n reasonCodes.some((reasonCode) =>\n OPENMELD_SERVICE_REASON_CODES.has(reasonCode)\n )\n ) {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"needs_openmeld_service\",\n rootCause: reasonCodes.includes(\"service.drifted\")\n ? \"daemon_service_drifted\"\n : \"daemon_service_not_ready\",\n reasonCodes,\n };\n }\n\n if (\n reasonCodes.some((reasonCode) =>\n PROFILE_CONNECTION_REASON_CODES.has(reasonCode)\n )\n ) {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"membership_only\",\n rootCause: resolveMembershipOnlyRootCause(reasonCodes),\n reasonCodes,\n };\n }\n\n if (candidate.localParticipationReadiness === \"ready\") {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"ready\",\n rootCause: \"unknown\",\n reasonCodes,\n };\n }\n\n if (reasonCodes.length === 0) {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"membership_only\",\n rootCause: \"unknown\",\n reasonCodes,\n };\n }\n\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n membershipAllowed: true,\n localParticipationState: \"membership_only\",\n rootCause: \"unknown\",\n reasonCodes,\n };\n}\n\nfunction normalizeReasonCodes(\n reasonCodes: readonly string[] | null | undefined\n): string[] {\n return [\n ...new Set((reasonCodes ?? []).map((code) => code.trim()).filter(Boolean)),\n ];\n}\n\nfunction resolveAgentPrepareRootCause(\n reasonCodes: readonly string[]\n): LocalParticipationRootCause {\n if (reasonCodes.includes(\"profile.unbound\")) {\n return \"profile_unbound\";\n }\n if (\n reasonCodes.includes(\"controller.binding.disabled\") ||\n reasonCodes.includes(\"controller.registry.disabled\")\n ) {\n return \"controller_disabled\";\n }\n if (\n reasonCodes.includes(\"controller.launch.choice_required\") ||\n reasonCodes.includes(\"controller.launch.needs_repair\")\n ) {\n return \"target_needs_repair\";\n }\n if (\n reasonCodes.includes(\"workspace.missing\") ||\n reasonCodes.includes(\"workspace.invalid\") ||\n reasonCodes.includes(\"projection.missing\")\n ) {\n return \"workspace_not_ready\";\n }\n return \"unknown\";\n}\n\nfunction resolveMembershipOnlyRootCause(\n reasonCodes: readonly string[]\n): LocalParticipationRootCause {\n if (reasonCodes.includes(\"profile.unbound\")) {\n return \"profile_unbound\";\n }\n if (reasonCodes.includes(\"controller.binding.disabled\")) {\n return \"controller_disabled\";\n }\n return \"unknown\";\n}\n","// Success-class reason codes describe a healthy sub-fact, not a failure.\n// Agent execution readiness assembles reason codes in the fixed order\n// profile -> binding -> localService -> service -> runtime -> claim ..., so a\n// clean profile plus a healthy Binding surfaces the success code\n// `agent_profile_binding.command_eligible` as element [0] while the real\n// blockers (route.*/service.* codes) come later. Showing a success code as the\n// support code for a failed or unavailable Binding is error swallowing, so\n// filter these out before choosing what to show a user.\nconst SUCCESS_CLASS_REASON_CODES: ReadonlySet<string> = new Set([\n \"agent_profile_binding.command_eligible\",\n \"claim.not_checked\",\n]);\n\n// Prefixes for reason codes that name an actual execution blocker. When a\n// blocking code is present it is preferred over any remaining non-blocking\n// code so the user sees the code that explains why the Binding is not runnable.\nconst BLOCKING_REASON_CODE_PREFIXES: readonly string[] = [\n \"route.\",\n \"service.\",\n \"agent_execution.\",\n \"local_service.\",\n];\n\nconst FALLBACK_SUPPORT_CODE = \"agent_profile_binding.unavailable\";\n\n/**\n * Choose the truthful support/reason code to show for a failed or unavailable\n * Assistant Binding.\n *\n * - Drops success-class codes (a success code must never be presented as the\n * reason a Binding failed).\n * - Prefers an actual blocking code (route.*, service.*, agent_execution.*,\n * local_service.*) when one survives filtering.\n * - Falls back to the first remaining code, then to the `reason` field\n * (e.g. `local_execution_evidence_unavailable`), then to a stable default.\n */\nexport function selectAssistantBindingSupportCode(input: {\n reason?: string | null;\n reasonCodes: readonly string[];\n}): string {\n const meaningfulCodes = input.reasonCodes\n .map((code) => code.trim())\n .filter((code) => code.length > 0 && !SUCCESS_CLASS_REASON_CODES.has(code));\n\n const blockingCode = meaningfulCodes.find((code) =>\n isBlockingReasonCode(code)\n );\n if (blockingCode) {\n return blockingCode;\n }\n\n const firstMeaningfulCode = meaningfulCodes[0];\n if (firstMeaningfulCode) {\n return firstMeaningfulCode;\n }\n\n const reason = input.reason?.trim();\n if (reason) {\n return reason;\n }\n\n return FALLBACK_SUPPORT_CODE;\n}\n\nfunction isBlockingReasonCode(code: string): boolean {\n return BLOCKING_REASON_CODE_PREFIXES.some((prefix) =>\n code.startsWith(prefix)\n );\n}\n","import {\n createAuthorityOpenMeldServiceRuntimeId,\n isAgentExecutionReadyOrConnecting,\n} from \"@openmeld/agent-runtime\";\nimport { createAgentProfileBindingApi } from \"@openmeld/api-client\";\nimport type {\n AgentControllerCollaborationMode,\n AgentControllerPermissionMode,\n EnsureAgentProfilePrimaryBindingResponse,\n GetAgentExecutionReadinessResponse,\n OpenCodePermissionConfig,\n OpenMeldRequestContext,\n} from \"@openmeld/schemas/types\";\nimport { sleep } from \"@openmeld/utils\";\nimport { resolveBaseUrl } from \"../config/base-url\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { buildOpenMeldRequestContextFromProfile } from \"../config/openmeld-request-context\";\nimport {\n type RuntimeAgentControllerReportSubmission,\n submitProfileRuntimeAgentControllerReport,\n} from \"../local-service/reporting/runtime-agent-controller-reporting-submission\";\nimport { computeRetryDelayMs } from \"../runtime/retry-delay\";\nimport { createCliApiClientFoundation } from \"../space/api-client-foundation\";\nimport { assessActionParticipationCandidate } from \"./action-participation-planner\";\nimport { selectAssistantBindingSupportCode } from \"./assistant-binding-support-code\";\nimport { resolveCurrentReplyReadinessSnapshot } from \"./current-reply-readiness-snapshot\";\nimport { resolveServiceParticipationReadiness } from \"./service-participation-readiness\";\n\n// computeRetryDelayMs schedule (250/500/1000/2000ms) sums to 5750ms across 5\n// sleeps, matching (and not undershooting) the prior fixed 8 x 500ms = 4000ms\n// budget before giving up.\nconst EXECUTION_READINESS_AFTER_BINDING_MAX_ATTEMPTS = 5;\n\nexport type AgentProfileRuntimeBindingEnsureResult = {\n existingBinding?: AgentProfileRuntimeBindingExistingBinding;\n source: \"agent_profile_binding_api\";\n status: \"accepted\" | \"rejected\" | \"skipped\" | \"unavailable\";\n outcome?: \"created\" | \"reused\" | \"reconnected\";\n reason?:\n | \"binding_rejected\"\n | \"binding_write_failed\"\n | \"local_execution_evidence_unavailable\"\n | \"profile_not_agent\"\n | \"runtime_reporting_unavailable\";\n reasonCodes: string[];\n routable: boolean;\n};\n\nexport type AgentProfileRuntimeBindingExistingBinding = {\n agentControllerConversationId?: string | null;\n agentControllerRef: string;\n openMeldServiceRuntimeId: string;\n agentProfileId?: string;\n bindingId?: string;\n bindingState?: \"enabled_primary\" | \"disabled_historical\";\n createdAtMs?: number;\n createdByProfileId?: string | null;\n disabledAtMs?: number | null;\n owner?: {\n id: string;\n kind: \"owner_account\";\n };\n reasonCode?: string | null;\n updatedAtMs?: number;\n agentControllerPermissionMode?: string | null;\n modelId?: string | null;\n reasoningLevel?: string | null;\n};\n\nexport async function ensureAgentProfileRuntimeBinding(input: {\n agentControllerCollaborationMode?: AgentControllerCollaborationMode;\n agentControllerConversationId?: string | null;\n agentControllerPermissionMode?: AgentControllerPermissionMode | null;\n confirmLocalExecutionEvidence?: boolean;\n modelId?: string | null;\n openCodePermission?: OpenCodePermissionConfig;\n profile: OpenMeldProfile;\n reasoningLevel?: string | null;\n runtimeReportSubmission: RuntimeAgentControllerReportSubmission;\n writeMode?: \"ensure\" | \"reconnect\";\n}): Promise<AgentProfileRuntimeBindingEnsureResult> {\n if (input.profile.profileKind !== \"agent\") {\n return {\n reason: \"profile_not_agent\",\n reasonCodes: [\"agent_profile_binding.profile_not_agent\"],\n routable: false,\n source: \"agent_profile_binding_api\",\n status: \"skipped\",\n };\n }\n\n const bindingInput = tryResolveBindingInput(input.runtimeReportSubmission);\n if (!bindingInput) {\n return {\n reason: \"runtime_reporting_unavailable\",\n reasonCodes: [\"agent_profile_binding.runtime_reporting_unavailable\"],\n routable: false,\n source: \"agent_profile_binding_api\",\n status: \"unavailable\",\n };\n }\n\n try {\n const gatewayUrl = await resolveBaseUrl();\n const api = createAgentProfileBindingApi(\n createCliApiClientFoundation(gatewayUrl)\n );\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.profile,\n });\n const agentControllerConversationId = normalizeOptionalText(\n input.agentControllerConversationId\n );\n const modelId = normalizeOptionalText(input.modelId);\n const reasoningLevel = modelId\n ? normalizeOptionalText(input.reasoningLevel)\n : null;\n const response = await api.ensurePrimaryBinding({\n agentProfileId: input.profile.openMeldProfileId,\n ...(input.agentControllerCollaborationMode\n ? {\n agentControllerCollaborationMode:\n input.agentControllerCollaborationMode,\n }\n : {}),\n ...(input.agentControllerPermissionMode\n ? { agentControllerPermissionMode: input.agentControllerPermissionMode }\n : {}),\n ...(agentControllerConversationId\n ? { agentControllerConversationId }\n : {}),\n agentControllerRef: bindingInput.agentControllerRef,\n deviceId: bindingInput.deviceId,\n lane: bindingInput.lane,\n requestContext,\n openMeldServiceRuntimeId: bindingInput.openMeldServiceRuntimeId,\n ...(modelId ? { modelId } : {}),\n ...(input.openCodePermission\n ? { openCodePermission: input.openCodePermission }\n : {}),\n ...(reasoningLevel ? { reasoningLevel } : {}),\n ...(input.writeMode === undefined ? {} : { writeMode: input.writeMode }),\n });\n\n if (response.status === \"accepted\") {\n if (input.confirmLocalExecutionEvidence === false) {\n return {\n outcome: response.outcome,\n reasonCodes: uniqueReasonCodes(response.reasonCodes),\n routable: response.routable,\n source: \"agent_profile_binding_api\",\n status: \"accepted\",\n };\n }\n\n const localExecutionEvidence =\n await confirmLocalExecutionEvidenceAfterBinding({\n agentProfileId: input.profile.openMeldProfileId,\n api,\n requestContext,\n });\n if (localExecutionEvidence.status !== \"accepted\") {\n // Readiness assembles reason codes profile -> binding -> ... so a clean\n // profile and healthy Binding surface the success code\n // agent_profile_binding.command_eligible as [0] while the real blockers\n // come later. Lead with a truthful support code so every consumer that\n // reads reasonCodes[0] sees the blocker, not a success code. The full\n // list is preserved after it for diagnostics.\n return {\n reason: \"local_execution_evidence_unavailable\",\n reasonCodes: orderReasonCodesBySupportRelevance({\n reason: \"local_execution_evidence_unavailable\",\n reasonCodes: localExecutionEvidence.reasonCodes,\n }),\n routable: false,\n source: \"agent_profile_binding_api\",\n status: \"unavailable\",\n };\n }\n\n return {\n outcome: response.outcome,\n reasonCodes: uniqueReasonCodes([\n ...response.reasonCodes,\n ...localExecutionEvidence.reasonCodes,\n ]),\n routable: response.routable,\n source: \"agent_profile_binding_api\",\n status: \"accepted\",\n };\n }\n\n const existingBinding = resolveExistingBindingFromCommandResponse(response);\n return {\n ...(existingBinding ? { existingBinding } : {}),\n reason: \"binding_rejected\",\n reasonCodes: response.reasonCodes,\n routable: false,\n source: \"agent_profile_binding_api\",\n status: \"rejected\",\n };\n } catch (error) {\n console.warn(\"[openmeld.agent_profile_binding.ensure_failed]\", {\n error: toErrorMessage(error),\n event: \"cli.agent_profile_binding.ensure_failed\",\n profileId: input.profile.openMeldProfileId,\n });\n return {\n reason: \"binding_write_failed\",\n reasonCodes: [\"agent_profile_binding.write_failed\"],\n routable: false,\n source: \"agent_profile_binding_api\",\n status: \"unavailable\",\n };\n }\n}\n\ntype AgentProfileBindingApi = ReturnType<typeof createAgentProfileBindingApi>;\n\nfunction resolveExistingBindingFromCommandResponse(\n response: EnsureAgentProfilePrimaryBindingResponse\n): AgentProfileRuntimeBindingExistingBinding | null {\n const executionTarget = response.binding?.executionTarget ?? null;\n const agentControllerRef = normalizeOptionalText(\n executionTarget?.agentControllerRef\n );\n const openMeldServiceRuntimeId = normalizeOptionalText(\n executionTarget?.openMeldServiceRuntimeId.value\n );\n if (!(agentControllerRef && openMeldServiceRuntimeId)) {\n return null;\n }\n return {\n agentControllerRef,\n openMeldServiceRuntimeId,\n ...(response.binding?.agentProfileId\n ? { agentProfileId: response.binding.agentProfileId }\n : {}),\n ...(executionTarget?.agentControllerConversationId\n ? {\n agentControllerConversationId:\n executionTarget.agentControllerConversationId,\n }\n : {}),\n };\n}\n\nasync function confirmLocalExecutionEvidenceAfterBinding(input: {\n agentProfileId: string;\n api: AgentProfileBindingApi;\n requestContext: OpenMeldRequestContext;\n}): Promise<\n | {\n reasonCodes: readonly string[];\n status: \"accepted\";\n }\n | {\n reasonCodes: readonly string[];\n status: \"unavailable\";\n }\n> {\n const notification = await input.api.notifyRouteCatalogChanged({\n agentProfileId: input.agentProfileId,\n reason: \"agent_profile_binding_changed\",\n requestContext: input.requestContext,\n });\n if (!notification.ok || notification.notifiedSessions < 1) {\n return {\n reasonCodes: [\"agent_profile_binding.local_service_not_connected\"],\n status: \"unavailable\",\n };\n }\n\n const readiness = await waitForExecutionReadinessAfterBinding(input);\n if (!readiness) {\n return {\n reasonCodes: [\"agent_profile_binding.execution_readiness_pending\"],\n status: \"unavailable\",\n };\n }\n if (isAgentExecutionReadyOrConnecting(readiness.agentExecutionReadiness)) {\n return {\n reasonCodes: readiness.agentExecutionReadiness.reasonCodes,\n status: \"accepted\",\n };\n }\n return {\n reasonCodes: readiness.agentExecutionReadiness.reasonCodes,\n status: \"unavailable\",\n };\n}\n\nasync function waitForExecutionReadinessAfterBinding(input: {\n agentProfileId: string;\n api: AgentProfileBindingApi;\n requestContext: OpenMeldRequestContext;\n}): Promise<GetAgentExecutionReadinessResponse | null> {\n let latest: GetAgentExecutionReadinessResponse | null = null;\n for (\n let attempt = 1;\n attempt <= EXECUTION_READINESS_AFTER_BINDING_MAX_ATTEMPTS;\n attempt++\n ) {\n latest = await input.api.getExecutionReadiness({\n agentProfileId: input.agentProfileId,\n requestContext: input.requestContext,\n });\n if (isAgentExecutionReadyOrConnecting(latest.agentExecutionReadiness)) {\n return latest;\n }\n await sleep(computeRetryDelayMs(attempt));\n }\n return latest;\n}\n\nexport async function syncAgentProfileRuntimeBindingFromCurrentReadiness(input: {\n agentControllerConversationId?: string | null;\n profile: OpenMeldProfile;\n}): Promise<{\n agentProfileBindingEnsure: AgentProfileRuntimeBindingEnsureResult;\n runtimeReportSubmission: RuntimeAgentControllerReportSubmission;\n}> {\n if (input.profile.profileKind !== \"agent\") {\n const runtimeReportSubmission: RuntimeAgentControllerReportSubmission = {\n reason: \"agent_controller_ref_unavailable\",\n reasonCodes: [\"runtime.reporting.profile_not_agent\"],\n source: \"runtime_reporting_api\",\n status: \"unavailable\",\n };\n return {\n agentProfileBindingEnsure: await ensureAgentProfileRuntimeBinding({\n agentControllerConversationId: input.agentControllerConversationId,\n profile: input.profile,\n runtimeReportSubmission,\n }),\n runtimeReportSubmission,\n };\n }\n\n const snapshot = await resolveCurrentReplyReadinessSnapshot({\n checkGatewayChain: true,\n includeDaemonRouteObservation: true,\n openClawDiagnosticsMode: \"repair\",\n ownerUserId: input.profile.ownerUserId,\n profile: input.profile,\n });\n const serviceReadiness = resolveServiceParticipationReadiness({\n deviceReplyReadiness: snapshot.deviceReplyReadiness,\n inventory: snapshot.inventory,\n runtimeStatus: snapshot.displayRuntimeStatus ?? snapshot.runtimeStatus,\n });\n const assessment = assessActionParticipationCandidate({\n profileId: input.profile.openMeldProfileId,\n profileName: input.profile.profileName,\n profileKind: input.profile.profileKind,\n localParticipationReadiness: serviceReadiness.serviceReadiness,\n localParticipationReasonCodes: snapshot.deviceReplyReadiness.reasonCodes,\n });\n const runtimeReportSubmission =\n await submitProfileRuntimeAgentControllerReport({\n localParticipationState: assessment.localParticipationState,\n profile: input.profile,\n reasonCodes: assessment.reasonCodes,\n });\n return {\n agentProfileBindingEnsure: await ensureAgentProfileRuntimeBinding({\n agentControllerConversationId: input.agentControllerConversationId,\n profile: input.profile,\n runtimeReportSubmission,\n }),\n runtimeReportSubmission,\n };\n}\n\nfunction tryResolveBindingInput(\n submission: RuntimeAgentControllerReportSubmission\n): {\n agentControllerRef: string;\n deviceId: string;\n lane: string;\n openMeldServiceRuntimeId: {\n source: \"runtime_registry_authority\";\n value: string;\n };\n} | null {\n if (\n submission.status !== \"submitted\" ||\n submission.agentControllerReportStatus !== \"accepted\" ||\n !submission.agentControllerRef ||\n !submission.deviceId ||\n !submission.lane ||\n !submission.openMeldServiceRuntimeId\n ) {\n return null;\n }\n\n let openMeldServiceRuntimeId: {\n source: \"runtime_registry_authority\";\n value: string;\n };\n try {\n openMeldServiceRuntimeId = createAuthorityOpenMeldServiceRuntimeId({\n openMeldServiceRuntimeId: submission.openMeldServiceRuntimeId,\n source: \"runtime_registry_authority\",\n });\n } catch {\n return null;\n }\n\n return {\n agentControllerRef: submission.agentControllerRef,\n deviceId: submission.deviceId,\n lane: submission.lane,\n openMeldServiceRuntimeId,\n };\n}\n\nfunction uniqueReasonCodes(reasonCodes: readonly string[]): string[] {\n return [...new Set(reasonCodes)];\n}\n\n// Lead the reason-code list with a truthful support code (never a success\n// code) while preserving the rest for diagnostics, so consumers that read\n// reasonCodes[0] see the blocker.\nfunction orderReasonCodesBySupportRelevance(input: {\n reason: string;\n reasonCodes: readonly string[];\n}): string[] {\n const supportCode = selectAssistantBindingSupportCode({\n reason: input.reason,\n reasonCodes: input.reasonCodes,\n });\n return uniqueReasonCodes([supportCode, ...input.reasonCodes]);\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n const message = error.message.trim();\n return message.length > 0 ? message : \"unknown error\";\n }\n const message = String(error ?? \"\").trim();\n return message.length > 0 ? message : \"unknown error\";\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { isCancel, select, text } from \"@clack/prompts\";\nimport type { AgentControllerPermissionMode } from \"@openmeld/schemas/types\";\nimport {\n createOpenMeldAgentProfile,\n createOpenMeldHumanProfile,\n getOpenMeldProfileCapabilities,\n type OpenMeldProfile,\n} from \"../config/openmeld-profiles-api\";\nimport { assertAdditionalHumanProfileCreationEnabled } from \"../config/profile-creation-capability\";\nimport { resolveOpenMeldProfileOrNull } from \"../config/resolve-openmeld-profile\";\nimport { resolveLocalAgentControllerReportInput } from \"../local-service/reporting/local-agent-controller-report-resolution\";\nimport { submitRuntimeAgentControllerReport } from \"../local-service/reporting/runtime-agent-controller-reporting-submission\";\nimport { createProfileCreateGuideError } from \"../runtime/dual-view-guide-catalog\";\nimport { ensureAgentProfileRuntimeBinding } from \"../system/ensure-agent-profile-runtime-binding\";\nimport { promptTextEntry } from \"../ui/text-entry\";\n\nconst CREATE_PROFILE_KIND_EXIT_VALUE = \"__create_profile_kind_exit__\";\nconst CREATE_PROFILE_KIND_BACK_VALUE = \"__create_profile_kind_back__\";\n\nexport type CreateProfileKind = \"human\" | \"agent\";\nexport const DEFAULT_CREATE_PROFILE_NAME_PLACEHOLDERS = {\n human: \"openmeld-ceo\",\n agent: \"my-codex-researcher\",\n} as const satisfies Record<CreateProfileKind, string>;\nexport type CreateProfilePromptResult<T> =\n | {\n status: \"submitted\";\n value: T;\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n };\n\ntype CreateProfileNamePlaceholderResolver =\n | Partial<Record<CreateProfileKind, string>>\n | ((profileKind: CreateProfileKind) => string | undefined);\n\nexport type CreateProfileLocalAgentSelection = {\n agentControllerPermissionMode?: AgentControllerPermissionMode;\n agentControllerConversationId?: string;\n agentControllerRef?: string;\n controllerEnabled?: boolean;\n modelId?: string;\n reasoningLevel?: string;\n};\n\nexport function normalizeCreateProfileKind(\n value: string | undefined\n): CreateProfileKind | null {\n const normalized = String(value ?? \"\")\n .trim()\n .toLowerCase();\n if (!normalized) {\n return null;\n }\n if (normalized === \"human\" || normalized === \"agent\") {\n return normalized;\n }\n throw new Error(\"invalid --kind value: use human|agent\");\n}\n\nexport function assertCreateProfileKindAllowedInView(input: {\n profileKind: CreateProfileKind;\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (input.resolvedView === \"agent\" && input.profileKind === \"human\") {\n throw createProfileCreateGuideError(\n \"agent view cannot create human profiles; switch to human view for human profile creation.\"\n );\n }\n}\n\nexport async function resolveCreateProfileKind(input: {\n explicitKind: string | undefined;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n promptMessage?: string;\n allowBack?: boolean;\n backLabel?: string;\n exitLabel?: string;\n}): Promise<CreateProfilePromptResult<CreateProfileKind>> {\n const explicitKind = normalizeCreateProfileKind(input.explicitKind);\n if (explicitKind) {\n assertCreateProfileKindAllowedInView({\n profileKind: explicitKind,\n resolvedView: input.resolvedView,\n });\n if (explicitKind === \"human\") {\n await assertAdditionalHumanProfileCreationAvailable(input.resolvedView);\n }\n return {\n status: \"submitted\",\n value: explicitKind,\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createProfileCreateGuideError(\n \"agent view requires explicit --kind and only supports creating agent profiles.\"\n );\n }\n throw new Error(\n \"missing required argument '--kind <human|agent>' for openmeld profile create\"\n );\n }\n\n const { additionalHumanProfileCreationEnabled } =\n await resolveAdditionalHumanProfileCreationCapability(input.resolvedView);\n const kindOptions =\n input.resolvedView === \"agent\" || !additionalHumanProfileCreationEnabled\n ? [\n {\n value: \"agent\",\n label: \"Agent\",\n },\n ]\n : [\n {\n value: \"human\",\n label: \"Human\",\n },\n {\n value: \"agent\",\n label: \"Agent\",\n },\n ];\n const selectedKind = await select({\n message: input.promptMessage ?? \"Profile kind\",\n options: [\n ...kindOptions,\n {\n value:\n input.allowBack === true\n ? CREATE_PROFILE_KIND_BACK_VALUE\n : CREATE_PROFILE_KIND_EXIT_VALUE,\n label:\n input.allowBack === true\n ? (input.backLabel ?? \"Back\")\n : (input.exitLabel ?? \"Exit\"),\n },\n ],\n });\n if (isCancel(selectedKind)) {\n return {\n status: \"cancelled\",\n };\n }\n if (selectedKind === CREATE_PROFILE_KIND_BACK_VALUE) {\n return {\n status: \"back\",\n };\n }\n if (selectedKind === CREATE_PROFILE_KIND_EXIT_VALUE) {\n return {\n status: \"cancelled\",\n };\n }\n\n if (!(selectedKind === \"human\" || selectedKind === \"agent\")) {\n throw new Error(\"invalid profile kind selection\");\n }\n if (selectedKind === \"human\" && !additionalHumanProfileCreationEnabled) {\n assertAdditionalHumanProfileCreationEnabled({\n additionalHumanProfileCreationEnabled,\n });\n }\n assertCreateProfileKindAllowedInView({\n profileKind: selectedKind,\n resolvedView: input.resolvedView,\n });\n return {\n status: \"submitted\",\n value: selectedKind,\n };\n}\n\nasync function assertAdditionalHumanProfileCreationAvailable(\n resolvedView: \"human\" | \"agent\"\n): Promise<void> {\n const capability =\n await resolveAdditionalHumanProfileCreationCapability(resolvedView);\n assertAdditionalHumanProfileCreationEnabled({\n additionalHumanProfileCreationEnabled:\n capability.additionalHumanProfileCreationEnabled,\n cause: capability.failure,\n });\n}\n\nasync function resolveAdditionalHumanProfileCreationCapability(\n resolvedView: \"human\" | \"agent\"\n): Promise<{\n additionalHumanProfileCreationEnabled: boolean;\n failure: unknown | null;\n}> {\n if (resolvedView === \"agent\") {\n return {\n additionalHumanProfileCreationEnabled: false,\n failure: null,\n };\n }\n try {\n return {\n ...(await getOpenMeldProfileCapabilities()),\n failure: null,\n };\n } catch (error) {\n console.warn(\n \"[openmeld.profile_capabilities.read_failed]\",\n toProfileCapabilityFailureDiagnostic(error)\n );\n return {\n additionalHumanProfileCreationEnabled: false,\n failure: error,\n };\n }\n}\n\nfunction toProfileCapabilityFailureDiagnostic(error: unknown): {\n cause: string | null;\n code: string | null;\n endpoint: string | null;\n message: string;\n name: string;\n status: number | null;\n} {\n const record =\n error && typeof error === \"object\"\n ? (error as Record<string, unknown>)\n : null;\n const cause = record?.cause;\n return {\n cause: cause instanceof Error ? cause.message : null,\n code: typeof record?.code === \"string\" ? record.code : null,\n endpoint: typeof record?.endpoint === \"string\" ? record.endpoint : null,\n message: error instanceof Error ? error.message : String(error),\n name: error instanceof Error ? error.name : typeof error,\n status: typeof record?.status === \"number\" ? record.status : null,\n };\n}\n\nexport async function resolveCreateProfileName(input: {\n explicitProfileName: string | undefined;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n profileKind?: CreateProfileKind;\n promptMessage?: string;\n promptPlaceholder?: string;\n allowBack?: boolean;\n backLabel?: string;\n}): Promise<CreateProfilePromptResult<string>> {\n const fromInput = String(input.explicitProfileName ?? \"\").trim();\n if (fromInput) {\n return {\n status: \"submitted\",\n value: fromInput,\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createProfileCreateGuideError(\n \"agent view requires explicit profile name (<profileName> or --name).\"\n );\n }\n throw new Error(\n \"missing required argument 'profileName' for openmeld profile create\"\n );\n }\n\n const promptPlaceholder =\n input.promptPlaceholder ??\n (input.profileKind\n ? DEFAULT_CREATE_PROFILE_NAME_PLACEHOLDERS[input.profileKind]\n : DEFAULT_CREATE_PROFILE_NAME_PLACEHOLDERS.agent);\n\n if (input.allowBack === true) {\n const value = await promptTextEntry({\n message: input.promptMessage ?? \"Profile name\",\n placeholder: promptPlaceholder,\n allowBack: true,\n backLabel: input.backLabel ?? \"Back\",\n requiredMessage: \"Profile name is required.\",\n });\n if (value.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (value.status === \"back\") {\n return {\n status: \"back\",\n };\n }\n return {\n status: \"submitted\",\n value: value.value.trim(),\n };\n }\n\n const value = await text({\n message: input.promptMessage ?? \"Profile name\",\n placeholder: promptPlaceholder,\n });\n if (isCancel(value)) {\n return {\n status: \"cancelled\",\n };\n }\n\n const profileName = String(value ?? \"\").trim();\n if (!profileName) {\n throw new Error(\"profileName is required\");\n }\n\n return {\n status: \"submitted\",\n value: profileName,\n };\n}\n\nexport async function resolveCreateProfileIdentity(input: {\n explicitKind: string | undefined;\n explicitProfileName: string | undefined;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n kindPromptMessage?: string;\n namePromptMessage?: string;\n namePromptPlaceholder?: CreateProfileNamePlaceholderResolver;\n allowBackFromKind?: boolean;\n kindBackLabel?: string;\n kindExitLabel?: string;\n allowBackFromNameToKind?: boolean;\n nameBackLabel?: string;\n}): Promise<\n CreateProfilePromptResult<{\n profileKind: CreateProfileKind;\n profileName: string;\n }>\n> {\n while (true) {\n const profileKind = await resolveCreateProfileKind({\n explicitKind: input.explicitKind,\n allowPrompt: input.allowPrompt,\n resolvedView: input.resolvedView,\n promptMessage: input.kindPromptMessage,\n allowBack: input.allowBackFromKind === true,\n backLabel: input.kindBackLabel,\n exitLabel: input.kindExitLabel,\n });\n if (profileKind.status !== \"submitted\") {\n return profileKind;\n }\n\n const profileName = await resolveCreateProfileName({\n explicitProfileName: input.explicitProfileName,\n allowPrompt: input.allowPrompt,\n resolvedView: input.resolvedView,\n profileKind: profileKind.value,\n promptMessage: input.namePromptMessage,\n promptPlaceholder: resolveCreateProfileNamePlaceholder({\n source: input.namePromptPlaceholder,\n profileKind: profileKind.value,\n }),\n allowBack: input.allowBackFromNameToKind === true,\n backLabel: input.nameBackLabel,\n });\n if (profileName.status === \"back\") {\n continue;\n }\n if (profileName.status !== \"submitted\") {\n return profileName;\n }\n\n return {\n status: \"submitted\",\n value: {\n profileKind: profileKind.value,\n profileName: profileName.value,\n },\n };\n }\n}\n\nexport async function createProfileByKind(input: {\n profileName: string;\n profileKind: CreateProfileKind;\n localAgentSelection?: CreateProfileLocalAgentSelection;\n}): Promise<OpenMeldProfile> {\n // OPENMELD_SETUP_TO_WAKE_PATH: HIGHEST_FACT user-confirmed-profile\n // Runtime discovery must not auto-create Agent Profiles. Agent Profiles come\n // from user intent, either directly or through a Setup Agent the user approved.\n const creatorProfileId = await resolveCurrentCreatorProfileId();\n if (input.profileKind === \"human\") {\n if (input.localAgentSelection) {\n throw new Error(\"--agent-controller can only be used with --kind agent\");\n }\n return createOpenMeldHumanProfile({\n profileName: input.profileName,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n });\n }\n const created = await createOpenMeldAgentProfile({\n profileName: input.profileName,\n ...(creatorProfileId ? { creatorProfileId } : {}),\n });\n if (input.localAgentSelection?.controllerEnabled !== false) {\n await bindCreatedAgentProfileToLocalRuntime({\n localAgentSelection: input.localAgentSelection,\n profile: created,\n });\n }\n return created;\n}\n\nasync function bindCreatedAgentProfileToLocalRuntime(input: {\n localAgentSelection: CreateProfileLocalAgentSelection | undefined;\n profile: OpenMeldProfile;\n}): Promise<void> {\n if (!input.localAgentSelection) {\n return;\n }\n const agentControllerRef = resolveCreateProfileAgentControllerRef(\n input.localAgentSelection\n );\n if (!agentControllerRef) {\n return;\n }\n const runtimeReportSubmission = await submitRuntimeAgentControllerReport(\n await resolveLocalAgentControllerReportInput({\n agentControllerRef,\n diagnosticProfileId: input.profile.openMeldProfileId,\n requireEnabled: false,\n })\n );\n await ensureAgentProfileRuntimeBinding({\n agentControllerPermissionMode:\n input.localAgentSelection.agentControllerPermissionMode,\n agentControllerConversationId:\n input.localAgentSelection.agentControllerConversationId,\n confirmLocalExecutionEvidence: false,\n modelId: input.localAgentSelection.modelId,\n profile: input.profile,\n reasoningLevel: input.localAgentSelection.reasoningLevel,\n runtimeReportSubmission,\n });\n}\n\nfunction resolveCreateProfileAgentControllerRef(\n selection: CreateProfileLocalAgentSelection\n): string | null {\n return normalizeOptionalText(selection.agentControllerRef);\n}\n\nasync function resolveCurrentCreatorProfileId(): Promise<string | null> {\n const currentProfile = await resolveOpenMeldProfileOrNull({\n allowDefaultFallback: true,\n allowUnauthenticated: true,\n persistSelection: false,\n }).catch(() => null);\n return currentProfile?.openMeldProfileId ?? null;\n}\n\nfunction resolveCreateProfileNamePlaceholder(input: {\n source?: CreateProfileNamePlaceholderResolver;\n profileKind: CreateProfileKind;\n}): string | undefined {\n if (!input.source) {\n return undefined;\n }\n if (typeof input.source === \"function\") {\n return input.source(input.profileKind);\n }\n return input.source[input.profileKind];\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { readFile } from \"node:fs/promises\";\nimport {\n buildTargetWakeLifecycleId,\n executionContextSelectionSchema,\n} from \"@openmeld/schemas\";\nimport type { ExecutionContextSelection } from \"@openmeld/schemas/types\";\nimport {\n createSpaceSendInputConflictGuideError,\n createSpaceSendInputEmptyGuideError,\n createSpaceSendInputFileReadFailedGuideError,\n createSpaceSendInputRequiredGuideError,\n} from \"../runtime/dual-view-guide-catalog\";\n\ntype ResolveSpaceSendTextInput = {\n allowEmpty?: boolean;\n text?: string;\n stdin?: boolean;\n file?: string;\n readFromStdin?: () => Promise<string>;\n readFromFile?: (path: string) => Promise<string>;\n};\n\nexport function resolveSpaceTaskSelection(input: {\n space: string;\n wakeTargets?: readonly string[];\n newTask?: boolean;\n forkFrom?: string;\n continueFrom?: string;\n taskAccess?: string;\n taskWorkspace?: string;\n}): ExecutionContextSelection | undefined {\n const modes =\n Number(input.newTask === true) +\n Number(Boolean(input.forkFrom)) +\n Number(Boolean(input.continueFrom));\n if (modes === 0 && !input.taskAccess && !input.taskWorkspace) {\n return undefined;\n }\n if (modes > 1) {\n throw new Error(\n \"Choose only one of --new-task, --fork-from, or --continue-from.\"\n );\n }\n const targetProfileId = input.wakeTargets?.[0];\n if (!targetProfileId || input.wakeTargets?.length !== 1) {\n throw new Error(\"Task selection requires exactly one --wake <profile-id>.\");\n }\n if (input.continueFrom && (input.taskAccess || input.taskWorkspace)) {\n throw new Error(\n \"A continued task keeps its original file access and workspace. Start a new task to change them.\"\n );\n }\n const sourceSignalId = input.forkFrom ?? input.continueFrom;\n const sourceWakeId = sourceSignalId\n ? buildTargetWakeLifecycleId({\n spaceId: input.space,\n sourceSignalId,\n targetProfileId,\n })\n : undefined;\n const preferences = {\n access: input.taskAccess,\n workspace: input.taskWorkspace,\n };\n let value: unknown;\n if (input.continueFrom) {\n value = { mode: \"resume\", sourceWakeId };\n } else if (input.forkFrom) {\n value = { mode: \"fork\", sourceWakeId, ...preferences };\n } else {\n value = { mode: input.newTask ? \"new\" : \"auto\", ...preferences };\n }\n const parsed = executionContextSelectionSchema.safeParse(value);\n if (!parsed.success) {\n throw new Error(\n parsed.error.issues[0]?.message ?? \"Invalid task selection.\"\n );\n }\n return parsed.data;\n}\n\nexport async function resolveSpaceSendText(\n input: ResolveSpaceSendTextInput\n): Promise<string> {\n const textValue = String(input.text ?? \"\");\n const stdinEnabled = input.stdin === true;\n const filePath = String(input.file ?? \"\").trim();\n\n const hasTextSource = textValue.length > 0;\n const hasFileSource = filePath.length > 0;\n const sourceCount =\n Number(hasTextSource) + Number(stdinEnabled) + Number(hasFileSource);\n\n if (sourceCount === 0) {\n if (input.allowEmpty) {\n return \"\";\n }\n throw createSpaceSendInputRequiredGuideError();\n }\n if (sourceCount > 1) {\n throw createSpaceSendInputConflictGuideError();\n }\n\n let resolvedText = textValue;\n if (hasFileSource) {\n const readFromFile = input.readFromFile ?? readSpaceSendFile;\n try {\n resolvedText = await readFromFile(filePath);\n } catch (error) {\n throw createSpaceSendInputFileReadFailedGuideError(\n filePath,\n toErrorMessage(error)\n );\n }\n }\n if (stdinEnabled) {\n const readFromStdin = input.readFromStdin ?? readSpaceSendStdin;\n resolvedText = await readFromStdin();\n }\n\n if (resolvedText.trim().length === 0 && !input.allowEmpty) {\n throw createSpaceSendInputEmptyGuideError();\n }\n\n return resolvedText;\n}\n\nfunction readSpaceSendFile(path: string): Promise<string> {\n return readFile(path, \"utf8\");\n}\n\nfunction readSpaceSendStdin(): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n const chunks: string[] = [];\n\n const cleanup = () => {\n process.stdin.off(\"data\", onData);\n process.stdin.off(\"end\", onEnd);\n process.stdin.off(\"error\", onError);\n };\n\n const onData = (chunk: string | Buffer) => {\n if (typeof chunk === \"string\") {\n chunks.push(chunk);\n return;\n }\n chunks.push(chunk.toString(\"utf8\"));\n };\n\n const onEnd = () => {\n cleanup();\n resolve(chunks.join(\"\"));\n };\n\n const onError = (error: Error) => {\n cleanup();\n reject(error);\n };\n\n process.stdin.setEncoding(\"utf8\");\n process.stdin.on(\"data\", onData);\n process.stdin.on(\"end\", onEnd);\n process.stdin.on(\"error\", onError);\n process.stdin.resume();\n });\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n return String(error ?? \"unknown error\");\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport pc from \"picocolors\";\nimport {\n formatOpenMeldCliCommand,\n resolveUserFacingCliEntryCommand,\n} from \"../runtime/cli-entry-command\";\nimport { formatCliVersionSummary } from \"../runtime/cli-version\";\nimport { outLine } from \"./io\";\nimport {\n ROOT_ENTRY_COMMANDS,\n ROOT_ENTRY_START_COMMAND,\n} from \"./root-entry-catalog\";\n\nconst ANSI_RESET = \"\\x1b[0m\";\nconst LOGO_SCALE = 1;\nconst LOGO_COLORS = [\n \"\\x1b[38;5;250m\",\n \"\\x1b[38;5;248m\",\n \"\\x1b[38;5;246m\",\n \"\\x1b[38;5;244m\",\n \"\\x1b[38;5;242m\",\n \"\\x1b[38;5;240m\",\n];\n\nconst OPENMELD_LOGO_LINES = [\n \" ██████╗ ██████╗ ███████╗███╗ ██╗███╗ ███╗███████╗██╗ ██████╗\",\n \"██╔═══██╗██╔══██╗██╔════╝████╗ ██║████╗ ████║██╔════╝██║ ██╔══██╗\",\n \"██║ ██║██████╔╝█████╗ ██╔██╗ ██║██╔████╔██║█████╗ ██║ ██║ ██║\",\n \"██║ ██║██╔═══╝ ██╔══╝ ██║╚██╗██║██║╚██╔╝██║██╔══╝ ██║ ██║ ██║\",\n \"╚██████╔╝██║ ███████╗██║ ╚████║██║ ╚═╝ ██║███████╗███████╗██████╔╝\",\n \" ╚═════╝ ╚═╝ ╚══════╝╚═╝ ╚═══╝╚═╝ ╚═╝╚══════╝╚══════╝╚═════╝ \",\n];\nconst OPENMELD_SUBTITLE_LINES = [\n \"OPENMELD CLI • https://openmeld.ai\",\n \"People and agents, working as one.\",\n];\nconst OPENMELD_CLI_NPX_COMMAND = \"npx -y openmeld@latest\";\nconst GLOBAL_INSTALL_COMMAND = \"npm install -g openmeld\";\nconst GLOBAL_INSTALL_SHORTCUT_COMMAND = \"openmeld start\";\nexport const OPENMELD_BRAND_SURFACE_BG_RGB = [20, 56, 60] as const;\nexport const OPENMELD_COMPOSER_SURFACE_BG_RGB = [38, 38, 38] as const;\n\nexport function renderOpenMeldLogo(): string {\n const useColor = pc.isColorSupported;\n const scaled = scaleMonospaceBlock(OPENMELD_LOGO_LINES, LOGO_SCALE);\n return scaled\n .map((line, index) => {\n if (!useColor) {\n return line;\n }\n const sourceIndex = Math.floor(index / LOGO_SCALE);\n const color =\n LOGO_COLORS[sourceIndex] ?? LOGO_COLORS.at(-1) ?? \"\\x1b[37m\";\n return `${color}${line}${ANSI_RESET}`;\n })\n .join(\"\\n\");\n}\n\nexport function renderOpenMeldHeader(): string {\n return `${renderOpenMeldLogo()}\\n${renderOpenMeldTagline()}`;\n}\n\nexport function renderOpenMeldBrandBlockLines(): string[] {\n return [\n ...renderOpenMeldLogo().split(\"\\n\"),\n ...renderOpenMeldTagline().split(\"\\n\"),\n pc.dim(formatCliVersionSummary()),\n ];\n}\n\nexport function renderOpenMeldBrandAccent(text: string): string {\n return pc.bold(pc.cyan(text));\n}\n\nexport function printOpenMeldBanner(): void {\n const startCallToAction = `${pc.dim(\"Try this first:\")} ${pc.bold(\n pc.cyan(formatOpenMeldCliCommand(ROOT_ENTRY_START_COMMAND))\n )}`;\n outLine(\"\");\n for (const line of renderOpenMeldBrandBlockLines()) {\n outLine(line);\n }\n outLine(\"\");\n for (const line of renderThinCalloutBox(startCallToAction)) {\n outLine(line);\n }\n if (shouldRenderGlobalInstallHint()) {\n outLine(\"\");\n for (const line of renderThinCalloutBox(buildGlobalInstallHintLines())) {\n outLine(line);\n }\n }\n outLine(\"\");\n for (const item of ROOT_ENTRY_COMMANDS) {\n outLine(\n ` ${pc.dim(\"$\")} ${pc.cyan(formatOpenMeldCliCommand(item.command))} ${pc.dim(item.description)}`\n );\n }\n outLine(\"\");\n}\n\nexport function renderOpenMeldTagline(): string {\n return OPENMELD_SUBTITLE_LINES.map((line) =>\n renderOpenMeldBrandAccent(line)\n ).join(\"\\n\");\n}\n\nfunction scaleMonospaceBlock(lines: string[], factor: number): string[] {\n if (factor <= 1) {\n return [...lines];\n }\n\n const output: string[] = [];\n for (const line of lines) {\n const scaledLine = [...line].map((char) => char.repeat(factor)).join(\"\");\n for (let i = 0; i < factor; i += 1) {\n output.push(scaledLine);\n }\n }\n return output;\n}\n\nfunction shouldRenderGlobalInstallHint(): boolean {\n return resolveUserFacingCliEntryCommand() === OPENMELD_CLI_NPX_COMMAND;\n}\n\nfunction buildGlobalInstallHintLines(): string[] {\n return [\n pc.dim(\"Install OpenMeld globally for shorter commands:\"),\n pc.bold(pc.cyan(GLOBAL_INSTALL_COMMAND)),\n `${pc.dim(\"After install, use:\")} ${pc.bold(\n pc.cyan(GLOBAL_INSTALL_SHORTCUT_COMMAND)\n )}`,\n ];\n}\n\nfunction renderThinCalloutBox(content: string | string[]): string[] {\n const lines = Array.isArray(content) ? content : [content];\n const innerWidth =\n Math.max(...lines.map((line) => stripAnsi(line).length), 0) + 2;\n return [\n `${pc.dim(\"┌\")}${pc.dim(\"─\".repeat(innerWidth))}${pc.dim(\"┐\")}`,\n ...lines.map((line) => {\n const padding = \" \".repeat(innerWidth - stripAnsi(line).length - 1);\n return `${pc.dim(\"│\")} ${line}${padding}${pc.dim(\"│\")}`;\n }),\n `${pc.dim(\"└\")}${pc.dim(\"─\".repeat(innerWidth))}${pc.dim(\"┘\")}`,\n ];\n}\n\nfunction stripAnsi(value: string): string {\n return stripVTControlCharacters(value);\n}\n","import {\n type BuiltinAgentControllerBrand,\n resolveBuiltinAgentControllerBrand,\n} from \"@openmeld/schemas\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport pc from \"picocolors\";\nimport { OPENMELD_COMPOSER_SURFACE_BG_RGB } from \"./brand\";\nimport { sanitizeTerminalDisplayText } from \"./terminal-safe-text\";\n\nexport type ProfileColorIdentityLike =\n | {\n agentControllerRef?: string;\n identityKey?: string;\n profileId?: string;\n profileName?: string;\n kind?: string;\n }\n | undefined;\n\nexport type DisplayProfileColorInput = {\n agentControllerRef?: string | null;\n kind?: string | null;\n profileKind?: string | null;\n owner?: string | null;\n ownerName?: string | null;\n ownerUserId?: string | null;\n openMeldProfileId?: string | null;\n profileId?: string | null;\n profileName?: string | null;\n};\n\nexport type PersonColorIdentityInput = {\n ownerUserId?: string | null;\n ownerName?: string | null;\n profileId?: string | null;\n profileName?: string | null;\n};\n\nexport type AgentColorIdentityInput = {\n agentControllerRef?: string | null;\n profileId?: string | null;\n profileName?: string | null;\n};\n\nexport type ProfileNameColorInput =\n | {\n label: string;\n target: \"display-profile\";\n profileIdentity: DisplayProfileColorInput | undefined;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n | {\n label: string;\n target: \"person\";\n personIdentity: PersonColorIdentityInput;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n | {\n label: string;\n target: \"agent\";\n agentIdentity: AgentColorIdentityInput;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n | {\n label: string;\n target: \"resolved\";\n profileIdentity: ProfileColorIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n };\n\ntype ColorizeFn = (input: string | number | null | undefined) => string;\ntype RgbColor = {\n r: number;\n g: number;\n b: number;\n};\n/**\n * Global, identity-stable fallback palettes.\n *\n * Space-aware surfaces should pass a members snapshot so every visible profile\n * name in that Space shares one scoped palette. When no snapshot is available,\n * we fall back to these deterministic global anchors.\n */\nconst PERSON_PROFILE_ACCENT_HUE_ANCHORS = [\n 18, 36, 54, 72, 94, 116, 138, 160, 182, 204, 226, 248, 270, 292, 314, 336,\n 350, 106, 150,\n] as const;\nconst AGENT_PROFILE_ACCENT_HUE_ANCHORS = [\n 8, 28, 48, 68, 88, 110, 134, 158, 184, 208, 232, 256, 280, 304, 328, 344, 196,\n 40, 120,\n] as const;\nconst PROFILE_ACCENT_HUE_STEP_DEGREES = 11;\nconst PROFILE_ACCENT_VARIANTS = 4;\nconst SPACE_SCOPED_BASE_HUE = 24;\nconst SPACE_SCOPED_GOLDEN_ANGLE_DEGREES = 137.508;\nconst SPACE_SCOPED_PRIMARY_HUE_STEP_DEGREES = 15;\nconst SPACE_SCOPED_MIN_CANDIDATE_COUNT = 24;\nconst SPACE_SCOPED_WRAP_COUNT = 3;\nconst SPACE_SCOPED_WRAP_SHIFT_DEGREES = 17;\nexport const HUMAN_PROFILE_NAME_COLOR_ENABLED = false;\n\ntype ProfileColorScope = {\n hueByIdentity: Map<string, number>;\n};\n\ntype DisplayProfileColorTarget = {\n kind: \"agent\" | \"person\";\n identity: ProfileColorIdentityLike;\n};\n\nconst profileColorScopeCache = new WeakMap<\n SpaceMembersSnapshot,\n ProfileColorScope\n>();\n\n/**\n * Low-level primitive. UI call sites should prefer the higher-level helpers\n * below so person-vs-agent identity resolution stays in one place.\n */\nexport function colorizeProfileLabel(\n label: string,\n profileIdentity: ProfileColorIdentityLike,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): string {\n if (!shouldColorizeProfileIdentity(profileIdentity)) {\n return sanitizeSingleLineText(label);\n }\n\n const colorize = toAnsiTrueColorColorize(\n resolveProfileAccentRgb(label, profileIdentity, options)\n );\n return colorize(sanitizeSingleLineText(label));\n}\n\nexport function resolveProfileAccentRgb(\n label: string,\n profileIdentity: ProfileColorIdentityLike,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): RgbColor {\n const builtinControllerBrand =\n resolveBuiltinAgentControllerBrandForIdentity(profileIdentity);\n if (builtinControllerBrand) {\n const [r, g, b] = builtinControllerBrand.accentRgb;\n return { r, g, b };\n }\n\n return toStableProfileRgb(\n resolveProfileColorKey(label, profileIdentity),\n profileIdentity,\n options?.spaceMembersSnapshot ?? null\n );\n}\n\nexport function resolveProfileSurfaceRgb(\n label: string,\n profileIdentity: ProfileColorIdentityLike,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): RgbColor {\n const builtinControllerBrand =\n resolveBuiltinAgentControllerBrandForIdentity(profileIdentity);\n if (builtinControllerBrand) {\n return deriveBuiltinControllerBrandSurfaceRgb(builtinControllerBrand);\n }\n\n if (profileIdentity?.kind === \"agent\") {\n return {\n r: OPENMELD_COMPOSER_SURFACE_BG_RGB[0],\n g: OPENMELD_COMPOSER_SURFACE_BG_RGB[1],\n b: OPENMELD_COMPOSER_SURFACE_BG_RGB[2],\n };\n }\n\n const paletteSeed = resolveProfilePaletteSeed(\n label,\n profileIdentity,\n options?.spaceMembersSnapshot ?? null\n );\n const saturation = 22 + (Math.floor(paletteSeed.hash / 53) % 8);\n const lightness = 18 + (Math.floor(paletteSeed.hash / 131) % 5);\n return hslToRgb(paletteSeed.hue, saturation / 100, lightness / 100);\n}\n\nexport function resolvePersonColorIdentity(\n input: PersonColorIdentityInput\n): ProfileColorIdentityLike {\n const ownerUserId = sanitizeSingleLineText(input.ownerUserId).trim();\n const ownerName = sanitizeSingleLineText(input.ownerName).trim();\n const profileId = sanitizeSingleLineText(input.profileId).trim();\n const profileName = sanitizeSingleLineText(input.profileName).trim();\n\n return {\n identityKey: ownerUserId || profileId || undefined,\n profileId: profileId || undefined,\n profileName: ownerName || profileName || undefined,\n kind: \"human\",\n };\n}\n\nexport function resolveAgentColorIdentity(\n input: AgentColorIdentityInput\n): ProfileColorIdentityLike {\n const agentControllerRef = sanitizeSingleLineText(\n input.agentControllerRef\n ).trim();\n const profileId = sanitizeSingleLineText(input.profileId).trim();\n const profileName = sanitizeSingleLineText(input.profileName).trim();\n const builtinControllerBrand =\n resolveBuiltinAgentControllerBrand(agentControllerRef);\n\n return {\n agentControllerRef: agentControllerRef || undefined,\n identityKey: builtinControllerBrand\n ? `builtin-controller:${builtinControllerBrand.controllerId}`\n : profileId || undefined,\n profileId: profileId || undefined,\n profileName: profileName || undefined,\n kind: \"agent\",\n };\n}\n\nexport function resolveDisplayProfileIdentity(input: {\n profileIdentity: DisplayProfileColorInput | undefined;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): DisplayProfileColorInput {\n const profileIdentity = normalizeDisplayProfileColorInput(\n input.profileIdentity\n );\n const profileKind = resolveDisplayProfileKind(profileIdentity);\n if (!input.spaceMembersSnapshot) {\n return profileIdentity;\n }\n\n if (profileKind === \"human\") {\n if (profileIdentity.ownerUserId || profileIdentity.ownerName) {\n return profileIdentity;\n }\n\n const matchingHumanSnapshot = findMatchingHumanSnapshot({\n profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n if (!matchingHumanSnapshot) {\n return profileIdentity;\n }\n\n return {\n ...profileIdentity,\n ownerUserId: matchingHumanSnapshot.ownerUserId ?? undefined,\n ownerName: matchingHumanSnapshot.ownerName ?? undefined,\n };\n }\n\n if (profileKind === \"agent\" && !profileIdentity.agentControllerRef) {\n const matchingAgentSnapshot = findMatchingAgentSnapshot({\n profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n if (matchingAgentSnapshot) {\n return {\n ...profileIdentity,\n agentControllerRef:\n matchingAgentSnapshot.agentControllerRef ?? undefined,\n };\n }\n }\n\n return profileIdentity;\n}\n\nexport function resolveDisplayProfileColorIdentity(input: {\n profileIdentity: DisplayProfileColorInput | undefined;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): ProfileColorIdentityLike {\n return resolveDisplayProfileColorTarget(input).identity;\n}\n\nexport function colorizeDisplayProfileLabel(input: {\n label: string;\n profileIdentity: DisplayProfileColorInput | undefined;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string {\n return colorizeProfileName({\n label: input.label,\n target: \"display-profile\",\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n}\n\nexport function colorizePersonLabel(\n label: string,\n personIdentity: PersonColorIdentityInput,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): string {\n return colorizeProfileName({\n label,\n target: \"person\",\n personIdentity,\n spaceMembersSnapshot: options?.spaceMembersSnapshot,\n });\n}\n\nexport function colorizeAgentLabel(\n label: string,\n agentIdentity: AgentColorIdentityInput,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): string {\n return colorizeProfileName({\n label,\n target: \"agent\",\n agentIdentity,\n spaceMembersSnapshot: options?.spaceMembersSnapshot,\n });\n}\n\nexport function colorizeResolvedProfileLabel(\n label: string,\n profileIdentity: ProfileColorIdentityLike,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): string {\n return colorizeProfileName({\n label,\n target: \"resolved\",\n profileIdentity,\n spaceMembersSnapshot: options?.spaceMembersSnapshot,\n });\n}\n\nexport function resolveDisplayProfileSurfaceRgb(input: {\n label: string;\n profileIdentity: DisplayProfileColorInput | undefined;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): RgbColor {\n return resolveProfileNameSurfaceRgb({\n label: input.label,\n target: \"display-profile\",\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n}\n\nexport function resolvePersonSurfaceRgb(\n label: string,\n personIdentity: PersonColorIdentityInput,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): RgbColor {\n return resolveProfileNameSurfaceRgb({\n label,\n target: \"person\",\n personIdentity,\n spaceMembersSnapshot: options?.spaceMembersSnapshot,\n });\n}\n\nexport function resolveAgentSurfaceRgb(\n label: string,\n agentIdentity: AgentColorIdentityInput,\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): RgbColor {\n return resolveProfileNameSurfaceRgb({\n label,\n target: \"agent\",\n agentIdentity,\n spaceMembersSnapshot: options?.spaceMembersSnapshot,\n });\n}\n\n/**\n * Single source of truth for every visible profile-name color in OpenMeld CLI.\n * Call sites must pass the semantic identity they are rendering:\n * - \"person\" for human/owner names\n * - \"agent\" for agent-profile names\n * - \"display-profile\" when the call site only has a generic profile identity\n */\nexport function colorizeProfileName(input: ProfileNameColorInput): string {\n const profileIdentity = resolveProfileNameColorIdentity(input);\n if (!shouldColorizeProfileIdentity(profileIdentity)) {\n return sanitizeSingleLineText(input.label);\n }\n\n return colorizeProfileLabel(input.label, profileIdentity, {\n spaceMembersSnapshot:\n \"spaceMembersSnapshot\" in input ? input.spaceMembersSnapshot : null,\n });\n}\n\nexport function resolveProfileNameColorIdentity(\n input: ProfileNameColorInput\n): ProfileColorIdentityLike {\n switch (input.target) {\n case \"display-profile\":\n return resolveDisplayProfileColorIdentity({\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n case \"person\":\n return resolvePersonColorIdentity(input.personIdentity);\n case \"agent\":\n return resolveAgentColorIdentity(input.agentIdentity);\n case \"resolved\":\n return input.profileIdentity;\n default:\n return undefined;\n }\n}\n\nexport function resolveProfileNameSurfaceRgb(\n input: ProfileNameColorInput\n): RgbColor {\n return resolveProfileSurfaceRgb(\n input.label,\n resolveProfileNameColorIdentity(input),\n {\n spaceMembersSnapshot:\n \"spaceMembersSnapshot\" in input ? input.spaceMembersSnapshot : null,\n }\n );\n}\n\nconst sanitizeSingleLineText = (\n value: string | number | null | undefined\n): string => sanitizeTerminalDisplayText(value, \"single-line\");\n\nfunction resolveProfileColorKey(\n label: string,\n profileIdentity: ProfileColorIdentityLike\n): string {\n const identityKey = sanitizeSingleLineText(\n profileIdentity?.identityKey\n ).trim();\n if (identityKey) {\n return identityKey.toLowerCase();\n }\n const profileId = sanitizeSingleLineText(profileIdentity?.profileId).trim();\n if (profileId) {\n return profileId.toLowerCase();\n }\n const profileName =\n sanitizeSingleLineText(profileIdentity?.profileName).trim() ||\n sanitizeSingleLineText(label).trim() ||\n \"unknown\";\n const profileKind = sanitizeSingleLineText(profileIdentity?.kind).trim();\n return `${profileName.toLowerCase()}::${profileKind.toLowerCase()}`;\n}\n\nfunction resolveBuiltinAgentControllerBrandForIdentity(\n profileIdentity: ProfileColorIdentityLike\n): BuiltinAgentControllerBrand | null {\n if (profileIdentity?.kind !== \"agent\") {\n return null;\n }\n\n return resolveBuiltinAgentControllerBrand(profileIdentity.agentControllerRef);\n}\n\nfunction shouldColorizeProfileIdentity(\n profileIdentity: ProfileColorIdentityLike\n): boolean {\n if (profileIdentity?.kind === \"human\") {\n return HUMAN_PROFILE_NAME_COLOR_ENABLED;\n }\n\n if (profileIdentity?.kind === \"agent\") {\n return (\n resolveBuiltinAgentControllerBrandForIdentity(profileIdentity) !== null\n );\n }\n\n return true;\n}\n\nfunction stableHash(value: string): number {\n let hash = 0;\n for (const char of value) {\n hash = (hash * 131 + char.charCodeAt(0)) % 2_147_483_647;\n }\n return hash;\n}\n\nfunction toStableProfileRgb(\n key: string,\n profileIdentity: ProfileColorIdentityLike,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): RgbColor {\n const paletteSeed = resolveProfilePaletteSeed(\n key,\n profileIdentity,\n spaceMembersSnapshot\n );\n const saturation = 58 + (Math.floor(paletteSeed.hash / 359) % 18);\n const lightness = 52 + (Math.floor(paletteSeed.hash / 131) % 12);\n return hslToRgb(paletteSeed.hue, saturation / 100, lightness / 100);\n}\n\nfunction resolveProfilePaletteSeed(\n label: string,\n profileIdentity: ProfileColorIdentityLike,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): { hash: number; hue: number } {\n const colorKey = resolveProfileColorKey(label, profileIdentity);\n const hash = stableHash(colorKey);\n const scopedHue = resolveSpaceScopedProfileHue({\n colorKey,\n spaceMembersSnapshot,\n });\n if (scopedHue !== null) {\n return {\n hash,\n hue: scopedHue,\n };\n }\n const hueAnchors = resolveProfileAccentHueAnchors(profileIdentity);\n const anchor = hueAnchors[hash % hueAnchors.length] ?? 210;\n const variant =\n Math.floor(hash / hueAnchors.length) % PROFILE_ACCENT_VARIANTS;\n const hueOffset =\n (variant - Math.floor(PROFILE_ACCENT_VARIANTS / 2)) *\n PROFILE_ACCENT_HUE_STEP_DEGREES;\n\n return {\n hash,\n hue: normalizeHue(anchor + hueOffset),\n };\n}\n\nfunction resolveProfileAccentHueAnchors(\n profileIdentity: ProfileColorIdentityLike\n): readonly number[] {\n return profileIdentity?.kind === \"agent\"\n ? AGENT_PROFILE_ACCENT_HUE_ANCHORS\n : PERSON_PROFILE_ACCENT_HUE_ANCHORS;\n}\n\nfunction resolveSpaceScopedProfileHue(input: {\n colorKey: string;\n spaceMembersSnapshot: SpaceMembersSnapshot | null;\n}): number | null {\n const snapshot = input.spaceMembersSnapshot;\n if (!snapshot) {\n return null;\n }\n\n const scope = resolveProfileColorScope(snapshot);\n return scope.hueByIdentity.get(input.colorKey) ?? null;\n}\n\nfunction resolveProfileColorScope(\n snapshot: SpaceMembersSnapshot\n): ProfileColorScope {\n const cachedScope = profileColorScopeCache.get(snapshot);\n if (cachedScope) {\n return cachedScope;\n }\n\n const scope: ProfileColorScope = {\n hueByIdentity: buildScopedHueAssignments({\n baseHue: resolveSpaceScopedBaseHue(snapshot.spaceId),\n identities: collectScopedColorIdentities(snapshot),\n }),\n };\n profileColorScopeCache.set(snapshot, scope);\n return scope;\n}\n\nfunction buildScopedHueAssignments(input: {\n baseHue: number;\n identities: readonly ProfileColorIdentityLike[];\n}): Map<string, number> {\n const uniqueColorKeys = [\n ...new Set(\n input.identities\n .map((identity) =>\n resolveProfileColorKey(identity?.profileName ?? \"\", identity)\n )\n .filter((colorKey) => colorKey.length > 0)\n ),\n ].sort((left, right) => {\n const leftHash = stableHash(left);\n const rightHash = stableHash(right);\n if (leftHash !== rightHash) {\n return leftHash - rightHash;\n }\n return left.localeCompare(right);\n });\n\n const assignments = new Map<string, number>();\n const assignedHues: number[] = [];\n const candidateHues = buildSpaceScopedHueCandidates(input.baseHue);\n for (const [index, colorKey] of uniqueColorKeys.entries()) {\n const preferredHue = resolveSpaceScopedPreferredHue({\n baseHue: input.baseHue,\n colorKey,\n index,\n });\n const assignedHue = chooseSpaceScopedHue({\n assignedHues,\n candidateHues,\n preferredHue,\n });\n assignments.set(colorKey, assignedHue);\n assignedHues.push(assignedHue);\n }\n return assignments;\n}\n\nfunction buildSpaceScopedHueCandidates(baseHue: number): readonly number[] {\n const candidates = new Set<number>();\n\n for (\n let stepIndex = 0;\n stepIndex < SPACE_SCOPED_MIN_CANDIDATE_COUNT;\n stepIndex += 1\n ) {\n const stepHue = stepIndex * SPACE_SCOPED_PRIMARY_HUE_STEP_DEGREES;\n for (\n let wrapIndex = 0;\n wrapIndex < SPACE_SCOPED_WRAP_COUNT;\n wrapIndex += 1\n ) {\n candidates.add(\n normalizeHue(\n baseHue + stepHue + wrapIndex * SPACE_SCOPED_WRAP_SHIFT_DEGREES\n )\n );\n }\n }\n\n return [...candidates];\n}\n\nfunction resolveSpaceScopedPreferredHue(input: {\n baseHue: number;\n colorKey: string;\n index: number;\n}): number {\n return normalizeHue(\n input.baseHue +\n stableHash(input.colorKey) +\n input.index * Math.round(SPACE_SCOPED_GOLDEN_ANGLE_DEGREES)\n );\n}\n\nfunction chooseSpaceScopedHue(input: {\n assignedHues: readonly number[];\n candidateHues: readonly number[];\n preferredHue: number;\n}): number {\n if (input.assignedHues.length === 0) {\n return (\n input.candidateHues\n .toSorted(\n (left, right) =>\n circularHueDistance(left, input.preferredHue) -\n circularHueDistance(right, input.preferredHue) || left - right\n )\n .at(0) ?? input.preferredHue\n );\n }\n\n return (\n input.candidateHues\n .toSorted((left, right) => {\n const leftMinDistance = resolveMinimumAssignedHueDistance(\n left,\n input.assignedHues\n );\n const rightMinDistance = resolveMinimumAssignedHueDistance(\n right,\n input.assignedHues\n );\n if (leftMinDistance !== rightMinDistance) {\n return rightMinDistance - leftMinDistance;\n }\n\n const leftPreferredDistance = circularHueDistance(\n left,\n input.preferredHue\n );\n const rightPreferredDistance = circularHueDistance(\n right,\n input.preferredHue\n );\n if (leftPreferredDistance !== rightPreferredDistance) {\n return leftPreferredDistance - rightPreferredDistance;\n }\n\n return left - right;\n })\n .at(0) ?? input.preferredHue\n );\n}\n\nfunction resolveMinimumAssignedHueDistance(\n hue: number,\n assignedHues: readonly number[]\n): number {\n let minimumDistance = Number.POSITIVE_INFINITY;\n for (const assignedHue of assignedHues) {\n minimumDistance = Math.min(\n minimumDistance,\n circularHueDistance(hue, assignedHue)\n );\n }\n return Number.isFinite(minimumDistance) ? minimumDistance : 0;\n}\n\nfunction circularHueDistance(left: number, right: number): number {\n const distance = Math.abs(normalizeHue(left) - normalizeHue(right));\n return Math.min(distance, 360 - distance);\n}\n\nfunction collectScopedColorIdentities(\n snapshot: SpaceMembersSnapshot\n): ProfileColorIdentityLike[] {\n const identities: ProfileColorIdentityLike[] = [];\n\n for (const human of snapshot.humans) {\n identities.push(\n resolvePersonColorIdentity({\n ownerUserId: human.ownerUserId,\n ownerName: human.ownerName,\n profileId: human.profileId,\n profileName: human.profileName,\n })\n );\n }\n\n for (const agent of snapshot.agents) {\n identities.push(\n resolveAgentColorIdentity({\n agentControllerRef: agent.agentControllerRef,\n profileId: agent.profileId,\n profileName: agent.profileName,\n })\n );\n identities.push(\n resolvePersonColorIdentity({\n ownerUserId: agent.ownerUserId,\n ownerName: agent.ownerName,\n profileName: agent.ownerName,\n })\n );\n identities.push(\n resolvePersonColorIdentity({\n ownerUserId: agent.addedByOwnerUserId,\n ownerName: agent.addedByDisplayName,\n profileId: agent.addedByProfileId,\n profileName: agent.addedByDisplayName,\n })\n );\n }\n\n return identities;\n}\n\nfunction normalizeHue(value: number): number {\n const normalized = value % 360;\n return normalized >= 0 ? normalized : normalized + 360;\n}\n\nfunction deriveBuiltinControllerBrandSurfaceRgb(\n brand: BuiltinAgentControllerBrand\n): RgbColor {\n const [red, green, blue] = brand.accentRgb;\n const { hue } = rgbToHsl(red, green, blue);\n return hslToRgb(hue, 0.24, 0.18);\n}\n\nfunction resolveSpaceScopedBaseHue(spaceId: string): number {\n const normalizedSpaceId = sanitizeSingleLineText(spaceId)\n .trim()\n .toLowerCase();\n if (!normalizedSpaceId) {\n return SPACE_SCOPED_BASE_HUE;\n }\n\n return normalizeHue(\n SPACE_SCOPED_BASE_HUE +\n (stableHash(normalizedSpaceId) %\n Math.round(SPACE_SCOPED_GOLDEN_ANGLE_DEGREES))\n );\n}\n\nfunction hslToRgb(\n hue: number,\n saturation: number,\n lightness: number\n): RgbColor {\n const chroma = (1 - Math.abs(2 * lightness - 1)) * saturation;\n const huePrime = hue / 60;\n const second = chroma * (1 - Math.abs((huePrime % 2) - 1));\n\n let red = 0;\n let green = 0;\n let blue = 0;\n\n if (huePrime >= 0 && huePrime < 1) {\n red = chroma;\n green = second;\n } else if (huePrime < 2) {\n red = second;\n green = chroma;\n } else if (huePrime < 3) {\n green = chroma;\n blue = second;\n } else if (huePrime < 4) {\n green = second;\n blue = chroma;\n } else if (huePrime < 5) {\n red = second;\n blue = chroma;\n } else {\n red = chroma;\n blue = second;\n }\n\n const match = lightness - chroma / 2;\n return {\n r: Math.round((red + match) * 255),\n g: Math.round((green + match) * 255),\n b: Math.round((blue + match) * 255),\n };\n}\n\nfunction rgbToHsl(\n red: number,\n green: number,\n blue: number\n): {\n hue: number;\n lightness: number;\n saturation: number;\n} {\n const normalizedRed = red / 255;\n const normalizedGreen = green / 255;\n const normalizedBlue = blue / 255;\n const max = Math.max(normalizedRed, normalizedGreen, normalizedBlue);\n const min = Math.min(normalizedRed, normalizedGreen, normalizedBlue);\n const chroma = max - min;\n const lightness = (max + min) / 2;\n\n if (chroma === 0) {\n return { hue: 0, lightness, saturation: 0 };\n }\n\n const saturation = chroma / (1 - Math.abs(2 * lightness - 1));\n\n let huePrime = 0;\n if (max === normalizedRed) {\n huePrime = (normalizedGreen - normalizedBlue) / chroma;\n } else if (max === normalizedGreen) {\n huePrime = (normalizedBlue - normalizedRed) / chroma + 2;\n } else {\n huePrime = (normalizedRed - normalizedGreen) / chroma + 4;\n }\n\n return {\n hue: normalizeHue(huePrime * 60),\n lightness,\n saturation,\n };\n}\n\nfunction toAnsiTrueColorColorize(color: RgbColor): ColorizeFn {\n if (!pc.isColorSupported) {\n return (value: string | number | null | undefined) => String(value ?? \"\");\n }\n const open = `\\u001B[38;2;${String(color.r)};${String(color.g)};${String(color.b)}m`;\n const close = \"\\u001B[39m\";\n return (value: string | number | null | undefined) =>\n `${open}${String(value ?? \"\")}${close}`;\n}\n\nfunction resolveDisplayProfileColorTarget(input: {\n profileIdentity: DisplayProfileColorInput | undefined;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): DisplayProfileColorTarget {\n const profileIdentity = resolveDisplayProfileIdentity(input);\n return resolveDisplayProfileKind(profileIdentity) === \"agent\"\n ? {\n kind: \"agent\",\n identity: resolveAgentColorIdentity({\n agentControllerRef: profileIdentity.agentControllerRef,\n profileId:\n profileIdentity.profileId ?? profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n }),\n }\n : {\n kind: \"person\",\n identity: resolvePersonColorIdentity({\n ownerUserId: profileIdentity.ownerUserId,\n ownerName: profileIdentity.ownerName,\n profileId:\n profileIdentity.profileId ?? profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n }),\n };\n}\n\nfunction resolveDisplayProfileKind(\n profileIdentity: DisplayProfileColorInput | undefined\n): \"human\" | \"agent\" | \"system\" | \"\" {\n const normalizedKind = sanitizeSingleLineText(\n profileIdentity?.kind ?? profileIdentity?.profileKind\n )\n .trim()\n .toLowerCase();\n if (\n normalizedKind === \"human\" ||\n normalizedKind === \"agent\" ||\n normalizedKind === \"system\"\n ) {\n return normalizedKind;\n }\n return \"\";\n}\n\nfunction normalizeDisplayProfileColorInput(\n profileIdentity: DisplayProfileColorInput | undefined\n): DisplayProfileColorInput {\n if (!profileIdentity) {\n return {};\n }\n\n const profileId = sanitizeSingleLineText(\n profileIdentity.openMeldProfileId ?? profileIdentity.profileId\n ).trim();\n const profileName = sanitizeSingleLineText(\n profileIdentity.profileName\n ).trim();\n const agentControllerRef = sanitizeSingleLineText(\n profileIdentity.agentControllerRef\n ).trim();\n const owner = sanitizeSingleLineText(profileIdentity.owner).trim();\n const ownerUserId = sanitizeSingleLineText(\n profileIdentity.ownerUserId\n ).trim();\n const ownerName = sanitizeSingleLineText(profileIdentity.ownerName).trim();\n const kind = sanitizeSingleLineText(\n profileIdentity.kind ?? profileIdentity.profileKind\n ).trim();\n\n return {\n ...(kind ? { kind } : {}),\n ...(agentControllerRef ? { agentControllerRef } : {}),\n ...(owner ? { owner } : {}),\n ...(ownerName ? { ownerName } : {}),\n ...(ownerUserId ? { ownerUserId } : {}),\n ...(profileId ? { profileId } : {}),\n ...(profileName ? { profileName } : {}),\n };\n}\n\nfunction findMatchingHumanSnapshot(input: {\n profileIdentity: DisplayProfileColorInput;\n spaceMembersSnapshot: SpaceMembersSnapshot;\n}) {\n const profileId = sanitizeSingleLineText(\n input.profileIdentity.openMeldProfileId ?? input.profileIdentity.profileId\n ).trim();\n if (!profileId) {\n return null;\n }\n return (\n input.spaceMembersSnapshot.humans.find(\n (humanSnapshot) =>\n humanSnapshot.status === \"active\" &&\n sanitizeSingleLineText(humanSnapshot.profileId).trim() === profileId\n ) ?? null\n );\n}\n\nfunction findMatchingAgentSnapshot(input: {\n profileIdentity: DisplayProfileColorInput;\n spaceMembersSnapshot: SpaceMembersSnapshot;\n}) {\n const profileId = sanitizeSingleLineText(\n input.profileIdentity.openMeldProfileId ?? input.profileIdentity.profileId\n ).trim();\n if (!profileId) {\n return null;\n }\n\n return (\n input.spaceMembersSnapshot.agents.find(\n (agentSnapshot) =>\n agentSnapshot.status === \"active\" &&\n sanitizeSingleLineText(agentSnapshot.profileId).trim() === profileId\n ) ?? null\n );\n}\n","import { isCancel, select } from \"@clack/prompts\";\nimport {\n buildAgentControllerRef,\n resolveSelectableCandidates,\n} from \"@openmeld/agent-runtime\";\nimport { resolveLocalRegistryAgentIdFromAgentControllerRef } from \"../agents/controller-identity\";\nimport {\n type AgentTargetState,\n listAgentTargetStates,\n updateAgentRegistrations,\n} from \"../agents/registry\";\nimport {\n createDefaultRuntimeAgentControllerSettings,\n type RuntimeAgentTransportMode,\n} from \"../config/runtime-config\";\nimport { promptSearchSelect, type SearchSelectItem } from \"../ui/search-select\";\n\nconst AGENT_PROFILE_SETUP_SKIP = \"__agent_profile_setup_skip__\";\nconst AGENT_PROFILE_SETUP_BACK = \"__agent_profile_setup_back__\";\nconst AGENT_PROFILE_RESPONSE_POLICY_MENTION_ONLY = \"mention_only\";\n\ntype EnabledBuiltinControllerCandidate = AgentTargetState & {\n targetKind: \"builtin\";\n};\n\ntype EnabledBuiltinControllerCandidatesResolution = {\n candidates: EnabledBuiltinControllerCandidate[];\n error?: string;\n};\n\nexport type AgentProfileSetupResult =\n | {\n status: \"configured\";\n agentControllerRef: string;\n controllerDisplayName: string;\n transportMode: RuntimeAgentTransportMode;\n responsePolicy: \"mention_only\";\n selectionMode: \"interactive\" | \"auto_first_available\";\n }\n | {\n status: \"skipped_no_enabled_controllers\";\n reason?: string;\n }\n | {\n status: \"skipped_by_user\";\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n };\n\ntype AgentControllerSelectionResult =\n | {\n status: \"selected\";\n candidate: EnabledBuiltinControllerCandidate;\n selectionMode: \"interactive\" | \"auto_first_available\";\n }\n | {\n status: \"skipped\";\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n };\n\ntype AgentTransportModeSelectionResult =\n | {\n status: \"submitted\";\n transportMode: RuntimeAgentTransportMode;\n prompted: boolean;\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n };\n\ntype AgentResponsePolicySelectionResult =\n | {\n status: \"submitted\";\n responsePolicy: \"mention_only\";\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n };\n\nexport async function resolveAgentProfileSetup(input: {\n interactive: boolean;\n useAutoSelectionWhenNonInteractive: boolean;\n selectControllerMessage?: string;\n selectTransportModeMessage?: string;\n selectResponsePolicyMessage?: string;\n skipControllerOptionLabel?: string;\n allowBackToCaller?: boolean;\n}): Promise<AgentProfileSetupResult> {\n const enabledCandidates = await resolveEnabledBuiltinCandidatesForSetup();\n\n if (enabledCandidates.candidates.length === 0) {\n return {\n status: \"skipped_no_enabled_controllers\",\n ...(enabledCandidates.error ? { reason: enabledCandidates.error } : {}),\n };\n }\n\n while (true) {\n const selectedController = await resolveAgentControllerSelection({\n interactive: input.interactive,\n useAutoSelectionWhenNonInteractive:\n input.useAutoSelectionWhenNonInteractive,\n candidates: enabledCandidates.candidates,\n message:\n input.selectControllerMessage ??\n \"Choose which agent controller this profile should use.\",\n skipOptionLabel: input.skipControllerOptionLabel ?? \"Skip for now\",\n allowBack: input.allowBackToCaller === true,\n });\n if (selectedController.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (selectedController.status === \"back\") {\n return {\n status: \"back\",\n };\n }\n if (selectedController.status === \"skipped\") {\n return {\n status: \"skipped_by_user\",\n };\n }\n\n const configuredController = await resolveConfiguredAgentController({\n interactive: input.interactive,\n selectedController,\n selectTransportModeMessage:\n input.selectTransportModeMessage ??\n \"How should this profile connect to its agent controller?\",\n selectResponsePolicyMessage:\n input.selectResponsePolicyMessage ??\n \"When should this profile auto-reply?\",\n allowResponsePolicyBack: input.allowBackToCaller === true,\n });\n if (configuredController.status === \"retry_controller\") {\n continue;\n }\n return configuredController.result;\n }\n}\n\nexport async function persistAgentTransportSelection(input: {\n agentControllerRef: string;\n transportMode: RuntimeAgentTransportMode;\n}): Promise<void> {\n const localAgentId =\n resolveLocalRegistryAgentIdFromAgentControllerRef({\n agentControllerRef: input.agentControllerRef,\n }) ?? input.agentControllerRef;\n await updateAgentRegistrations((current) => {\n const index = current.findIndex(\n (controller) => controller.agentId === localAgentId\n );\n if (index < 0) {\n return current;\n }\n const controller = current[index];\n if (!controller || controller.transportMode === input.transportMode) {\n return current;\n }\n const next = [...current];\n next[index] = {\n ...controller,\n transportMode: input.transportMode,\n updatedAt: new Date().toISOString(),\n };\n return next;\n });\n}\n\nexport function resolveEnabledBuiltinControllerCandidates(\n states: AgentTargetState[]\n): EnabledBuiltinControllerCandidatesResolution {\n return {\n candidates: resolveSelectableCandidates(states),\n };\n}\n\nasync function resolveEnabledBuiltinCandidatesForSetup(): Promise<EnabledBuiltinControllerCandidatesResolution> {\n return await listAgentTargetStates()\n .then((states) => resolveEnabledBuiltinControllerCandidates(states))\n .catch((error) => ({\n candidates: [],\n error:\n error instanceof Error && error.message.trim().length > 0\n ? error.message.trim()\n : \"agents registry unavailable\",\n }));\n}\n\nasync function resolveConfiguredAgentController(input: {\n interactive: boolean;\n selectedController: Extract<\n AgentControllerSelectionResult,\n { status: \"selected\" }\n >;\n selectTransportModeMessage: string;\n selectResponsePolicyMessage: string;\n allowResponsePolicyBack: boolean;\n}): Promise<\n | {\n status: \"retry_controller\";\n }\n | {\n status: \"resolved\";\n result: AgentProfileSetupResult;\n }\n> {\n while (true) {\n const transportMode = await resolveAgentTransportModeSelection({\n interactive: input.interactive,\n candidate: input.selectedController.candidate,\n message: input.selectTransportModeMessage,\n });\n if (transportMode.status === \"cancelled\") {\n return {\n status: \"resolved\",\n result: {\n status: \"cancelled\",\n },\n };\n }\n if (transportMode.status === \"back\") {\n return {\n status: \"retry_controller\",\n };\n }\n\n const responsePolicy = await resolveAgentResponsePolicy({\n interactive: input.interactive,\n message: input.selectResponsePolicyMessage,\n allowBack: input.allowResponsePolicyBack,\n });\n if (responsePolicy.status === \"cancelled\") {\n return {\n status: \"resolved\",\n result: {\n status: \"cancelled\",\n },\n };\n }\n if (responsePolicy.status === \"back\") {\n if (!transportMode.prompted) {\n return {\n status: \"retry_controller\",\n };\n }\n continue;\n }\n\n return {\n status: \"resolved\",\n result: {\n status: \"configured\",\n agentControllerRef: buildAgentControllerRef({\n kind: \"builtin\",\n id: input.selectedController.candidate.agentId,\n }),\n controllerDisplayName: input.selectedController.candidate.displayName,\n transportMode: transportMode.transportMode,\n responsePolicy: responsePolicy.responsePolicy,\n selectionMode: input.selectedController.selectionMode,\n },\n };\n }\n}\n\nasync function resolveAgentControllerSelection(input: {\n interactive: boolean;\n useAutoSelectionWhenNonInteractive: boolean;\n candidates: EnabledBuiltinControllerCandidate[];\n message: string;\n skipOptionLabel: string;\n allowBack: boolean;\n}): Promise<AgentControllerSelectionResult> {\n if (!input.interactive) {\n if (!input.useAutoSelectionWhenNonInteractive) {\n return {\n status: \"skipped\",\n };\n }\n const candidate = input.candidates[0] ?? null;\n if (!candidate) {\n return {\n status: \"skipped\",\n };\n }\n return {\n status: \"selected\",\n candidate,\n selectionMode: \"auto_first_available\",\n };\n }\n\n const choice = await promptSearchSelect({\n message: input.message,\n items: [\n ...input.candidates.map(buildAgentControllerSearchItem),\n {\n value: AGENT_PROFILE_SETUP_SKIP,\n label: input.skipOptionLabel,\n detail: \"Continue without controller setup.\",\n searchText: `${input.skipOptionLabel} Continue without controller setup`,\n },\n ],\n maxVisible: 8,\n allowBack: input.allowBack,\n backLabel: \"Back\",\n });\n if (choice.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (choice.status === \"back\") {\n return {\n status: \"back\",\n };\n }\n if (choice.status !== \"submitted\") {\n return {\n status: \"skipped\",\n };\n }\n if (choice.value === AGENT_PROFILE_SETUP_SKIP) {\n return {\n status: \"skipped\",\n };\n }\n\n const selectedId = String(choice.value).trim();\n const candidate =\n input.candidates.find((item) => item.agentId === selectedId) ?? null;\n if (!candidate) {\n return {\n status: \"skipped\",\n };\n }\n\n return {\n status: \"selected\",\n candidate,\n selectionMode: \"interactive\",\n };\n}\n\nfunction buildAgentControllerSearchItem(\n candidate: EnabledBuiltinControllerCandidate\n): SearchSelectItem<string> {\n const defaultTransportMode = resolveCandidateDefaultTransportMode(candidate);\n return {\n value: candidate.agentId,\n label: candidate.displayName,\n detail: `ID ${candidate.agentId} · default transport: ${defaultTransportMode}`,\n searchText: [\n candidate.displayName,\n candidate.agentId,\n defaultTransportMode,\n ].join(\" \"),\n };\n}\n\nasync function resolveAgentTransportModeSelection(input: {\n interactive: boolean;\n candidate: EnabledBuiltinControllerCandidate;\n message: string;\n}): Promise<AgentTransportModeSelectionResult> {\n const defaultTransportMode = resolveCandidateDefaultTransportMode(\n input.candidate\n );\n if (input.candidate.transportModes.length <= 1) {\n return {\n status: \"submitted\",\n transportMode: defaultTransportMode,\n prompted: false,\n };\n }\n if (!input.interactive) {\n return {\n status: \"submitted\",\n transportMode: defaultTransportMode,\n prompted: false,\n };\n }\n\n const selected = await select({\n message: input.message,\n options: [\n ...input.candidate.transportModes.map((transportMode) => ({\n value: transportMode.mode,\n label: transportMode.label,\n hint: transportMode.description,\n })),\n {\n value: AGENT_PROFILE_SETUP_BACK,\n label: \"Back\",\n },\n ],\n initialValue: defaultTransportMode,\n });\n if (isCancel(selected)) {\n return {\n status: \"cancelled\",\n };\n }\n if (selected === AGENT_PROFILE_SETUP_BACK) {\n return {\n status: \"back\",\n };\n }\n\n const selectedMode = String(selected).trim();\n const matched = input.candidate.transportModes.find(\n (transportMode) => transportMode.mode === selectedMode\n );\n return {\n status: \"submitted\",\n transportMode: matched?.mode ?? defaultTransportMode,\n prompted: true,\n };\n}\n\nasync function resolveAgentResponsePolicy(input: {\n interactive: boolean;\n message: string;\n allowBack: boolean;\n}): Promise<AgentResponsePolicySelectionResult> {\n if (!input.interactive) {\n return {\n status: \"submitted\",\n responsePolicy: AGENT_PROFILE_RESPONSE_POLICY_MENTION_ONLY,\n };\n }\n\n const selected = await select({\n message: input.message,\n options: [\n {\n value: AGENT_PROFILE_RESPONSE_POLICY_MENTION_ONLY,\n label: \"Only When Mentioned (Default)\",\n hint: \"Auto-reply only when someone explicitly mentions this profile.\",\n },\n ...(input.allowBack\n ? [\n {\n value: AGENT_PROFILE_SETUP_BACK,\n label: \"Back\",\n },\n ]\n : []),\n ],\n initialValue: AGENT_PROFILE_RESPONSE_POLICY_MENTION_ONLY,\n });\n if (isCancel(selected)) {\n return {\n status: \"cancelled\",\n };\n }\n if (selected === AGENT_PROFILE_SETUP_BACK) {\n return {\n status: \"back\",\n };\n }\n return {\n status: \"submitted\",\n responsePolicy: AGENT_PROFILE_RESPONSE_POLICY_MENTION_ONLY,\n };\n}\n\nfunction resolveCandidateDefaultTransportMode(input: {\n agentId: string;\n defaultTransportMode?: RuntimeAgentTransportMode;\n transportModes: Array<{ mode: RuntimeAgentTransportMode }>;\n}): RuntimeAgentTransportMode {\n if (input.defaultTransportMode) {\n return input.defaultTransportMode;\n }\n return (\n input.transportModes[0]?.mode ??\n createDefaultRuntimeAgentControllerSettings(input.agentId).transportMode\n );\n}\n","import { parseAgentControllerRef } from \"@openmeld/schemas\";\nimport { listBuiltinAgentsRegistryEntries } from \"../agents/registry-source\";\nimport { sanitizeTerminalDisplayText } from \"./terminal-safe-text\";\n\nconst MULTI_SPACE_PATTERN = /\\s+/g;\n\nexport function resolveControllerDisplayName(\n agentControllerRef: string | null | undefined\n): string {\n const normalized = sanitizeTerminalDisplayText(\n agentControllerRef,\n \"single-line\"\n )\n .trim()\n .replace(MULTI_SPACE_PATTERN, \" \");\n if (!normalized) {\n return \"\";\n }\n return normalized.startsWith(\"builtin:\")\n ? normalized.slice(\"builtin:\".length)\n : normalized;\n}\n\nexport function resolveHumanControllerDisplayName(input: {\n agentControllerRef: string | null | undefined;\n}): string {\n const normalized = resolveControllerDisplayName(input.agentControllerRef);\n if (!normalized) {\n return \"\";\n }\n\n const builtinAgentId = resolveBuiltinAgentId(input);\n if (!builtinAgentId) {\n return normalized;\n }\n\n const builtinEntry = listBuiltinAgentsRegistryEntries().find(\n (entry) => entry.id === builtinAgentId\n );\n return builtinEntry?.displayName ?? normalized;\n}\n\nfunction resolveBuiltinAgentId(input: {\n agentControllerRef: string | null | undefined;\n}): string | null {\n const parsed = parseAgentControllerRef(input.agentControllerRef);\n return parsed?.kind === \"builtin\" ? parsed.id : null;\n}\n","import type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport type { OpenClawLocalDiagnostics } from \"../provider-hosts/openclaw/diagnostics\";\nimport { formatOpenMeldCliCommand } from \"../runtime/cli-entry-command\";\nimport { resolveGatewayChainRepairGuidance } from \"./gateway-chain-readiness\";\nimport { resolveOpenClawDiagnosticsGuidance } from \"./provider-diagnostics/openclaw/guidance\";\nimport type {\n AgentReplyReadinessStatus,\n ReplyReadinessReasonCode,\n} from \"./reply-readiness\";\nimport {\n REPLY_READINESS_COPY,\n resolveReplyReadinessGuidanceSummaryCopy,\n} from \"./reply-readiness-copy\";\nimport { resolveServiceParticipationReadiness } from \"./service-participation-readiness\";\n\nexport type ReplyReadinessGuidance = {\n primaryReasonCode: ReplyReadinessReasonCode | null;\n summary: string;\n nextSteps: string[];\n};\n\nexport function buildReplyReadinessGuidance(input: {\n openClawLocalDiagnostics?: OpenClawLocalDiagnostics | null;\n profile: OpenMeldProfile;\n replyReadiness: AgentReplyReadinessStatus;\n}): ReplyReadinessGuidance {\n if (input.replyReadiness.replyReadiness === \"ready\") {\n return {\n primaryReasonCode: null,\n summary: REPLY_READINESS_COPY.guidance.readySummary,\n nextSteps: [\n formatOpenMeldCliCommand(\"openmeld space join YOUR_SPACE_ID\"),\n REPLY_READINESS_COPY.guidance.readyMentionInstruction,\n ],\n };\n }\n\n const primaryReasonCode =\n input.replyReadiness.reasonCodes[0] ?? \"route.not_registered\";\n const serviceGuidance = buildServiceReplyReadinessGuidance({\n primaryReasonCode,\n replyReadiness: input.replyReadiness,\n });\n\n if (serviceGuidance) {\n return serviceGuidance;\n }\n\n const openClawGuidance = buildOpenClawReplyReadinessGuidance({\n diagnostics: input.openClawLocalDiagnostics ?? null,\n primaryReasonCode,\n profile: input.profile,\n });\n if (openClawGuidance) {\n return openClawGuidance;\n }\n\n return {\n primaryReasonCode,\n summary: buildReplyReadinessGuidanceSummary(primaryReasonCode),\n nextSteps: buildReplyReadinessNextSteps({\n localAgentId: input.replyReadiness.localAgentId,\n profile: input.profile,\n reasonCode: primaryReasonCode,\n }),\n };\n}\n\nfunction buildOpenClawReplyReadinessGuidance(input: {\n diagnostics: OpenClawLocalDiagnostics | null;\n primaryReasonCode: ReplyReadinessReasonCode;\n profile: OpenMeldProfile;\n}): ReplyReadinessGuidance | null {\n if (\n !input.diagnostics ||\n (input.primaryReasonCode !== \"controller.bootstrap.failed\" &&\n input.primaryReasonCode !== \"controller.gateway.unhealthy\")\n ) {\n return null;\n }\n const guidance = resolveOpenClawDiagnosticsGuidance({\n diagnostics: input.diagnostics,\n profileId: input.profile.openMeldProfileId,\n });\n return {\n primaryReasonCode: input.primaryReasonCode,\n summary: guidance.summary,\n nextSteps: guidance.nextCommands.map((command) =>\n formatOpenMeldCliCommand(command)\n ),\n };\n}\n\nfunction buildServiceReplyReadinessGuidance(input: {\n primaryReasonCode: ReplyReadinessReasonCode;\n replyReadiness: AgentReplyReadinessStatus;\n}): ReplyReadinessGuidance | null {\n switch (input.primaryReasonCode) {\n case \"service.not_installed\":\n case \"service.drifted\":\n case \"service.not_running\":\n case \"dispatch.storage_not_ready\":\n case \"service.gateway_chain_unhealthy\": {\n const serviceParticipationReadiness =\n resolveServiceParticipationReadiness({\n deviceReplyReadiness: input.replyReadiness.deviceReplyReadiness,\n });\n return {\n primaryReasonCode: input.primaryReasonCode,\n summary: serviceParticipationReadiness.detailText,\n nextSteps: serviceParticipationReadiness.nextSteps,\n };\n }\n default:\n return null;\n }\n}\n\nfunction buildReplyReadinessGuidanceSummary(\n reasonCode: ReplyReadinessReasonCode\n): string {\n return resolveReplyReadinessGuidanceSummaryCopy(reasonCode);\n}\n\nfunction buildReplyReadinessNextSteps(input: {\n localAgentId?: string | null;\n profile: OpenMeldProfile;\n reasonCode: ReplyReadinessReasonCode;\n}): string[] {\n const profileId = input.profile.openMeldProfileId;\n\n switch (input.reasonCode) {\n case \"local_agents.none_needed\":\n return [\n formatOpenMeldCliCommand(\"openmeld start\"),\n formatOpenMeldCliCommand(\"openmeld service install\"),\n formatOpenMeldCliCommand(\"openmeld service start\"),\n ];\n case \"profile.inactive\":\n return [\n formatOpenMeldCliCommand(\"openmeld profile list\"),\n formatOpenMeldCliCommand(\"openmeld profile set <agent-profile-id>\"),\n ];\n case \"profile.unbound\":\n return [REPLY_READINESS_COPY.guidance.selectProfileAgentInstruction];\n case \"controller.binding.disabled\":\n return [REPLY_READINESS_COPY.guidance.turnOnProfileAgentInstruction];\n case \"projection.missing\":\n return [\n formatOpenMeldCliCommand(\n `openmeld service status --profile ${profileId}`\n ),\n ];\n case \"controller.registry.disabled\":\n return [\n formatOpenMeldCliCommand(\"openmeld agents enable --agent <agent-id>\"),\n formatOpenMeldCliCommand(\"openmeld agents list\"),\n ];\n case \"controller.launch.choice_required\":\n return buildLocalAgentInstallChoiceNextSteps({\n localAgentId: input.localAgentId,\n });\n case \"controller.launch.needs_repair\":\n return buildLocalAgentLaunchRepairNextSteps({\n localAgentId: input.localAgentId,\n });\n case \"workspace.missing\":\n case \"workspace.invalid\":\n return buildLocalAgentLaunchRepairNextSteps({\n localAgentId: input.localAgentId,\n });\n case \"runtime.adapter.unsupported\":\n return [\n formatOpenMeldCliCommand(\"openmeld agents detect\"),\n formatOpenMeldCliCommand(\"openmeld agents list\"),\n ];\n case \"controller.bootstrap.failed\":\n return [\n ...buildLocalAgentLaunchRepairNextSteps({\n localAgentId: input.localAgentId,\n }),\n formatOpenMeldCliCommand(\"openclaw agents list\"),\n ];\n case \"controller.gateway.unhealthy\":\n return [\n ...buildLocalAgentLaunchRepairNextSteps({\n localAgentId: input.localAgentId,\n }),\n formatOpenMeldCliCommand(\"openclaw health --json\"),\n ];\n case \"route.offline\":\n return [\n formatOpenMeldCliCommand(\n `openmeld service status --profile ${profileId}`\n ),\n formatOpenMeldCliCommand(\"openmeld service repair\"),\n ];\n case \"route.not_registered\":\n return [\n formatOpenMeldCliCommand(\n `openmeld service status --profile ${profileId}`\n ),\n formatOpenMeldCliCommand(\"openmeld doctor --repair\"),\n ];\n case \"service.gateway_chain_unhealthy\":\n return resolveGatewayChainRepairGuidance({}).nextSteps;\n case \"dispatch.storage_not_ready\":\n return resolveGatewayChainRepairGuidance({\n failureKind: \"dispatch_storage_not_ready\",\n }).nextSteps;\n default:\n return [formatOpenMeldCliCommand(\"openmeld doctor --repair\")];\n }\n}\n\nfunction buildLocalAgentInstallChoiceNextSteps(input: {\n localAgentId?: string | null;\n}): string[] {\n const agentId = normalizeOptionalText(input.localAgentId);\n if (!agentId) {\n return [\n formatOpenMeldCliCommand(\"openmeld agents enable --agent <agent-id>\"),\n formatOpenMeldCliCommand(\"openmeld agents list\"),\n ];\n }\n\n return [\n formatOpenMeldCliCommand(`openmeld agents enable --agent ${agentId}`),\n formatOpenMeldCliCommand(`openmeld agents repair --agent ${agentId}`),\n ];\n}\n\nfunction buildLocalAgentLaunchRepairNextSteps(input: {\n localAgentId?: string | null;\n}): string[] {\n const agentId = normalizeOptionalText(input.localAgentId);\n if (!agentId) {\n return [\n formatOpenMeldCliCommand(\"openmeld agents repair --agent <agent-id>\"),\n formatOpenMeldCliCommand(\"openmeld agents list\"),\n ];\n }\n\n return [\n formatOpenMeldCliCommand(`openmeld agents repair --agent ${agentId}`),\n ];\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import {\n buildAgentControllerRef,\n parseAgentControllerRef,\n} from \"@openmeld/agent-runtime\";\nimport { resolveAgentTargetState } from \"../agents/registry\";\nimport { resolveRegistryRuntimeAdapterContractByAgentControllerRef } from \"../agents/registry-source\";\nimport {\n type AgentsEnableResult,\n type AgentsRepairResult,\n runAgentsEnable,\n runAgentsRepair,\n} from \"../commands/agents\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport {\n createDefaultRuntimeAgentControllerSettings,\n type RuntimeAgentTransportMode,\n} from \"../config/runtime-config\";\nimport { syncDeviceRuntimeStateProjection } from \"../local-service/reporting/device-runtime-state-sync\";\nimport { resolveLocalAgentControllerReportInput } from \"../local-service/reporting/local-agent-controller-report-resolution\";\nimport {\n type RuntimeAgentControllerReportSubmission,\n submitRuntimeAgentControllerReport,\n} from \"../local-service/reporting/runtime-agent-controller-reporting-submission\";\nimport type { SelectedAgentControllerReportResult } from \"../local-service/reporting/selected-agent-controller-reporting\";\nimport {\n persistAgentTransportSelection,\n resolveAgentProfileSetup,\n} from \"../profile/agent-setup-flow\";\nimport { resolveAgentProfilePrimaryAgentControllerReport } from \"./agent-profile-primary-binding\";\nimport { resolveCurrentReplyReadinessSnapshot } from \"./current-reply-readiness-snapshot\";\nimport {\n type AgentProfileRuntimeBindingEnsureResult,\n ensureAgentProfileRuntimeBinding,\n} from \"./ensure-agent-profile-runtime-binding\";\nimport {\n type ProfileWorkspaceStateSyncResult,\n syncProfileWorkspaceState,\n} from \"./profile-workspace-state\";\n\ntype LocalAgentReadinessPreparationStatus =\n | \"prepared\"\n | \"unchanged\"\n | \"cancelled\";\n\nexport type LocalAgentReadinessPreparationResult = {\n preparedConnections: PreparedAgentProfileConnection[];\n status: LocalAgentReadinessPreparationStatus;\n profiles: OpenMeldProfile[];\n};\n\nexport type PreparedAgentProfileConnection = {\n agentProfileBindingEnsure: AgentProfileRuntimeBindingEnsureResult;\n profileId: string;\n runtimeReport: SelectedAgentControllerReportResult;\n};\n\ntype ProfileReadinessSnapshot = Awaited<\n ReturnType<typeof resolveProfileReadinessSnapshot>\n>;\n\nexport async function prepareLocalAgentReadiness(input: {\n explicitLocalAgentSelections?: ReadonlyMap<string, string>;\n profiles: readonly OpenMeldProfile[];\n interactive: boolean;\n view?: string;\n}): Promise<LocalAgentReadinessPreparationResult> {\n const nextProfiles: OpenMeldProfile[] = [];\n const preparedConnections: PreparedAgentProfileConnection[] = [];\n let preparedAny = false;\n\n for (const profile of input.profiles) {\n if (profile.profileKind !== \"agent\") {\n nextProfiles.push(profile);\n continue;\n }\n\n const result = await prepareSingleAgentProfile({\n profile,\n explicitLocalAgentId: input.explicitLocalAgentSelections?.get(\n profile.openMeldProfileId\n ),\n interactive: input.interactive,\n view: input.view,\n });\n if (result.status === \"cancelled\") {\n return {\n preparedConnections,\n status: \"cancelled\",\n profiles: nextProfiles,\n };\n }\n if (result.status === \"prepared\") {\n preparedAny = true;\n }\n if (result.preparedConnection) {\n preparedConnections.push(result.preparedConnection);\n }\n nextProfiles.push(result.profile);\n }\n\n return {\n preparedConnections,\n status: preparedAny ? \"prepared\" : \"unchanged\",\n profiles: nextProfiles,\n };\n}\n\nasync function prepareSingleAgentProfile(input: {\n explicitLocalAgentId?: string;\n profile: OpenMeldProfile;\n interactive: boolean;\n view?: string;\n}): Promise<{\n preparedConnection?: PreparedAgentProfileConnection;\n status: LocalAgentReadinessPreparationStatus;\n profile: OpenMeldProfile;\n}> {\n const profile = input.profile;\n let prepared = false;\n let preparedConnection: PreparedAgentProfileConnection | undefined;\n let snapshot = await resolveProfileReadinessSnapshot(profile);\n if (input.explicitLocalAgentId) {\n preparedConnection = await bindAgentProfileToExplicitLocalAgent({\n localAgentId: input.explicitLocalAgentId,\n profile,\n });\n prepared = true;\n snapshot = await resolveProfileReadinessSnapshot(profile);\n }\n const initialReasonCodes = collectPreparationReasonCodes(snapshot);\n\n if (\n !input.explicitLocalAgentId &&\n needsControllerSetup({ profile, reasonCodes: initialReasonCodes })\n ) {\n if (!input.interactive) {\n return {\n status: \"unchanged\",\n profile,\n };\n }\n\n const setupResult = await resolveAgentProfileSetup({\n interactive: true,\n useAutoSelectionWhenNonInteractive: false,\n selectControllerMessage:\n \"Choose which local agent this profile should use on this device.\",\n selectTransportModeMessage:\n \"How should this profile connect to its local agent?\",\n selectResponsePolicyMessage: \"When should this profile auto-reply?\",\n skipControllerOptionLabel: \"Skip for now\",\n allowBackToCaller: false,\n });\n if (setupResult.status === \"cancelled\" || setupResult.status === \"back\") {\n return {\n status: \"cancelled\",\n profile,\n };\n }\n if (setupResult.status === \"configured\") {\n preparedConnection = await prepareAgentProfileConnection({\n agentControllerRef: setupResult.agentControllerRef,\n profile,\n transportMode: setupResult.transportMode,\n });\n prepared = true;\n snapshot = await resolveProfileReadinessSnapshot(profile);\n }\n }\n\n const launchPreparation = await prepareLocalAgentLaunchIfNeeded({\n interactive: input.interactive,\n profile,\n reasonCodes: collectPreparationReasonCodes(snapshot),\n view: input.view,\n });\n if (launchPreparation.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n profile,\n };\n }\n if (launchPreparation.status === \"prepared\") {\n prepared = true;\n snapshot = launchPreparation.snapshot;\n }\n\n const readinessRepair = await repairProfileReadinessState({\n profile,\n reasonCodes: collectPreparationReasonCodes(snapshot),\n view: input.view,\n });\n if (readinessRepair.prepared) {\n prepared = true;\n }\n\n return {\n ...(preparedConnection ? { preparedConnection } : {}),\n status: prepared ? \"prepared\" : \"unchanged\",\n profile,\n };\n}\n\nasync function bindAgentProfileToExplicitLocalAgent(input: {\n localAgentId: string;\n profile: OpenMeldProfile;\n}): Promise<PreparedAgentProfileConnection> {\n const target = await resolveAgentTargetState(input.localAgentId);\n if (!canBindExplicitLocalAgentForNewProfileSelection(target)) {\n const displayName = target?.displayName ?? input.localAgentId;\n throw new Error(\n target?.lifecycleStatus === \"suspended\"\n ? `OpenMeld no longer offers ${displayName} for new Agent Profiles.`\n : `OpenMeld cannot use ${displayName} for new Agent Profiles on this computer.`\n );\n }\n\n const agentControllerRef = buildAgentControllerRef({\n kind: \"builtin\",\n id: input.localAgentId,\n });\n\n return await prepareAgentProfileConnection({\n agentControllerRef,\n confirmLocalExecutionEvidence: false,\n profile: input.profile,\n transportMode: resolveDefaultTransportModeForLocalAgent({\n agentControllerRef,\n localAgentId: input.localAgentId,\n }),\n writeMode: \"reconnect\",\n });\n}\n\nasync function prepareAgentProfileConnection(input: {\n agentControllerRef: string;\n confirmLocalExecutionEvidence?: boolean;\n profile: OpenMeldProfile;\n transportMode: RuntimeAgentTransportMode;\n writeMode?: \"ensure\" | \"reconnect\";\n}): Promise<PreparedAgentProfileConnection> {\n const agentController = parseAgentControllerRef(input.agentControllerRef);\n if (!agentController) {\n throw new Error(\n `OpenMeld local agent setup returned an invalid Agent Controller reference: ${input.agentControllerRef}`\n );\n }\n await persistAgentTransportSelection({\n agentControllerRef: agentController.ref,\n transportMode: input.transportMode,\n });\n const reportInput = await resolveLocalAgentControllerReportInput({\n agentControllerRef: agentController.ref,\n diagnosticProfileId: input.profile.openMeldProfileId,\n requireEnabled: false,\n });\n const runtimeReportSubmission =\n await submitRuntimeAgentControllerReport(reportInput);\n const agentProfileBindingEnsure = await ensureAgentProfileRuntimeBinding({\n ...(input.confirmLocalExecutionEvidence === undefined\n ? {}\n : {\n confirmLocalExecutionEvidence: input.confirmLocalExecutionEvidence,\n }),\n profile: input.profile,\n runtimeReportSubmission,\n ...(input.writeMode ? { writeMode: input.writeMode } : {}),\n });\n return {\n agentProfileBindingEnsure,\n profileId: input.profile.openMeldProfileId,\n runtimeReport: buildSelectedAgentControllerReportResult({\n agentControllerRef: agentController.ref,\n agentId: agentController.id,\n reportInput,\n runtimeReportSubmission,\n }),\n };\n}\n\nfunction buildSelectedAgentControllerReportResult(input: {\n agentControllerRef: string;\n agentId: string;\n reportInput: {\n localParticipationState: SelectedAgentControllerReportResult[\"localParticipationState\"];\n reasonCodes: readonly string[];\n };\n runtimeReportSubmission: RuntimeAgentControllerReportSubmission;\n}): SelectedAgentControllerReportResult {\n return {\n agentId: input.agentId,\n agentControllerRef: input.agentControllerRef,\n localParticipationState: input.reportInput.localParticipationState,\n reasonCodes: [...input.reportInput.reasonCodes],\n runtimeReportSubmission: input.runtimeReportSubmission,\n };\n}\n\nfunction canBindExplicitLocalAgentForNewProfileSelection(\n target: Awaited<ReturnType<typeof resolveAgentTargetState>>\n): boolean {\n return (\n target?.targetKind === \"builtin\" &&\n target.lifecycleStatus !== \"suspended\" &&\n target.selectable\n );\n}\n\nfunction resolveDefaultTransportModeForLocalAgent(input: {\n agentControllerRef: string;\n localAgentId: string;\n}): RuntimeAgentTransportMode {\n const runtimeAdapterContract =\n resolveRegistryRuntimeAdapterContractByAgentControllerRef(\n input.agentControllerRef\n );\n return (\n runtimeAdapterContract?.defaultTransportMode ??\n runtimeAdapterContract?.transportModes[0] ??\n createDefaultRuntimeAgentControllerSettings(input.localAgentId)\n .transportMode\n );\n}\n\nasync function prepareLocalAgentLaunchIfNeeded(input: {\n interactive: boolean;\n profile: OpenMeldProfile;\n reasonCodes: readonly string[];\n view?: string;\n}): Promise<\n | {\n status: \"cancelled\" | \"unchanged\";\n }\n | {\n snapshot: ProfileReadinessSnapshot;\n status: \"prepared\";\n }\n> {\n if (needsLocalAgentLaunchChoice(input.reasonCodes)) {\n const enableResult = await runAgentsEnable({\n agent: [await requireProfileLocalAgentId(input.profile, \"enable\")],\n interactive: input.interactive,\n view: input.view,\n });\n if (enableResult.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n assertLocalAgentLaunchPreparationCompleted({\n profileId: input.profile.openMeldProfileId,\n result: enableResult,\n });\n return {\n snapshot: await resolveProfileReadinessSnapshot(input.profile),\n status: \"prepared\",\n };\n }\n\n if (needsLocalAgentLaunchRepair(input.reasonCodes)) {\n const repairResult = await runAgentsRepair({\n agent: [await requireProfileLocalAgentId(input.profile, \"repair\")],\n interactive: input.interactive,\n view: input.view,\n });\n if (repairResult.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n assertLocalAgentLaunchPreparationCompleted({\n profileId: input.profile.openMeldProfileId,\n result: repairResult,\n });\n return {\n snapshot: await resolveProfileReadinessSnapshot(input.profile),\n status: \"prepared\",\n };\n }\n\n return { status: \"unchanged\" };\n}\n\nasync function repairProfileReadinessState(input: {\n profile: OpenMeldProfile;\n reasonCodes: readonly string[];\n view?: string;\n}): Promise<{ prepared: boolean }> {\n let prepared = false;\n\n if (input.reasonCodes.includes(\"projection.missing\")) {\n await syncDeviceRuntimeStateProjection({\n mode: \"repair\",\n });\n prepared = true;\n }\n\n if (\n input.reasonCodes.includes(\"workspace.missing\") ||\n input.reasonCodes.includes(\"workspace.invalid\")\n ) {\n const workspaceSync = await syncProfileWorkspaceState({\n mode: \"repair\",\n profileIds: [input.profile.openMeldProfileId],\n });\n if (\n didWorkspaceRepairPrepareProfile({\n profileId: input.profile.openMeldProfileId,\n workspaceSync,\n })\n ) {\n prepared = true;\n }\n }\n\n return { prepared };\n}\n\nfunction needsControllerSetup(input: {\n profile: OpenMeldProfile;\n reasonCodes: readonly string[];\n}): boolean {\n return (\n input.reasonCodes.includes(\"agent_profile_binding.missing\") ||\n input.reasonCodes.includes(\"agent_profile_binding.owner_missing\") ||\n input.reasonCodes.includes(\"profile.unbound\") ||\n input.reasonCodes.includes(\"controller.binding.disabled\")\n );\n}\n\nfunction needsLocalAgentLaunchChoice(reasonCodes: readonly string[]): boolean {\n return reasonCodes.includes(\"controller.launch.choice_required\");\n}\n\nfunction needsLocalAgentLaunchRepair(reasonCodes: readonly string[]): boolean {\n return (\n !needsLocalAgentLaunchChoice(reasonCodes) &&\n reasonCodes.includes(\"controller.launch.needs_repair\")\n );\n}\n\nasync function resolveProfileLocalAgentId(\n profile: OpenMeldProfile\n): Promise<string | null> {\n const executionTarget = await resolveAgentProfilePrimaryAgentControllerReport(\n {\n profile,\n }\n ).catch(() => null);\n return executionTarget?.localAgentId ?? null;\n}\n\nasync function requireProfileLocalAgentId(\n profile: OpenMeldProfile,\n action: \"enable\" | \"repair\"\n): Promise<string> {\n const agentId = await resolveProfileLocalAgentId(profile);\n if (agentId) {\n return agentId;\n }\n\n if (action === \"enable\") {\n throw new Error(\n \"OpenMeld found more than one local agent install for this profile, but could not identify which local agent the profile uses. Run `openmeld agents enable --agent <agent-id>` and choose one install before running setup again.\"\n );\n }\n\n throw new Error(\n \"OpenMeld found that this profile's local agent needs repair, but could not identify which local agent the profile uses. Run `openmeld agents repair --agent <agent-id>` before running setup again.\"\n );\n}\n\nfunction assertLocalAgentLaunchPreparationCompleted(input: {\n profileId: string;\n result: AgentsEnableResult | AgentsRepairResult;\n}): void {\n if (input.result.status === \"back\") {\n throw new Error(\n \"OpenMeld local agent preparation cannot continue until you choose one local agent install.\"\n );\n }\n\n const blockingError = input.result.summary.errors[0] ?? null;\n if (!blockingError) {\n return;\n }\n\n throw new Error(\n formatLocalAgentLaunchPreparationFailure({\n error: blockingError,\n profileId: input.profileId,\n })\n );\n}\n\nfunction formatLocalAgentLaunchPreparationFailure(input: {\n error: AgentsEnableResult[\"summary\"][\"errors\"][number];\n profileId: string;\n}): string {\n if (input.error.code === \"controller.launch.choice_required\") {\n const commands = resolveLocalAgentChoiceCommands({\n agentId: input.error.agentId,\n nextSteps: input.error.nextSteps,\n installChoices: input.error.installChoices,\n });\n const reason =\n normalizeOptionalText(input.error.reason) ||\n `OpenMeld found more than one ${input.error.agentId} install on this computer.`;\n if (commands.length > 0) {\n return `${reason} Run one of these commands first: ${formatCommandChoiceList(commands)}. Then run \\`openmeld setup --profile ${input.profileId}\\` again.`;\n }\n return `${reason} Run \\`openmeld agents enable --agent ${input.error.agentId}\\` in an interactive Terminal and choose one install. Then run \\`openmeld setup --profile ${input.profileId}\\` again.`;\n }\n\n if (input.error.code === \"controller.launch.needs_repair\") {\n return `OpenMeld could not connect ${input.error.agentId} on this computer. Run \\`openmeld agents repair --agent ${input.error.agentId}\\`, then run \\`openmeld setup --profile ${input.profileId}\\` again. Detail: ${input.error.reason}`;\n }\n\n const nextStep = input.error.nextSteps?.[0] ?? null;\n if (nextStep) {\n return `OpenMeld could not connect ${input.error.agentId} on this computer. Run \\`${nextStep}\\`, then run \\`openmeld setup --profile ${input.profileId}\\` again. Detail: ${input.error.reason}`;\n }\n\n return `OpenMeld could not connect ${input.error.agentId} on this computer. Detail: ${input.error.reason}`;\n}\n\nfunction resolveLocalAgentChoiceCommands(input: {\n agentId: string;\n installChoices?: AgentsEnableResult[\"summary\"][\"errors\"][number][\"installChoices\"];\n nextSteps?: readonly string[];\n}): string[] {\n if (input.nextSteps && input.nextSteps.length > 0) {\n return [...input.nextSteps];\n }\n\n return (input.installChoices ?? []).map(\n (installChoice) =>\n `openmeld agents enable --agent ${input.agentId} --install ${installChoice.installId}`\n );\n}\n\nfunction formatCommandChoiceList(commands: readonly string[]): string {\n return commands.map((command) => `\\`${command}\\``).join(\" or \");\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nasync function resolveProfileReadinessSnapshot(profile: OpenMeldProfile) {\n return await resolveCurrentReplyReadinessSnapshot({\n checkGatewayChain: false,\n ownerUserId: profile.ownerUserId,\n profile,\n });\n}\n\nfunction collectPreparationReasonCodes(\n snapshot: Awaited<ReturnType<typeof resolveProfileReadinessSnapshot>>\n): string[] {\n const reasonCodes: string[] = [];\n for (const reasonCode of snapshot.deviceReplyReadiness.reasonCodes) {\n if (!reasonCodes.includes(reasonCode)) {\n reasonCodes.push(reasonCode);\n }\n }\n for (const reasonCode of snapshot.agentReplyReadiness?.reasonCodes ?? []) {\n if (!reasonCodes.includes(reasonCode)) {\n reasonCodes.push(reasonCode);\n }\n }\n return reasonCodes;\n}\n\nfunction didWorkspaceRepairPrepareProfile(input: {\n profileId: string;\n workspaceSync: ProfileWorkspaceStateSyncResult;\n}): boolean {\n if (input.workspaceSync.status === \"skipped\") {\n return false;\n }\n\n if (!input.workspaceSync.projectedProfileIds.includes(input.profileId)) {\n return false;\n }\n\n return !(\n input.workspaceSync.invalidWorkspaceProfileIds.includes(input.profileId) ||\n input.workspaceSync.missingWorkspaceProfileIds.includes(input.profileId)\n );\n}\n","import { formatAgentOverviewPayload } from \"../runtime/agent-overview-payload\";\nimport {\n createSpaceAddMembersGuideError,\n createSpaceContractSetGuideError,\n createSpaceCreateGuideError,\n createSpaceDeleteHumanApprovalGuideError,\n createSpaceLeaveGuideError,\n createSpaceMenuGuideError,\n createSpacePublicationSetGuideError,\n createSpaceRemoveMembersGuideError,\n createSpaceResultGuideError,\n createSpaceSubcommandTargetGuideError,\n createSpaceTargetGuideError,\n createSpaceUpdatesGuideError,\n} from \"../runtime/dual-view-guide-catalog\";\nimport type { Presenter } from \"../runtime/presenter\";\nimport { outJsonLine } from \"../ui/io\";\nimport { SPACE_ADD_MEMBERS_AGENT_OVERVIEW_STAGES } from \"./add-members-progress-contract\";\n\nexport type SpaceAgentOverviewCommand =\n | \"menu\"\n | \"create\"\n | \"join\"\n | \"watch\"\n | \"send\"\n | \"history\"\n | \"contract\"\n | \"contract_set\"\n | \"publication_set\"\n | \"status\"\n | \"updates\"\n | \"result\"\n | \"password\"\n | \"guide\"\n | \"add_members\"\n | \"add_agents\"\n | \"add_human_profiles\"\n | \"remove_members\"\n | \"leave\"\n | \"delete\"\n | \"list\";\n\nconst STAGES_BY_COMMAND: Record<SpaceAgentOverviewCommand, readonly string[]> =\n {\n menu: [\"choose_subcommand\", \"run_subcommand\"],\n create: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"service_check\",\n \"preflight\",\n \"create_space\",\n \"join_optional\",\n ],\n join: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"service_check\",\n \"preflight\",\n \"role_context\",\n \"connect\",\n ],\n watch: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"service_check\",\n \"resolve_target\",\n \"connect\",\n ],\n send: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"preflight\",\n \"resolve_message\",\n \"send_message\",\n ],\n history: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"read_history\",\n ],\n contract: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"read_contract\",\n ],\n contract_set: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"patch_contract\",\n ],\n publication_set: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"verify_owner\",\n \"verify_space_password\",\n \"patch_contract\",\n ],\n status: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"read_space_status\",\n ],\n updates: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"read_updates\",\n ],\n result: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"read_dispatch_result\",\n ],\n password: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"resolve_target\",\n \"update_password\",\n ],\n guide: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"resolve_target\",\n \"read_or_update_guide\",\n ],\n add_members: SPACE_ADD_MEMBERS_AGENT_OVERVIEW_STAGES,\n add_agents: SPACE_ADD_MEMBERS_AGENT_OVERVIEW_STAGES,\n add_human_profiles: SPACE_ADD_MEMBERS_AGENT_OVERVIEW_STAGES,\n remove_members: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"resolve_target\",\n \"remove_members\",\n ],\n leave: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"resolve_target\",\n \"confirm_human_view\",\n \"leave_space\",\n \"sync_profile_space_history\",\n ],\n delete: [\n \"check_arguments\",\n \"authenticate\",\n \"check_profile\",\n \"confirm_human_approval\",\n \"delete_space\",\n ],\n list: [\"authenticate\", \"check_profile\", \"list_spaces\"],\n };\n\nconst SUMMARY_BY_COMMAND: Record<SpaceAgentOverviewCommand, string> = {\n menu: \"Use explicit `openmeld space` subcommands in agent view instead of the interactive menu.\",\n create:\n \"Use `openmeld space create --view agent` to create a space with explicit arguments and machine-readable follow-up output.\",\n join: \"Use `openmeld space join --view agent` with an explicit space ID to connect deterministically.\",\n watch:\n \"Use `openmeld space watch --view agent` with an explicit space ID to read space activity deterministically.\",\n send: \"Use `openmeld space send --view agent` with an explicit space ID and explicit message input.\",\n history:\n \"Use `openmeld space history --kind text --brief --view agent` with an explicit space ID for conversation context. Use `--json` only when you need signal envelopes plus `messageReadProjection`.\",\n contract:\n \"Use `openmeld space contract --view agent` with an explicit space ID to read the current space contract deterministically.\",\n contract_set:\n \"Use `openmeld space contract set --view agent` with an explicit space ID and explicit patch flags to update the current space contract deterministically.\",\n publication_set:\n \"Use `openmeld space publication set --view agent` with an explicit Space ID, mode, owner profile, and Space password to change how agent output becomes visible.\",\n status:\n \"Use `openmeld space status --view agent` with an explicit space ID to read the current space status deterministically.\",\n updates:\n \"Use `openmeld space updates --view agent` with an explicit anchor signal to read formal post-anchor updates deterministically as signal envelopes plus `messageReadProjection`.\",\n result:\n \"Use `openmeld space result --view agent` with exactly one selector to read an archived dispatch result plus `messageReadProjection`. Use `openmeld service trace --view agent` to diagnose Wake execution and the final visible Space outcome.\",\n password:\n \"Use `openmeld space password --view agent` with an explicit space ID and one explicit password action.\",\n guide:\n \"Use `openmeld space guide --view agent` to read, `openmeld space guide set --view agent` to update, and `openmeld space guide clear --view agent` to clear the current space guide deterministically.\",\n add_members:\n \"Use `openmeld space add-members --profile <profile-id> <space-id> --member <profile-id...> --view agent` with explicit acting profile, Space ID, and member selection.\",\n add_agents:\n \"Use `openmeld space add-agents --profile <profile-id> <space-id> --agent-profile <agent-profile-id...> --view agent` with explicit acting profile, Space ID, and Agent Profile selection. This command only adds Agent Profiles.\",\n add_human_profiles:\n \"Use `openmeld space add-human-profiles --profile <profile-id> <space-id> --human-profile <human-profile-id...> --view agent` with explicit acting profile, Space ID, and Human Profile selection. This command only adds Human Profiles.\",\n remove_members:\n \"Use `openmeld space remove-members --profile <profile-id> <space-id> --member <profile-id...> --view agent` with explicit acting profile, Space ID, and member selection.\",\n leave:\n \"Use `openmeld space leave --view agent` with an explicit space ID to remove the current profile from a space.\",\n delete:\n \"Use `openmeld space delete --view agent` only to guide a human operator; deletion still needs human approval.\",\n list: \"Use `openmeld space list --view agent` to inspect known spaces for the current OpenMeld profile.\",\n};\n\nconst SPACE_LIST_COMMANDS = [\n \"openmeld space list --profile <profile-id> --view agent\",\n \"openmeld space create --profile <profile-id> --name <space-name> --view agent\",\n \"openmeld space join --profile <profile-id> <space-id> --view agent\",\n] as const;\n\nconst SPACE_LIST_NOTES = [\n \"List uses the current OpenMeld profile context. Pass --profile explicitly in isolated or non-persistent sessions.\",\n] as const;\n\nexport function emitSpaceAgentOverview(input: {\n presenter: Presenter;\n resolvedView: \"human\" | \"agent\";\n command: SpaceAgentOverviewCommand;\n}): void {\n if (input.resolvedView !== \"agent\") {\n return;\n }\n\n input.presenter.data({\n code: `space.${input.command}.agent_overview`,\n payload: formatAgentOverviewPayload(\n buildSpaceAgentOverviewPayload(input.command)\n ),\n });\n}\n\nexport function emitSpaceCliAgentOverview(\n command: SpaceAgentOverviewCommand\n): void {\n outJsonLine({\n type: \"result\",\n code: `space.${command}.agent_overview`,\n payload: formatAgentOverviewPayload(\n buildSpaceAgentOverviewPayload(command)\n ),\n });\n}\n\nfunction buildSpaceAgentOverviewPayload(command: SpaceAgentOverviewCommand): {\n summary: string;\n requiredArguments: string[];\n optionalArguments: string[];\n commands: string[];\n stages: readonly string[];\n notes: string[];\n humanActionRequired: {\n possible: boolean;\n steps: string[];\n };\n} {\n if (command === \"list\") {\n return {\n summary: SUMMARY_BY_COMMAND.list,\n requiredArguments: [],\n optionalArguments: [\n \"--limit <n>\",\n \"--json\",\n \"parent option: openmeld space --gateway-url <url>\",\n \"--profile <profile-id>\",\n ],\n commands: [...SPACE_LIST_COMMANDS],\n stages: STAGES_BY_COMMAND.list,\n notes: [...SPACE_LIST_NOTES],\n humanActionRequired: {\n possible: false,\n steps: [],\n },\n };\n }\n\n const guide = resolveGuide(command).guide;\n return {\n summary: SUMMARY_BY_COMMAND[command],\n requiredArguments: guide.agentRequiredArgs ?? [],\n optionalArguments: guide.agentOptionalArgs ?? [],\n commands: guide.agentCommands ?? [],\n stages: STAGES_BY_COMMAND[command],\n notes: guide.notes ?? [],\n humanActionRequired: resolveSpaceAgentOverviewHumanActionRequired({\n command,\n humanSteps: guide.humanSteps ?? [],\n }),\n };\n}\n\nfunction resolveSpaceAgentOverviewHumanActionRequired(input: {\n command: Exclude<SpaceAgentOverviewCommand, \"list\">;\n humanSteps: string[];\n}): { possible: boolean; steps: string[] } {\n if (input.command !== \"delete\") {\n return {\n possible: false,\n steps: [],\n };\n }\n return {\n possible: input.humanSteps.length > 0,\n steps: input.humanSteps,\n };\n}\n\nfunction resolveGuide(command: Exclude<SpaceAgentOverviewCommand, \"list\">) {\n switch (command) {\n case \"menu\":\n return createSpaceMenuGuideError();\n case \"create\":\n return createSpaceCreateGuideError();\n case \"join\":\n return createSpaceTargetGuideError(\"join\");\n case \"watch\":\n return createSpaceTargetGuideError(\"watch\");\n case \"send\":\n return createSpaceSubcommandTargetGuideError(\"send\");\n case \"history\":\n return createSpaceSubcommandTargetGuideError(\"history\");\n case \"contract\":\n return createSpaceTargetGuideError(\"contract\");\n case \"contract_set\":\n return createSpaceContractSetGuideError();\n case \"publication_set\":\n return createSpacePublicationSetGuideError();\n case \"status\":\n return createSpaceTargetGuideError(\"status\");\n case \"updates\":\n return createSpaceUpdatesGuideError();\n case \"result\":\n return createSpaceResultGuideError();\n case \"password\":\n return createSpaceSubcommandTargetGuideError(\"password\");\n case \"guide\":\n return createSpaceTargetGuideError(\"guide\");\n case \"add_members\":\n return createSpaceAddMembersGuideError();\n case \"add_agents\":\n return createSpaceAddMembersGuideError(undefined, \"space.add-agents\");\n case \"add_human_profiles\":\n return createSpaceAddMembersGuideError(\n undefined,\n \"space.add-human-profiles\"\n );\n case \"remove_members\":\n return createSpaceRemoveMembersGuideError();\n case \"leave\":\n return createSpaceLeaveGuideError();\n case \"delete\":\n return createSpaceDeleteHumanApprovalGuideError();\n default:\n return createSpaceMenuGuideError();\n }\n}\n","import {\n createAccountSpaceIndexApi,\n createFetchTransport,\n createOpenMeldApiClient,\n resolveAccountSpaceIndexGatewayHost,\n} from \"@openmeld/api-client\";\nimport type {\n AccountSpaceIndexResponse,\n OpenMeldRequestContext,\n} from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"./request-headers\";\n\nconst ACCOUNT_SPACE_INDEX_TIMEOUT_MS = 10_000;\n\nexport async function listAccountSpaceIndex(input: {\n baseUrl: string;\n requestContext: OpenMeldRequestContext;\n includePurposes?: boolean;\n limit?: number;\n scope: \"account\" | \"profile\";\n selectedProfileId: string;\n}): Promise<AccountSpaceIndexResponse> {\n return await createAccountSpaceIndexApi(\n createOpenMeldApiClient({\n baseUrl: input.baseUrl,\n transport: createFetchTransport({\n fetch,\n defaultTimeoutMs: ACCOUNT_SPACE_INDEX_TIMEOUT_MS,\n }),\n getRequestContextHeaders: async ({ requestUrl, requestContext }) =>\n await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl,\n requestContext,\n }),\n })\n ).listAccountSpaces({\n requestContext: input.requestContext,\n gatewayHost: resolveAccountSpaceIndexGatewayHost(input.baseUrl),\n ...(input.includePurposes === true ? { includePurposes: true } : {}),\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n scope: input.scope,\n selectedProfileId: input.selectedProfileId,\n timeoutMs: ACCOUNT_SPACE_INDEX_TIMEOUT_MS,\n });\n}\n","import {\n buildProfileSpaceHistoryListPath,\n buildProfileSpaceHistoryStatusPath,\n buildProfileSpaceHistoryUpsertPath,\n createFetchTransport,\n createOpenMeldApiClient,\n createProfileSpaceHistoryApi,\n OpenMeldApiClientHttpError,\n OpenMeldApiClientInvalidResponseError,\n resolveProfileSpaceHistoryGatewayHost,\n} from \"@openmeld/api-client\";\nimport type {\n OpenMeldRequestContext,\n PatchProfileSpaceHistoryStatusBody,\n PatchProfileSpaceHistoryStatusResponse,\n ProfileSpaceHistoryRecord,\n ProfileSpaceHistoryStatus,\n UpsertProfileSpaceHistoryBody,\n UpsertProfileSpaceHistoryResponse,\n} from \"@openmeld/schemas\";\nimport { normalizeBaseUrl } from \"../protocol/urls\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"./request-headers\";\n\nconst PROFILE_SPACE_HISTORY_TIMEOUT_MS = 10_000;\n\nexport class ProfileSpaceHistoryApiError extends Error {\n readonly status: number | null;\n readonly code: string | null;\n readonly endpoint: string;\n readonly canFallbackToLocal: boolean;\n\n constructor(input: {\n message: string;\n endpoint: string;\n status?: number | null;\n code?: string | null;\n canFallbackToLocal?: boolean;\n }) {\n super(input.message);\n this.name = \"ProfileSpaceHistoryApiError\";\n this.status =\n typeof input.status === \"number\" ? Math.trunc(input.status) : null;\n this.code = normalizeOptionalText(input.code);\n this.endpoint = input.endpoint;\n this.canFallbackToLocal = input.canFallbackToLocal === true;\n }\n}\n\nexport async function listProfileSpaceHistory(input: {\n baseUrl: string;\n requestContext: OpenMeldRequestContext;\n openMeldProfileId: string;\n profileName?: string;\n statuses?: ProfileSpaceHistoryStatus[];\n pinned?: boolean;\n limit?: number;\n}): Promise<ProfileSpaceHistoryRecord[]> {\n const gatewayHost = resolveGatewayHost(input.baseUrl);\n const endpoint = toAbsoluteEndpoint({\n baseUrl: input.baseUrl,\n path: buildProfileSpaceHistoryListPath({\n profileId: input.openMeldProfileId,\n gatewayHost,\n ...(input.statuses === undefined ? {} : { statuses: input.statuses }),\n ...(input.pinned === undefined ? {} : { pinned: input.pinned }),\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n }),\n });\n\n try {\n return [\n ...(await createApi(input.baseUrl).listProfileSpaceHistory({\n requestContext: input.requestContext,\n profileId: input.openMeldProfileId,\n gatewayHost,\n ...(input.statuses === undefined ? {} : { statuses: input.statuses }),\n ...(input.pinned === undefined ? {} : { pinned: input.pinned }),\n ...(input.limit === undefined ? {} : { limit: input.limit }),\n timeoutMs: PROFILE_SPACE_HISTORY_TIMEOUT_MS,\n })),\n ];\n } catch (error) {\n throw toProfileSpaceHistoryApiError({\n error,\n endpoint,\n invalidResponseCanFallbackToLocal: true,\n });\n }\n}\n\nexport async function upsertProfileSpaceHistory(input: {\n baseUrl: string;\n requestContext: OpenMeldRequestContext;\n openMeldProfileId: string;\n profileName?: string;\n spaceId: string;\n body: UpsertProfileSpaceHistoryBody;\n}): Promise<UpsertProfileSpaceHistoryResponse> {\n const endpoint = toAbsoluteEndpoint({\n baseUrl: input.baseUrl,\n path: buildProfileSpaceHistoryUpsertPath({\n profileId: input.openMeldProfileId,\n spaceId: input.spaceId,\n }),\n });\n\n try {\n return await createApi(input.baseUrl).upsertProfileSpaceHistory({\n requestContext: input.requestContext,\n profileId: input.openMeldProfileId,\n spaceId: input.spaceId,\n body: input.body,\n timeoutMs: PROFILE_SPACE_HISTORY_TIMEOUT_MS,\n });\n } catch (error) {\n throw toProfileSpaceHistoryApiError({\n error,\n endpoint,\n invalidResponseCanFallbackToLocal: false,\n });\n }\n}\n\nexport async function updateProfileSpaceHistoryStatus(input: {\n baseUrl: string;\n requestContext: OpenMeldRequestContext;\n openMeldProfileId: string;\n profileName?: string;\n spaceId: string;\n body: PatchProfileSpaceHistoryStatusBody;\n}): Promise<PatchProfileSpaceHistoryStatusResponse> {\n const endpoint = toAbsoluteEndpoint({\n baseUrl: input.baseUrl,\n path: buildProfileSpaceHistoryStatusPath({\n profileId: input.openMeldProfileId,\n spaceId: input.spaceId,\n }),\n });\n\n try {\n return await createApi(input.baseUrl).updateProfileSpaceHistoryStatus({\n requestContext: input.requestContext,\n profileId: input.openMeldProfileId,\n spaceId: input.spaceId,\n body: input.body,\n timeoutMs: PROFILE_SPACE_HISTORY_TIMEOUT_MS,\n });\n } catch (error) {\n throw toProfileSpaceHistoryApiError({\n error,\n endpoint,\n invalidResponseCanFallbackToLocal: false,\n });\n }\n}\n\nexport function resolveGatewayHost(baseUrl: string): string {\n return resolveProfileSpaceHistoryGatewayHost(baseUrl);\n}\n\nfunction createApi(baseUrl: string) {\n return createProfileSpaceHistoryApi(\n createOpenMeldApiClient({\n baseUrl,\n transport: createFetchTransport({\n fetch,\n defaultTimeoutMs: PROFILE_SPACE_HISTORY_TIMEOUT_MS,\n }),\n getRequestContextHeaders: async ({ requestUrl, requestContext }) =>\n await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl,\n requestContext,\n }),\n })\n );\n}\n\nfunction toAbsoluteEndpoint(input: { baseUrl: string; path: string }): string {\n return new URL(input.path, `${normalizeBaseUrl(input.baseUrl)}/`).toString();\n}\n\nfunction toProfileSpaceHistoryApiError(input: {\n error: unknown;\n endpoint: string;\n invalidResponseCanFallbackToLocal: boolean;\n}): ProfileSpaceHistoryApiError {\n if (input.error instanceof ProfileSpaceHistoryApiError) {\n return input.error;\n }\n\n if (input.error instanceof OpenMeldApiClientInvalidResponseError) {\n return new ProfileSpaceHistoryApiError({\n endpoint: input.endpoint,\n status: input.error.status,\n code: \"profile_space_history.response_invalid\",\n message: input.error.message,\n canFallbackToLocal: input.invalidResponseCanFallbackToLocal,\n });\n }\n\n if (input.error instanceof OpenMeldApiClientHttpError) {\n const parsedRawBody = parseJson(input.error.rawBody);\n const code =\n readErrorField(parsedRawBody, \"code\") ??\n input.error.upstreamCode ??\n input.error.code;\n const message = extractHttpErrorMessage(input.error);\n return new ProfileSpaceHistoryApiError({\n endpoint: input.endpoint,\n status: input.error.status,\n code,\n message,\n canFallbackToLocal: shouldFallbackToLocal({\n status: input.error.status,\n code,\n message,\n }),\n });\n }\n\n const genericCode = readGenericErrorCode(input.error);\n if (\n genericCode === \"network.timeout\" ||\n genericCode === \"network.request_failed\"\n ) {\n return new ProfileSpaceHistoryApiError({\n endpoint: input.endpoint,\n status: readGenericErrorStatus(input.error),\n code: \"profile_space_history.network_error\",\n message: toNetworkErrorMessage(input.error),\n canFallbackToLocal: true,\n });\n }\n\n return new ProfileSpaceHistoryApiError({\n endpoint: input.endpoint,\n code: \"profile_space_history.network_error\",\n message: toNetworkErrorMessage(input.error),\n canFallbackToLocal: true,\n });\n}\n\nfunction extractHttpErrorMessage(error: OpenMeldApiClientHttpError): string {\n const raw = normalizeOptionalText(error.rawBody);\n if (raw) {\n try {\n const parsed = JSON.parse(raw) as unknown;\n return extractErrorMessage(parsed, raw, error.status);\n } catch {\n return raw;\n }\n }\n return `profile-space-history request failed with status ${error.status}`;\n}\n\nfunction extractErrorMessage(\n payload: unknown,\n raw: string,\n status: number\n): string {\n const message = readErrorField(payload, \"message\");\n if (message) {\n return message;\n }\n const fallback = normalizeOptionalText(raw);\n if (fallback) {\n return fallback;\n }\n return `profile-space-history request failed with status ${status}`;\n}\n\nfunction readErrorField(\n payload: unknown,\n field: \"code\" | \"message\"\n): string | null {\n if (!payload || typeof payload !== \"object\") {\n return null;\n }\n const record = payload as Record<string, unknown>;\n if (typeof record[field] === \"string\") {\n return normalizeOptionalText(record[field]);\n }\n if (\n record.error &&\n typeof record.error === \"object\" &&\n typeof (record.error as Record<string, unknown>)[field] === \"string\"\n ) {\n return normalizeOptionalText(\n (record.error as Record<string, unknown>)[field]\n );\n }\n return null;\n}\n\nfunction shouldFallbackToLocal(input: {\n status: number;\n code: string | null;\n message: string;\n}): boolean {\n if (\n input.status === 401 ||\n input.status === 403 ||\n input.code === \"auth.unauthenticated\"\n ) {\n return false;\n }\n if (isProfileMissing404(input)) {\n return false;\n }\n if (input.status >= 500) {\n return true;\n }\n if (input.status === 408 || input.status === 429) {\n return true;\n }\n if (input.status === 404 && input.code !== \"profile.not_found\") {\n return true;\n }\n return false;\n}\n\nfunction isProfileMissing404(input: {\n status: number;\n code: string | null;\n message: string;\n}): boolean {\n if (input.status !== 404) {\n return false;\n }\n if (input.code === \"profile.not_found\") {\n return true;\n }\n if (input.code && input.code !== \"upstream_error\") {\n return false;\n }\n\n const normalizedMessage = normalizeOptionalText(input.message)?.toLowerCase();\n if (!normalizedMessage?.includes(\"profile\")) {\n return false;\n }\n\n return (\n normalizedMessage.includes(\"not found\") ||\n normalizedMessage.includes(\"disabled\") ||\n normalizedMessage.includes(\"inactive\") ||\n normalizedMessage.includes(\"deleted\")\n );\n}\n\nfunction readGenericErrorCode(error: unknown): string | null {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const code = (error as { code?: unknown }).code;\n return typeof code === \"string\" ? normalizeOptionalText(code) : null;\n}\n\nfunction readGenericErrorStatus(error: unknown): number | null {\n if (!error || typeof error !== \"object\") {\n return null;\n }\n const status = (error as { status?: unknown }).status;\n return typeof status === \"number\" && Number.isInteger(status) ? status : null;\n}\n\nfunction parseJson(raw: string): unknown {\n try {\n return JSON.parse(raw) as unknown;\n } catch {\n return null;\n }\n}\n\nfunction toNetworkErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n const message = normalizeOptionalText(error.message);\n if (message) {\n return message;\n }\n return error.name;\n }\n return \"network error\";\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport type { RuntimeAgentControllerReportSubmission } from \"../local-service/reporting/runtime-agent-controller-reporting-submission\";\nimport {\n type AgentProfileRuntimeBindingEnsureResult,\n syncAgentProfileRuntimeBindingFromCurrentReadiness,\n} from \"./ensure-agent-profile-runtime-binding\";\n\nexport const FORMAL_AGENT_BINDING_NOT_READY_REASON_TEXT =\n \"OpenMeld could not finish connecting this Agent Profile to this computer.\";\n\nexport type FormalAgentBindingBackstopResult = {\n agentProfileBindingEnsure: AgentProfileRuntimeBindingEnsureResult;\n reasonCodes: string[];\n reasonText: string | null;\n runtimeReportSubmission: RuntimeAgentControllerReportSubmission;\n status: \"ready\" | \"not_ready\";\n};\n\nexport async function ensureFormalAgentBindingForReadyLocalProfile(input: {\n profile: OpenMeldProfile;\n}): Promise<FormalAgentBindingBackstopResult> {\n const result = await syncAgentProfileRuntimeBindingFromCurrentReadiness({\n profile: input.profile,\n });\n const bindingEnsure = result.agentProfileBindingEnsure;\n if (bindingEnsure.status === \"accepted\" && bindingEnsure.routable) {\n return {\n agentProfileBindingEnsure: bindingEnsure,\n reasonCodes: bindingEnsure.reasonCodes,\n reasonText: null,\n runtimeReportSubmission: result.runtimeReportSubmission,\n status: \"ready\",\n };\n }\n\n return {\n agentProfileBindingEnsure: bindingEnsure,\n reasonCodes:\n bindingEnsure.reasonCodes.length > 0\n ? [...bindingEnsure.reasonCodes]\n : [\"agent_profile_binding.unavailable\"],\n reasonText: FORMAL_AGENT_BINDING_NOT_READY_REASON_TEXT,\n runtimeReportSubmission: result.runtimeReportSubmission,\n status: \"not_ready\",\n };\n}\n","import { cancel, confirm, isCancel } from \"@clack/prompts\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport type { LocalServiceDemand } from \"../local-service/lifecycle/local-service-demand\";\nimport type { Presenter } from \"../runtime/presenter/types\";\nimport { runDaemonServiceParticipationGate } from \"../system/local-service-participation-gate\";\nimport type {\n ActionParticipationPlan,\n LocalParticipationOrchestratorOutcome,\n} from \"./action-participation-planner\";\nimport { prepareLocalAgentReadiness } from \"./local-agent-readiness-preparation\";\n\nexport async function runLocalParticipationOrchestrator(input: {\n intent: \"start\" | \"space_join\" | \"space_create_join\" | \"space_add_members\";\n plan: ActionParticipationPlan;\n presenter: Presenter;\n resolvedView: \"human\" | \"agent\";\n allowPrompt: boolean;\n gatewayUrl?: string;\n localDemand?: LocalServiceDemand | null;\n forceServicePrompt?: boolean;\n profilesToPrepare?: readonly OpenMeldProfile[];\n view?: string;\n}): Promise<LocalParticipationOrchestratorOutcome> {\n if (input.plan.hasAgentPreparationWork) {\n if (\n input.resolvedView !== \"human\" ||\n !input.allowPrompt ||\n !input.profilesToPrepare ||\n input.profilesToPrepare.length === 0\n ) {\n return {\n status: \"continued\",\n };\n }\n\n const prepareNow = await confirm({\n message: buildAgentPreparationPromptMessage(input.profilesToPrepare),\n active: \"Set up now\",\n inactive: \"Not now\",\n initialValue: true,\n });\n if (isCancel(prepareNow)) {\n cancel(\"Cancelled.\");\n return {\n status: \"cancelled\",\n };\n }\n if (!prepareNow) {\n return {\n status: \"continued\",\n };\n }\n\n const preparationResult = await prepareLocalAgentReadiness({\n profiles: input.profilesToPrepare,\n interactive: true,\n view: input.view,\n });\n if (preparationResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (preparationResult.status === \"prepared\") {\n return {\n status: \"recheck_required\",\n };\n }\n }\n\n if (!input.plan.shouldOfferServiceGate) {\n return {\n status: \"continued\",\n };\n }\n\n const gateResult = await runDaemonServiceParticipationGate({\n intent: input.intent,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n allowPrompt: input.allowPrompt,\n gatewayUrl: input.gatewayUrl,\n localDemand: input.localDemand ?? null,\n forcePrompt: input.forceServicePrompt,\n view: input.view,\n });\n if (gateResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n return {\n status: gateResult.status === \"aligned\" ? \"recheck_required\" : \"continued\",\n };\n}\n\nfunction buildAgentPreparationPromptMessage(\n profiles: readonly Pick<OpenMeldProfile, \"profileName\">[]\n): string {\n if (profiles.length === 1) {\n return `${profiles[0]?.profileName ?? \"This agent\"} still needs local setup on this device before it can wake or reply in the background. Set it up now?`;\n }\n return `${String(profiles.length)} local agent profiles still need setup on this device before they can wake or reply in the background. Set them up now?`;\n}\n","import { buildUnifiedCardFrame } from \"./card-frame\";\n\nconst SPACE_ACCESS_WARNING_TITLE = \"⚠️ Check Before You Continue\";\n\nexport function buildSpaceAccessPromptCardMessage(input: {\n lines: string[];\n question: string;\n}): string {\n const frame = buildUnifiedCardFrame({\n title: SPACE_ACCESS_WARNING_TITLE,\n rowTextList: input.lines,\n minContentWidth: 76,\n });\n return [\n frame.top,\n frame.empty,\n ...frame.rows,\n frame.empty,\n frame.bottom,\n input.question,\n ].join(\"\\n\");\n}\n","import { buildSpaceAccessPromptCardMessage } from \"./space-access-prompt-card\";\n\nexport type SpaceCreateInitialAccessMode = \"public\" | \"members_only\";\n\nexport type SpaceCreatePasswordPromptConfig = {\n message: string;\n setPasswordLabel: string;\n skipPasswordLabel: string;\n};\n\nexport function buildSpaceCreatePasswordPromptConfig(input: {\n accessMode: SpaceCreateInitialAccessMode;\n minimumLength: number;\n}): SpaceCreatePasswordPromptConfig {\n return {\n message: buildSpaceAccessPromptCardMessage({\n lines: [\n resolveSpaceCreatePasswordlessAccessText(input.accessMode),\n \"With a password, only people who have it can open and join the Space.\",\n `Passwords must be at least ${input.minimumLength} characters.`,\n ],\n question: \"Require a password to open and join?\",\n }),\n setPasswordLabel: \"Yes, require a password to open and join\",\n skipPasswordLabel:\n input.accessMode === \"public\"\n ? \"No, anyone with the link can join\"\n : \"No, keep access members-only\",\n };\n}\n\nexport function resolveSpaceCreatePasswordlessAccessText(\n accessMode: SpaceCreateInitialAccessMode\n): string {\n return accessMode === \"public\"\n ? \"Without a password, anyone with this Space link can read what is shared here and join.\"\n : \"Without a password, only current members can open this Space. New participants must be added explicitly.\";\n}\n","import {\n buildCommandAuthenticationPromptMessage,\n ensureCommandAuthenticationOrCancel,\n} from \"../auth/command-auth\";\nimport { getCurrentCommandCheckState } from \"../command-entry-checks/current-command-check-state\";\nimport { resolveBaseUrl } from \"../config/base-url\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { resolveOpenMeldProfileOrNull } from \"../config/resolve-openmeld-profile\";\nimport { resolveRuntimeContext } from \"../runtime/context\";\nimport {\n createSpaceProfileRequiredGuideError,\n createSpaceUnsupportedProfileKindGuideError,\n} from \"../runtime/dual-view-guide-catalog\";\nimport { canUseInteractivePrompts } from \"../runtime/interaction\";\nimport { formatMessage } from \"../runtime/messages\";\nimport { createPresenter } from \"../runtime/presenter/index\";\n\nconst SPACE_ID_HEX_REGEX = /^[0-9a-f]{64}$/i;\n// Signal IDs are bare crypto.randomUUID() (canonical 36-char UUID). We lock only\n// the shape (not the v4 version/variant nibbles) and accept upper-case, so a\n// short prefix is caught locally without coupling to the id-generation strategy.\nconst SIGNAL_ID_UUID_REGEX =\n /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;\n\nexport type PreparedSpaceCommandContext = {\n status: \"ready\";\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n interactive: boolean;\n baseUrl: string;\n authenticatedGatewayUrl: string | null;\n};\n\nexport async function prepareAuthenticatedSpaceCommandContext(input: {\n profile?: string;\n baseUrl?: string;\n view?: string;\n promptMessage: string;\n checkGatewayMismatch?: boolean;\n entryChecksHandled?: boolean;\n runtime?: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter?: ReturnType<typeof createPresenter>;\n interactive?: boolean;\n}): Promise<PreparedSpaceCommandContext | { status: \"cancelled\" }> {\n const runtime =\n input.runtime ??\n (await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n }));\n const presenter = input.presenter ?? createPresenter(runtime);\n const interactive = input.interactive ?? canUseInteractivePrompts(runtime);\n const baseUrl = await resolveBaseUrl(input.baseUrl);\n if (!input.entryChecksHandled) {\n const authReady = await ensureHumanSpaceCommandAuthenticationOrCancel({\n runtime,\n gatewayUrl: input.checkGatewayMismatch === false ? undefined : baseUrl,\n promptMessage: input.promptMessage,\n allowPrompt: interactive,\n });\n if (!authReady) {\n return {\n status: \"cancelled\",\n };\n }\n }\n\n return {\n status: \"ready\",\n runtime,\n presenter,\n interactive,\n baseUrl,\n authenticatedGatewayUrl:\n input.checkGatewayMismatch === false ? null : baseUrl,\n };\n}\n\nexport async function ensureSpaceCommandGatewayAuthenticationOrCancel(input: {\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n allowPrompt: boolean;\n promptMessage: string;\n gatewayUrl: string;\n authenticatedGatewayUrl?: string | null;\n}): Promise<string | null> {\n const targetGatewayUrl = normalizeOptionalString(input.gatewayUrl);\n if (!targetGatewayUrl) {\n return normalizeOptionalString(input.authenticatedGatewayUrl);\n }\n\n const authenticatedGatewayUrl = normalizeOptionalString(\n input.authenticatedGatewayUrl\n );\n if (\n authenticatedGatewayUrl !== null &&\n authenticatedGatewayUrl === targetGatewayUrl\n ) {\n return authenticatedGatewayUrl;\n }\n\n const authReady = await ensureHumanSpaceCommandAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: targetGatewayUrl,\n promptMessage: input.promptMessage,\n allowPrompt: input.allowPrompt,\n });\n if (!authReady) {\n return null;\n }\n\n return targetGatewayUrl;\n}\n\nexport function assertValidSpaceIdTarget(input: {\n space: string;\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (isValidSpaceId(input.space)) {\n return;\n }\n\n throw new Error(\n formatMessage(input.resolvedView, \"space.target.invalid\", {\n space: input.space,\n })\n );\n}\n\n// Reject a short/malformed signal id locally, before any network round-trip, so\n// the user gets a clear \"use the full id\" message instead of a late upstream\n// \"anchor not found\". Empty/unset values are not validated here — each command\n// decides its own required-ness. Thread ids (thr_ prefix) are NOT signal ids and\n// must not be passed through this guard.\nexport function assertFullSignalIdArgument(input: {\n value: string | undefined;\n flag:\n | \"--after-signal\"\n | \"--around-signal\"\n | \"--reply-to\"\n | \"--signal\"\n | \"--thread-root-signal\";\n resolvedView: \"human\" | \"agent\";\n}): void {\n const normalized = String(input.value ?? \"\").trim();\n if (normalized.length === 0) {\n return;\n }\n if (SIGNAL_ID_UUID_REGEX.test(normalized)) {\n return;\n }\n throw new Error(\n formatMessage(input.resolvedView, \"signal.id.invalid\", {\n flag: input.flag,\n value: normalized,\n })\n );\n}\n\nexport async function resolveOpenMeldProfileForSpaceCommand(input: {\n openMeldProfileId?: string;\n resolvedView: \"human\" | \"agent\";\n interactive: boolean;\n}): Promise<OpenMeldProfile> {\n const currentSelectedProfile =\n getCurrentCommandCheckState().selectedProfile?.profile ?? null;\n if (\n currentSelectedProfile &&\n (String(input.openMeldProfileId ?? \"\").trim().length === 0 ||\n currentSelectedProfile.openMeldProfileId === input.openMeldProfileId)\n ) {\n if (\n !isProfileKindSupportedForSpaceCommand(currentSelectedProfile.profileKind)\n ) {\n throw createSpaceUnsupportedProfileKindGuideError({\n profileId: currentSelectedProfile.openMeldProfileId,\n profileKind: currentSelectedProfile.profileKind,\n });\n }\n return currentSelectedProfile;\n }\n\n const openMeldProfile = await resolveOpenMeldProfileOrNull({\n openMeldProfileId: input.openMeldProfileId,\n persistSelection: false,\n allowDefaultFallback: false,\n });\n if (openMeldProfile) {\n if (!isProfileKindSupportedForSpaceCommand(openMeldProfile.profileKind)) {\n throw createSpaceUnsupportedProfileKindGuideError({\n profileId: openMeldProfile.openMeldProfileId,\n profileKind: openMeldProfile.profileKind,\n });\n }\n return openMeldProfile;\n }\n\n const canBootstrapDefaultHumanProfile =\n input.resolvedView === \"human\" &&\n input.interactive &&\n String(input.openMeldProfileId ?? \"\").trim().length === 0;\n if (canBootstrapDefaultHumanProfile) {\n const fallbackHumanProfile = await resolveOpenMeldProfileOrNull({\n profileKind: \"human\",\n persistSelection: true,\n allowDefaultFallback: true,\n });\n if (fallbackHumanProfile) {\n return fallbackHumanProfile;\n }\n }\n\n throw createSpaceProfileRequiredGuideError();\n}\n\nexport function buildSpaceReadAuthenticationPromptMessage(\n action: string\n): string {\n return buildCommandAuthenticationPromptMessage(action);\n}\n\nasync function ensureHumanSpaceCommandAuthenticationOrCancel(input: {\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n promptMessage: string;\n allowPrompt: boolean;\n gatewayUrl?: string;\n}): Promise<boolean> {\n if (input.runtime.resolvedView !== \"human\") {\n return true;\n }\n\n return await ensureCommandAuthenticationOrCancel({\n runtime: input.runtime,\n ...(input.gatewayUrl ? { gatewayUrl: input.gatewayUrl } : {}),\n promptMessage: input.promptMessage,\n allowPrompt: input.allowPrompt,\n });\n}\n\nfunction isValidSpaceId(space: string): boolean {\n return SPACE_ID_HEX_REGEX.test(space.trim());\n}\n\nfunction isProfileKindSupportedForSpaceCommand(profileKind: string): boolean {\n return profileKind === \"human\" || profileKind === \"agent\";\n}\n\nfunction normalizeOptionalString(\n value: string | null | undefined\n): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import { OpenMeldApiClientHttpError } from \"@openmeld/api-client\";\nimport { GatewayHttpError } from \"./gateway-response\";\n\nconst HTTP_ERROR_MESSAGE_REGEX = /^HTTP\\s+(\\d{3})\\s*:\\s*([\\s\\S]*)$/i;\nconst MIN_HTTP_STATUS = 100;\nconst MAX_HTTP_STATUS = 599;\n\nexport type ParsedHttpFailure = {\n status: number;\n body: string;\n code: string;\n message: string;\n upstreamCode: string | null;\n};\n\nexport function parseHttpFailure(error: unknown): ParsedHttpFailure | null {\n if (\n error instanceof OpenMeldApiClientHttpError ||\n error instanceof GatewayHttpError\n ) {\n const payload = safeJsonParse(error.rawBody);\n const body = error.rawBody;\n return {\n status: error.status,\n body,\n code: resolveHttpErrorCode(payload, error.code),\n message: resolveHttpErrorMessage(payload, error.message),\n upstreamCode: resolveHttpErrorField(payload, \"upstreamCode\") ?? null,\n };\n }\n\n const rawMessage = toErrorMessage(error);\n const match = HTTP_ERROR_MESSAGE_REGEX.exec(rawMessage.trim());\n if (!match) {\n return null;\n }\n\n const status = Number.parseInt(match[1] ?? \"\", 10);\n if (\n !Number.isFinite(status) ||\n status < MIN_HTTP_STATUS ||\n status > MAX_HTTP_STATUS\n ) {\n return null;\n }\n\n const body = match[2] ?? \"\";\n const payload = safeJsonParse(body);\n return {\n status,\n body,\n code: resolveHttpErrorCode(payload),\n message: resolveHttpErrorMessage(payload),\n upstreamCode: resolveHttpErrorField(payload, \"upstreamCode\") ?? null,\n };\n}\n\nfunction resolveHttpErrorField(\n payload: unknown,\n field: \"code\" | \"message\" | \"upstreamCode\"\n): string | null {\n return normalizeOptionalText(readHttpErrorField(payload, field));\n}\n\nfunction resolveHttpErrorCode(payload: unknown, fallback?: string): string {\n return resolveHttpErrorField(payload, \"code\") ?? fallback ?? \"\";\n}\n\nfunction resolveHttpErrorMessage(payload: unknown, fallback?: string): string {\n return resolveHttpErrorField(payload, \"message\") ?? fallback ?? \"\";\n}\n\nfunction readHttpErrorField(\n payload: unknown,\n field: \"code\" | \"message\" | \"upstreamCode\"\n): string {\n if (!payload || typeof payload !== \"object\") {\n return \"\";\n }\n\n const record = payload as {\n code?: unknown;\n message?: unknown;\n upstreamCode?: unknown;\n error?: {\n code?: unknown;\n message?: unknown;\n upstreamCode?: unknown;\n } | null;\n };\n\n if (typeof record[field] === \"string\") {\n return record[field];\n }\n\n if (record.error && typeof record.error[field] === \"string\") {\n return record.error[field] ?? \"\";\n }\n\n return \"\";\n}\n\nfunction safeJsonParse(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n\n return String(error);\n}\n","import { parseHttpFailure } from \"./http-failure\";\n\nconst HTTP_STATUS_IN_TEXT_REGEX = /^HTTP\\s+(\\d{3}):/i;\n\nexport function normalizeOptionalString(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function parseHttpErrorMessage(error: unknown): {\n status: number;\n body: string;\n code: string;\n message: string;\n} | null {\n return parseHttpFailure(error);\n}\n\nexport function resolveUpstreamStatus(input: {\n status: number;\n body: string;\n message: string;\n}): number {\n if (input.status !== 502) {\n return input.status;\n }\n\n const wrapped = resolveStatusFromText(input.message);\n if (wrapped !== null) {\n return wrapped;\n }\n const fromBody = resolveStatusFromText(input.body);\n if (fromBody !== null) {\n return fromBody;\n }\n return input.status;\n}\n\nfunction resolveStatusFromText(value: string): number | null {\n const match = HTTP_STATUS_IN_TEXT_REGEX.exec(value.trim());\n if (!match) {\n return null;\n }\n const status = Number.parseInt(match[1] ?? \"\", 10);\n return Number.isFinite(status) ? status : null;\n}\n\nexport function readHttpErrorField(\n payload: unknown,\n field: \"code\" | \"message\"\n): string {\n if (!payload || typeof payload !== \"object\") {\n return \"\";\n }\n const record = payload as {\n code?: unknown;\n message?: unknown;\n error?: { code?: unknown; message?: unknown } | null;\n };\n if (typeof record[field] === \"string\") {\n return record[field];\n }\n if (record.error && typeof record.error[field] === \"string\") {\n return record.error[field] ?? \"\";\n }\n return \"\";\n}\n\nexport function readHttpRequestId(payload: unknown): string {\n if (!payload || typeof payload !== \"object\") {\n return \"\";\n }\n const record = payload as {\n requestId?: unknown;\n error?: { requestId?: unknown } | null;\n };\n if (typeof record.requestId === \"string\") {\n return record.requestId;\n }\n if (record.error && typeof record.error.requestId === \"string\") {\n return record.error.requestId;\n }\n return \"\";\n}\n\nexport function safeJsonParse(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nexport function toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n","import { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\n\nexport const SPACE_ID_HEX_REGEX = /^[0-9a-f]{64}$/i;\nexport const sanitizeSingleLinePromptText = (\n value: string | number | null | undefined\n): string => sanitizeTerminalDisplayText(value, \"single-line\").trim();\nexport const MENTION_ALIAS_TOKEN_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\nexport const MENTION_ALIAS_MAX_LENGTH = 128;\nexport const TRAILING_SLASHES_RE = /\\/+$/u;\n\nexport function resolveGatewayHost(baseUrl: string | undefined): string | null {\n if (typeof baseUrl !== \"string\" || baseUrl.trim().length === 0) {\n return null;\n }\n try {\n return new URL(baseUrl).host.toLowerCase();\n } catch {\n return null;\n }\n}\n\nexport function normalizeDisplayValue(\n value: unknown,\n fallback = \"unknown\"\n): string {\n const normalized = sanitizeSingleLinePromptText(String(value ?? \"\"));\n return normalized.length > 0 ? normalized : fallback;\n}\n\nexport function shortenSpaceId(spaceId: string): string {\n const normalized = sanitizeSingleLinePromptText(spaceId);\n if (normalized.length <= 14) {\n return normalized;\n }\n return `${normalized.slice(0, 8)}...${normalized.slice(-6)}`;\n}\n\nexport function isValidSpaceId(space: string): boolean {\n // Contract lock: space command targets are canonical spaceId only (64-char hex),\n // never space name.\n const normalized = space.trim();\n return SPACE_ID_HEX_REGEX.test(normalized);\n}\n\nexport function isInputClosed(stream: NodeJS.ReadStream): boolean {\n return stream.destroyed || stream.readableEnded;\n}\n\nexport function normalizeGuideInput(\n value: string | undefined\n): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\nexport function normalizeMentionAliasInput(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim();\n if (\n normalized.length === 0 ||\n normalized.length > MENTION_ALIAS_MAX_LENGTH ||\n !MENTION_ALIAS_TOKEN_REGEX.test(normalized)\n ) {\n return undefined;\n }\n return normalized;\n}\n\nexport function normalizeRoleInput(\n value: string | undefined\n): string | undefined {\n const normalized = String(value ?? \"\").trim();\n if (!normalized) {\n return undefined;\n }\n return normalized;\n}\n","import { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\n\nexport type SpaceDisplayProjectionInput = {\n currentProfileId?: string | null;\n currentProfileName?: string | null;\n spaceId: string | null | undefined;\n spaceName?: string | null;\n creatorProfileName?: string | null;\n creatorProfileId?: string | null;\n availableViaProfileName?: string | null;\n availableViaProfileId?: string | null;\n spaceCreatedAt?: string | null;\n lastJoinedAt?: string | null;\n passwordProtected?: boolean | null;\n};\n\nexport type SpaceMetadataFieldId =\n | \"spaceId\"\n | \"spaceCreatedAt\"\n | \"spaceCreator\"\n | \"spaceCreatorProfileId\"\n | \"availableVia\"\n | \"availableViaProfileId\"\n | \"lastJoinedAt\";\n\nexport type SpaceMetadataField = {\n id: SpaceMetadataFieldId;\n label: string;\n value: string;\n};\n\nexport type SpaceDisplayProjection = {\n spaceId: string | null;\n spaceName: string | null;\n creatorProfileName: string | null;\n creatorProfileId: string | null;\n creatorDisplayName: string | null;\n availableViaProfileName: string | null;\n availableViaProfileId: string | null;\n availableViaDisplayName: string | null;\n spaceCreatedAt: string | null;\n lastJoinedAt: string | null;\n passwordProtected: boolean | null;\n};\n\nexport function buildSpaceDisplayProjection(\n input: SpaceDisplayProjectionInput\n): SpaceDisplayProjection {\n const currentProfileId = normalizeSpaceDisplayText(input.currentProfileId);\n const currentProfileName = normalizeSpaceDisplayText(\n input.currentProfileName\n );\n const creatorProfileName = normalizeSpaceDisplayText(\n input.creatorProfileName\n );\n const creatorProfileId = normalizeSpaceDisplayText(input.creatorProfileId);\n const availableViaProfileName = normalizeSpaceDisplayText(\n input.availableViaProfileName\n );\n const availableViaProfileId = normalizeSpaceDisplayText(\n input.availableViaProfileId\n );\n\n return {\n spaceId: normalizeSpaceDisplayText(input.spaceId),\n spaceName: normalizeSpaceDisplayText(input.spaceName),\n creatorProfileName,\n creatorProfileId,\n creatorDisplayName: resolveSpaceProfileDisplayName({\n currentProfileId,\n currentProfileName,\n profileId: creatorProfileId,\n profileName: creatorProfileName,\n }),\n availableViaProfileName,\n availableViaProfileId,\n availableViaDisplayName: resolveSpaceProfileDisplayName({\n currentProfileId,\n currentProfileName,\n profileId: availableViaProfileId,\n profileName: availableViaProfileName,\n }),\n spaceCreatedAt: normalizeSpaceDisplayText(input.spaceCreatedAt),\n lastJoinedAt: normalizeSpaceDisplayText(input.lastJoinedAt),\n passwordProtected:\n typeof input.passwordProtected === \"boolean\"\n ? input.passwordProtected\n : null,\n };\n}\n\nexport function buildSpaceMetadataFields(input: {\n projection: SpaceDisplayProjection;\n includeAvailableVia?: boolean;\n includeCreatedAt?: boolean;\n includeLastJoinedAt?: boolean;\n}): SpaceMetadataField[] {\n const fields: SpaceMetadataField[] = [\n {\n id: \"spaceId\",\n label: \"Space ID\",\n value: formatSpaceDisplayValue(input.projection.spaceId),\n },\n {\n id: \"spaceCreator\",\n label: \"Space Creator\",\n value: formatSpaceDisplayValue(\n input.projection.creatorDisplayName,\n \"unknown-profile\"\n ),\n },\n {\n id: \"spaceCreatorProfileId\",\n label: \"Space Creator Profile ID\",\n value: formatSpaceDisplayValue(\n input.projection.creatorProfileId,\n \"unknown-profile\"\n ),\n },\n ];\n\n if (input.includeAvailableVia === true) {\n fields.push(\n {\n id: \"availableVia\",\n label: \"Available via\",\n value: formatSpaceDisplayValue(\n input.projection.availableViaDisplayName\n ),\n },\n {\n id: \"availableViaProfileId\",\n label: \"Available via Profile ID\",\n value: formatSpaceDisplayValue(input.projection.availableViaProfileId),\n }\n );\n }\n\n if (input.includeCreatedAt === true) {\n fields.push({\n id: \"spaceCreatedAt\",\n label: \"Space Created\",\n value: formatSpaceDisplayValue(input.projection.spaceCreatedAt),\n });\n }\n\n if (input.includeLastJoinedAt === true) {\n fields.push({\n id: \"lastJoinedAt\",\n label: \"Last joined\",\n value: formatSpaceDisplayValue(input.projection.lastJoinedAt),\n });\n }\n\n return fields;\n}\n\nexport function formatSpaceDisplayValue(\n value: string | null | undefined,\n fallback = \"unknown\"\n): string {\n return value ?? fallback;\n}\n\nexport function resolveSpaceDisplayName(\n value: string | null | undefined,\n fallback: string\n): string {\n return value ?? fallback;\n}\n\nexport function normalizeSpaceDisplayText(\n value: string | number | null | undefined\n): string | null {\n const normalized = sanitizeTerminalDisplayText(value, \"single-line\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction resolveSpaceProfileDisplayName(input: {\n currentProfileId: string | null;\n currentProfileName: string | null;\n profileId: string | null;\n profileName: string | null;\n}): string | null {\n if (input.profileName) {\n return input.profileName;\n }\n if (\n input.profileId &&\n input.currentProfileId &&\n input.profileId === input.currentProfileId\n ) {\n return input.currentProfileName ?? input.profileId;\n }\n return input.profileId;\n}\n","import type { SpaceCreator } from \"@openmeld/protocol\";\nimport type { AccountSpaceIndexItem } from \"@openmeld/schemas/types\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { normalizeOptionalString } from \"./command-http-errors\";\nimport {\n normalizeDisplayValue,\n resolveGatewayHost,\n} from \"./command-input-normalizers\";\nimport type { SpaceConfig } from \"./local-state\";\nimport {\n buildSpaceDisplayProjection,\n buildSpaceMetadataFields,\n resolveSpaceDisplayName,\n} from \"./space-display-projection\";\n\ntype KnownSpaceSource = \"cloud\" | \"local\";\nconst LEGACY_WELCOMING_SPACE_PURPOSE = \"openmeld_welcoming_space\";\n\nexport type KnownSpaceOption = {\n source: KnownSpaceSource;\n space: string;\n baseUrl?: string;\n name?: string | null;\n creatorProfileName?: string | null;\n creatorProfileId?: string | null;\n creatorOwnerUserId?: string | null;\n creatorKind?: string | null;\n availableViaProfileName?: string | null;\n availableViaProfileId?: string | null;\n spaceCreatedAt?: string | null;\n spaceUpdatedAt?: string | null;\n lastJoinedAt?: string | null;\n lastSeenTs?: number | null;\n passwordProtected?: boolean | null;\n status?: string | null;\n updatedAt?: string | null;\n gatewayHost?: string | null;\n spacePurpose?: string | null;\n activeAgentCount?: number | null;\n activeHumanCount?: number | null;\n activeMemberCount?: number | null;\n};\n\nexport type KnownSpaceVisibilityScope = \"profile\" | \"owner\";\n\nexport type KnownSpaceDeletedNotice = {\n gatewayHost: string;\n spaceId: string;\n spaceName: string | null;\n deletedAt: string;\n deletedByProfileName: string | null;\n deletedByProfileId: string | null;\n};\n\ntype KnownSpaceDetailVariant = \"full\" | \"delete_confirmation\";\n\nexport function toKnownSpaceOptionFromAccountIndex(\n item: AccountSpaceIndexItem,\n baseUrl: string\n): KnownSpaceOption {\n return {\n source: \"cloud\",\n space: item.spaceId,\n baseUrl,\n name: item.spaceName,\n creatorProfileName: item.creatorProfileName,\n creatorProfileId: item.creatorProfileId,\n creatorOwnerUserId: item.creatorOwnerUserId,\n creatorKind: item.creatorKind,\n availableViaProfileName: item.openProfileName,\n availableViaProfileId: item.openProfileId,\n spaceCreatedAt: item.spaceCreatedAt,\n spaceUpdatedAt: item.spaceUpdatedAt,\n lastJoinedAt: item.lastJoinedAt,\n lastSeenTs: item.lastSeenTs,\n status: item.status,\n updatedAt: item.updatedAt,\n gatewayHost: item.gatewayHost,\n spacePurpose: item.spacePurpose,\n activeAgentCount: item.activeAgentCount,\n activeHumanCount: item.activeHumanCount,\n activeMemberCount: item.activeMemberCount,\n };\n}\n\nexport function resolveKnownSpaceVisibilityScope(input: {\n openMeldProfile: OpenMeldProfile;\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): KnownSpaceVisibilityScope {\n if (\n input.openMeldProfile.profileKind === \"human\" &&\n input.openMeldProfile.isDefault === true &&\n (input.command === \"join\" ||\n input.command === \"watch\" ||\n input.command === \"guide\" ||\n input.command === \"delete\")\n ) {\n return \"owner\";\n }\n return \"profile\";\n}\n\nexport function shouldLoadCloudKnownSpaces(input: {\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n visibilityScope: KnownSpaceVisibilityScope;\n}): boolean {\n if (\n input.command === \"join\" ||\n input.command === \"watch\" ||\n input.command === \"guide\" ||\n input.command === \"delete\" ||\n input.command === \"password\" ||\n input.command === \"add_members\" ||\n input.command === \"remove_members\" ||\n input.command === \"leave\"\n ) {\n return true;\n }\n return input.visibilityScope === \"owner\";\n}\n\nexport function filterKnownSpacesForSelection(\n spaces: KnownSpaceOption[]\n): KnownSpaceOption[] {\n return spaces.filter((space) => !isHiddenKnownSpaceForSelection(space));\n}\n\nfunction isHiddenKnownSpaceForSelection(space: KnownSpaceOption): boolean {\n return (\n normalizeOptionalString(space.spacePurpose) ===\n LEGACY_WELCOMING_SPACE_PURPOSE\n );\n}\n\nexport function sortKnownSpacesForSelection(\n spaces: KnownSpaceOption[]\n): KnownSpaceOption[] {\n return [...spaces].sort((left, right) => {\n const leftSortKey = resolveKnownSpaceSortKey(left);\n const rightSortKey = resolveKnownSpaceSortKey(right);\n if (leftSortKey.rank !== rightSortKey.rank) {\n return rightSortKey.rank - leftSortKey.rank;\n }\n if (leftSortKey.timestamp !== rightSortKey.timestamp) {\n return rightSortKey.timestamp - leftSortKey.timestamp;\n }\n if (leftSortKey.name !== rightSortKey.name) {\n return leftSortKey.name.localeCompare(rightSortKey.name);\n }\n return leftSortKey.space.localeCompare(rightSortKey.space);\n });\n}\n\nfunction resolveKnownSpaceSortKey(space: KnownSpaceOption): {\n rank: number;\n timestamp: number;\n name: string;\n space: string;\n} {\n const joinedAt = parseKnownSpaceTimestamp(space.lastJoinedAt);\n if (joinedAt !== null) {\n return {\n rank: 3,\n timestamp: joinedAt,\n name: normalizeKnownSpaceSortName(space.name),\n space: space.space,\n };\n }\n\n const lastSeenTs =\n typeof space.lastSeenTs === \"number\" && Number.isFinite(space.lastSeenTs)\n ? space.lastSeenTs\n : null;\n if (lastSeenTs !== null) {\n return {\n rank: 2,\n timestamp: lastSeenTs,\n name: normalizeKnownSpaceSortName(space.name),\n space: space.space,\n };\n }\n\n const updatedAt =\n parseKnownSpaceTimestamp(space.updatedAt) ??\n parseKnownSpaceTimestamp(space.spaceUpdatedAt) ??\n parseKnownSpaceTimestamp(space.spaceCreatedAt) ??\n 0;\n return {\n rank: updatedAt > 0 ? 1 : 0,\n timestamp: updatedAt,\n name: normalizeKnownSpaceSortName(space.name),\n space: space.space,\n };\n}\n\nfunction parseKnownSpaceTimestamp(\n value: string | null | undefined\n): number | null {\n const normalized = normalizeOptionalString(value);\n if (!normalized) {\n return null;\n }\n const timestamp = Date.parse(normalized);\n return Number.isFinite(timestamp) ? timestamp : null;\n}\n\nfunction normalizeKnownSpaceSortName(value: string | null | undefined): string {\n return normalizeOptionalString(value)?.toLowerCase() ?? \"untitled-space\";\n}\n\nexport function normalizeKnownSpaceVisibilityScope(\n visibilityScope?: KnownSpaceVisibilityScope\n): KnownSpaceVisibilityScope {\n return visibilityScope === \"owner\" ? \"owner\" : \"profile\";\n}\n\nexport function formatKnownSpaceName(input: {\n space: KnownSpaceOption;\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentOwnerUserId?: string;\n command?:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): string {\n const projection = buildKnownSpaceDisplayProjection({\n space: input.space,\n currentProfileId: input.currentProfileId,\n });\n const name = resolveSpaceDisplayName(projection.spaceName, \"untitled-space\");\n if (input.command === \"password\") {\n return input.space.passwordProtected === true ? `🔒 ${name}` : name;\n }\n const nameWithProtectionMarker =\n input.resolvedView === \"human\" && input.space.passwordProtected === true\n ? `🔒 - ${name}`\n : name;\n return nameWithProtectionMarker;\n}\n\nexport function formatKnownSpaceOptionLabel(input: {\n space: KnownSpaceOption;\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentProfileName?: string;\n currentOwnerUserId?: string;\n command?:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): string {\n const lines = formatKnownSpaceDetailLines(input);\n const label = formatKnownSpaceName({\n space: input.space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n });\n if (lines.length === 0) {\n return label;\n }\n return [label, ...lines.map((line) => ` - ${line}`)].join(\"\\n\");\n}\n\nexport function formatKnownSpaceListLine(input: {\n index: number;\n space: KnownSpaceOption;\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentProfileName?: string;\n currentOwnerUserId?: string;\n command?:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): string {\n const title = `${String(input.index)}. ${formatKnownSpaceName({\n space: input.space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n })}`;\n const lines = formatKnownSpaceDetailLines({\n space: input.space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n ...(input.currentProfileName\n ? { currentProfileName: input.currentProfileName }\n : {}),\n ...(input.command ? { command: input.command } : {}),\n });\n return [title, ...lines.map((line) => ` ${line}`)].join(\"\\n\");\n}\n\nexport function buildKnownSpaceData(\n item: KnownSpaceOption,\n index: number\n): Record<string, unknown> {\n return {\n index,\n spaceId: item.space,\n name: formatKnownSpaceName({\n space: item,\n resolvedView: \"agent\",\n currentProfileId: \"\",\n }),\n source: item.source,\n creatorProfileName: item.creatorProfileName ?? null,\n creatorProfileId: item.creatorProfileId ?? null,\n creatorOwnerUserId: item.creatorOwnerUserId ?? null,\n creatorKind: item.creatorKind ?? null,\n availableViaProfileName: item.availableViaProfileName ?? null,\n availableViaProfileId: item.availableViaProfileId ?? null,\n spaceCreatedAt: item.spaceCreatedAt ?? null,\n spaceUpdatedAt: item.spaceUpdatedAt ?? null,\n lastJoinedAt: item.lastJoinedAt ?? null,\n lastSeenTs: item.lastSeenTs ?? null,\n status: item.status ?? null,\n gatewayHost: item.gatewayHost ?? null,\n baseUrl: item.baseUrl ?? null,\n spacePurpose: item.spacePurpose ?? null,\n activeAgentCount: item.activeAgentCount ?? null,\n activeHumanCount: item.activeHumanCount ?? null,\n activeMemberCount: item.activeMemberCount ?? null,\n };\n}\n\nexport function formatKnownSpaceDetailLines(input: {\n space: KnownSpaceOption;\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentProfileName?: string;\n currentOwnerUserId?: string;\n detailVariant?: KnownSpaceDetailVariant;\n command?:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): string[] {\n const projection = buildKnownSpaceDisplayProjection({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n });\n const detailVariant = input.detailVariant ?? \"full\";\n const lines = buildSpaceMetadataFields({\n projection,\n includeAvailableVia: detailVariant !== \"delete_confirmation\",\n includeCreatedAt: detailVariant !== \"delete_confirmation\",\n includeLastJoinedAt: detailVariant !== \"delete_confirmation\",\n }).map((field) => `${field.label}: ${field.value}`);\n\n if (detailVariant === \"delete_confirmation\") {\n return lines;\n }\n\n if (input.resolvedView === \"human\") {\n if (input.space.source === \"local\") {\n lines.push(\"Source: local cache\");\n }\n return lines;\n }\n\n lines.push(`Gateway: ${normalizeDisplayValue(input.space.gatewayHost)}`);\n lines.push(`Status: ${normalizeDisplayValue(input.space.status)}`);\n lines.push(`Creator kind: ${normalizeDisplayValue(input.space.creatorKind)}`);\n lines.push(\n `Space updated: ${normalizeDisplayValue(input.space.spaceUpdatedAt)}`\n );\n lines.push(`Last seen ts: ${normalizeDisplayValue(input.space.lastSeenTs)}`);\n lines.push(`Record updated: ${normalizeDisplayValue(input.space.updatedAt)}`);\n lines.push(`Source: ${input.space.source}`);\n\n return lines;\n}\n\nexport function toKnownSpaceOptionFromLocal(\n item: SpaceConfig,\n availableViaProfile?: OpenMeldProfile\n): KnownSpaceOption {\n const creatorProfileName = resolveLocalCreatorProfileName(item.creator);\n const creatorProfileId = resolveLocalCreatorProfileId(item.creator);\n const creatorOwnerUserId = resolveLocalCreatorOwnerUserId(item.creator);\n\n return {\n source: \"local\",\n space: item.space,\n baseUrl: item.baseUrl,\n name: item.name ?? null,\n creatorProfileName,\n creatorProfileId,\n creatorOwnerUserId,\n creatorKind:\n typeof item.creator?.kind === \"string\" ? item.creator.kind : null,\n availableViaProfileName: availableViaProfile?.profileName ?? null,\n availableViaProfileId: availableViaProfile?.openMeldProfileId ?? null,\n spaceCreatedAt: item.spaceCreatedAt ?? null,\n spaceUpdatedAt: item.spaceUpdatedAt ?? null,\n lastJoinedAt: resolveKnownSpaceLastSeenTimestamp(item.lastSeenTs),\n lastSeenTs:\n typeof item.lastSeenTs === \"number\" && Number.isFinite(item.lastSeenTs)\n ? item.lastSeenTs\n : null,\n passwordProtected:\n typeof item.passwordProtected === \"boolean\"\n ? item.passwordProtected\n : null,\n updatedAt: item.updatedAt,\n gatewayHost: resolveGatewayHost(item.baseUrl),\n spacePurpose: item.spacePurpose ?? null,\n activeAgentCount: item.activeAgentCount ?? null,\n activeHumanCount: item.activeHumanCount ?? null,\n activeMemberCount: item.activeMemberCount ?? null,\n };\n}\n\nfunction resolveLocalCreatorProfileId(\n creator: SpaceCreator | undefined\n): string | null {\n if (typeof creator?.profile === \"string\") {\n return creator.profile;\n }\n if (typeof creator?.profileId === \"string\") {\n return creator.profileId;\n }\n return null;\n}\n\nfunction resolveLocalCreatorProfileName(\n creator: SpaceCreator | undefined\n): string | null {\n if (typeof creator?.profileName !== \"string\") {\n return null;\n }\n const normalized = creator.profileName.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction resolveLocalCreatorOwnerUserId(\n creator: SpaceCreator | undefined\n): string | null {\n if (typeof creator?.ownerUserId !== \"string\") {\n return null;\n }\n const normalized = creator.ownerUserId.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function buildKnownSpaceDisplayProjection(input: {\n space: KnownSpaceOption;\n currentProfileId: string;\n currentProfileName?: string;\n}) {\n return buildSpaceDisplayProjection({\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n spaceId: input.space.space,\n spaceName: input.space.name,\n creatorProfileId: input.space.creatorProfileId,\n creatorProfileName: input.space.creatorProfileName,\n availableViaProfileId: input.space.availableViaProfileId,\n availableViaProfileName: input.space.availableViaProfileName,\n spaceCreatedAt: input.space.spaceCreatedAt,\n lastJoinedAt: resolveKnownSpaceJoinedTimestamp(input.space),\n passwordProtected: input.space.passwordProtected,\n });\n}\n\nexport function resolveKnownSpaceJoinedTimestamp(\n space: KnownSpaceOption\n): string | null {\n return (\n normalizeOptionalString(space.lastJoinedAt) ??\n resolveKnownSpaceLastSeenTimestamp(space.lastSeenTs)\n );\n}\n\nexport function resolveKnownSpaceLastSeenTimestamp(\n value: number | null | undefined\n): string | null {\n if (\n typeof value !== \"number\" ||\n !Number.isFinite(value) ||\n value < 1_000_000_000_000\n ) {\n return null;\n }\n return new Date(value).toISOString();\n}\n","import type { AgentTargetState } from \"../agents/registry\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport {\n formatInlineOpenMeldCliCommands,\n formatOpenMeldCliCommand,\n} from \"../runtime/cli-entry-command\";\nimport {\n formatSpaceMemberCommandRecoveryCopy,\n REPLY_READINESS_COPY,\n resolveReplyReadinessAvailabilityReasonCopy,\n} from \"../system/reply-readiness-copy\";\nimport type { ServiceParticipationReadiness } from \"../system/service-participation-readiness\";\nimport { normalizeOptionalString } from \"./command-http-errors\";\nimport { sanitizeSingleLinePromptText } from \"./command-input-normalizers\";\n\nexport type SpaceMembershipProfileKind = \"human\" | \"agent\";\n\nexport type SpaceMemberCandidate = {\n openMeldProfile?: OpenMeldProfile;\n profileId: string;\n profileHandle?: string;\n profileName: string;\n profileKind: SpaceMembershipProfileKind;\n targetMentionLabel?: string | null;\n ownerProfileName?: string;\n ownerUserId?: string;\n ownerName?: string;\n agentControllerRef?: string;\n controllerEnabled?: boolean;\n localTargetAgentId?: string | null;\n localTargetDisplayName?: string | null;\n localTargetLaunchStatus?: AgentTargetState[\"launchStatus\"] | null;\n localTargetSelectable?: boolean;\n localParticipationBindingConfirmed?: boolean;\n localParticipationReadiness?: ServiceParticipationReadiness | null;\n localParticipationChecked?: boolean;\n localParticipationReasonCodes?: string[];\n localParticipationReasonText?: string | null;\n alreadyJoined: boolean;\n needsActivation: boolean;\n organizationDirectoryProfile?: boolean;\n isOrganizationCenterAgent?: boolean;\n};\n\ntype SpaceMemberRecoveryNextAction =\n | {\n command: string;\n kind: \"command\";\n }\n | {\n instruction: string;\n kind: \"instruction\";\n };\n\nconst SPACE_MEMBER_PROFILE_CONNECTION_REASON_CODES: ReadonlySet<string> =\n new Set([\"profile.unbound\", \"agent_profile_binding.missing\"]);\n\nconst SPACE_MEMBER_PROFILE_RECONNECT_REASON_CODES: ReadonlySet<string> =\n new Set([\n \"agent_profile_binding.owner_mismatch\",\n \"agent_profile_binding.runtime_mismatch\",\n \"agent_profile_binding.capability_mismatch\",\n \"claim_eligibility.binding_capability_mismatch\",\n \"claim_eligibility.binding_owner_mismatch\",\n \"claim_eligibility.binding_runtime_mismatch\",\n \"claim_eligibility.owner_mismatch\",\n \"claim_eligibility.openmeld_service_runtime_id_mismatch\",\n \"local_service.identity_mismatch\",\n ]);\n\nconst SPACE_MEMBER_SERVICE_STATUS_REASON_CODES: ReadonlySet<string> = new Set([\n \"agent_profile_binding.local_service_not_connected\",\n \"agent_profile_binding.execution_readiness_pending\",\n \"route.offline\",\n \"route.not_registered\",\n \"service.gateway_chain_unhealthy\",\n \"dispatch.storage_not_ready\",\n]);\n\nconst SPACE_MEMBER_LOCAL_AGENT_REPAIR_REASON_CODES: ReadonlySet<string> =\n new Set([\n \"controller.launch.needs_repair\",\n \"controller.launch.choice_required\",\n \"workspace.missing\",\n \"workspace.invalid\",\n \"controller.bootstrap.failed\",\n \"controller.gateway.unhealthy\",\n ]);\n\nexport function resolveSpaceMemberJoinOnlyNextAction(\n candidate: Pick<\n SpaceMemberCandidate,\n | \"controllerEnabled\"\n | \"agentControllerRef\"\n | \"localParticipationReadiness\"\n | \"localParticipationReasonCodes\"\n | \"localTargetAgentId\"\n | \"profileId\"\n >\n): SpaceMemberRecoveryNextAction {\n if (candidate.localParticipationReadiness === \"not_running\") {\n return {\n command: buildSpaceMemberProfileStatusCommand(candidate.profileId),\n kind: \"command\",\n };\n }\n if (candidate.localParticipationReadiness === \"not_installed\") {\n return {\n command: buildSpaceMemberProfileStatusCommand(candidate.profileId),\n kind: \"command\",\n };\n }\n if (\n candidate.localParticipationReadiness === \"needs_repair\" ||\n hasSpaceMemberReasonCode(\n candidate,\n SPACE_MEMBER_LOCAL_AGENT_REPAIR_REASON_CODES\n )\n ) {\n return {\n command: buildSpaceMemberRepairCommand({\n agentId: candidate.localTargetAgentId,\n profileId: candidate.profileId,\n }),\n kind: \"command\",\n };\n }\n if (\n hasSpaceMemberReasonCode(\n candidate,\n SPACE_MEMBER_SERVICE_STATUS_REASON_CODES\n )\n ) {\n const profileConnectionAction =\n resolveSpaceMemberProfileConnectionAction(candidate);\n if (profileConnectionAction) {\n return profileConnectionAction;\n }\n return {\n command: buildSpaceMemberProfileStatusCommand(candidate.profileId),\n kind: \"command\",\n };\n }\n const profileConnectionAction =\n resolveSpaceMemberProfileConnectionAction(candidate);\n if (profileConnectionAction) {\n return profileConnectionAction;\n }\n return {\n instruction: REPLY_READINESS_COPY.spaceMember.checkProfileInstruction,\n kind: \"instruction\",\n };\n}\n\nexport function resolveSpaceMemberCandidateStatusLabel(\n candidate: SpaceMemberCandidate\n): string | null {\n const statuses = resolveSpaceMemberCandidateStatusBadges(candidate);\n if (statuses.length === 0) {\n return null;\n }\n return statuses.join(\" · \");\n}\n\nconst TRAILING_PERIOD_RE = /\\.$/u;\n\nexport function resolveSpaceMemberCandidateStatusBadges(\n candidate: SpaceMemberCandidate\n): string[] {\n if (candidate.profileKind !== \"agent\") {\n return [];\n }\n if (candidate.localParticipationChecked !== true) {\n return [];\n }\n if (isSpaceMemberCandidateBackgroundReplyReady(candidate)) {\n return [REPLY_READINESS_COPY.spaceMember.connectedBadge];\n }\n if (isSpaceMemberCandidateRepairableLocalParticipationCandidate(candidate)) {\n return [REPLY_READINESS_COPY.spaceMember.needsRepairBadge];\n }\n return [\n resolveSpaceMemberJoinOnlyReason(candidate).replace(TRAILING_PERIOD_RE, \"\"),\n REPLY_READINESS_COPY.spaceMember.joinsOnlyBadge,\n ];\n}\n\nexport function isSpaceMemberCandidateBackgroundReplyReady(\n candidate: Pick<\n SpaceMemberCandidate,\n | \"profileKind\"\n | \"agentControllerRef\"\n | \"controllerEnabled\"\n | \"localTargetSelectable\"\n | \"localParticipationReadiness\"\n >\n): boolean {\n return (\n candidate.profileKind === \"agent\" &&\n candidate.controllerEnabled === true &&\n typeof candidate.agentControllerRef === \"string\" &&\n candidate.agentControllerRef.trim().length > 0 &&\n candidate.localTargetSelectable === true &&\n candidate.localParticipationReadiness === \"ready\"\n );\n}\n\nexport function isSpaceMemberCandidateRepairableLocalParticipationCandidate(\n candidate: Pick<\n SpaceMemberCandidate,\n | \"profileKind\"\n | \"agentControllerRef\"\n | \"controllerEnabled\"\n | \"localTargetAgentId\"\n | \"localTargetLaunchStatus\"\n | \"localParticipationReadiness\"\n >\n): boolean {\n return (\n candidate.profileKind === \"agent\" &&\n candidate.controllerEnabled === true &&\n typeof candidate.agentControllerRef === \"string\" &&\n candidate.agentControllerRef.trim().length > 0 &&\n ((typeof candidate.localTargetAgentId === \"string\" &&\n candidate.localTargetAgentId.trim().length > 0 &&\n candidate.localTargetLaunchStatus === \"needs_repair\") ||\n candidate.localParticipationReadiness === \"needs_repair\")\n );\n}\n\nexport function resolveSpaceMemberJoinOnlyReason(\n candidate: Pick<\n SpaceMemberCandidate,\n | \"controllerEnabled\"\n | \"agentControllerRef\"\n | \"localParticipationReadiness\"\n | \"localParticipationReasonText\"\n >\n): string {\n if (\n candidate.controllerEnabled !== true ||\n typeof candidate.agentControllerRef !== \"string\" ||\n candidate.agentControllerRef.trim().length === 0\n ) {\n return resolveReplyReadinessAvailabilityReasonCopy(\"profile.unbound\");\n }\n if (candidate.localParticipationReadiness === \"not_running\") {\n return resolveReplyReadinessAvailabilityReasonCopy(\"service.not_running\");\n }\n if (candidate.localParticipationReadiness === \"not_installed\") {\n return resolveReplyReadinessAvailabilityReasonCopy(\"service.not_installed\");\n }\n const reasonText = normalizeOptionalString(\n candidate.localParticipationReasonText\n );\n if (reasonText) {\n const sanitizedReasonText = sanitizeSingleLinePromptText(reasonText);\n if (sanitizedReasonText) {\n return sanitizedReasonText.endsWith(\".\")\n ? sanitizedReasonText\n : `${sanitizedReasonText}.`;\n }\n }\n return REPLY_READINESS_COPY.spaceMember.incompleteReason;\n}\n\nfunction resolveSpaceMemberProfileConnectionAction(\n candidate: Pick<\n SpaceMemberCandidate,\n \"controllerEnabled\" | \"agentControllerRef\" | \"localParticipationReasonCodes\"\n >\n): SpaceMemberRecoveryNextAction | null {\n const reasonCodes = candidate.localParticipationReasonCodes ?? [];\n if (\n reasonCodes.some((reasonCode) =>\n SPACE_MEMBER_PROFILE_RECONNECT_REASON_CODES.has(reasonCode)\n )\n ) {\n return {\n instruction: REPLY_READINESS_COPY.spaceMember.reconnectProfileInstruction,\n kind: \"instruction\",\n };\n }\n if (\n candidate.controllerEnabled !== true ||\n typeof candidate.agentControllerRef !== \"string\" ||\n candidate.agentControllerRef.trim().length === 0 ||\n reasonCodes.some((reasonCode) =>\n SPACE_MEMBER_PROFILE_CONNECTION_REASON_CODES.has(reasonCode)\n )\n ) {\n return {\n instruction:\n REPLY_READINESS_COPY.spaceMember.selectProfileAgentInstruction,\n kind: \"instruction\",\n };\n }\n if (reasonCodes.includes(\"controller.binding.disabled\")) {\n return {\n instruction:\n REPLY_READINESS_COPY.spaceMember.turnOnProfileAgentInstruction,\n kind: \"instruction\",\n };\n }\n return null;\n}\n\nfunction hasSpaceMemberReasonCode(\n candidate: Pick<SpaceMemberCandidate, \"localParticipationReasonCodes\">,\n reasonCodes: ReadonlySet<string>\n): boolean {\n return (candidate.localParticipationReasonCodes ?? []).some((reasonCode) =>\n reasonCodes.has(reasonCode)\n );\n}\n\nexport function formatSpaceMemberRecoveryNextAction(\n action: SpaceMemberRecoveryNextAction\n): string {\n if (action.kind === \"instruction\") {\n return action.instruction;\n }\n if (action.command === \"openmeld agents list\") {\n return formatInlineOpenMeldCliCommands(\n REPLY_READINESS_COPY.spaceMember.agentsListRepairInstruction\n );\n }\n return formatSpaceMemberCommandRecoveryCopy(\n formatOpenMeldCliCommand(action.command)\n );\n}\n\nexport function resolveSpaceMemberTerminalProfileLabel(\n profileName: unknown\n): string {\n const normalizedProfileName = normalizeOptionalString(profileName);\n return (\n sanitizeSingleLinePromptText(normalizedProfileName) ||\n REPLY_READINESS_COPY.spaceMember.fallbackProfileLabel\n );\n}\n\nexport function resolveSpaceMemberTerminalLocalTargetLabel(input: {\n displayName?: string | null;\n agentId?: string | null;\n}): string {\n const displayName = sanitizeSingleLinePromptText(input.displayName);\n if (displayName) {\n return displayName;\n }\n const agentId = sanitizeSingleLinePromptText(input.agentId);\n if (agentId) {\n return agentId;\n }\n return REPLY_READINESS_COPY.spaceMember.fallbackLocalTargetLabel;\n}\n\nfunction buildSpaceMemberProfileStatusCommand(profileId: string): string {\n const sanitizedProfileId = sanitizeSingleLinePromptText(profileId);\n return sanitizedProfileId\n ? `openmeld service status --profile ${sanitizedProfileId}`\n : \"openmeld service status\";\n}\n\nexport function buildSpaceMemberRepairCommand(input: {\n agentId?: string | null;\n profileId: string;\n}): string {\n const sanitizedAgentId = sanitizeSingleLinePromptText(input.agentId);\n if (sanitizedAgentId) {\n return `openmeld agents repair --agent ${sanitizedAgentId}`;\n }\n return \"openmeld agents list\";\n}\n","import { cancel, isCancel, multiselect, select, text } from \"@clack/prompts\";\nimport pc from \"picocolors\";\nimport { formatMessage } from \"../runtime/messages\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport {\n promptSearchMultiselect,\n promptSearchSelect,\n} from \"../ui/search-select\";\nimport { promptTextEntry } from \"../ui/text-entry\";\nimport { normalizeOptionalString } from \"./command-http-errors\";\nimport {\n isInputClosed,\n isValidSpaceId,\n sanitizeSingleLinePromptText,\n shortenSpaceId,\n} from \"./command-input-normalizers\";\nimport {\n buildKnownSpaceDisplayProjection,\n formatKnownSpaceName,\n formatKnownSpaceOptionLabel,\n type KnownSpaceDeletedNotice,\n type KnownSpaceOption,\n type KnownSpaceVisibilityScope,\n normalizeKnownSpaceVisibilityScope,\n resolveKnownSpaceJoinedTimestamp,\n} from \"./command-known-space-projection\";\nimport {\n isLocalSpaceStateCorruptResult,\n readSpaceCacheDeletionNoticeState,\n toLocalSpaceStateIntegrityError,\n writeSpaceCacheDeletionNoticeState,\n} from \"./local-state\";\nimport { formatSpaceDisplayValue } from \"./space-display-projection\";\n\nexport type SpaceDeleteTarget = {\n space: string;\n baseUrl?: string;\n name?: string | null;\n creatorProfileName?: string | null;\n creatorProfileId?: string | null;\n creatorOwnerUserId?: string | null;\n creatorKind?: string | null;\n};\n\nexport type SpaceDeleteTargetSelectionResult =\n | {\n status: \"submitted\";\n targets: SpaceDeleteTarget[];\n allowBackToSelection: boolean;\n }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\nexport type SpaceJoinTargetResolution =\n | {\n status: \"submitted\";\n value: SpaceSelectionTarget;\n }\n | {\n status: \"cancelled\" | \"back\" | \"create\";\n value: null;\n };\n\nasync function consumeKnownSpaceDeletedNoticePromptLines(input: {\n openMeldProfileId: string;\n deletedNotices: KnownSpaceDeletedNotice[];\n}): Promise<string[]> {\n if (input.deletedNotices.length === 0) {\n return [];\n }\n\n await markKnownSpaceDeletedNoticesSeen({\n openMeldProfileId: input.openMeldProfileId,\n deletedNotices: input.deletedNotices,\n });\n return [formatKnownSpaceDeletedNoticeMessage(input.deletedNotices)];\n}\n\nexport async function maybeEmitKnownSpaceDeletedNotices(input: {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n openMeldProfileId: string;\n deletedNotices: KnownSpaceDeletedNotice[];\n}): Promise<void> {\n if (input.deletedNotices.length === 0) {\n return;\n }\n\n if (input.resolvedView === \"human\") {\n input.presenter.line({\n code: \"space.deleted_notices\",\n text: formatKnownSpaceDeletedNoticeMessage(input.deletedNotices),\n });\n await markKnownSpaceDeletedNoticesSeen({\n openMeldProfileId: input.openMeldProfileId,\n deletedNotices: input.deletedNotices,\n });\n return;\n }\n\n input.presenter.data({\n code: \"space.deleted_notices\",\n payload: {\n deletedNotices: input.deletedNotices.map((item) =>\n buildKnownSpaceDeletedNoticeData(item)\n ),\n },\n });\n}\n\nfunction formatKnownSpaceDeletedNoticeMessage(\n deletedNotices: KnownSpaceDeletedNotice[]\n): string {\n const visible = deletedNotices\n .slice(0, 3)\n .map((item) => formatKnownSpaceDeletedNoticeLabel(item, \"human\"));\n const suffix =\n deletedNotices.length > visible.length\n ? `, +${String(deletedNotices.length - visible.length)} more`\n : \"\";\n return `Removed from your space list: ${visible.join(\", \")}${suffix}.`;\n}\n\nfunction formatKnownSpaceDeletedNoticeLabel(\n item: KnownSpaceDeletedNotice,\n resolvedView: \"human\" | \"agent\"\n): string {\n const name =\n sanitizeSingleLinePromptText(item.spaceName) ||\n shortenSpaceId(item.spaceId);\n const deletedByName = normalizeOptionalString(item.deletedByProfileName);\n const deletedById = normalizeOptionalString(item.deletedByProfileId);\n\n if (resolvedView === \"human\") {\n return deletedByName\n ? `${name} (deleted by ${sanitizeSingleLinePromptText(deletedByName)})`\n : `${name} (deleted)`;\n }\n\n if (deletedByName && deletedById) {\n return `${name} (deleted by ${sanitizeSingleLinePromptText(deletedByName)} · ${sanitizeSingleLinePromptText(deletedById)})`;\n }\n if (deletedByName) {\n return `${name} (deleted by ${sanitizeSingleLinePromptText(deletedByName)})`;\n }\n if (deletedById) {\n return `${name} (deleted by ${sanitizeSingleLinePromptText(deletedById)})`;\n }\n return `${name} (deleted)`;\n}\n\nasync function markKnownSpaceDeletedNoticesSeen(input: {\n openMeldProfileId: string;\n deletedNotices: KnownSpaceDeletedNotice[];\n}): Promise<void> {\n if (input.deletedNotices.length === 0) {\n return;\n }\n\n const existingStateResult = await readSpaceCacheDeletionNoticeState({\n openMeldProfileId: input.openMeldProfileId,\n });\n if (isLocalSpaceStateCorruptResult(existingStateResult)) {\n throw toLocalSpaceStateIntegrityError({\n operation: \"marking known-space deletion notices as seen\",\n result: existingStateResult,\n });\n }\n const existing =\n existingStateResult.kind === \"ok\" ? existingStateResult.value.seen : {};\n const seen = { ...existing };\n const now = new Date().toISOString();\n let changed = false;\n for (const item of input.deletedNotices) {\n const key = buildKnownSpaceDeletedNoticeStateKey({\n gatewayHost: item.gatewayHost,\n spaceId: item.spaceId,\n });\n if (typeof seen[key] === \"string\" && seen[key].trim().length > 0) {\n continue;\n }\n seen[key] = now;\n changed = true;\n }\n if (!changed) {\n return;\n }\n\n await writeSpaceCacheDeletionNoticeState({\n openMeldProfileId: input.openMeldProfileId,\n seen,\n }).catch(() => undefined);\n}\n\nfunction buildKnownSpaceDeletedNoticeStateKey(input: {\n gatewayHost: string;\n spaceId: string;\n}): string {\n return `${input.gatewayHost}:${input.spaceId}`;\n}\n\nfunction buildKnownSpaceDeletedNoticeData(\n item: KnownSpaceDeletedNotice\n): Record<string, unknown> {\n return {\n gatewayHost: item.gatewayHost,\n spaceId: item.spaceId,\n spaceName: item.spaceName,\n deletedAt: item.deletedAt,\n deletedByProfileName: item.deletedByProfileName,\n deletedByProfileId: item.deletedByProfileId,\n };\n}\n\nexport type SpaceSelectionCommand =\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n\nexport type SpaceSelectionInput = {\n known: KnownSpaceOption[];\n deletedNotices?: KnownSpaceDeletedNotice[];\n command: SpaceSelectionCommand;\n passwordAction?: \"set\" | \"clear\";\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentProfileName?: string;\n currentOwnerUserId?: string;\n visibilityScope?: KnownSpaceVisibilityScope;\n allowBack?: boolean;\n};\n\nexport type SpaceSelectionTarget = {\n space: string;\n baseUrl?: string;\n name?: string;\n};\n\nexport type SpaceSelectionTargetResult =\n | { status: \"submitted\"; target: SpaceSelectionTarget }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\ntype HumanManualSpaceIdResult =\n | { status: \"submitted\"; value: string }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\ntype PasswordSpaceTargetSelectionResult =\n | { status: \"submitted\"; target: SpaceSelectionTarget }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\nexport function promptSpaceSelectionTarget(\n input: SpaceSelectionInput\n): Promise<SpaceSelectionTargetResult> {\n if (input.known.length === 0) {\n return promptSpaceSelectionWithoutKnownSpaces(input);\n }\n return promptKnownSpaceSelection(input);\n}\n\nexport async function promptSpacePasswordTargetSelection(\n input: SpaceSelectionInput\n): Promise<PasswordSpaceTargetSelectionResult> {\n if (input.known.length === 0) {\n const target = await promptSpaceSelectionWithoutKnownSpaces({\n ...input,\n allowBack: true,\n });\n if (target.status !== \"submitted\") {\n return target;\n }\n return { status: \"submitted\", target: target.target };\n }\n\n if (input.resolvedView === \"human\") {\n return promptHumanSpacePasswordTargetSelection(input);\n }\n return promptAgentSpacePasswordTargetSelection(input);\n}\n\nasync function promptSpaceSelectionWithoutKnownSpaces(\n input: SpaceSelectionInput\n): Promise<SpaceSelectionTargetResult> {\n const emptyMessage = resolveEmptySpaceSelectionMessage(\n input.command,\n input.passwordAction,\n input.visibilityScope\n );\n if (input.command === \"join\" && input.resolvedView === \"human\") {\n const manual = await promptHumanManualSpaceId({\n message: emptyMessage,\n description: \"Paste a 64-character hex space ID to join it.\",\n allowBack: false,\n });\n if (manual.status !== \"submitted\") {\n return manual.status === \"back\"\n ? { status: \"back\" }\n : { status: \"cancelled\" };\n }\n return {\n status: \"submitted\",\n target: { space: manual.value },\n };\n }\n\n if (input.resolvedView === \"human\") {\n const manual = await promptHumanManualSpaceId({\n message: emptyMessage,\n description: \"Paste a 64-character hex space ID.\",\n allowBack: input.allowBack === true,\n });\n if (manual.status !== \"submitted\") {\n return manual;\n }\n return {\n status: \"submitted\",\n target: { space: manual.value },\n };\n }\n\n const manual = await promptManualSpace(emptyMessage, input.resolvedView);\n return manual\n ? {\n status: \"submitted\",\n target: { space: manual },\n }\n : {\n status: \"cancelled\",\n };\n}\n\nasync function promptHumanSpacePasswordTargetSelection(\n input: SpaceSelectionInput\n): Promise<PasswordSpaceTargetSelectionResult> {\n let noticeLines = await consumeKnownSpaceDeletedNoticePromptLines({\n openMeldProfileId: input.currentProfileId,\n deletedNotices: input.deletedNotices ?? [],\n });\n for (;;) {\n writeInteractivePromptSpacer();\n const selected = await promptSearchSelect({\n message: resolveSpaceSelectionMessage(\n input.command,\n input.passwordAction,\n input.visibilityScope,\n input.resolvedView\n ),\n items: buildHumanKnownSpaceSearchItems({\n known: input.known,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n }),\n maxVisible: 8,\n allowBack: true,\n backLabel: \"Back\",\n noticeLines,\n });\n noticeLines = [];\n if (selected.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (selected.status === \"back\") {\n return { status: \"back\" };\n }\n if (selected.value === \"manual\") {\n const manual = await promptHumanManualSpaceId({\n message: \"Enter a space ID manually\",\n description: \"Paste a 64-character hex space ID.\",\n allowBack: true,\n });\n if (manual.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (manual.status === \"back\") {\n continue;\n }\n return {\n status: \"submitted\",\n target: { space: manual.value },\n };\n }\n\n const target = toSpaceSelectionTargetFromKnownValue(\n input.known,\n selected.value\n );\n if (!target) {\n continue;\n }\n return {\n status: \"submitted\",\n target,\n };\n }\n}\n\nasync function promptAgentSpacePasswordTargetSelection(\n input: SpaceSelectionInput\n): Promise<PasswordSpaceTargetSelectionResult> {\n const options = input.known.slice(0, 20).map((space, index) => ({\n label: formatKnownSpaceOptionLabel({\n space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n }),\n value: `known:${String(index)}`,\n }));\n options.push(\n {\n label: \"Enter a space ID manually\",\n value: \"manual\",\n },\n {\n label: \"Back\",\n value: \"back\",\n }\n );\n\n const selected = await select({\n message: resolveSpaceSelectionMessage(\n input.command,\n input.passwordAction,\n input.visibilityScope,\n input.resolvedView\n ),\n options,\n });\n if (isCancel(selected)) {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (selected === \"back\") {\n return { status: \"back\" };\n }\n if (selected === \"manual\") {\n const manual = await promptManualSpace(\n \"Enter a space ID (64-character hex):\",\n input.resolvedView\n );\n return manual\n ? {\n status: \"submitted\",\n target: { space: manual },\n }\n : { status: \"cancelled\" };\n }\n\n const target = toSpaceSelectionTargetFromKnownValue(input.known, selected);\n return target\n ? {\n status: \"submitted\",\n target,\n }\n : { status: \"cancelled\" };\n}\n\nexport async function promptHumanJoinSelectionWithoutKnownSpaces(\n visibilityScope: KnownSpaceVisibilityScope\n): Promise<SpaceJoinTargetResolution> {\n for (;;) {\n writeInteractivePromptSpacer();\n const selected = await select({\n message: [\n \"No spaces yet\",\n pc.dim(\n resolveSpaceVisibilitySummary({\n visibilityScope,\n resolvedView: \"human\",\n })\n ),\n pc.dim(\n \"Paste a space ID someone shared with you, create a new space, or go back.\"\n ),\n \"\",\n ].join(\"\\n\"),\n options: [\n {\n value: \"manual\",\n label: \"Enter a space ID manually\",\n hint: \"Best if someone shared a space ID with you\",\n },\n {\n value: \"create\",\n label: \"Create a new space and join\",\n hint: \"Fastest way to get started\",\n },\n {\n value: \"back\",\n label: \"Back\",\n hint: \"Return to the previous step\",\n },\n ],\n });\n if (isCancel(selected)) {\n cancel(\"Cancelled.\");\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n if (selected === \"back\") {\n return {\n status: \"back\",\n value: null,\n };\n }\n if (selected === \"create\") {\n return {\n status: \"create\",\n value: null,\n };\n }\n\n const manual = await promptHumanManualSpaceId({\n message: \"Enter a space ID manually\",\n description: \"Paste a 64-character hex space ID to join it.\",\n allowBack: true,\n });\n if (manual.status === \"submitted\") {\n return {\n status: \"submitted\",\n value: { space: manual.value },\n };\n }\n if (manual.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n }\n}\n\nfunction resolveEmptySpaceSelectionMessage(\n command: SpaceSelectionCommand,\n passwordAction?: \"set\" | \"clear\",\n visibilityScope?: KnownSpaceVisibilityScope\n): string {\n if (\n command === \"join\" ||\n command === \"add_members\" ||\n command === \"remove_members\" ||\n command === \"leave\"\n ) {\n if (normalizeKnownSpaceVisibilityScope(visibilityScope) === \"owner\") {\n return \"No spaces across the profiles you own were found yet. Enter a space ID (64-character hex):\";\n }\n return \"No spaces for this profile were found yet. Enter a space ID (64-character hex):\";\n }\n if (command === \"delete\") {\n return \"No known spaces found yet. Enter a space ID (64-character hex):\";\n }\n if (command === \"password\") {\n if (passwordAction === \"clear\") {\n return \"No password-protected spaces created by this profile were found yet. Enter a space ID (64-character hex):\";\n }\n if (passwordAction === \"set\") {\n return \"No unprotected spaces created by this profile were found yet. Enter a space ID (64-character hex):\";\n }\n return \"No spaces created by this profile were found yet. Enter a space ID (64-character hex):\";\n }\n return \"No local spaces found yet. Enter a space ID (64-character hex):\";\n}\n\nasync function promptKnownSpaceSelection(\n input: SpaceSelectionInput\n): Promise<SpaceSelectionTargetResult> {\n if (\n input.resolvedView === \"human\" &&\n (input.command === \"add_members\" ||\n input.command === \"remove_members\" ||\n input.command === \"leave\" ||\n input.command === \"watch\")\n ) {\n return promptHumanKnownSpaceSelection(input);\n }\n\n const options = input.known.slice(0, 20).map((space, index) => ({\n label: formatKnownSpaceOptionLabel({\n space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n }),\n value: `known:${String(index)}`,\n }));\n options.push({\n label: \"Enter a space ID manually\",\n value: \"manual\",\n });\n if (input.allowBack === true) {\n options.push({\n label: \"Back\",\n value: \"back\",\n });\n }\n\n const selected = await select({\n message: resolveSpaceSelectionMessage(\n input.command,\n input.passwordAction,\n input.visibilityScope,\n input.resolvedView\n ),\n options,\n });\n if (isCancel(selected)) {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (selected === \"back\") {\n return { status: \"back\" };\n }\n if (selected === \"manual\") {\n const manual = await promptManualSpace(\n \"Enter a space ID (64-character hex):\",\n input.resolvedView\n );\n return manual\n ? {\n status: \"submitted\",\n target: { space: manual },\n }\n : {\n status: \"cancelled\",\n };\n }\n const target = toSpaceSelectionTargetFromKnownValue(input.known, selected);\n return target\n ? {\n status: \"submitted\",\n target,\n }\n : {\n status: \"cancelled\",\n };\n}\n\nfunction promptHumanKnownSpaceSelection(\n input: SpaceSelectionInput\n): Promise<SpaceSelectionTargetResult> {\n if (input.command === \"watch\") {\n return promptHumanWatchKnownSpaceSelection(input);\n }\n\n return promptHumanKnownSpaceSelectionWithInlineManual(input);\n}\n\nasync function promptHumanWatchKnownSpaceSelection(\n input: SpaceSelectionInput\n): Promise<SpaceSelectionTargetResult> {\n const selected = await promptHumanKnownSpaceBrowseSelection({\n input,\n allowSourceBack: input.allowBack === true,\n manualDescription: \"Paste a 64-character hex space ID.\",\n });\n if (selected.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (selected.status === \"back\") {\n return { status: \"back\" };\n }\n if (!selected.value) {\n return { status: \"cancelled\" };\n }\n return {\n status: \"submitted\",\n target: selected.value,\n };\n}\n\nasync function promptHumanKnownSpaceSelectionWithInlineManual(\n input: SpaceSelectionInput\n): Promise<SpaceSelectionTargetResult> {\n let noticeLines = await consumeKnownSpaceDeletedNoticePromptLines({\n openMeldProfileId: input.currentProfileId,\n deletedNotices: input.deletedNotices ?? [],\n });\n for (;;) {\n const selected = await promptSearchSelect({\n message: resolveSpaceSelectionMessage(\n input.command,\n input.passwordAction,\n input.visibilityScope,\n input.resolvedView\n ),\n items: buildHumanKnownSpaceSearchItems({\n known: input.known,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n }),\n maxVisible: 8,\n allowBack: input.allowBack === true,\n backLabel: \"Back\",\n noticeLines,\n });\n noticeLines = [];\n if (selected.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (selected.status === \"back\") {\n return { status: \"back\" };\n }\n if (selected.value === \"manual\") {\n const manual = await promptHumanManualSpaceId({\n message: \"Enter a space ID manually\",\n description: \"Paste a 64-character hex space ID.\",\n allowBack: true,\n });\n if (manual.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (manual.status === \"back\") {\n continue;\n }\n return {\n status: \"submitted\",\n target: { space: manual.value },\n };\n }\n const target = toSpaceSelectionTargetFromKnownValue(\n input.known,\n selected.value\n );\n return target\n ? {\n status: \"submitted\",\n target,\n }\n : {\n status: \"cancelled\",\n };\n }\n}\n\nexport async function promptSpaceJoinSelection(\n input: SpaceSelectionInput\n): Promise<SpaceJoinTargetResolution> {\n if (input.resolvedView === \"human\") {\n const selected = await promptHumanKnownSpaceBrowseSelection({\n input,\n allowSourceBack: true,\n manualDescription: \"Paste a 64-character hex space ID to join it.\",\n });\n if (selected.status !== \"submitted\") {\n return {\n status: selected.status,\n value: null,\n };\n }\n if (!selected.value) {\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n return {\n status: \"submitted\",\n value: selected.value,\n };\n }\n\n const knownSpaceOptions = input.known.map((space, index) => ({\n label: formatKnownSpaceOptionLabel({\n space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n }),\n value: `known:${String(index)}`,\n }));\n\n for (;;) {\n const source = await promptKnownSpaceSourceSelection({\n command: \"join\",\n knownCount: input.known.length,\n visibilityScope: input.visibilityScope,\n resolvedView: input.resolvedView,\n allowBack: true,\n });\n if (source === \"cancelled\") {\n cancel(\"Cancelled.\");\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n if (source === \"back\") {\n return {\n status: \"back\",\n value: null,\n };\n }\n\n const selectedTarget =\n source === \"manual\"\n ? await promptJoinManualTargetSelection(input.resolvedView)\n : await promptJoinKnownSpaceTargetSelection({\n input,\n knownSpaceOptions,\n });\n if (selectedTarget.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n if (selectedTarget.status === \"back\" || selectedTarget.value === null) {\n continue;\n }\n return {\n status: \"submitted\",\n value: selectedTarget.value,\n };\n }\n}\n\nasync function promptKnownSpaceSourceSelection(input: {\n command: \"join\" | \"watch\";\n knownCount: number;\n visibilityScope?: KnownSpaceVisibilityScope;\n resolvedView: \"human\" | \"agent\";\n allowBack: boolean;\n}): Promise<\"history\" | \"manual\" | \"back\" | \"cancelled\"> {\n const selected = await select({\n message: resolveSpaceSelectionMessage(\n input.command,\n undefined,\n input.visibilityScope,\n input.resolvedView\n ),\n options: [\n {\n value: \"history\",\n label: resolveKnownSpaceHistoryOptionLabel(input.visibilityScope),\n hint: `${String(input.knownCount)} ${input.knownCount === 1 ? \"space\" : \"spaces\"}`,\n },\n {\n value: \"manual\",\n label: \"Enter a space ID manually\",\n hint: \"Best if someone shared a space ID with you\",\n },\n ...(input.allowBack\n ? [\n {\n value: \"back\",\n label: \"Back\",\n hint: \"Return to the previous step\",\n },\n ]\n : []),\n ],\n });\n if (isCancel(selected)) {\n return \"cancelled\";\n }\n if (selected === \"back\") {\n return \"back\";\n }\n if (selected === \"history\" || selected === \"manual\") {\n return selected;\n }\n return \"cancelled\";\n}\n\nfunction resolveKnownSpaceHistoryOptionLabel(\n visibilityScope?: KnownSpaceVisibilityScope\n): string {\n return normalizeKnownSpaceVisibilityScope(visibilityScope) === \"owner\"\n ? \"Choose a space from your profiles\"\n : \"Choose a space you created or joined\";\n}\n\nasync function promptJoinManualTargetSelection(\n resolvedView: \"human\" | \"agent\"\n): Promise<{\n status: HumanManualSpaceIdResult[\"status\"];\n value: SpaceSelectionTarget | null;\n}> {\n if (resolvedView === \"human\") {\n const manual = await promptHumanManualSpaceId({\n message: \"Enter a space ID manually\",\n description: \"Paste a 64-character hex space ID to join it.\",\n allowBack: true,\n });\n if (manual.status !== \"submitted\") {\n return {\n status: manual.status,\n value: null,\n };\n }\n return {\n status: \"submitted\",\n value: { space: manual.value },\n };\n }\n\n const manual = await promptManualSpace(\n \"Enter a space ID (64-character hex):\",\n resolvedView\n );\n if (!manual) {\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n return {\n status: \"submitted\",\n value: { space: manual },\n };\n}\n\nasync function promptJoinKnownSpaceTargetSelection(input: {\n input: SpaceSelectionInput;\n knownSpaceOptions: Array<{ label: string; value: string }>;\n}): Promise<{\n status: \"submitted\" | \"back\" | \"cancelled\";\n value: SpaceSelectionTarget | null;\n}> {\n if (input.input.resolvedView === \"human\") {\n return promptHumanKnownSpaceSearchSelection({\n input: input.input,\n allowBack: true,\n });\n }\n\n const selected = await promptAgentSpaceJoinKnownSpaceSelection({\n knownSpaceOptions: input.knownSpaceOptions,\n visibilityScope: input.input.visibilityScope,\n });\n if (selected.status !== \"submitted\") {\n return {\n status: selected.status,\n value: null,\n };\n }\n return {\n status: \"submitted\",\n value: toSpaceSelectionTargetFromKnownValue(\n input.input.known,\n selected.value\n ),\n };\n}\n\nasync function promptHumanKnownSpaceBrowseSelection(input: {\n input: SpaceSelectionInput;\n allowSourceBack: boolean;\n manualDescription: string;\n}): Promise<\n | {\n status: \"submitted\";\n value: SpaceSelectionTarget | null;\n }\n | {\n status: \"back\" | \"cancelled\";\n value: null;\n }\n> {\n for (;;) {\n const source = await promptKnownSpaceSourceSelection({\n command: input.input.command === \"watch\" ? \"watch\" : \"join\",\n knownCount: input.input.known.length,\n visibilityScope: input.input.visibilityScope,\n resolvedView: input.input.resolvedView,\n allowBack: input.allowSourceBack,\n });\n if (source === \"cancelled\") {\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n if (source === \"back\") {\n return {\n status: \"back\",\n value: null,\n };\n }\n if (source === \"manual\") {\n const manual = await promptHumanManualSpaceId({\n message: \"Enter a space ID manually\",\n description: input.manualDescription,\n allowBack: true,\n });\n if (manual.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n if (manual.status === \"back\") {\n continue;\n }\n return {\n status: \"submitted\",\n value: { space: manual.value },\n };\n }\n\n const selected = await promptHumanKnownSpaceSearchSelection({\n input: input.input,\n allowBack: true,\n });\n if (selected.status === \"back\") {\n continue;\n }\n return selected;\n }\n}\n\nasync function promptHumanKnownSpaceSearchSelection(input: {\n input: SpaceSelectionInput;\n allowBack: boolean;\n}): Promise<\n | {\n status: \"submitted\";\n value: SpaceSelectionTarget | null;\n }\n | {\n status: \"back\" | \"cancelled\";\n value: null;\n }\n> {\n const noticeLines = await consumeKnownSpaceDeletedNoticePromptLines({\n openMeldProfileId: input.input.currentProfileId,\n deletedNotices: input.input.deletedNotices ?? [],\n });\n writeInteractivePromptSpacer();\n const selected = await promptSearchSelect({\n message: resolveSpaceSelectionMessage(\n input.input.command,\n input.input.passwordAction,\n input.input.visibilityScope,\n input.input.resolvedView\n ),\n items: input.input.known.map((space, index) =>\n buildHumanKnownSpaceSearchItem({\n space,\n index,\n currentProfileId: input.input.currentProfileId,\n currentProfileName: input.input.currentProfileName,\n currentOwnerUserId: input.input.currentOwnerUserId,\n command: input.input.command,\n })\n ),\n maxVisible: 8,\n allowBack: input.allowBack,\n backLabel: \"Back\",\n noticeLines,\n });\n if (selected.status !== \"submitted\") {\n return {\n status: selected.status,\n value: null,\n };\n }\n return {\n status: \"submitted\",\n value: toSpaceSelectionTargetFromKnownValue(\n input.input.known,\n selected.value\n ),\n };\n}\n\nfunction writeInteractivePromptSpacer(): void {\n if (process.stdout.isTTY !== true) {\n return;\n }\n process.stdout.write(\"\\n\");\n}\n\nasync function promptAgentSpaceJoinKnownSpaceSelection(input: {\n knownSpaceOptions: Array<{ label: string; value: string }>;\n visibilityScope?: KnownSpaceVisibilityScope;\n}): Promise<\n | {\n status: \"submitted\";\n value: string;\n }\n | {\n status: \"cancelled\";\n value: null;\n }\n | {\n status: \"back\";\n value: null;\n }\n> {\n const selected = await select({\n message: resolveSpaceSelectionMessage(\n \"join\",\n undefined,\n input.visibilityScope,\n \"agent\"\n ),\n options: [\n ...input.knownSpaceOptions,\n {\n value: \"back\",\n label: \"Back\",\n hint: \"Return to join options\",\n },\n ],\n });\n if (isCancel(selected)) {\n cancel(\"Cancelled.\");\n return {\n status: \"cancelled\",\n value: null,\n };\n }\n if (selected === \"back\") {\n return {\n status: \"back\",\n value: null,\n };\n }\n return {\n status: \"submitted\",\n value: selected,\n };\n}\n\nfunction toSpaceSelectionTargetFromKnownValue(\n known: KnownSpaceOption[],\n selectedValue: string\n): SpaceSelectionTarget | null {\n const selectedIndex = Number.parseInt(\n selectedValue.replace(\"known:\", \"\"),\n 10\n );\n const matched = known[selectedIndex];\n if (!matched) {\n return null;\n }\n return {\n space: matched.space,\n ...(matched?.baseUrl ? { baseUrl: matched.baseUrl } : {}),\n ...(matched?.name ? { name: matched.name } : {}),\n };\n}\n\nfunction buildHumanKnownSpaceSearchItem(input: {\n space: KnownSpaceOption;\n index: number;\n currentProfileId: string;\n currentProfileName?: string;\n currentOwnerUserId?: string;\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): {\n value: string;\n label: string;\n detail: string;\n searchText: string;\n} {\n return {\n value: `known:${String(input.index)}`,\n label: formatKnownSpaceName({\n space: input.space,\n resolvedView: \"human\",\n currentProfileId: input.currentProfileId,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n }),\n detail: buildHumanKnownSpaceDetailLine({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n command: input.command,\n }),\n searchText: buildHumanKnownSpaceSearchText({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n }),\n };\n}\n\nfunction buildHumanKnownSpaceSearchItems(input: {\n known: KnownSpaceOption[];\n currentProfileId: string;\n currentProfileName?: string;\n currentOwnerUserId?: string;\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): Array<{\n value: string;\n label: string;\n detail?: string;\n searchText: string;\n}> {\n return [\n ...input.known.map((space, index) =>\n buildHumanKnownSpaceSearchItem({\n space,\n index,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n currentOwnerUserId: input.currentOwnerUserId,\n command: input.command,\n })\n ),\n {\n value: \"manual\",\n label: \"Enter a space ID manually\",\n searchText: \"Enter a space ID manually\\nmanual\\nspace id\",\n },\n ];\n}\n\nfunction buildHumanKnownSpaceDetailLine(input: {\n space: KnownSpaceOption;\n currentProfileId: string;\n currentProfileName?: string;\n command?:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): string {\n const projection = buildKnownSpaceDisplayProjection({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n });\n const idLabel = `ID ${shortenSpaceId(formatSpaceDisplayValue(projection.spaceId))}`;\n const creatorLabel = projection.creatorDisplayName;\n const viaLabel = projection.availableViaDisplayName;\n const parts = [idLabel];\n if (creatorLabel) {\n parts.push(`Created by ${creatorLabel}`);\n }\n if (viaLabel && viaLabel !== creatorLabel) {\n parts.push(`via ${viaLabel}`);\n }\n const joinedLabel = formatJoinedRelativeLabel(\n resolveKnownSpaceJoinedTimestamp(input.space)\n );\n if (joinedLabel) {\n parts.push(sanitizeSingleLinePromptText(joinedLabel));\n }\n return parts.join(\" · \");\n}\n\nfunction buildHumanKnownSpaceSearchText(input: {\n space: KnownSpaceOption;\n currentProfileId: string;\n currentProfileName?: string;\n}): string {\n const projection = buildKnownSpaceDisplayProjection({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n });\n return [\n formatSpaceDisplayValue(projection.spaceId, \"\"),\n formatSpaceDisplayValue(projection.spaceName, \"\"),\n formatSpaceDisplayValue(projection.creatorProfileName, \"\"),\n formatSpaceDisplayValue(projection.creatorProfileId, \"\"),\n sanitizeSingleLinePromptText(\n normalizeOptionalString(input.space.creatorOwnerUserId)\n ),\n formatSpaceDisplayValue(projection.availableViaProfileName, \"\"),\n formatSpaceDisplayValue(projection.availableViaProfileId, \"\"),\n formatSpaceDisplayValue(projection.creatorDisplayName, \"\"),\n formatSpaceDisplayValue(projection.availableViaDisplayName, \"\"),\n ]\n .filter((value): value is string => typeof value === \"string\")\n .join(\"\\n\");\n}\n\nfunction formatJoinedRelativeLabel(value: string | null): string | null {\n if (!value) {\n return null;\n }\n\n const timestamp = Date.parse(value);\n if (!Number.isFinite(timestamp)) {\n return null;\n }\n\n const elapsedMs = Math.max(0, Date.now() - timestamp);\n const elapsedMinutes = Math.floor(elapsedMs / 60_000);\n if (elapsedMinutes < 1) {\n return \"joined now\";\n }\n if (elapsedMinutes < 60) {\n return `joined ${String(elapsedMinutes)}m ago`;\n }\n\n const elapsedHours = Math.floor(elapsedMinutes / 60);\n if (elapsedHours < 24) {\n return `joined ${String(elapsedHours)}h ago`;\n }\n\n const elapsedDays = Math.floor(elapsedHours / 24);\n return `joined ${String(elapsedDays)}d ago`;\n}\n\nasync function promptHumanManualSpaceId(input: {\n message: string;\n description: string;\n allowBack: boolean;\n}): Promise<HumanManualSpaceIdResult> {\n const result = await promptTextEntry({\n message: input.message,\n description: input.description,\n placeholder: \"e.g. 01234567...89abcdef\",\n allowBack: input.allowBack,\n backLabel: \"Back\",\n validate: (value) =>\n isValidSpaceId(value)\n ? null\n : \"Space ID must be a 64-character hex value.\",\n });\n if (result.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (result.status === \"back\") {\n return { status: \"back\" };\n }\n return {\n status: \"submitted\",\n value: result.value,\n };\n}\n\nexport async function promptSpaceDeleteSelection(input: {\n known: KnownSpaceOption[];\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentProfileName: string;\n allowBack?: boolean;\n}): Promise<SpaceDeleteTargetSelectionResult> {\n if (input.known.length === 0) {\n if (input.resolvedView === \"human\") {\n const manual = await promptHumanManualSpaceId({\n message:\n \"No spaces you can delete were found. Enter a space ID manually\",\n description: \"Paste a 64-character hex space ID to delete it.\",\n allowBack: input.allowBack === true,\n });\n if (manual.status !== \"submitted\") {\n return manual;\n }\n return {\n status: \"submitted\",\n allowBackToSelection: true,\n targets: [{ space: manual.value }],\n };\n }\n\n const manual = await promptManualSpace(\n \"No spaces you can delete were found. Enter a space ID (64-character hex):\",\n input.resolvedView\n );\n return manual\n ? {\n status: \"submitted\",\n allowBackToSelection: true,\n targets: [{ space: manual }],\n }\n : {\n status: \"cancelled\",\n };\n }\n\n if (input.resolvedView === \"human\") {\n return promptHumanSpaceDeleteSelection(input);\n }\n\n const knownSpaces = input.known.slice(0, 20);\n const selected = await multiselect({\n message: \"Choose space(s) to delete\",\n options: buildSpaceDeleteSelectionOptions({\n knownSpaces,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n }),\n required: true,\n });\n if (isCancel(selected)) {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n\n const normalized = normalizeSpaceDeleteSelection(selected);\n const { targets, manualRequested } = toSpaceDeleteTargetsFromSelection({\n knownSpaces,\n selected: normalized,\n });\n\n if (manualRequested) {\n const manual = await promptManualSpace(\n \"Enter a space ID (64-character hex):\",\n input.resolvedView\n );\n if (!manual) {\n return { status: \"cancelled\" };\n }\n targets.push({ space: manual });\n }\n\n const deduped = dedupeSpaceDeleteTargets(targets);\n return deduped.length > 0\n ? {\n status: \"submitted\",\n targets: deduped,\n allowBackToSelection: true,\n }\n : { status: \"cancelled\" };\n}\n\nasync function promptHumanSpaceDeleteSelection(input: {\n known: KnownSpaceOption[];\n currentProfileId: string;\n currentProfileName: string;\n allowBack?: boolean;\n}): Promise<SpaceDeleteTargetSelectionResult> {\n let initialSelectedValues: string[] = [];\n\n for (;;) {\n const selected = await promptSearchMultiselect({\n message: \"Choose space(s) to delete\",\n items: [\n ...input.known.map((space, index) =>\n buildHumanSpaceDeleteSearchItem({\n space,\n index,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n })\n ),\n {\n value: \"manual\",\n label: \"Enter a space ID manually\",\n searchText: \"Enter a space ID manually\\nmanual\\nspace id\",\n },\n ],\n maxVisible: 8,\n required: true,\n initialSelectedValues,\n allowBack: input.allowBack === true,\n backLabel: \"Back\",\n });\n if (selected.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (selected.status === \"back\") {\n return { status: \"back\" };\n }\n\n const normalized = normalizeSpaceDeleteSelection(selected.value);\n const { targets, manualRequested } = toSpaceDeleteTargetsFromSelection({\n knownSpaces: input.known,\n selected: normalized,\n });\n if (!manualRequested) {\n const deduped = dedupeSpaceDeleteTargets(targets);\n return deduped.length > 0\n ? {\n status: \"submitted\",\n targets: deduped,\n allowBackToSelection: true,\n }\n : { status: \"cancelled\" };\n }\n\n const manual = await promptHumanManualSpaceId({\n message: \"Enter a space ID manually\",\n description:\n \"Paste a 64-character hex space ID to add it to the delete list.\",\n allowBack: true,\n });\n if (manual.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (manual.status === \"back\") {\n initialSelectedValues = normalized.filter((value) => value !== \"manual\");\n continue;\n }\n\n targets.push({ space: manual.value });\n const deduped = dedupeSpaceDeleteTargets(targets);\n return deduped.length > 0\n ? {\n status: \"submitted\",\n targets: deduped,\n allowBackToSelection: true,\n }\n : { status: \"cancelled\" };\n }\n}\n\nfunction buildHumanSpaceDeleteSearchItem(input: {\n space: KnownSpaceOption;\n index: number;\n currentProfileId: string;\n currentProfileName?: string;\n}): {\n value: string;\n label: string;\n detail: string;\n searchText: string;\n} {\n return {\n value: `known:${String(input.index)}`,\n label: formatKnownSpaceName({\n space: input.space,\n resolvedView: \"human\",\n currentProfileId: input.currentProfileId,\n command: \"delete\",\n }),\n detail: buildHumanKnownSpaceDetailLine({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n command: \"delete\",\n }),\n searchText: buildHumanKnownSpaceSearchText({\n space: input.space,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n }),\n };\n}\n\nfunction buildSpaceDeleteSelectionOptions(input: {\n knownSpaces: KnownSpaceOption[];\n resolvedView: \"human\" | \"agent\";\n currentProfileId: string;\n currentProfileName: string;\n}): Array<{ label: string; value: string }> {\n return [\n ...input.knownSpaces.map((space, index) => ({\n label: formatKnownSpaceOptionLabel({\n space,\n resolvedView: input.resolvedView,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n command: \"delete\",\n }),\n value: `known:${String(index)}`,\n })),\n {\n label: \"Enter a space ID manually\",\n value: \"manual\",\n },\n ];\n}\n\nfunction toSpaceDeleteTargetsFromSelection(input: {\n knownSpaces: KnownSpaceOption[];\n selected: string[];\n}): { targets: SpaceDeleteTarget[]; manualRequested: boolean } {\n const targets: SpaceDeleteTarget[] = [];\n let manualRequested = false;\n for (const item of input.selected) {\n if (item === \"manual\") {\n manualRequested = true;\n continue;\n }\n const selectedIndex = Number.parseInt(item.replace(\"known:\", \"\"), 10);\n const matched = input.knownSpaces[selectedIndex];\n if (!matched) {\n continue;\n }\n targets.push(toSpaceDeleteTarget(matched));\n }\n return { targets, manualRequested };\n}\n\nexport function toSpaceDeleteTarget(\n space: KnownSpaceOption\n): SpaceDeleteTarget {\n return {\n space: space.space,\n ...(space.baseUrl ? { baseUrl: space.baseUrl } : {}),\n ...(space.name === undefined ? {} : { name: space.name }),\n ...(space.creatorProfileName === undefined\n ? {}\n : { creatorProfileName: space.creatorProfileName }),\n ...(space.creatorProfileId === undefined\n ? {}\n : { creatorProfileId: space.creatorProfileId }),\n ...(space.creatorOwnerUserId === undefined\n ? {}\n : { creatorOwnerUserId: space.creatorOwnerUserId }),\n ...(space.creatorKind === undefined\n ? {}\n : { creatorKind: space.creatorKind }),\n };\n}\n\nfunction normalizeSpaceDeleteSelection(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const selected: string[] = [];\n for (const item of value) {\n const normalized = String(item ?? \"\").trim();\n if (!normalized || selected.includes(normalized)) {\n continue;\n }\n selected.push(normalized);\n }\n return selected;\n}\n\nfunction dedupeSpaceDeleteTargets(\n targets: SpaceDeleteTarget[]\n): SpaceDeleteTarget[] {\n const deduped: SpaceDeleteTarget[] = [];\n const knownIds = new Set<string>();\n for (const target of targets) {\n const spaceId = target.space.trim().toLowerCase();\n if (!spaceId || knownIds.has(spaceId)) {\n continue;\n }\n knownIds.add(spaceId);\n deduped.push(target);\n }\n return deduped;\n}\n\nfunction resolveSpaceSelectionMessage(\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\",\n passwordAction?: \"set\" | \"clear\",\n visibilityScope?: KnownSpaceVisibilityScope,\n resolvedView: \"human\" | \"agent\" = \"human\"\n): string {\n let message: string;\n if (command === \"password\") {\n if (passwordAction === \"clear\") {\n message =\n \"Choose a password-protected space you created to clear password\";\n } else if (passwordAction === \"set\") {\n message = \"Choose an unprotected space you created to set password\";\n } else {\n message = \"Choose a space you created to configure password\";\n }\n } else if (command === \"add_members\") {\n message = \"Choose a space to add members\";\n } else if (command === \"remove_members\") {\n message = \"Choose a space to remove members\";\n } else if (command === \"leave\") {\n message = \"Choose a space to leave\";\n } else {\n message = `Choose a space to ${command}`;\n }\n return applySpaceVisibilityToPromptMessage({\n message,\n command,\n visibilityScope,\n resolvedView,\n });\n}\n\nfunction applySpaceVisibilityToPromptMessage(input: {\n message: string;\n command: SpaceSelectionCommand;\n visibilityScope?: KnownSpaceVisibilityScope;\n resolvedView: \"human\" | \"agent\";\n}): string {\n if (\n input.resolvedView !== \"human\" ||\n (input.command !== \"join\" &&\n input.command !== \"watch\" &&\n input.command !== \"guide\")\n ) {\n return input.message;\n }\n return [\n input.message,\n pc.dim(\n resolveSpaceVisibilitySummary({\n visibilityScope: input.visibilityScope,\n resolvedView: input.resolvedView,\n })\n ),\n ].join(\"\\n\");\n}\n\nexport function resolveSpaceVisibilitySummary(input: {\n visibilityScope?: KnownSpaceVisibilityScope;\n resolvedView: \"human\" | \"agent\";\n}): string {\n if (normalizeKnownSpaceVisibilityScope(input.visibilityScope) === \"owner\") {\n return \"Showing spaces from your main profile and your other human and agent profiles.\";\n }\n return input.resolvedView === \"agent\"\n ? \"Showing spaces for this profile only.\"\n : \"Showing spaces for this profile only.\";\n}\n\nasync function promptManualSpace(\n message: string,\n resolvedView: \"human\" | \"agent\"\n): Promise<string | null> {\n const maxAttempts = 5;\n for (let attempt = 0; attempt < maxAttempts; attempt += 1) {\n if (isInputClosed(process.stdin)) {\n cancel(\"Cancelled.\");\n return null;\n }\n\n const value = await text({\n message,\n placeholder: \"e.g. 012345...abcdef\",\n });\n if (isCancel(value)) {\n cancel(\"Cancelled.\");\n return null;\n }\n if (value === undefined && isInputClosed(process.stdin)) {\n cancel(\"Cancelled.\");\n return null;\n }\n\n const normalized = typeof value === \"string\" ? value.trim() : \"\";\n if (normalized.length > 0) {\n if (isValidSpaceId(normalized)) {\n return normalized;\n }\n process.stderr.write(\n `${formatMessage(resolvedView, \"space.target.invalid\", {\n space: normalized,\n })}\\n`\n );\n continue;\n }\n\n process.stderr.write(\"Space ID is required.\\n\");\n }\n\n cancel(\"Cancelled.\");\n return null;\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport { listAccountSpaceIndex } from \"../config/account-space-index-api\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { buildOpenMeldRequestContextFromProfile } from \"../config/openmeld-request-context\";\nimport {\n createSpaceSubcommandTargetGuideError,\n createSpaceTargetGuideError,\n} from \"../runtime/dual-view-guide-catalog\";\nimport { formatMessage } from \"../runtime/messages\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport { createDelayedSpinner } from \"../ui/delayed-spinner\";\nimport { assertValidSpaceIdTarget } from \"./command-context\";\nimport { normalizeOptionalString } from \"./command-http-errors\";\nimport {\n filterKnownSpacesForSelection,\n type KnownSpaceDeletedNotice,\n type KnownSpaceOption,\n type KnownSpaceVisibilityScope,\n resolveKnownSpaceVisibilityScope,\n shouldLoadCloudKnownSpaces,\n sortKnownSpacesForSelection,\n toKnownSpaceOptionFromAccountIndex,\n toKnownSpaceOptionFromLocal,\n} from \"./command-known-space-projection\";\nimport {\n maybeEmitKnownSpaceDeletedNotices,\n promptSpaceDeleteSelection,\n promptSpaceSelectionTarget,\n type SpaceDeleteTarget,\n type SpaceDeleteTargetSelectionResult,\n toSpaceDeleteTarget,\n} from \"./command-selection-prompts\";\nimport {\n LocalSpaceStateIntegrityError,\n listSpaceConfigs,\n type SpaceConfig,\n toSpaceConfigListIntegrityError,\n} from \"./local-state\";\nimport { fetchSpaceMeta } from \"./meta-api\";\n\nexport const SPACE_LOADING_SPINNER_MESSAGE = \"Loading spaces...\";\n\nexport function requireReadableSpaceConfigList(\n result: Awaited<ReturnType<typeof listSpaceConfigs>>,\n operation: string\n): SpaceConfig[] {\n if (result.kind === \"corrupt\") {\n throw toSpaceConfigListIntegrityError({\n operation,\n result,\n });\n }\n return result.items;\n}\n\nexport type KnownSpaceSelectionResult = {\n items: KnownSpaceOption[];\n visibilityScope: KnownSpaceVisibilityScope;\n deletedNotices: KnownSpaceDeletedNotice[];\n};\n\nexport function filterKnownSpacesCreatedByProfile(input: {\n known: KnownSpaceOption[];\n profileId: string;\n}): KnownSpaceOption[] {\n const profileId = normalizeOptionalString(input.profileId);\n if (!profileId) {\n return [];\n }\n return input.known.filter((item) => {\n const creatorProfileId =\n typeof item.creatorProfileId === \"string\"\n ? normalizeOptionalString(item.creatorProfileId)\n : null;\n return creatorProfileId === profileId;\n });\n}\n\nasync function resolveOwnedKnownSpacesForDelete(input: {\n known: KnownSpaceOption[];\n openMeldProfile: OpenMeldProfile;\n openMeldProfileId: string;\n profileName: string;\n ownerUserId?: string;\n baseUrl: string;\n}): Promise<KnownSpaceOption[]> {\n const currentProfileId = normalizeOptionalString(input.openMeldProfileId);\n const currentOwnerUserId = normalizeOptionalString(input.ownerUserId);\n if (!currentProfileId) {\n return [];\n }\n\n const owned: KnownSpaceOption[] = [];\n for (const candidate of input.known) {\n const initialOwnership = classifyKnownSpaceOwnershipForDelete({\n item: candidate,\n currentProfileId,\n currentOwnerUserId,\n });\n if (initialOwnership === \"foreign\") {\n continue;\n }\n\n const shouldHydrate =\n initialOwnership === \"unknown\" ||\n shouldHydrateCreatorProfileNameForDelete({\n item: candidate,\n currentProfileId,\n });\n const hydrated = shouldHydrate\n ? await hydrateKnownSpaceForDeleteFromMeta({\n item: candidate,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n })\n : candidate;\n const finalOwnership = classifyKnownSpaceOwnershipForDelete({\n item: hydrated,\n currentProfileId,\n currentOwnerUserId,\n });\n if (finalOwnership !== \"owned\") {\n continue;\n }\n owned.push(\n applyKnownSpaceDeleteCreatorFallback({\n item: hydrated,\n currentProfileId,\n currentProfileName: input.profileName,\n currentOwnerUserId,\n })\n );\n }\n return owned;\n}\n\nasync function resolveExplicitSpaceDeleteTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n}): Promise<SpaceDeleteTarget> {\n const matchedKnown = await findKnownSpaceForDeleteBySpaceId({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n });\n if (matchedKnown) {\n return toSpaceDeleteTarget(matchedKnown);\n }\n\n const localKnown = requireReadableSpaceConfigList(\n await listSpaceConfigs({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n }),\n \"listing known local spaces for explicit delete target resolution\"\n );\n const matchedLocal = localKnown.find((item) => item.space === input.space);\n if (matchedLocal) {\n return toSpaceDeleteTarget(\n toKnownSpaceOptionFromLocal(matchedLocal, input.openMeldProfile)\n );\n }\n const candidate = {\n source: \"local\" as const,\n space: input.space,\n baseUrl: input.baseUrl,\n };\n const hydrated = await hydrateKnownSpaceForDeleteFromMeta({\n item: candidate,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n });\n return toSpaceDeleteTarget(hydrated);\n}\n\nasync function findKnownSpaceForDeleteBySpaceId(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n}): Promise<KnownSpaceOption | null> {\n const knownResult = await resolveKnownSpacesForSelection({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"delete\",\n }).catch((error) => {\n if (error instanceof LocalSpaceStateIntegrityError) {\n throw error;\n }\n return null;\n });\n const matched = knownResult?.items.find((item) => item.space === input.space);\n if (!matched) {\n return null;\n }\n\n const [authorized] = await resolveOwnedKnownSpacesForDelete({\n known: [matched],\n openMeldProfile: input.openMeldProfile,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n ownerUserId: input.openMeldProfile.ownerUserId,\n baseUrl: input.baseUrl,\n });\n if (authorized) {\n return authorized;\n }\n\n return await hydrateKnownSpaceForDeleteFromMeta({\n item: matched,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n });\n}\n\ntype DeleteOwnership = \"owned\" | \"foreign\" | \"unknown\";\n\nfunction classifyKnownSpaceOwnershipForDelete(input: {\n item: KnownSpaceOption;\n currentProfileId: string;\n currentOwnerUserId: string | null;\n}): DeleteOwnership {\n const creatorKind = resolveMetaCreatorKind(input.item.creatorKind);\n const creatorProfileId = normalizeOptionalString(input.item.creatorProfileId);\n if (!creatorKind) {\n return \"unknown\";\n }\n if (creatorKind === \"system\") {\n return \"foreign\";\n }\n if (creatorKind === \"human\") {\n if (!creatorProfileId) {\n return \"unknown\";\n }\n return creatorProfileId === input.currentProfileId ? \"owned\" : \"foreign\";\n }\n const creatorOwnerUserId = normalizeOptionalString(\n input.item.creatorOwnerUserId\n );\n if (!(creatorOwnerUserId && input.currentOwnerUserId)) {\n return \"unknown\";\n }\n return creatorOwnerUserId === input.currentOwnerUserId ? \"owned\" : \"foreign\";\n}\n\nfunction shouldHydrateCreatorProfileNameForDelete(input: {\n item: KnownSpaceOption;\n currentProfileId: string;\n}): boolean {\n if (normalizeOptionalString(input.item.creatorProfileName)) {\n return false;\n }\n const creatorKind = resolveMetaCreatorKind(input.item.creatorKind);\n const creatorProfileId = normalizeOptionalString(input.item.creatorProfileId);\n if (creatorKind === \"human\" && creatorProfileId === input.currentProfileId) {\n return false;\n }\n return true;\n}\n\nasync function hydrateKnownSpaceForDeleteFromMeta(input: {\n item: KnownSpaceOption;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n}): Promise<KnownSpaceOption> {\n const targetBaseUrl = input.item.baseUrl ?? input.baseUrl;\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n });\n try {\n const meta = await fetchSpaceMeta({\n requestContext,\n baseUrl: targetBaseUrl,\n space: input.item.space,\n });\n const creatorProfileId = resolveMetaCreatorProfileId(meta.creator);\n const creatorProfileName = resolveMetaCreatorProfileName(meta.creator);\n const creatorOwnerUserId = resolveMetaCreatorOwnerUserId(meta.creator);\n const creatorKind = resolveMetaCreatorKind(meta.creator?.kind);\n const spaceName =\n typeof meta.name === \"string\" ? normalizeOptionalString(meta.name) : null;\n const spaceCreatedAt =\n typeof meta.createdAt === \"string\"\n ? normalizeOptionalString(meta.createdAt)\n : null;\n const spaceUpdatedAt =\n typeof meta.updatedAt === \"string\"\n ? normalizeOptionalString(meta.updatedAt)\n : null;\n return {\n ...input.item,\n ...(spaceName === null ? {} : { name: spaceName }),\n ...(creatorProfileName === null ? {} : { creatorProfileName }),\n ...(creatorProfileId === null ? {} : { creatorProfileId }),\n ...(creatorOwnerUserId === null ? {} : { creatorOwnerUserId }),\n ...(creatorKind === null ? {} : { creatorKind }),\n ...(spaceCreatedAt === null ? {} : { spaceCreatedAt }),\n ...(spaceUpdatedAt === null ? {} : { spaceUpdatedAt }),\n };\n } catch {\n return input.item;\n }\n}\n\nfunction applyKnownSpaceDeleteCreatorFallback(input: {\n item: KnownSpaceOption;\n currentProfileId: string;\n currentProfileName: string;\n currentOwnerUserId: string | null;\n}): KnownSpaceOption {\n const creatorProfileName = normalizeOptionalString(\n input.item.creatorProfileName\n );\n const creatorOwnerUserId = normalizeOptionalString(\n input.item.creatorOwnerUserId\n );\n const creatorProfileId = normalizeOptionalString(input.item.creatorProfileId);\n\n const nextCreatorProfileName =\n creatorProfileName ??\n (creatorProfileId === input.currentProfileId\n ? normalizeOptionalString(input.currentProfileName)\n : null);\n const nextCreatorOwnerUserId =\n creatorOwnerUserId ?? normalizeOptionalString(input.currentOwnerUserId);\n\n if (\n nextCreatorProfileName === creatorProfileName &&\n nextCreatorOwnerUserId === creatorOwnerUserId\n ) {\n return input.item;\n }\n\n return {\n ...input.item,\n ...(nextCreatorProfileName\n ? { creatorProfileName: nextCreatorProfileName }\n : {}),\n ...(nextCreatorOwnerUserId\n ? { creatorOwnerUserId: nextCreatorOwnerUserId }\n : {}),\n };\n}\n\nexport async function resolveSpaceTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space?: string;\n command: \"join\" | \"watch\" | \"guide\" | \"delete\" | \"password\";\n allowPrompt: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): Promise<{ space: string; baseUrl?: string } | null> {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (explicitSpace) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n const known = requireReadableSpaceConfigList(\n await listSpaceConfigs({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n }),\n \"listing known local spaces for explicit target resolution\"\n );\n const matched = known.find((item) => item.space === explicitSpace);\n return {\n space: explicitSpace,\n ...(matched?.baseUrl ? { baseUrl: matched.baseUrl } : {}),\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n if (input.command === \"password\") {\n throw createSpaceSubcommandTargetGuideError(\"password\");\n }\n throw createSpaceTargetGuideError(input.command);\n }\n throw new Error(\n formatMessage(input.resolvedView, \"space.target.missing\", {\n command: input.command,\n })\n );\n }\n\n const known = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: input.command,\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n const inlineDeletedNotices =\n input.resolvedView === \"human\" && known.items.length > 0\n ? known.deletedNotices\n : [];\n if (inlineDeletedNotices.length === 0) {\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: known.deletedNotices,\n });\n }\n const target = await promptSpaceSelectionTarget({\n known: known.items,\n command: input.command,\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n visibilityScope: known.visibilityScope,\n deletedNotices: inlineDeletedNotices,\n });\n return target.status === \"submitted\" ? target.target : null;\n}\n\nexport async function resolveSpaceDeleteTargets(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space?: string;\n allowPrompt: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowBack?: boolean;\n}): Promise<SpaceDeleteTargetSelectionResult> {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (explicitSpace) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n return {\n status: \"submitted\",\n allowBackToSelection: false,\n targets: [\n await resolveExplicitSpaceDeleteTarget({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: explicitSpace,\n }),\n ],\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceTargetGuideError(\"delete\");\n }\n throw new Error(\n formatMessage(input.resolvedView, \"space.target.missing\", {\n command: \"delete\",\n })\n );\n }\n\n const known = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"delete\",\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: known.deletedNotices,\n });\n const ownedKnownSpaces = await resolveOwnedKnownSpacesForDelete({\n known: known.items,\n openMeldProfile: input.openMeldProfile,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n ownerUserId: input.openMeldProfile.ownerUserId,\n baseUrl: input.baseUrl,\n });\n return promptSpaceDeleteSelection({\n known: ownedKnownSpaces,\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n allowBack: input.allowBack === true,\n });\n}\n\nasync function resolveKnownSpacesForSelection(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n}): Promise<KnownSpaceSelectionResult> {\n const visibilityScope = resolveKnownSpaceVisibilityScope({\n openMeldProfile: input.openMeldProfile,\n command: input.command,\n });\n if (\n !shouldLoadCloudKnownSpaces({\n command: input.command,\n visibilityScope,\n })\n ) {\n return {\n items: await listLocalKnownSpacesForSelection(input.openMeldProfile),\n visibilityScope,\n deletedNotices: [],\n };\n }\n\n const scope = visibilityScope === \"owner\" ? \"account\" : \"profile\";\n let index: Awaited<ReturnType<typeof listAccountSpaceIndex>>;\n try {\n index = await listAccountSpaceIndex({\n baseUrl: input.baseUrl,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n }),\n includePurposes: true,\n limit: 500,\n scope,\n selectedProfileId: input.openMeldProfile.openMeldProfileId,\n });\n } catch (error) {\n if (!canFallbackToLocalKnownSpaces(error)) {\n throw error;\n }\n return {\n items: await listLocalKnownSpacesForSelection(input.openMeldProfile),\n visibilityScope,\n deletedNotices: [],\n };\n }\n\n return {\n items: sortKnownSpacesForSelection(\n filterKnownSpacesForSelection(\n [...index.pinnedItems, ...index.spaceItems].map((item) =>\n toKnownSpaceOptionFromAccountIndex(item, input.baseUrl)\n )\n )\n ),\n visibilityScope,\n deletedNotices: [],\n };\n}\n\nasync function listLocalKnownSpacesForSelection(\n openMeldProfile: OpenMeldProfile\n): Promise<KnownSpaceOption[]> {\n const localKnown = requireReadableSpaceConfigList(\n await listSpaceConfigs({\n openMeldProfileId: openMeldProfile.openMeldProfileId,\n }),\n `listing known local spaces for profile ${openMeldProfile.openMeldProfileId}`\n );\n return sortKnownSpacesForSelection(\n filterKnownSpacesForSelection(\n localKnown.map((item) =>\n toKnownSpaceOptionFromLocal(item, openMeldProfile)\n )\n )\n );\n}\n\nfunction canFallbackToLocalKnownSpaces(error: unknown): boolean {\n if (error instanceof TypeError) {\n return true;\n }\n if (!(error && typeof error === \"object\")) {\n return false;\n }\n const explicitFallback = (error as { canFallbackToLocal?: unknown })\n .canFallbackToLocal;\n if (explicitFallback === true) {\n return true;\n }\n const status = (error as { status?: unknown }).status;\n return typeof status === \"number\" && status >= 500;\n}\n\nexport async function resolveKnownSpacesForSelectionWithLoading(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n command:\n | \"join\"\n | \"watch\"\n | \"guide\"\n | \"delete\"\n | \"password\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n showLoading: boolean;\n}): Promise<KnownSpaceSelectionResult> {\n const loadingSpinner = createDelayedSpinner({\n enabled: input.showLoading,\n message: SPACE_LOADING_SPINNER_MESSAGE,\n });\n loadingSpinner.start();\n\n try {\n const result = await resolveKnownSpacesForSelection({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: input.command,\n });\n loadingSpinner.complete();\n return result;\n } catch (error) {\n loadingSpinner.fail();\n throw error;\n }\n}\n\nexport function normalizeMetaForHistory(meta: SpaceMeta): {\n spaceName?: string | null;\n creatorProfileId?: string | null;\n creatorKind?: \"human\" | \"agent\" | \"system\" | null;\n spaceCreatedAt?: string | null;\n spaceUpdatedAt?: string | null;\n} | null {\n const creatorProfileId = resolveMetaCreatorProfileId(meta.creator);\n const creatorKind = resolveMetaCreatorKind(meta.creator?.kind);\n const spaceName =\n typeof meta.name === \"string\" ? normalizeOptionalString(meta.name) : null;\n const spaceCreatedAt =\n typeof meta.createdAt === \"string\"\n ? normalizeOptionalString(meta.createdAt)\n : null;\n const spaceUpdatedAt =\n typeof meta.updatedAt === \"string\"\n ? normalizeOptionalString(meta.updatedAt)\n : null;\n\n const hasData =\n spaceName !== null ||\n creatorProfileId !== null ||\n creatorKind !== null ||\n spaceCreatedAt !== null ||\n spaceUpdatedAt !== null;\n if (!hasData) {\n return null;\n }\n\n return {\n ...(spaceName === null ? {} : { spaceName }),\n ...(creatorProfileId === null ? {} : { creatorProfileId }),\n ...(creatorKind === null ? {} : { creatorKind }),\n ...(spaceCreatedAt === null ? {} : { spaceCreatedAt }),\n ...(spaceUpdatedAt === null ? {} : { spaceUpdatedAt }),\n };\n}\n\nfunction resolveMetaCreatorProfileId(\n creator: SpaceMeta[\"creator\"]\n): string | null {\n if (!creator || typeof creator !== \"object\") {\n return null;\n }\n if (typeof creator.profileId === \"string\") {\n return normalizeOptionalString(creator.profileId);\n }\n if (typeof creator.profile === \"string\") {\n return normalizeOptionalString(creator.profile);\n }\n return null;\n}\n\nfunction resolveMetaCreatorProfileName(\n creator: SpaceMeta[\"creator\"]\n): string | null {\n if (!creator || typeof creator !== \"object\") {\n return null;\n }\n if (typeof creator.profileName !== \"string\") {\n return null;\n }\n return normalizeOptionalString(creator.profileName);\n}\n\nfunction resolveMetaCreatorOwnerUserId(\n creator: SpaceMeta[\"creator\"]\n): string | null {\n if (!creator || typeof creator !== \"object\") {\n return null;\n }\n if (typeof creator.ownerUserId !== \"string\") {\n return null;\n }\n return normalizeOptionalString(creator.ownerUserId);\n}\n\nfunction resolveMetaCreatorKind(\n kind: unknown\n): \"human\" | \"agent\" | \"system\" | null {\n if (kind === \"human\" || kind === \"agent\" || kind === \"system\") {\n return kind;\n }\n return null;\n}\n","export class SpaceCommandOutputHandledError extends Error {\n readonly code = \"openmeld.space.output_handled\";\n readonly shouldPrintMessage: boolean;\n\n constructor(\n message: string,\n input: {\n shouldPrintMessage?: boolean;\n } = {}\n ) {\n super(message);\n this.name = \"SpaceCommandOutputHandledError\";\n this.shouldPrintMessage = input.shouldPrintMessage === true;\n }\n}\n\nexport function isSpaceCommandOutputHandledError(\n error: unknown\n): error is SpaceCommandOutputHandledError {\n return (\n error instanceof SpaceCommandOutputHandledError ||\n (typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n \"message\" in error &&\n \"shouldPrintMessage\" in error &&\n (error as { code?: unknown }).code === \"openmeld.space.output_handled\" &&\n typeof (error as { message?: unknown }).message === \"string\" &&\n typeof (error as { shouldPrintMessage?: unknown }).shouldPrintMessage ===\n \"boolean\")\n );\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport { toSpaceCursorUrl } from \"../protocol/urls\";\nimport {\n normalizeMentionAliasInput,\n normalizeRoleInput,\n} from \"./command-input-normalizers\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { parseSpaceMetaPayload } from \"./space-meta-response\";\n\nconst PLAN_DONE_PREFIX_RE = /^(PLAN|DONE)\\b/i;\nconst ACK_SIGNAL_REFERENCE_RE = /\\bACK\\s*[::]\\s*[-_a-z0-9]{6,}/i;\nconst TEXT_NEWLINE_SPLIT_RE = /\\r?\\n/u;\n\nexport function resolveWorkflowAckHint(text: string): string | null {\n const leadingMarker = resolveLeadingWorkflowMarker(text);\n if (!leadingMarker) {\n return null;\n }\n if (ACK_SIGNAL_REFERENCE_RE.test(text)) {\n return null;\n }\n return \"Directive guard: PLAN/DONE updates should include ACK:<owner-signal-id> after syncing latest history. If unclear, send BLOCKED: and wait for owner decision.\";\n}\n\nfunction resolveLeadingWorkflowMarker(text: string): \"PLAN\" | \"DONE\" | null {\n for (const line of text.split(TEXT_NEWLINE_SPLIT_RE)) {\n const trimmed = line.trim();\n if (trimmed.length === 0) {\n continue;\n }\n const match = PLAN_DONE_PREFIX_RE.exec(trimmed);\n if (!match) {\n continue;\n }\n const marker = match[1];\n if (!marker) {\n continue;\n }\n if (marker.toUpperCase() === \"PLAN\") {\n return \"PLAN\";\n }\n return \"DONE\";\n }\n return null;\n}\n\nexport function parseCreateSpaceResponse(raw: string): {\n spaceId: string;\n meta?: SpaceMeta;\n} {\n let parsed: { spaceId?: unknown; meta?: unknown };\n try {\n parsed = JSON.parse(raw) as { spaceId?: unknown; meta?: unknown };\n } catch {\n throw new Error(\"Unexpected response: invalid JSON\");\n }\n if (\n typeof parsed.spaceId !== \"string\" ||\n parsed.spaceId.trim().length === 0\n ) {\n throw new Error(\"Unexpected response: missing spaceId\");\n }\n\n if (parsed.meta !== undefined) {\n return {\n spaceId: parsed.spaceId,\n meta: parseSpaceMetaPayload({\n data: parsed.meta,\n endpoint: \"createSpace\",\n operation: \"createSpaceMeta\",\n }),\n };\n }\n\n return {\n spaceId: parsed.spaceId,\n };\n}\n\nexport async function fetchSpaceCursor(input: {\n requestContext: import(\"@openmeld/schemas/types\").OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n}): Promise<{\n role?: string;\n mentionAlias?: string;\n}> {\n const endpoint = toSpaceCursorUrl(\n input.baseUrl,\n input.space,\n input.requestContext.actorContext.openMeldProfileId\n );\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.fetch_cursor\",\n init: {\n method: \"GET\",\n headers,\n },\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n return parseSpaceCursorResponse({\n raw,\n endpoint,\n operation: \"fetchSpaceCursor\",\n });\n}\n\nexport function parseSpaceCursorResponse(input: {\n raw: string;\n endpoint: string;\n operation: \"fetchSpaceCursor\" | \"updateSpaceCursor\";\n}): {\n role?: string;\n mentionAlias?: string;\n} {\n try {\n const parsed = JSON.parse(input.raw) as {\n role?: unknown;\n mentionAlias?: unknown;\n };\n const role = normalizeRoleInput(\n typeof parsed.role === \"string\" ? parsed.role : undefined\n );\n const mentionAlias = normalizeMentionAliasInput(\n typeof parsed.mentionAlias === \"string\" ? parsed.mentionAlias : undefined\n );\n return {\n ...(role ? { role } : {}),\n ...(mentionAlias ? { mentionAlias } : {}),\n };\n } catch (err) {\n const reason = err instanceof Error ? err.message : String(err);\n throw new Error(\n `${input.operation} received invalid JSON from ${input.endpoint}: ${reason}; raw=${input.raw}`\n );\n }\n}\n","import type {\n HelloAck,\n Profile,\n ServerErrorFrame,\n SignalEnvelope,\n SpaceAgentStreamDeltaFrame,\n SpaceAgentStreamTerminalFrame,\n SpaceLiveInvalidationFrame,\n SpaceLiveSignalFrame,\n} from \"@openmeld/protocol\";\nimport {\n MAX_TEXT_LENGTH,\n parseEnvelope as parseProtocolEnvelope,\n parseIncoming as parseProtocolIncoming,\n parseServerErrorFrame as parseProtocolServerErrorFrame,\n} from \"@openmeld/protocol\";\nimport { toLegacySpaceImageGeometryWireValue } from \"@openmeld/schemas\";\nimport type {\n MessageEnvelope,\n SpaceAgentStreamPartFrame,\n} from \"@openmeld/schemas/types\";\n\ntype ParsedIncomingServerMessage = NonNullable<\n ReturnType<typeof parseProtocolIncoming>\n>;\ntype CliIgnoredIncomingFrame =\n | ServerErrorFrame\n | SpaceAgentStreamDeltaFrame\n | SpaceAgentStreamPartFrame\n | SpaceAgentStreamTerminalFrame\n | SpaceLiveInvalidationFrame\n | SpaceLiveSignalFrame;\n\nexport function makeHello(profile: Profile) {\n return {\n type: \"hello\",\n profile,\n capabilities: {\n spaceImageGeometry: true,\n spaceMessageAddressing: true,\n },\n };\n}\n\nexport function makeTextSignal(\n text: string,\n options?: {\n messageEnvelope?: MessageEnvelope;\n meta?: Record<string, unknown>;\n }\n) {\n return toLegacySpaceImageGeometryWireValue({\n type: \"signal.text\",\n data: {\n text,\n ...(options?.messageEnvelope\n ? { messageEnvelope: options.messageEnvelope }\n : {}),\n ...(options?.meta ? { meta: options.meta } : {}),\n },\n });\n}\n\nexport function sanitizeText(\n value: string\n): { ok: true; value: string } | { ok: false; reason: string } {\n const text = String(value ?? \"\").trim();\n if (text.length === 0) {\n return { ok: false, reason: \"empty\" };\n }\n if (text.length > MAX_TEXT_LENGTH) {\n return { ok: false, reason: `too long (>${MAX_TEXT_LENGTH} chars)` };\n }\n return { ok: true, value: text };\n}\n\nexport function parseEnvelope(value: unknown): SignalEnvelope | null {\n return parseProtocolEnvelope(value);\n}\n\nexport function parseIncoming(\n value: unknown\n): SignalEnvelope | HelloAck | null {\n const parsed = parseProtocolIncoming(value);\n if (!parsed || isCliIgnoredIncomingFrame(parsed)) {\n return null;\n }\n return parsed;\n}\n\nexport function parseServerErrorFrame(value: unknown): ServerErrorFrame | null {\n return parseProtocolServerErrorFrame(value);\n}\n\nfunction isCliIgnoredIncomingFrame(\n parsed: ParsedIncomingServerMessage\n): parsed is CliIgnoredIncomingFrame {\n return (\n \"error\" in parsed ||\n parsed.type === \"space.agent_stream_delta\" ||\n parsed.type === \"space.agent_stream_part\" ||\n parsed.type === \"space.agent_stream_terminal\" ||\n parsed.type === \"space.signal\" ||\n parsed.type === \"space.members.changed\" ||\n parsed.type === \"space.meta.changed\" ||\n parsed.type === \"agent.readiness.invalidated\"\n );\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\n\nexport type SpaceAccessPresentationInput = Pick<\n SpaceMeta,\n \"accessMode\" | \"passwordProtected\"\n> &\n Partial<Pick<SpaceMeta, \"visibility\">>;\n\nexport function resolveOrganizationVisibilityLabel(\n visibility: SpaceMeta[\"visibility\"]\n): string {\n return visibility === \"public\"\n ? \"discoverable; Organization members can join\"\n : \"invite only\";\n}\n\nexport function resolveLinkAccessLabel(\n input: SpaceAccessPresentationInput\n): string {\n switch (input.accessMode) {\n case \"members_only\":\n return \"members only\";\n case \"public\":\n return \"anyone with the link\";\n case \"public_view_join_password\":\n return \"anyone can view; password required to join\";\n case \"protected\":\n return \"password required to view and join\";\n default:\n if (input.passwordProtected === true) {\n return \"password required\";\n }\n if (input.passwordProtected === false) {\n return \"anyone with the link\";\n }\n return \"unknown\";\n }\n}\n","import type { HelloAck, SignalEnvelope, SpaceMeta } from \"@openmeld/protocol\";\nimport { canonicalizeBuiltinAgentControllerRef } from \"@openmeld/schemas\";\nimport type {\n AgentProfileBindingModelSelection,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport { resolveLinkAccessLabel } from \"./access-presentation\";\n\nfunction normalizeOptionalText(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport type NormalizedOwnerFields = {\n ownerUserId: string | null;\n ownerName: string | null;\n};\n\nexport function resolveNormalizedOwnerFields(input: {\n ownerUserId?: unknown;\n ownerName?: unknown;\n owner?: unknown;\n}): NormalizedOwnerFields {\n return {\n ownerUserId:\n normalizeOptionalText(input.ownerUserId) ??\n normalizeOptionalText(input.owner),\n ownerName: normalizeOptionalText(input.ownerName),\n };\n}\n\nexport function normalizeAgentControllerRef(\n agentControllerRef: unknown\n): string | null {\n const normalized = normalizeOptionalText(agentControllerRef);\n if (!normalized) {\n return null;\n }\n return canonicalizeBuiltinAgentControllerRef(normalized) ?? normalized;\n}\n\nexport function normalizeAgentOutputProfile(\n profile: SignalEnvelope[\"profile\"] | HelloAck[\"profile\"] | null | undefined\n): SignalEnvelope[\"profile\"] | HelloAck[\"profile\"] | undefined {\n if (!(profile && typeof profile === \"object\")) {\n return undefined;\n }\n\n const { ownerUserId, ownerName } = resolveNormalizedOwnerFields({\n ownerUserId: (profile as { ownerUserId?: unknown }).ownerUserId,\n ownerName: (profile as { ownerName?: unknown }).ownerName,\n owner: (profile as { owner?: unknown }).owner,\n });\n const agentControllerRef = normalizeAgentControllerRef(\n (profile as { agentControllerRef?: unknown }).agentControllerRef\n );\n\n return {\n ...profile,\n ...(ownerUserId ? { ownerUserId } : {}),\n ...(ownerName ? { ownerName } : {}),\n ...(agentControllerRef ? { agentControllerRef } : {}),\n };\n}\n\nexport function normalizeAgentOutputEvent(\n event: SignalEnvelope | HelloAck\n): SignalEnvelope | HelloAck {\n if (!(\"profile\" in event)) {\n return event;\n }\n const normalizedProfile = normalizeAgentOutputProfile(event.profile);\n if (!normalizedProfile) {\n return event;\n }\n const nextEvent = {\n ...event,\n profile: normalizedProfile,\n };\n if (\"owner\" in nextEvent.profile) {\n (nextEvent.profile as { owner?: unknown }).owner = undefined;\n }\n return nextEvent;\n}\n\nexport function normalizeAgentOutputMembersSnapshot(\n snapshot: SpaceMembersSnapshot\n): SpaceMembersSnapshot {\n const normalizedHumans = snapshot.humans.map((human) => {\n const ownerUserId = normalizeOptionalText(human.ownerUserId);\n const ownerName = normalizeOptionalText(human.ownerName);\n return {\n ...human,\n ownerUserId,\n ownerName,\n };\n });\n const normalizedAgents = snapshot.agents.map((agent) => {\n const ownerUserId = normalizeOptionalText(agent.ownerUserId);\n const ownerName = normalizeOptionalText(agent.ownerName);\n const agentControllerRef = normalizeAgentControllerRef(\n agent.agentControllerRef\n );\n return {\n ...agent,\n ownerUserId,\n ownerName,\n agentControllerRef,\n };\n });\n\n return {\n ...snapshot,\n humans: normalizedHumans,\n agents: normalizedAgents,\n };\n}\n\nexport function buildAgentSessionMetaPayload(input: {\n accessMode?: SpaceMeta[\"accessMode\"];\n gatewayUrl: string;\n mode: \"interactive chat\" | \"watch-only stream\" | \"history viewer\";\n passwordProtected?: boolean;\n agentControllerConversationId?: string;\n agentControllerRef?: string;\n modelSelection?: AgentProfileBindingModelSelection | null;\n profileId: string;\n profileKind?: \"human\" | \"agent\" | \"system\";\n profileName: string;\n ownerName?: string;\n ownerUserId?: string;\n spaceCreatedAt?: string;\n spaceCreatorId?: string;\n spaceCreatorName?: string;\n spaceId: string;\n spaceName?: string;\n visibility?: SpaceMeta[\"visibility\"];\n}): Record<string, unknown> {\n const access = resolveLinkAccessLabel(input);\n let security: \"Secure\" | \"Public\" | \"Unknown\" = \"Unknown\";\n if (input.passwordProtected === true) {\n security = \"Secure\";\n } else if (input.passwordProtected === false) {\n security = \"Public\";\n }\n\n const payload: Record<string, unknown> = {\n type: \"system.session.meta\",\n gatewayUrl: input.gatewayUrl,\n mode: input.mode,\n profileId: input.profileId,\n profileName: input.profileName,\n access,\n security,\n spaceId: input.spaceId,\n };\n\n appendOptionalStringField(payload, \"spaceName\", input.spaceName);\n appendOptionalStringField(payload, \"spaceCreatedAt\", input.spaceCreatedAt);\n appendOptionalStringField(payload, \"spaceCreatorId\", input.spaceCreatorId);\n appendOptionalStringField(\n payload,\n \"spaceCreatorName\",\n input.spaceCreatorName\n );\n appendOptionalBooleanField(\n payload,\n \"passwordProtected\",\n input.passwordProtected\n );\n appendOptionalStringField(payload, \"accessMode\", input.accessMode);\n appendOptionalStringField(payload, \"visibility\", input.visibility);\n appendOptionalStringField(payload, \"profileKind\", input.profileKind);\n appendOptionalStringField(payload, \"ownerUserId\", input.ownerUserId);\n appendOptionalStringField(payload, \"ownerName\", input.ownerName);\n appendOptionalStringField(\n payload,\n \"agentControllerRef\",\n normalizeAgentControllerRef(input.agentControllerRef)\n );\n appendOptionalStringField(\n payload,\n \"agentControllerConversationId\",\n input.agentControllerConversationId\n );\n appendOptionalModelSelectionField(payload, input.modelSelection);\n return payload;\n}\n\nfunction appendOptionalStringField(\n payload: Record<string, unknown>,\n key: string,\n value: unknown\n): void {\n const normalized = normalizeOptionalText(value);\n if (normalized) {\n payload[key] = normalized;\n }\n}\n\nfunction appendOptionalBooleanField(\n payload: Record<string, unknown>,\n key: string,\n value: unknown\n): void {\n if (typeof value === \"boolean\") {\n payload[key] = value;\n }\n}\n\nfunction appendOptionalModelSelectionField(\n payload: Record<string, unknown>,\n value: AgentProfileBindingModelSelection | null | undefined\n): void {\n const modelId = normalizeOptionalText(value?.modelId);\n if (!modelId) {\n return;\n }\n const reasoningLevel = normalizeOptionalText(value?.reasoningLevel);\n payload.modelSelection = {\n modelId,\n ...(reasoningLevel ? { reasoningLevel } : {}),\n };\n}\n","import type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport {\n createSpaceTargetCatalog,\n type SpaceTargetCatalog,\n} from \"@openmeld/space\";\n\nexport type SpaceMentionLabelState = {\n exactMentionLabels: readonly string[];\n primaryMentionLabel: string;\n};\n\nconst targetCatalogBySnapshot = new WeakMap<\n SpaceMembersSnapshot,\n SpaceTargetCatalog\n>();\nconst mentionLabelStateBySnapshot = new WeakMap<\n SpaceMembersSnapshot,\n ReadonlyMap<string, SpaceMentionLabelState>\n>();\n\nexport function resolvePrimarySpaceMentionLabel(input: {\n profileId: string | null | undefined;\n snapshot: SpaceMembersSnapshot | null | undefined;\n}): string | null {\n return resolveSpaceMentionLabelState(input)?.primaryMentionLabel ?? null;\n}\n\nexport function resolveSpaceMentionLabelState(input: {\n profileId: string | null | undefined;\n snapshot: SpaceMembersSnapshot | null | undefined;\n}): SpaceMentionLabelState | null {\n const profileId =\n typeof input.profileId === \"string\" ? input.profileId.trim() : \"\";\n if (!(profileId && input.snapshot)) {\n return null;\n }\n\n return (\n resolveSpaceMentionLabelStateByProfileId(input.snapshot).get(profileId) ??\n null\n );\n}\n\nexport function buildSpacePrimaryMentionLabelByProfileId(\n snapshot: SpaceMembersSnapshot\n): ReadonlyMap<string, string> {\n return new Map(\n [...resolveSpaceMentionLabelStateByProfileId(snapshot)].map(\n ([profileId, labelState]) => [profileId, labelState.primaryMentionLabel]\n )\n );\n}\n\nfunction resolveSpaceMentionLabelStateByProfileId(\n snapshot: SpaceMembersSnapshot\n): ReadonlyMap<string, SpaceMentionLabelState> {\n const cachedState = mentionLabelStateBySnapshot.get(snapshot);\n if (cachedState) {\n return cachedState;\n }\n\n const labelStateByProfileId = new Map<string, SpaceMentionLabelState>();\n for (const [profileId, entry] of resolveSpaceTargetCatalog(snapshot)\n .byProfileId) {\n labelStateByProfileId.set(profileId, {\n exactMentionLabels: entry.exactMentionLabels,\n primaryMentionLabel: entry.primaryMentionLabel,\n });\n }\n\n mentionLabelStateBySnapshot.set(snapshot, labelStateByProfileId);\n return labelStateByProfileId;\n}\n\nfunction resolveSpaceTargetCatalog(\n snapshot: SpaceMembersSnapshot\n): SpaceTargetCatalog {\n const cachedCatalog = targetCatalogBySnapshot.get(snapshot);\n if (cachedCatalog) {\n return cachedCatalog;\n }\n\n const targetCatalog = createSpaceTargetCatalog(snapshot);\n targetCatalogBySnapshot.set(snapshot, targetCatalog);\n return targetCatalog;\n}\n","import { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\n\nconst OPENMELD_SYSTEM_PROFILE_ID = \"openmeld-system\";\nconst OPENMELD_SYSTEM_PROFILE_NAME = \"openmeld system\";\n\ntype OpenMeldSystemProfileIdentityLike =\n | {\n kind?: unknown;\n openMeldProfileId?: unknown;\n profileId?: unknown;\n profileName?: unknown;\n }\n | null\n | undefined;\n\nconst normalizeProfileValue = (value: unknown): string =>\n sanitizeTerminalDisplayText(\n typeof value === \"string\" || typeof value === \"number\" ? value : \"\",\n \"single-line\"\n )\n .trim()\n .toLowerCase();\n\nexport function isOpenMeldSystemProfileIdentity(\n profileIdentity: OpenMeldSystemProfileIdentityLike\n): boolean {\n if (!profileIdentity || typeof profileIdentity !== \"object\") {\n return false;\n }\n\n const kind = normalizeProfileValue(profileIdentity.kind);\n if (kind === \"system\") {\n return true;\n }\n\n const profileId = normalizeProfileValue(\n profileIdentity.openMeldProfileId ?? profileIdentity.profileId\n );\n if (profileId === OPENMELD_SYSTEM_PROFILE_ID) {\n return true;\n }\n\n const profileName = normalizeProfileValue(profileIdentity.profileName);\n return profileName === OPENMELD_SYSTEM_PROFILE_NAME;\n}\n","import {\n buildSpaceMessageReadRelationSummary,\n type SpaceMessageReadProjection,\n type SpaceMessageReadRelationSummary,\n type SpaceMessageReadTargetRef,\n type SpaceMessageReplyContext,\n} from \"@openmeld/space\";\n\nexport type HumanMessageSemanticLines = {\n relationLines: readonly string[];\n replyLine: string | null;\n};\n\nexport function buildHumanMessageRelationLines(\n projection:\n | Pick<\n SpaceMessageReadProjection,\n \"wakeTargets\" | \"referenceTargets\" | \"mentionTargets\"\n >\n | null\n | undefined\n): readonly string[] {\n if (!projection) {\n return [];\n }\n return buildSpaceMessageReadRelationSummary({\n wakeTargets: projection.wakeTargets,\n referenceTargets: projection.referenceTargets,\n mentionTargets: projection.mentionTargets,\n }).map(formatHumanRelationSummaryLine);\n}\n\nexport function buildHumanReplyContextLine(\n replyContext: SpaceMessageReplyContext | null | undefined\n): string | null {\n const summary = buildHumanReplyContextSummary(replyContext);\n return summary ? `reply to ${summary}` : null;\n}\n\nexport function buildHumanReplyContextSummary(\n replyContext: SpaceMessageReplyContext | null | undefined\n): string | null {\n if (!replyContext) {\n return null;\n }\n\n const actorLabel =\n normalizeDisplayText(replyContext.actorDisplayName) ??\n normalizeDisplayText(replyContext.actorProfileId);\n if (!actorLabel) {\n return null;\n }\n\n const semanticPreview = buildHumanReplySemanticPreview(replyContext);\n return semanticPreview ? `${actorLabel} · ${semanticPreview}` : actorLabel;\n}\n\nexport function formatHumanReadTargetList(\n targets: readonly SpaceMessageReadTargetRef[]\n): string {\n return targets\n .map(\n (target) => normalizeDisplayText(target.displayName) ?? target.profileId\n )\n .join(\", \");\n}\n\nexport function buildHumanMessageSemanticLines(input: {\n projection?: SpaceMessageReadProjection | null;\n replyContext?: SpaceMessageReplyContext | null;\n}): HumanMessageSemanticLines {\n return {\n relationLines: buildHumanMessageRelationLines(input.projection),\n replyLine: buildHumanReplyContextLine(input.replyContext),\n };\n}\n\nfunction buildHumanReplySemanticPreview(\n replyContext: SpaceMessageReplyContext\n): string | null {\n const relationSummary = replyContext.relationSummary ?? [];\n if (relationSummary.length > 0) {\n return relationSummary.map(formatHumanRelationSummaryLine).join(\" · \");\n }\n\n if (replyContext.resolved !== true) {\n return null;\n }\n\n return normalizeDisplayText(replyContext.previewText);\n}\n\nfunction formatHumanRelationSummaryLine(\n summary: SpaceMessageReadRelationSummary\n): string {\n return `${summary.relation}: ${formatHumanReadTargetList(summary.targets)}`;\n}\n\nfunction normalizeDisplayText(value: string | null | undefined): string | null {\n const normalized = String(value ?? \"\")\n .replace(/\\s+/gu, \" \")\n .trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import stringWidth from \"string-width\";\nimport { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\n\nconst REPLY_PREVIEW_FENCED_BLOCK_RE = /```[\\s\\S]*?```/gu;\nconst REPLY_PREVIEW_LEADING_MENTION_PATTERN =\n /^@[A-Za-z0-9][A-Za-z0-9._-]{0,127}(?:[.,!?;:,。!?;:]+)?(?:\\s+|$)/u;\n\nexport function buildHumanReplyCuePreview(\n value: string,\n maxVisibleWidth: number\n): string {\n const sanitizedPreview = sanitizeReplyCueText(value);\n if (!sanitizedPreview) {\n return \"\";\n }\n\n const previewBody =\n stripLeadingReplyCueMention(sanitizedPreview) || sanitizedPreview;\n return truncateReplyCuePreview(previewBody, maxVisibleWidth);\n}\n\nfunction sanitizeReplyCueText(value: string): string {\n return sanitizeTerminalDisplayText(\n value.replace(REPLY_PREVIEW_FENCED_BLOCK_RE, \" \"),\n \"single-line\"\n )\n .replace(/\\s+/gu, \" \")\n .trim();\n}\n\nfunction stripLeadingReplyCueMention(value: string): string {\n const match = REPLY_PREVIEW_LEADING_MENTION_PATTERN.exec(value);\n if (!match) {\n return value;\n }\n\n return value.slice(match[0].length).trimStart();\n}\n\nfunction truncateReplyCuePreview(\n value: string,\n maxVisibleWidth: number\n): string {\n if (stringWidth(value) <= maxVisibleWidth) {\n return value;\n }\n if (maxVisibleWidth <= 1) {\n return \"…\";\n }\n\n const ellipsis = \"…\";\n const targetWidth = maxVisibleWidth - stringWidth(ellipsis);\n let result = \"\";\n let currentWidth = 0;\n\n for (const char of value) {\n const nextWidth = currentWidth + stringWidth(char);\n if (nextWidth > targetWidth) {\n break;\n }\n result += char;\n currentWidth = nextWidth;\n }\n\n return `${result.trimEnd()}${ellipsis}`;\n}\n","import pc from \"picocolors\";\n\nconst POSITIVE_ACCENT_RGB = {\n b: 80,\n g: 255,\n r: 174,\n} as const;\n\nexport function renderPositiveAccentText(text: string): string {\n if (!pc.isColorSupported) {\n return text;\n }\n return `\\u001B[38;2;${String(POSITIVE_ACCENT_RGB.r)};${String(POSITIVE_ACCENT_RGB.g)};${String(POSITIVE_ACCENT_RGB.b)}m${text}\\u001B[39m`;\n}\n","import type { SpaceAccessPresentationInput } from \"../space/access-presentation\";\nimport { buildSpaceAccessPromptCardMessage } from \"./space-access-prompt-card\";\n\ntype PublicSpaceConfirmPromptConfig = {\n active: string;\n inactive: string;\n message: string;\n vertical: boolean;\n};\n\nexport type PublicSpaceExposure = \"anyone_can_join\" | \"anyone_can_view\";\n\nexport function resolvePublicSpaceExposure(\n input: SpaceAccessPresentationInput\n): PublicSpaceExposure | null {\n switch (input.accessMode) {\n case \"public\":\n return \"anyone_can_join\";\n case \"public_view_join_password\":\n return \"anyone_can_view\";\n case \"members_only\":\n case \"protected\":\n return null;\n default:\n // Older Space metadata did not include accessMode. Organization\n // visibility is independent of link access, so the legacy password fact\n // is the only safe compatibility signal here.\n return input.passwordProtected === false ? \"anyone_can_join\" : null;\n }\n}\n\nexport function buildPublicSpaceWarningLines(\n exposure: PublicSpaceExposure\n): [string, string] {\n const firstLine =\n exposure === \"anyone_can_join\"\n ? \"Anyone with this Space link can read what is shared here and join.\"\n : \"Anyone with this Space link can read what is shared here. A password is required to join.\";\n return [\n firstLine,\n \"Only bring an agent if you're comfortable sharing anything it posts with people who have the link.\",\n ];\n}\n\nexport function buildPublicSpaceJoinConfirmPromptConfig(input: {\n exposure: PublicSpaceExposure;\n}): PublicSpaceConfirmPromptConfig {\n return {\n active: \"Yes, join this Space\",\n inactive: \"No, go back\",\n message: buildPublicSpacePromptMessage(\n \"Do you want to join this Space?\",\n input.exposure\n ),\n vertical: true,\n };\n}\n\nexport function buildPublicSpaceBringAgentsConfirmPromptConfig(input: {\n agentCount: number;\n exposure: PublicSpaceExposure;\n}): PublicSpaceConfirmPromptConfig {\n const singular = input.agentCount === 1;\n return {\n active: singular ? \"Yes, bring this agent\" : \"Yes, bring these agents\",\n inactive: singular\n ? \"No, join without this agent\"\n : \"No, join without these agents\",\n message: buildPublicSpacePromptMessage(\n singular\n ? \"Bring this agent into a Space that anyone with the link can read?\"\n : \"Bring these agents into a Space that anyone with the link can read?\",\n input.exposure\n ),\n vertical: true,\n };\n}\n\nfunction buildPublicSpacePromptMessage(\n question: string,\n exposure: PublicSpaceExposure\n): string {\n return buildSpaceAccessPromptCardMessage({\n lines: buildPublicSpaceWarningLines(exposure),\n question,\n });\n}\n","import type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport {\n buildSpaceMentionProfileIndex,\n collectResolvedSpaceMentions,\n type SpaceMentionProfileIdentity,\n type SpaceMentionProfileIndex,\n} from \"@openmeld/space\";\n\nexport type MentionHighlightProfileIdentity = SpaceMentionProfileIdentity;\nexport type SpaceMentionHighlightIndex = SpaceMentionProfileIndex;\n\nexport function buildSpaceMentionHighlightIndex(\n snapshot: SpaceMembersSnapshot\n): SpaceMentionHighlightIndex {\n return buildSpaceMentionProfileIndex(snapshot);\n}\n\nexport function highlightSpaceMentions(input: {\n text: string;\n index?: SpaceMentionHighlightIndex | null;\n render: (\n mentionText: string,\n profileIdentity: MentionHighlightProfileIdentity\n ) => string;\n}): string {\n if (!(input.index && input.text.length > 0)) {\n return input.text;\n }\n const matches = collectResolvedSpaceMentions({\n text: input.text,\n index: input.index,\n });\n if (matches.length === 0) {\n return input.text;\n }\n\n let cursor = 0;\n let highlighted = \"\";\n for (const match of matches) {\n highlighted += input.text.slice(cursor, match.start);\n highlighted += input.render(match.mentionText, match.profileIdentity);\n cursor = match.end;\n }\n highlighted += input.text.slice(cursor);\n return highlighted;\n}\n","import type {\n HelloAck,\n SignalEnvelope,\n SignalTextReplyTo,\n SpaceMeta,\n} from \"@openmeld/protocol\";\nimport {\n AGENT_REPLY_PREVIEW_END_PURPOSE,\n AGENT_REPLY_PREVIEW_PURPOSE,\n AGENT_REPLYING_END_PURPOSE,\n AGENT_REPLYING_PURPOSE,\n CONVERSATION_CONTINUITY_WARNING_PURPOSE,\n DISPATCH_ACTIVITY_DISPATCHING_PURPOSE,\n DISPATCH_ACTIVITY_FAILED_PURPOSE,\n DISPATCH_ACTIVITY_RETRYING_PURPOSE,\n normalizeOptionalWorkingDirectory,\n SPACE_MEMBER_JOIN_NOTICE_PURPOSE,\n SPACE_MEMBER_REMOVE_NOTICE_PURPOSE,\n} from \"@openmeld/schemas\";\nimport type {\n AgentControllerConversationRef,\n AgentProfileBindingModelSelection,\n SpaceMemberAgentSnapshot,\n SpaceMemberHumanSnapshot,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport {\n buildSpaceMemberAgentPresencePresentation,\n resolveSpaceMemberAgentOwnerWakeDiagnosticsView,\n} from \"@openmeld/space\";\nimport pc from \"picocolors\";\nimport { resolveRegistryOriginLaunchCommand } from \"../agents/registry-source\";\nimport { formatOpenMeldCliCommand } from \"../runtime/cli-entry-command\";\nimport { resolveLinkAccessLabel } from \"../space/access-presentation\";\nimport { resolveNormalizedOwnerFields } from \"../space/agent-output-contract\";\nimport {\n resolvePrimarySpaceMentionLabel,\n resolveSpaceMentionLabelState,\n} from \"../space/mention-label-state\";\nimport { isOpenMeldSystemProfileIdentity } from \"../space/openmeld-system-profile\";\nimport { buildHumanMessageRelationLines } from \"../space/read-projection/human-message-read-display\";\nimport { buildHumanReplyCuePreview } from \"../space/reply-cue-preview\";\nimport {\n buildSpaceDisplayProjection,\n buildSpaceMetadataFields,\n formatSpaceDisplayValue,\n resolveSpaceDisplayName,\n} from \"../space/space-display-projection\";\nimport { buildUnifiedCardFrame } from \"./card-frame\";\nimport { resolveControllerDisplayName } from \"./controller-display\";\nimport { renderPositiveAccentText } from \"./positive-accent\";\nimport {\n colorizeAgentLabel,\n colorizeDisplayProfileLabel,\n colorizePersonLabel,\n resolveDisplayProfileIdentity,\n} from \"./profile-label-color\";\nimport {\n buildPublicSpaceWarningLines,\n resolvePublicSpaceExposure,\n} from \"./public-space-warning\";\nimport {\n highlightSpaceMentions,\n type SpaceMentionHighlightIndex,\n} from \"./space-mention-highlight\";\nimport { sanitizeTerminalDisplayText } from \"./terminal-safe-text\";\n\nexport type OutputMode = \"ndjson\" | \"text\";\nexport type HumanFormattedMessage = {\n bodyLines: readonly string[];\n relationLines: readonly string[];\n metaLines: readonly string[];\n headerBadge?: string | null;\n};\ntype ResolvedView = \"human\" | \"agent\";\ntype TextEventFormatOptions = {\n view: ResolvedView;\n selfProfileId?: string;\n mentionHighlightIndex?: SpaceMentionHighlightIndex | null;\n replyLine?: string | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n};\ntype ProfileIdentityLike =\n | {\n profileName?: string | null;\n kind?: string | null;\n profileId?: string | null;\n ownerUserId?: string | null;\n owner?: string | null;\n ownerName?: string | null;\n agentControllerRef?: string | null;\n agentControllerConversationId?: string | null;\n agentControllerConversation?: AgentControllerConversationRef | null;\n modelSelection?: AgentProfileBindingModelSelection | null;\n workingDirectory?: string | null;\n }\n | undefined;\ntype SystemNoticeMentionHint = {\n mentionLabel: string;\n agentControllerRef?: string;\n profileId?: string;\n profileName?: string;\n};\ntype SystemNoticeProfileHighlight = {\n label: string;\n renderedLabel: string;\n};\n\nconst AGENT_CONTEXT_HIDDEN_TOKENS = new Set([\n \"pending\",\n \"no-context\",\n \"none\",\n \"unknown\",\n]);\nconst MENTION_DISPATCH_HINT_META_PURPOSE = \"mention_dispatch_hint\";\nconst MENTION_FAILURE_HINT_PREFIX = 'Mention skipped for \"';\nconst MENTION_FAILURE_HINT_LEGACY_PREFIX = \"Mention skipped. Try this:\";\nconst SYSTEM_BROADCAST_LABEL = pc.cyan(\"📣 system\");\nconst AGENT_SPEAKER_AVATAR = \"🤖\";\nconst HUMAN_SPEAKER_AVATAR = \"👤\";\nconst HUMAN_REPLY_CUE_PREVIEW_MAX_VISIBLE_WIDTH = 28;\n\nconst sanitizeSingleLineText = (\n value: string | number | null | undefined\n): string => sanitizeTerminalDisplayText(value, \"single-line\");\n\nconst sanitizeMultilineText = (\n value: string | number | null | undefined\n): string => sanitizeTerminalDisplayText(value, \"multi-line\");\n\nconst sanitizeTrimmedSingleLineText = (\n value: string | number | null | undefined\n): string => sanitizeSingleLineText(value).trim();\n\nexport function formatInputPrompt(\n profileIdentity: {\n profileName?: string;\n kind?: string;\n profileId?: string;\n ownerUserId?: string;\n ownerName?: string;\n },\n options?: {\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): string {\n const profileName = resolveHumanProfileLabel(profileIdentity);\n const profileKind = resolveHumanProfileKind(profileIdentity);\n const suffix = profileKind ? ` (${profileKind})` : \"\";\n const label = `${profileName}${suffix}`;\n return `- ${colorizeDisplayProfileLabel({\n label,\n profileIdentity,\n spaceMembersSnapshot: options?.spaceMembersSnapshot,\n })}: `;\n}\n\nexport function formatCatchupMarker(view: ResolvedView): string {\n if (view === \"human\") {\n return `* ${SYSTEM_BROADCAST_LABEL}: Conversation after you left.`;\n }\n return \"system: conversation_after_you_left\";\n}\n\nexport function formatTextEvent(\n event: SignalEnvelope | HelloAck,\n options: TextEventFormatOptions\n): string | null {\n switch (event.type) {\n case \"system.hello.ack\":\n return formatHelloAck(event, options);\n case \"presence.join\":\n return formatPresenceJoin(event, options);\n case \"presence.quit\":\n return formatPresenceQuit(event, options);\n case \"signal.text\":\n return formatSignalText(event, options);\n case \"signal.status\":\n return formatSignalStatus(event, options);\n case \"signal.system_notice\":\n return formatSignalSystemNotice(event, options);\n default:\n return null;\n }\n}\n\ntype ConnectIntroInput = {\n accessMode?: SpaceMeta[\"accessMode\"];\n spaceId: string;\n spaceName?: string;\n spaceCreatedAt?: string;\n spaceCreatorName?: string;\n spaceCreatorId?: string;\n passwordProtected?: boolean;\n profileId: string;\n profileName: string;\n profileKind?: \"human\" | \"agent\" | \"system\";\n ownerUserId?: string;\n ownerName?: string;\n agentControllerRef?: string;\n agentControllerConversationId?: string;\n agentControllerConversation?: AgentControllerConversationRef | null;\n modelSelection?: AgentProfileBindingModelSelection | null;\n workingDirectory?: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot;\n gatewayUrl: string;\n stdio: boolean;\n visibility?: SpaceMeta[\"visibility\"];\n};\n\nexport function formatConnectIntro(input: ConnectIntroInput): string[] {\n return [\n \"\",\n ...buildSpaceInfoCardLines({\n gatewayUrl: input.gatewayUrl,\n modeLabel: input.stdio ? \"interactive chat\" : \"watch-only stream\",\n accessMode: input.accessMode,\n passwordProtected: input.passwordProtected,\n spaceCreatedAt: input.spaceCreatedAt,\n spaceCreatorId: input.spaceCreatorId,\n spaceCreatorName: input.spaceCreatorName,\n spaceId: input.spaceId,\n spaceName: input.spaceName,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n visibility: input.visibility,\n }),\n ...(input.spaceMembersSnapshot\n ? [\"\", ...buildSpaceMembersCardLines(input.spaceMembersSnapshot)]\n : []),\n \"\",\n ...buildProfileCardLines({\n agentControllerConversationId: input.agentControllerConversationId,\n agentControllerRef: input.agentControllerRef,\n profileId: input.profileId,\n profileKind: input.profileKind,\n profileName: input.profileName,\n ownerUserId: input.ownerUserId,\n ownerName: input.ownerName,\n agentControllerConversation: input.agentControllerConversation,\n modelSelection: input.modelSelection,\n workingDirectory: input.workingDirectory,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }),\n \"\",\n ];\n}\n\nexport type ConnectIntroCardRow = {\n label: string;\n value: string;\n};\n\nexport type SpaceInfoFact = {\n label: string;\n value: string;\n};\n\nexport type SpaceInfoCardInput = {\n accessMode?: SpaceMeta[\"accessMode\"];\n gatewayUrl: string;\n modeLabel: string;\n passwordProtected?: boolean;\n spaceCreatedAt?: string;\n spaceCreatorId?: string;\n spaceCreatorName?: string;\n spaceId: string;\n spaceName?: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n visibility?: SpaceMeta[\"visibility\"];\n};\n\nexport type SpaceInfoData = {\n facts: readonly SpaceInfoFact[];\n joinCommand: string;\n publicWarningLines: readonly string[];\n};\n\nexport type SpaceMembersPanelSectionId = \"humans\" | \"agents\";\n\nexport type SpaceMembersPanelItemSource = {\n id: string;\n mentionLabel: string | null;\n ownerUserId: string | null;\n ownerName: string | null;\n profileId: string;\n profileKind:\n | SpaceMemberHumanSnapshot[\"profileKind\"]\n | SpaceMemberAgentSnapshot[\"profileKind\"];\n profileName: string;\n renderedLines: readonly string[];\n searchKey: string;\n};\n\nexport type SpaceMembersPanelSectionSource = {\n id: SpaceMembersPanelSectionId;\n items: readonly SpaceMembersPanelItemSource[];\n title: string;\n};\n\nexport type SpaceMembersPanelSource = {\n sections: readonly SpaceMembersPanelSectionSource[];\n};\n\ntype ProfileCardInput = {\n agentControllerConversationId?: string;\n agentControllerRef?: string;\n profileId: string;\n profileKind?: \"human\" | \"agent\" | \"system\";\n profileName: string;\n ownerUserId?: string;\n ownerName?: string;\n agentControllerConversation?: AgentControllerConversationRef | null;\n modelSelection?: AgentProfileBindingModelSelection | null;\n workingDirectory?: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n};\n\nexport function buildSpaceInfoCardLines(input: SpaceInfoCardInput): string[] {\n const rows = buildSpaceInfoRows(input);\n return buildConnectIntroCardLines({\n title: \"🛰️ Space Info\",\n rows,\n minContentWidth: 76,\n });\n}\n\nexport function buildSpaceInfoPanelLines(input: SpaceInfoCardInput): string[] {\n return buildConnectIntroRowLines(buildSpaceInfoRows(input));\n}\n\nexport function buildSpaceInfoData(input: SpaceInfoCardInput): SpaceInfoData {\n const projection = buildSpaceDisplayProjection({\n spaceId: input.spaceId,\n spaceName: input.spaceName,\n creatorProfileId: input.spaceCreatorId,\n creatorProfileName: input.spaceCreatorName,\n spaceCreatedAt: input.spaceCreatedAt,\n passwordProtected: input.passwordProtected,\n });\n const accessFacts = {\n accessMode: input.accessMode,\n passwordProtected: input.passwordProtected,\n visibility: input.visibility,\n };\n const publicExposure = resolvePublicSpaceExposure(accessFacts);\n const gatewayUrl = sanitizeTrimmedSingleLineText(input.gatewayUrl);\n const metadataFacts = buildSpaceMetadataFields({\n projection,\n includeCreatedAt: true,\n }).map<SpaceInfoFact>((field) => {\n if (field.id !== \"spaceCreator\") {\n return {\n label: field.label,\n value: field.value,\n };\n }\n\n return {\n label: field.label,\n value:\n projection.creatorDisplayName && projection.creatorProfileId\n ? colorizePersonLabel(\n projection.creatorDisplayName,\n {\n profileId: projection.creatorProfileId,\n profileName: projection.creatorDisplayName,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n )\n : formatSpaceDisplayValue(projection.creatorDisplayName, \"(unknown)\"),\n };\n });\n\n return {\n facts: [\n {\n label: \"Space Name\",\n value: resolveSpaceDisplayName(projection.spaceName, \"(unnamed)\"),\n },\n ...metadataFacts,\n {\n label: \"Link access\",\n value: resolveLinkAccessLabel(accessFacts),\n },\n {\n label: \"Gateway URL\",\n value: gatewayUrl,\n },\n {\n label: \"Mode\",\n value: sanitizeTrimmedSingleLineText(input.modeLabel) || \"(unknown)\",\n },\n ],\n joinCommand: formatOpenMeldCliCommand(\n `openmeld space join ${input.spaceId}`\n ),\n publicWarningLines: publicExposure\n ? buildPublicSpaceWarningLines(publicExposure)\n : [],\n };\n}\n\nexport function buildSpaceInfoRows(\n input: SpaceInfoCardInput\n): ConnectIntroCardRow[] {\n const spaceInfo = buildSpaceInfoData(input);\n\n const rows: ConnectIntroCardRow[] = [\n ...spaceInfo.facts,\n {\n label: \"\",\n value: \"\",\n },\n {\n label: \"To join this space, run:\",\n value: \"\",\n },\n {\n label: pc.cyan(spaceInfo.joinCommand),\n value: \"\",\n },\n ];\n\n if (spaceInfo.publicWarningLines.length > 0) {\n rows.push(\n {\n label: \"\",\n value: \"\",\n },\n ...spaceInfo.publicWarningLines.map((line) => ({\n label: line,\n value: \"\",\n }))\n );\n }\n\n return rows;\n}\n\nexport function buildProfileCardLines(input: ProfileCardInput): string[] {\n const profileIdentity: ProfileIdentityLike = {\n agentControllerConversationId: input.agentControllerConversationId,\n agentControllerRef: input.agentControllerRef,\n kind: input.profileKind,\n ownerUserId: input.ownerUserId,\n ownerName: input.ownerName,\n profileId: input.profileId,\n profileName: input.profileName,\n agentControllerConversation: input.agentControllerConversation,\n modelSelection: input.modelSelection,\n workingDirectory: input.workingDirectory,\n };\n const rows = buildProfileRows({\n input,\n profileIdentity,\n });\n return buildConnectIntroCardLines({\n title: \"👤 Your profile in this space\",\n rows,\n minContentWidth: 76,\n });\n}\n\nfunction buildProfileRows(input: {\n input: ProfileCardInput;\n profileIdentity: ProfileIdentityLike;\n}): ConnectIntroCardRow[] {\n const ownerUserId = sanitizeTrimmedSingleLineText(input.input.ownerUserId);\n const ownerName = sanitizeTrimmedSingleLineText(input.input.ownerName);\n const rows: ConnectIntroCardRow[] = [\n {\n label: \"Profile Name\",\n value: colorizeDisplayProfileLabel({\n label: resolveHumanProfileName(input.profileIdentity),\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.input.spaceMembersSnapshot,\n }),\n },\n {\n label: \"Profile ID\",\n value: sanitizeTrimmedSingleLineText(input.input.profileId),\n },\n {\n label: \"Type\",\n value: resolveHumanProfileKind(input.profileIdentity) || \"unknown\",\n },\n ];\n\n if (ownerName) {\n rows.push({\n label: \"Owner Name\",\n value: colorizePersonLabel(\n ownerName,\n {\n ownerUserId: ownerUserId || input.input.profileId,\n ownerName,\n profileName: ownerName,\n },\n {\n spaceMembersSnapshot: input.input.spaceMembersSnapshot,\n }\n ),\n });\n }\n\n if (ownerUserId && ownerUserId !== ownerName) {\n rows.push({\n label: \"Owner\",\n value: ownerUserId,\n });\n }\n\n const agentControllerRef = resolveAgentControllerRef(input.profileIdentity);\n if (agentControllerRef) {\n const controllerDisplay = resolveControllerDisplayName(agentControllerRef);\n rows.push({\n label: \"Agent Controller\",\n value: controllerDisplay\n ? colorizeAgentLabel(\n controllerDisplay,\n {\n agentControllerRef,\n profileId: input.profileIdentity?.profileId,\n profileName: input.profileIdentity?.profileName,\n },\n {\n spaceMembersSnapshot: input.input.spaceMembersSnapshot,\n }\n )\n : agentControllerRef,\n });\n }\n\n const originDisplay = agentControllerRef\n ? resolveAgentOriginDisplay({\n agentControllerRef,\n agentControllerConversationId: resolveAgentControllerConversationId(\n input.profileIdentity\n ),\n model: resolveProfileModelId(input.profileIdentity),\n workingDirectory: resolveWorkingDirectory(input.profileIdentity),\n })\n : resolveAgentControllerConversationId(input.profileIdentity);\n if (originDisplay) {\n rows.push({\n label: \"Origin\",\n value: originDisplay,\n });\n }\n\n return rows;\n}\n\nexport function buildSpaceMembersCardLines(\n snapshot: SpaceMembersSnapshot\n): string[] {\n const rowTextList = buildSpaceMembersPanelLines(snapshot);\n const frame = buildUnifiedCardFrame({\n title: \"👥 Space Members\",\n rowTextList,\n minContentWidth: 76,\n });\n return [frame.top, frame.empty, ...frame.rows, frame.empty, frame.bottom];\n}\n\nexport function buildSpaceMembersLoadingCardLines(): string[] {\n const frame = buildUnifiedCardFrame({\n title: \"👥 Space Members\",\n rowTextList: buildSpaceMembersLoadingPanelLines(),\n minContentWidth: 76,\n });\n return [frame.top, frame.empty, ...frame.rows, frame.empty, frame.bottom];\n}\n\nexport function buildSpaceMembersPanelLines(\n snapshot: SpaceMembersSnapshot\n): string[] {\n const source = buildSpaceMembersPanelSource(snapshot);\n const rows: string[] = [];\n for (const section of source.sections) {\n if (section.items.length === 0) {\n continue;\n }\n if (rows.length > 0) {\n rows.push(\"\");\n }\n rows.push(pc.bold(section.title));\n for (const item of section.items) {\n rows.push(...item.renderedLines);\n }\n }\n if (rows.length === 0) {\n rows.push(pc.dim(\"No members yet.\"));\n }\n return rows;\n}\n\nexport function buildSpaceMembersPanelSource(\n snapshot: SpaceMembersSnapshot\n): SpaceMembersPanelSource {\n return {\n sections: [\n buildSpaceMembersPanelSectionSource({\n id: \"agents\",\n members: snapshot.agents,\n snapshot,\n title: \"🤖 Agents\",\n }),\n buildSpaceMembersPanelSectionSource({\n id: \"humans\",\n members: snapshot.humans,\n snapshot,\n title: \"👤 Humans\",\n }),\n ].filter((section) => section.items.length > 0),\n };\n}\n\nexport function buildSpaceMembersLoadingPanelLines(): string[] {\n return [\"Members are still loading.\"];\n}\n\nfunction formatSpaceMemberCardRows(\n member: SpaceMemberHumanSnapshot | SpaceMemberAgentSnapshot,\n snapshot: SpaceMembersSnapshot\n): string[] {\n const profileId = sanitizeTrimmedSingleLineText(member.profileId);\n const coloredProfileName = colorizeDisplayProfileLabel({\n label: member.profileName,\n profileIdentity: member,\n spaceMembersSnapshot: snapshot,\n });\n const rows = [`${coloredProfileName} ${pc.dim(`· ${profileId}`)}`];\n\n if (member.profileKind === \"human\") {\n const metadataLine = buildSpaceMemberHumanMetadataLine(member);\n if (metadataLine) {\n rows.push(` ${metadataLine}`);\n }\n const relatedAgentsLine = buildHumanRelatedAgentsLine({\n profileIdentity: {\n kind: \"human\",\n profileId: member.profileId,\n profileName: member.profileName,\n ownerUserId: member.ownerUserId ?? undefined,\n ownerName: member.ownerName ?? undefined,\n },\n spaceMembersSnapshot: snapshot,\n });\n if (relatedAgentsLine) {\n rows.push(` ${pc.dim(relatedAgentsLine)}`);\n }\n return rows;\n }\n\n const metadataLine = buildSpaceMemberAgentMetadataLine(member, snapshot);\n if (metadataLine) {\n rows.push(` ${metadataLine}`);\n }\n const statusLine = buildSpaceMemberAgentStatusLine(member, snapshot);\n if (statusLine) {\n rows.push(` ${statusLine}`);\n }\n return rows;\n}\n\nfunction buildSpaceMembersPanelSectionSource(input: {\n id: SpaceMembersPanelSectionId;\n members: readonly (SpaceMemberHumanSnapshot | SpaceMemberAgentSnapshot)[];\n snapshot: SpaceMembersSnapshot;\n title: string;\n}): SpaceMembersPanelSectionSource {\n return {\n id: input.id,\n items: input.members.map((member) =>\n buildSpaceMembersPanelItemSource(member, input.snapshot)\n ),\n title: input.title,\n };\n}\n\nfunction buildSpaceMembersPanelItemSource(\n member: SpaceMemberHumanSnapshot | SpaceMemberAgentSnapshot,\n snapshot: SpaceMembersSnapshot\n): SpaceMembersPanelItemSource {\n const mentionLabels = resolveSpaceMentionLabelState({\n profileId: member.profileId,\n snapshot,\n });\n return {\n id: sanitizeTrimmedSingleLineText(member.profileId),\n ownerUserId:\n \"ownerUserId\" in member\n ? sanitizeTrimmedSingleLineText(member.ownerUserId)\n : null,\n ownerName:\n \"ownerName\" in member\n ? sanitizeTrimmedSingleLineText(member.ownerName)\n : null,\n profileId: sanitizeTrimmedSingleLineText(member.profileId),\n profileKind: member.profileKind,\n profileName: sanitizeTrimmedSingleLineText(member.profileName),\n renderedLines: formatSpaceMemberCardRows(member, snapshot),\n searchKey: buildSpaceMembersPanelItemSearchKey(member, mentionLabels),\n mentionLabel: mentionLabels?.primaryMentionLabel ?? null,\n };\n}\n\nfunction buildSpaceMembersPanelItemSearchKey(\n member: SpaceMemberHumanSnapshot | SpaceMemberAgentSnapshot,\n mentionLabels: {\n exactMentionLabels: readonly string[];\n primaryMentionLabel: string;\n } | null\n): string {\n const searchValues = [\n member.profileName,\n member.profileId,\n \"ownerName\" in member ? member.ownerName : null,\n \"ownerUserId\" in member ? member.ownerUserId : null,\n ...(mentionLabels?.exactMentionLabels ?? []),\n ];\n\n return searchValues\n .map((value) => sanitizeTrimmedSingleLineText(value))\n .filter((value) => value.length > 0)\n .join(\" \")\n .toLowerCase();\n}\n\nfunction buildSpaceMemberHumanMetadataLine(\n member: SpaceMemberHumanSnapshot\n): string | null {\n const segments: string[] = [];\n segments.push(pc.dim(resolveHumanMemberRoleLabel(member)));\n if (member.liveNow) {\n segments.push(colorizeLiveNowLabel());\n }\n const seenLabel = resolveSpaceMemberSeenLabel(member);\n if (seenLabel) {\n segments.push(pc.dim(seenLabel));\n }\n return joinStyledMetadataSegments(segments);\n}\n\nfunction buildSpaceMemberAgentMetadataLine(\n member: SpaceMemberAgentSnapshot,\n snapshot: SpaceMembersSnapshot\n): string | null {\n const segments: string[] = [];\n const ownerDisplay =\n sanitizeTrimmedSingleLineText(member.ownerName) ||\n sanitizeTrimmedSingleLineText(member.ownerUserId);\n if (ownerDisplay) {\n segments.push(pc.dim(`owner: ${ownerDisplay}`));\n }\n const addedByDisplay = resolveAgentAddedByDisplay({\n agentSnapshot: member,\n spaceMembersSnapshot: snapshot,\n });\n if (addedByDisplay) {\n segments.push(pc.dim(`added by: ${addedByDisplay.label}`));\n }\n return segments.length > 0 ? pc.dim(segments.join(\" · \")) : null;\n}\n\nfunction buildSpaceMemberAgentStatusLine(\n member: SpaceMemberAgentSnapshot,\n snapshot: SpaceMembersSnapshot\n): string | null {\n const segments: string[] = [];\n const controllerDisplay = resolveControllerDisplayName(\n sanitizeTrimmedSingleLineText(member.agentControllerRef)\n );\n const mentionSegment = formatSpaceMemberMentionSegment(member, snapshot);\n if (mentionSegment) {\n segments.push(mentionSegment);\n }\n const manualSegment = formatSpaceMemberManualParticipationSegment(member);\n if (manualSegment) {\n segments.push(pc.dim(manualSegment));\n } else {\n const presence = buildSpaceMemberAgentPresencePresentation(member);\n if (presence.status === \"offline\" || presence.status === \"unavailable\") {\n segments.push(pc.dim(presence.shortLabel));\n }\n }\n if (controllerDisplay) {\n segments.push(\n `${pc.dim(\"via \")}${colorizeAgentLabel(\n controllerDisplay,\n {\n agentControllerRef: member.agentControllerRef,\n profileId: member.profileId,\n profileName: member.profileName,\n },\n {\n spaceMembersSnapshot: snapshot,\n }\n )}`\n );\n }\n if (member.liveNow) {\n segments.push(colorizeLiveNowLabel());\n }\n const seenLabel = resolveSpaceMemberSeenLabel(member);\n if (seenLabel) {\n segments.push(pc.dim(seenLabel));\n }\n return joinStyledMetadataSegments(segments);\n}\n\nfunction formatSpaceMemberManualParticipationSegment(\n member: SpaceMemberAgentSnapshot\n): string | null {\n const readiness =\n resolveSpaceMemberAgentOwnerWakeDiagnosticsView(member)\n .agentExecutionReadiness ?? null;\n if (!readiness) {\n return null;\n }\n if (hasManualParticipationOnlyReason(readiness.reasonCodes)) {\n return \"manual join/send only\";\n }\n return null;\n}\n\nfunction hasManualParticipationOnlyReason(\n reasonCodes: readonly string[]\n): boolean {\n return reasonCodes.some(\n (reasonCode) =>\n reasonCode === \"agent_profile_binding.missing\" ||\n reasonCode === \"profile.unbound\"\n );\n}\n\nfunction formatSpaceMemberMentionSegment(\n member: SpaceMemberAgentSnapshot,\n snapshot: SpaceMembersSnapshot\n): string | null {\n const mentionLabel = resolvePrimarySpaceMentionLabel({\n profileId: member.profileId,\n snapshot,\n });\n if (!mentionLabel) {\n return null;\n }\n const highlightedMentionLabel = colorizeAgentLabel(\n `@${mentionLabel}(wake)`,\n {\n agentControllerRef: member.agentControllerRef,\n profileId: member.profileId,\n profileName: member.profileName,\n },\n {\n spaceMembersSnapshot: snapshot,\n }\n );\n return `${pc.dim(\"mention: \")}${highlightedMentionLabel}`;\n}\n\nfunction joinStyledMetadataSegments(segments: string[]): string | null {\n return segments.length > 0 ? segments.join(pc.dim(\" · \")) : null;\n}\n\nfunction buildConnectIntroCardLines(input: {\n title: string;\n rows: ConnectIntroCardRow[];\n minContentWidth?: number;\n}): string[] {\n const rowTextList = buildConnectIntroRowLines(input.rows);\n const frame = buildUnifiedCardFrame({\n title: input.title,\n rowTextList,\n minContentWidth: input.minContentWidth ?? 56,\n });\n return [frame.top, frame.empty, ...frame.rows, frame.empty, frame.bottom];\n}\n\nfunction buildConnectIntroRowLines(\n rows: readonly ConnectIntroCardRow[]\n): string[] {\n return rows.map((row) => `${row.label} ${row.value}`);\n}\n\nfunction formatHumanSpeaker(\n profileIdentity: ProfileIdentityLike,\n input?: {\n includeKind?: boolean;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n }\n): string {\n const profileName = resolveHumanProfileLabel(profileIdentity);\n const profileKind = resolveHumanProfileKind(profileIdentity);\n const label =\n input?.includeKind && profileKind\n ? `${profileName} (${profileKind})`\n : profileName;\n const speaker = colorizeDisplayProfileLabel({\n label,\n profileIdentity,\n spaceMembersSnapshot: input?.spaceMembersSnapshot,\n });\n if (profileKind === \"agent\") {\n return `${AGENT_SPEAKER_AVATAR} ${speaker}`;\n }\n if (profileKind === \"human\") {\n return `${HUMAN_SPEAKER_AVATAR} ${speaker}`;\n }\n return speaker;\n}\n\nfunction formatHelloAck(\n event: HelloAck,\n options: TextEventFormatOptions\n): string {\n if (options.view === \"human\") {\n const acknowledgedName = colorizeDisplayProfileLabel({\n label: resolveHumanProfileLabel(event.profile),\n profileIdentity: event.profile,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n });\n return `* ${SYSTEM_BROADCAST_LABEL}: connected as ${acknowledgedName}.`;\n }\n const profileDescriptor = resolveAgentViewProfileDescriptor(event.profile);\n return `${pc.cyan(\"system\")}: hello.ack ${profileDescriptor}`;\n}\n\nfunction formatPresenceJoin(\n event: SignalEnvelope,\n options: TextEventFormatOptions\n): string {\n if (options.view === \"human\") {\n return formatHumanSystemPresenceLine({\n profileIdentity: event.profile,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n verb: \"joined the space.\",\n });\n }\n return `${pc.green(\"+\")} ${resolveAgentViewProfileDescriptor(event.profile)}`;\n}\n\nfunction formatPresenceQuit(\n event: SignalEnvelope,\n options: TextEventFormatOptions\n): string {\n if (options.view === \"human\") {\n return formatHumanSystemPresenceLine({\n profileIdentity: event.profile,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n verb: \"left the space.\",\n });\n }\n return `${pc.red(\"-\")} ${resolveAgentViewProfileDescriptor(event.profile)}`;\n}\n\nfunction formatSignalText(\n event: SignalEnvelope,\n options: TextEventFormatOptions\n): string | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n if (isTransientSignalTextHintClearEvent(event)) {\n return null;\n }\n const textEvent = event;\n const text =\n typeof textEvent.data.text === \"string\"\n ? sanitizeMultilineText(textEvent.data.text)\n : \"\";\n const isTransientHint = isTransientSignalTextHint(event);\n if (isTransientHint) {\n return null;\n }\n const renderedSystemNotice = resolveRenderedSystemNotice(\n event,\n options.spaceMembersSnapshot ?? null\n );\n if (renderedSystemNotice) {\n if (options.view === \"human\") {\n return `* ${SYSTEM_BROADCAST_LABEL}: ${appendRenderedSystemNoticeMentionHint(\n {\n text: highlightSystemNoticeProfileNames({\n text: renderedSystemNotice.text,\n highlights: renderedSystemNotice.highlights,\n }),\n wakeHint: renderedSystemNotice.wakeHint,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n }\n )}`;\n }\n return `${pc.cyan(\"system\")}: ${appendRenderedSystemNoticeMentionHint({\n text: renderedSystemNotice.text,\n wakeHint: renderedSystemNotice.wakeHint,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n })}`;\n }\n if (options.view === \"human\" && isMentionFailureHintSignalText(event, text)) {\n return null;\n }\n if (\n options.view === \"human\" &&\n isOpenMeldSystemProfileIdentity(event.profile)\n ) {\n return formatHumanSystemBroadcastLine(text);\n }\n if (options.view === \"human\") {\n const formattedMessage = buildHumanFormattedMessage({\n event,\n mentionHighlightIndex: options.mentionHighlightIndex,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n });\n if (!formattedMessage) {\n return null;\n }\n const ts = formatSignalTimestamp(event.ts);\n const speaker = formatHumanSpeaker(event.profile, {\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n });\n const [primaryBodyLine = \"\", ...bodyDetailLines] =\n formattedMessage.bodyLines;\n const detailLines = [\n ...bodyDetailLines,\n ...(options.replyLine ? [options.replyLine] : []),\n ...formattedMessage.metaLines,\n ];\n if (detailLines.length === 0) {\n return `- ${speaker} ${ts}: ${primaryBodyLine}`;\n }\n return [`- ${speaker} ${ts}: ${primaryBodyLine}`, ...detailLines].join(\n \"\\n\"\n );\n }\n const label = resolveAgentViewProfileDescriptor(event.profile);\n return `${pc.bold(label)}: ${text}`;\n}\n\nfunction formatSignalStatus(\n event: SignalEnvelope,\n options: TextEventFormatOptions\n): string | null {\n if (event.type !== \"signal.status\") {\n return null;\n }\n const text = sanitizeMultilineText(event.data.text).trim();\n if (!text) {\n return null;\n }\n if (options.view === \"human\") {\n if (isOpenMeldSystemProfileIdentity(event.profile)) {\n return formatHumanSystemBroadcastLine(text);\n }\n const formattedMessage = buildHumanFormattedMessage({\n event,\n mentionHighlightIndex: options.mentionHighlightIndex,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n });\n if (!formattedMessage) {\n return null;\n }\n const ts = formatSignalTimestamp(event.ts);\n const speaker = formatHumanSpeaker(event.profile, {\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n });\n const statusBadge = buildHumanStatusBadge(event.data.status);\n const [primaryBodyLine = \"\", ...bodyDetailLines] =\n formattedMessage.bodyLines;\n const leadingLine = statusBadge\n ? `- ${speaker} ${ts} ${statusBadge}: ${primaryBodyLine}`\n : `- ${speaker} ${ts}: ${primaryBodyLine}`;\n const detailLines = [\n ...bodyDetailLines,\n ...(options.replyLine ? [options.replyLine] : []),\n ...formattedMessage.metaLines,\n ];\n if (detailLines.length === 0) {\n return leadingLine;\n }\n return [leadingLine, ...detailLines].join(\"\\n\");\n }\n\n const label = resolveAgentViewProfileDescriptor(event.profile);\n return `${pc.bold(label)} ${pc.dim(`[status: ${event.data.status}]`)}: ${text}`;\n}\n\nfunction formatHumanSystemBroadcastLine(text: string): string | null {\n const normalizedText = text.trim();\n return normalizedText\n ? `* ${SYSTEM_BROADCAST_LABEL}: ${normalizedText}`\n : null;\n}\n\nfunction formatSignalSystemNotice(\n event: SignalEnvelope,\n options: TextEventFormatOptions\n): string | null {\n if (event.type !== \"signal.system_notice\") {\n return null;\n }\n const text = sanitizeMultilineText(event.data.text).trim();\n if (!text) {\n return null;\n }\n\n if (options.view === \"human\") {\n const detailLines = buildHumanSystemNoticeLines({\n event,\n replyLine: options.replyLine ?? null,\n spaceMembersSnapshot: options.spaceMembersSnapshot,\n });\n const [primaryLine = text, ...restLines] = detailLines;\n return [`* ${SYSTEM_BROADCAST_LABEL}: ${primaryLine}`, ...restLines].join(\n \"\\n\"\n );\n }\n\n const label = resolveAgentViewProfileDescriptor(event.profile);\n const detailLines = buildVisibleSystemNoticeReasonLines(event);\n return [`${pc.bold(label)}: ${text}`, ...detailLines].join(\"\\n\");\n}\n\nexport function buildHumanFormattedMessage(input: {\n event: SignalEnvelope;\n mentionHighlightIndex?: SpaceMentionHighlightIndex | null;\n messageReadProjection?: Parameters<typeof buildHumanMessageRelationLines>[0];\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): HumanFormattedMessage | null {\n const text = resolveHumanFormattedMessageBodyText(input);\n if (text === null) {\n return null;\n }\n const highlightedText = highlightHumanChatMentions({\n text,\n mentionHighlightIndex: input.mentionHighlightIndex,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n return {\n bodyLines: highlightedText.split(\"\\n\"),\n relationLines:\n input.event.type === \"signal.text\"\n ? buildHumanMessageRelationLines(input.messageReadProjection ?? null)\n : [],\n metaLines: [\n ...buildHumanViewStatusMetadataLines(input.event),\n ...buildHumanViewMessageMetadataLines({\n profileIdentity: input.event.profile,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }),\n ...buildHumanViewTraceMetadataLines(input.event),\n ],\n headerBadge: resolveHumanMessageHeaderBadge(input.event),\n };\n}\n\nfunction buildHumanViewTraceMetadataLines(event: SignalEnvelope): string[] {\n if (\n !(\n event.type === \"signal.text\" ||\n event.type === \"signal.status\" ||\n event.type === \"signal.system_notice\"\n )\n ) {\n return [];\n }\n\n const traceCommands = buildHumanViewTraceCommands(event);\n if (traceCommands.length === 0) {\n return [];\n }\n return traceCommands.map((command) => pc.dim(`trace: ${command}`));\n}\n\nfunction buildHumanViewTraceCommands(event: SignalEnvelope): string[] {\n const meta = readObjectField(event.data, \"meta\");\n const dispatchId =\n readStringField(event.data, \"dispatchId\") ??\n readStringField(meta, \"dispatchId\");\n if (dispatchId) {\n return [\n formatOpenMeldCliCommand(\n `openmeld service trace --space ${event.spaceId} --dispatch ${dispatchId} --view agent`\n ),\n ];\n }\n\n const clientMessageId = readStringField(meta, \"clientMessageId\");\n if (!clientMessageId) {\n return [];\n }\n const targetProfileIds = readStringArrayField(\n readObjectField(event.data, \"messageEnvelope\"),\n \"activationTargets\"\n );\n return targetProfileIds.map((targetProfileId) =>\n formatOpenMeldCliCommand(\n `openmeld service trace --space ${event.spaceId} --client-message ${clientMessageId} --target-profile ${targetProfileId} --view agent`\n )\n );\n}\n\nfunction readObjectField(\n value: unknown,\n field: string\n): Record<string, unknown> | null {\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const nested = (value as Record<string, unknown>)[field];\n return nested && typeof nested === \"object\"\n ? (nested as Record<string, unknown>)\n : null;\n}\n\nfunction readStringField(value: unknown, field: string): string | null {\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const raw = (value as Record<string, unknown>)[field];\n if (typeof raw !== \"string\") {\n return null;\n }\n const normalized = raw.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction readStringArrayField(value: unknown, field: string): string[] {\n if (!(value && typeof value === \"object\")) {\n return [];\n }\n const raw = (value as Record<string, unknown>)[field];\n if (!Array.isArray(raw)) {\n return [];\n }\n return raw.flatMap((item) => {\n if (typeof item !== \"string\") {\n return [];\n }\n const normalized = item.trim();\n return normalized.length > 0 ? [normalized] : [];\n });\n}\n\nfunction resolveHumanMessageHeaderBadge(event: SignalEnvelope): string | null {\n if (event.type !== \"signal.status\") {\n return null;\n }\n return buildTranscriptStatusBadge(event.data.status);\n}\n\nfunction resolveHumanFormattedMessageBodyText(input: {\n event: SignalEnvelope;\n mentionHighlightIndex?: SpaceMentionHighlightIndex | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string | null {\n if (isOpenMeldSystemProfileIdentity(input.event.profile)) {\n return null;\n }\n if (input.event.type === \"signal.text\") {\n const event = input.event;\n if (isTransientSignalTextHintClearEvent(input.event)) {\n return null;\n }\n const text =\n typeof event.data.text === \"string\"\n ? sanitizeMultilineText(event.data.text)\n : \"\";\n if (isTransientSignalTextHint(input.event)) {\n return null;\n }\n if (\n resolveRenderedSystemNotice(\n input.event,\n input.spaceMembersSnapshot ?? null\n )\n ) {\n return null;\n }\n if (isMentionFailureHintSignalText(input.event, text)) {\n return null;\n }\n return text;\n }\n if (input.event.type === \"signal.status\") {\n const text = sanitizeMultilineText(input.event.data.text).trim();\n return text || null;\n }\n return null;\n}\n\nfunction buildHumanSystemNoticeLines(input: {\n event: Extract<SignalEnvelope, { type: \"signal.system_notice\" }>;\n replyLine?: string | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string[] {\n const lines = [\n sanitizeMultilineText(input.event.data.text).trim(),\n ...buildVisibleSystemNoticeReasonLines(input.event),\n ];\n const replyLine =\n input.replyLine ?? buildHumanReplyReferenceLine(input.event.data.replyTo);\n if (replyLine) {\n lines.push(replyLine);\n }\n lines.push(...buildHumanSystemNoticeMetadataLines(input));\n return lines.filter((line) => line.trim().length > 0);\n}\n\nfunction buildHumanSystemNoticeMetadataLines(input: {\n event: Extract<SignalEnvelope, { type: \"signal.system_notice\" }>;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string[] {\n const actorProfileIdentity = resolveSystemNoticeActorProfileIdentity(input);\n if (actorProfileIdentity) {\n return buildHumanViewMessageMetadataLines({\n profileIdentity: actorProfileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n }\n return buildHumanViewMessageMetadataLines({\n profileIdentity: input.event.profile,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n}\n\nfunction buildVisibleSystemNoticeReasonLines(\n event: Extract<SignalEnvelope, { type: \"signal.system_notice\" }>\n): string[] {\n const reason = resolveVisibleStaySilentReason(event);\n if (!reason) {\n return [];\n }\n const [firstLine, ...restLines] = reason.split(\"\\n\");\n return [\n `agent reason: ${firstLine}`,\n ...restLines.map((line) => ` ${line}`),\n ];\n}\n\nfunction resolveVisibleStaySilentReason(\n event: Extract<SignalEnvelope, { type: \"signal.system_notice\" }>\n): string | null {\n if (event.data.noticeType !== \"stay_silent\") {\n return null;\n }\n\n const reason = sanitizeMultilineText(event.data.reason).trim();\n if (!reason) {\n return null;\n }\n\n const text = sanitizeMultilineText(event.data.text).trim();\n if (systemNoticeTextAlreadyIncludesReason({ reason, text })) {\n return null;\n }\n return reason;\n}\n\nfunction systemNoticeTextAlreadyIncludesReason(input: {\n text: string;\n reason: string;\n}): boolean {\n const normalizedText = input.text.toLowerCase();\n const normalizedReason = input.reason.toLowerCase();\n return (\n normalizedReason.length > 0 && normalizedText.includes(normalizedReason)\n );\n}\n\nfunction buildHumanViewStatusMetadataLines(event: SignalEnvelope): string[] {\n if (event.type !== \"signal.status\") {\n return [];\n }\n return [];\n}\n\nfunction buildTranscriptStatusBadge(status: string): string {\n return `status: ${status}`;\n}\n\nfunction buildHumanStatusBadge(status: string): string {\n return `[${buildTranscriptStatusBadge(status)}]`;\n}\n\nfunction buildHumanReplyReferenceLine(\n replyTo: SignalTextReplyTo | undefined\n): string | null {\n if (!replyTo) {\n return null;\n }\n const profileName = sanitizeTrimmedSingleLineText(replyTo.profileName);\n const previewText = buildHumanReplyCuePreview(\n String(replyTo.previewText ?? \"\"),\n HUMAN_REPLY_CUE_PREVIEW_MAX_VISIBLE_WIDTH\n );\n if (profileName && previewText) {\n return pc.dim(`reply to ${profileName} · ${previewText}`);\n }\n if (profileName) {\n return pc.dim(`reply to ${profileName}`);\n }\n return null;\n}\n\nfunction highlightHumanChatMentions(input: {\n text: string;\n mentionHighlightIndex?: SpaceMentionHighlightIndex | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string {\n return highlightSpaceMentions({\n text: input.text,\n index: input.mentionHighlightIndex,\n render: (mentionText, profileIdentity) =>\n colorizeDisplayProfileLabel({\n label: mentionText,\n profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }),\n });\n}\n\nfunction isMentionFailureHintSignalText(\n event: SignalEnvelope,\n text: string\n): boolean {\n const meta = resolveSignalTextMeta(event);\n const purpose = String(meta?.purpose ?? \"\").trim();\n if (purpose === MENTION_DISPATCH_HINT_META_PURPOSE) {\n return true;\n }\n if (purpose.length > 0) {\n return false;\n }\n\n // Legacy fallback: hide old-format hint text only when emitted by OpenMeld System.\n if (!isOpenMeldSystemProfileIdentity(event.profile)) {\n return false;\n }\n\n const normalized = text.trimStart();\n if (!normalized) {\n return false;\n }\n return (\n normalized.startsWith(MENTION_FAILURE_HINT_PREFIX) ||\n normalized.startsWith(MENTION_FAILURE_HINT_LEGACY_PREFIX)\n );\n}\n\nfunction isTransientSignalTextHint(event: SignalEnvelope): boolean {\n const rawMeta = resolveSignalTextMeta(event);\n if (!rawMeta) {\n return false;\n }\n if (rawMeta.transient !== true) {\n return false;\n }\n const purpose = String(rawMeta.purpose ?? \"\").trim();\n if (!purpose) {\n return true;\n }\n return (\n purpose === AGENT_REPLYING_PURPOSE ||\n purpose === CONVERSATION_CONTINUITY_WARNING_PURPOSE ||\n purpose === AGENT_REPLY_PREVIEW_PURPOSE ||\n purpose === DISPATCH_ACTIVITY_DISPATCHING_PURPOSE ||\n purpose === DISPATCH_ACTIVITY_RETRYING_PURPOSE ||\n purpose === DISPATCH_ACTIVITY_FAILED_PURPOSE\n );\n}\n\nfunction isTransientSignalTextHintClearEvent(event: SignalEnvelope): boolean {\n const rawMeta = resolveSignalTextMeta(event);\n if (rawMeta?.transient !== true) {\n return false;\n }\n const purpose = String(rawMeta.purpose ?? \"\").trim();\n return (\n purpose === AGENT_REPLYING_END_PURPOSE ||\n purpose === AGENT_REPLY_PREVIEW_END_PURPOSE\n );\n}\n\nfunction resolveSignalTextMeta(\n event: SignalEnvelope\n): Record<string, unknown> | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n if (\n !event.data ||\n typeof event.data !== \"object\" ||\n Array.isArray(event.data)\n ) {\n return null;\n }\n const meta = (event.data as { meta?: unknown }).meta;\n if (!meta || typeof meta !== \"object\" || Array.isArray(meta)) {\n return null;\n }\n return meta as Record<string, unknown>;\n}\n\nfunction readSignalMetaText(\n meta: Record<string, unknown>,\n key: string\n): string {\n const value = meta[key];\n return typeof value === \"string\" || typeof value === \"number\"\n ? sanitizeTrimmedSingleLineText(value)\n : \"\";\n}\n\nfunction resolveSpaceMembershipNoticeText(\n event: SignalEnvelope,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): {\n text: string;\n wakeHint: SystemNoticeMentionHint | null;\n highlights: SystemNoticeProfileHighlight[];\n} | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n const textEvent = event;\n const meta = resolveSignalTextMeta(event);\n if (!meta || meta.transient === true) {\n return null;\n }\n const purpose = String(meta.purpose ?? \"\").trim();\n let action: \"member_added\" | \"member_removed\" | null = null;\n if (purpose === SPACE_MEMBER_JOIN_NOTICE_PURPOSE) {\n action = \"member_added\";\n } else if (purpose === SPACE_MEMBER_REMOVE_NOTICE_PURPOSE) {\n action = \"member_removed\";\n }\n if (!action) {\n return null;\n }\n const rawText = textEvent.data.text;\n const text =\n typeof rawText === \"string\" ? sanitizeTrimmedSingleLineText(rawText) : \"\";\n if (!text) {\n return null;\n }\n const actorLabel = readSignalMetaText(\n meta,\n action === \"member_added\" ? \"addedByDisplayName\" : \"removedByDisplayName\"\n );\n const actorProfileId = readSignalMetaText(\n meta,\n action === \"member_added\" ? \"addedByProfileId\" : \"removedByProfileId\"\n );\n const targetProfileId = readSignalMetaText(meta, \"targetProfileId\");\n const targetProfileName = readSignalMetaText(meta, \"targetProfileName\");\n const targetProfileKind = readSignalMetaText(meta, \"targetProfileKind\");\n const actorProfileIdentity = resolveDisplayProfileIdentity({\n profileIdentity: {\n kind: event.profile?.kind,\n profileId:\n actorProfileId ||\n sanitizeTrimmedSingleLineText(event.profile?.profileId) ||\n undefined,\n profileName:\n actorLabel ||\n sanitizeTrimmedSingleLineText(event.profile?.profileName) ||\n undefined,\n ...(() => {\n const profileRecord =\n event.profile && typeof event.profile === \"object\"\n ? (event.profile as Record<string, unknown>)\n : null;\n const normalizedOwner = resolveNormalizedOwnerFields({\n ownerUserId:\n typeof profileRecord?.ownerUserId === \"string\"\n ? profileRecord.ownerUserId\n : undefined,\n ownerName: event.profile?.ownerName,\n owner:\n typeof profileRecord?.owner === \"string\"\n ? profileRecord.owner\n : undefined,\n });\n return {\n ...(normalizedOwner.ownerUserId\n ? { ownerUserId: normalizedOwner.ownerUserId }\n : {}),\n ...(normalizedOwner.ownerName\n ? { ownerName: normalizedOwner.ownerName }\n : {}),\n };\n })(),\n },\n spaceMembersSnapshot,\n });\n const targetProfileIdentity = resolveDisplayProfileIdentity({\n profileIdentity: {\n profileId: targetProfileId || undefined,\n profileName: targetProfileName,\n kind:\n targetProfileKind === \"agent\" || targetProfileKind === \"human\"\n ? targetProfileKind\n : undefined,\n },\n spaceMembersSnapshot,\n });\n return {\n text,\n wakeHint:\n action === \"member_added\"\n ? resolveSpaceMemberJoinNoticeWakeHint(meta, spaceMembersSnapshot)\n : null,\n highlights: [\n ...(actorLabel\n ? [\n {\n label: actorLabel,\n renderedLabel: colorizeDisplayProfileLabel({\n label: actorLabel,\n profileIdentity: actorProfileIdentity,\n spaceMembersSnapshot,\n }),\n } satisfies SystemNoticeProfileHighlight,\n ]\n : []),\n ...(targetProfileName\n ? [\n {\n label: targetProfileName,\n renderedLabel: colorizeDisplayProfileLabel({\n label: targetProfileName,\n profileIdentity: targetProfileIdentity,\n spaceMembersSnapshot,\n }),\n } satisfies SystemNoticeProfileHighlight,\n ]\n : []),\n ],\n };\n}\n\nfunction resolveRenderedSystemNotice(\n event: SignalEnvelope,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): {\n text: string;\n wakeHint: SystemNoticeMentionHint | null;\n highlights: SystemNoticeProfileHighlight[];\n} | null {\n return resolveSpaceMembershipNoticeText(event, spaceMembersSnapshot);\n}\n\nfunction resolveSpaceMemberJoinNoticeWakeHint(\n meta: Record<string, unknown>,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): SystemNoticeMentionHint | null {\n if (readSignalMetaText(meta, \"targetProfileKind\") !== \"agent\") {\n return null;\n }\n const profileId = readSignalMetaText(meta, \"targetProfileId\");\n const snapshotAgent =\n profileId && spaceMembersSnapshot\n ? (spaceMembersSnapshot.agents.find(\n (agent) => agent.profileId === profileId\n ) ?? null)\n : null;\n const persistedTargetMentionLabel = sanitizeTrimmedSingleLineText(\n readSignalMetaText(meta, \"targetMentionLabel\")\n );\n const legacyMentionLabel = sanitizeTrimmedSingleLineText(\n readSignalMetaText(meta, \"mentionLabel\")\n );\n const mentionLabel =\n persistedTargetMentionLabel ||\n legacyMentionLabel ||\n resolvePrimarySpaceMentionLabel({\n profileId,\n snapshot: spaceMembersSnapshot,\n }) ||\n sanitizeTrimmedSingleLineText(\n readSignalMetaText(meta, \"targetProfileName\")\n ) ||\n sanitizeTrimmedSingleLineText(profileId);\n if (!mentionLabel) {\n return null;\n }\n\n return {\n mentionLabel,\n ...(snapshotAgent?.agentControllerRef\n ? { agentControllerRef: snapshotAgent.agentControllerRef }\n : {}),\n ...(profileId ? { profileId } : {}),\n ...(snapshotAgent?.profileName\n ? { profileName: snapshotAgent.profileName }\n : {}),\n };\n}\n\nfunction appendRenderedSystemNoticeMentionHint(input: {\n text: string;\n wakeHint: SystemNoticeMentionHint | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string {\n if (!input.text) {\n return \"\";\n }\n if (!input.wakeHint) {\n return input.text;\n }\n return `${input.text} ${formatInlineMentionHint(\n input.wakeHint,\n input.spaceMembersSnapshot ?? null\n )}`;\n}\n\nfunction formatInlineMentionHint(\n input: SystemNoticeMentionHint,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): string {\n const highlightedMentionLabel = colorizeAgentLabel(\n `\\`@${input.mentionLabel}(wake)\\``,\n {\n agentControllerRef: input.agentControllerRef,\n profileId: input.profileId,\n profileName: input.profileName ?? input.mentionLabel,\n },\n {\n spaceMembersSnapshot,\n }\n );\n return `${pc.dim(\"· Mention as \")}${highlightedMentionLabel}`;\n}\n\nfunction formatHumanSystemPresenceLine(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n verb: string;\n}): string {\n const speaker = formatHumanSystemPresenceSpeaker({\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n return `* ${SYSTEM_BROADCAST_LABEL}: ${speaker}${pc.dim(` ${input.verb}`)}`;\n}\n\nfunction formatHumanSystemPresenceSpeaker(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string {\n const profileIdentity = resolveDisplayProfileIdentity({\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n const label = colorizeDisplayProfileLabel({\n label: resolveHumanProfileLabel(profileIdentity),\n profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n const kind = resolveHumanProfileKind(profileIdentity);\n if (kind === \"agent\") {\n return `${AGENT_SPEAKER_AVATAR} ${label}`;\n }\n if (kind === \"human\") {\n return `${HUMAN_SPEAKER_AVATAR} ${label}`;\n }\n return label;\n}\n\nfunction highlightSystemNoticeProfileNames(input: {\n text: string;\n highlights: SystemNoticeProfileHighlight[];\n}): string {\n const normalizedText = sanitizeTrimmedSingleLineText(input.text);\n if (!normalizedText) {\n return \"\";\n }\n const matches: Array<{\n start: number;\n end: number;\n renderedLabel: string;\n }> = [];\n\n for (const highlight of input.highlights) {\n const label = sanitizeTrimmedSingleLineText(highlight.label);\n if (!label) {\n continue;\n }\n let searchIndex = 0;\n while (searchIndex < normalizedText.length) {\n const start = normalizedText.indexOf(label, searchIndex);\n if (start < 0) {\n break;\n }\n matches.push({\n start,\n end: start + label.length,\n renderedLabel: highlight.renderedLabel,\n });\n searchIndex = start + label.length;\n }\n }\n\n if (matches.length === 0) {\n return normalizedText;\n }\n\n matches.sort((left, right) => {\n if (left.start !== right.start) {\n return left.start - right.start;\n }\n return right.end - left.end;\n });\n\n let cursor = 0;\n let output = \"\";\n for (const match of matches) {\n if (match.start < cursor) {\n continue;\n }\n output += normalizedText.slice(cursor, match.start);\n output += match.renderedLabel;\n cursor = match.end;\n }\n output += normalizedText.slice(cursor);\n return output;\n}\n\nfunction resolveAgentViewProfileDescriptor(\n profileIdentity: ProfileIdentityLike\n): string {\n const profileId =\n sanitizeTrimmedSingleLineText(profileIdentity?.profileId) || \"unknown\";\n const metadata = resolveAgentViewProfileMetadata(profileIdentity);\n return metadata.length > 0\n ? `${profileId} (${metadata.join(\", \")})`\n : profileId;\n}\n\nfunction resolveHumanProfileName(profileIdentity: ProfileIdentityLike): string {\n const name = sanitizeTrimmedSingleLineText(profileIdentity?.profileName);\n return name || \"unknown\";\n}\n\nfunction resolveHumanProfileLabel(\n profileIdentity: ProfileIdentityLike\n): string {\n return resolveHumanProfileName(profileIdentity);\n}\n\nfunction resolveHumanProfileKind(\n profileIdentity: ProfileIdentityLike\n): \"human\" | \"agent\" | \"\" {\n const normalizedKind = sanitizeTrimmedSingleLineText(profileIdentity?.kind);\n if (normalizedKind === \"human\" || normalizedKind === \"agent\") {\n return normalizedKind;\n }\n return \"\";\n}\n\nfunction resolveHumanReadableOwner(\n profileIdentity: ProfileIdentityLike\n): string {\n const normalizedOwner = resolveNormalizedOwnerFields({\n ownerUserId: profileIdentity?.ownerUserId,\n ownerName: profileIdentity?.ownerName,\n owner: profileIdentity?.owner,\n });\n const ownerName = sanitizeTrimmedSingleLineText(normalizedOwner.ownerName);\n if (ownerName) {\n return ownerName;\n }\n const ownerUserId = sanitizeTrimmedSingleLineText(\n normalizedOwner.ownerUserId\n );\n if (ownerUserId) {\n return ownerUserId;\n }\n return \"\";\n}\n\nfunction buildHumanViewMessageMetadataLines(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string[] {\n const profileKind = resolveHumanProfileKind(input.profileIdentity);\n if (profileKind === \"agent\") {\n return buildHumanAgentMessageMetadataLines(input);\n }\n if (profileKind === \"human\") {\n return buildHumanMemberMessageMetadataLines({\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n }\n return [];\n}\n\nfunction buildHumanAgentMessageMetadataLines(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string[] {\n const agentSnapshot = findAgentSpaceMemberSnapshot(input);\n const agentControllerRef =\n resolveAgentControllerRef(input.profileIdentity) ||\n sanitizeTrimmedSingleLineText(agentSnapshot?.agentControllerRef);\n const controllerDisplay = resolveControllerDisplayName(agentControllerRef);\n const metadataSegments = [\n controllerDisplay\n ? `${pc.dim(\"agent via \")}${colorizeAgentLabel(\n controllerDisplay,\n {\n agentControllerRef,\n profileId: agentSnapshot?.profileId,\n profileName: agentSnapshot?.profileName,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n )}`\n : pc.dim(\"agent\"),\n ];\n const ownerDisplay =\n resolveHumanReadableOwner(input.profileIdentity) ||\n sanitizeTrimmedSingleLineText(agentSnapshot?.ownerName) ||\n sanitizeTrimmedSingleLineText(agentSnapshot?.ownerUserId);\n if (ownerDisplay) {\n metadataSegments.push(pc.dim(`owner: ${ownerDisplay}`));\n }\n\n const addedByDisplay = resolveAgentAddedByDisplay({\n agentSnapshot,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n if (addedByDisplay) {\n metadataSegments.push(pc.dim(`added by: ${addedByDisplay.label}`));\n }\n\n const lines = [joinStyledMetadataSegments(metadataSegments) ?? \"\"];\n // Origin metadata is sensitive. If the event payload already omitted it, do\n // not rehydrate it from a members snapshot side channel.\n const originDisplay = agentControllerRef\n ? resolveAgentOriginDisplay({\n agentControllerRef,\n agentControllerConversationId: resolveAgentControllerConversationId(\n input.profileIdentity\n ),\n model: resolveProfileModelId(input.profileIdentity),\n workingDirectory: resolveWorkingDirectory(input.profileIdentity),\n })\n : resolveAgentControllerConversationId(input.profileIdentity);\n if (originDisplay) {\n lines.push(pc.dim(`origin: ${originDisplay}`));\n }\n return lines;\n}\n\nfunction resolveSystemNoticeActorProfileIdentity(input: {\n event: Extract<SignalEnvelope, { type: \"signal.system_notice\" }>;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): ProfileIdentityLike | null {\n const actorProfileId = sanitizeTrimmedSingleLineText(\n input.event.data.actorProfileId\n );\n if (!actorProfileId) {\n return null;\n }\n\n const actorSnapshot =\n input.spaceMembersSnapshot?.agents.find(\n (agent) =>\n agent.status === \"active\" &&\n sanitizeTrimmedSingleLineText(agent.profileId) === actorProfileId\n ) ?? null;\n if (!actorSnapshot) {\n return {\n kind: \"agent\",\n profileId: actorProfileId,\n };\n }\n\n return {\n kind: \"agent\",\n profileId: actorSnapshot.profileId,\n profileName: actorSnapshot.profileName,\n ownerUserId: actorSnapshot.ownerUserId,\n ownerName: actorSnapshot.ownerName,\n agentControllerRef: actorSnapshot.agentControllerRef,\n modelSelection: actorSnapshot.modelSelection,\n };\n}\n\nfunction buildHumanMemberMessageMetadataLines(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string[] {\n const humanSnapshot = findHumanSpaceMemberSnapshot({\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n\n const metadataSegments = [\"human\"];\n if (humanSnapshot) {\n metadataSegments.push(resolveHumanMemberRoleLabel(humanSnapshot));\n const seenLabel = resolveSpaceMemberSeenLabel(humanSnapshot);\n if (seenLabel) {\n metadataSegments.push(seenLabel);\n }\n }\n\n const lines = [pc.dim(metadataSegments.join(\" · \"))];\n const relatedAgentsLine = buildHumanRelatedAgentsLine({\n profileIdentity: input.profileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n if (relatedAgentsLine) {\n lines.push(relatedAgentsLine);\n }\n return lines;\n}\n\nfunction findHumanSpaceMemberSnapshot(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): SpaceMemberHumanSnapshot | null {\n const snapshot = input.spaceMembersSnapshot;\n if (!snapshot) {\n return null;\n }\n\n const profileId = sanitizeTrimmedSingleLineText(\n input.profileIdentity?.profileId\n );\n if (profileId) {\n const activeMatch = snapshot.humans.find(\n (member) =>\n member.status === \"active\" &&\n sanitizeTrimmedSingleLineText(member.profileId) === profileId\n );\n if (activeMatch) {\n return activeMatch;\n }\n }\n\n const profileName = resolveHumanProfileName(input.profileIdentity);\n if (!profileName) {\n return null;\n }\n\n return (\n snapshot.humans.find(\n (member) =>\n member.status === \"active\" &&\n areCaseInsensitiveMatches(member.profileName, profileName)\n ) ?? null\n );\n}\n\nfunction findAgentSpaceMemberSnapshot(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): SpaceMemberAgentSnapshot | null {\n const snapshot = input.spaceMembersSnapshot;\n if (!snapshot) {\n return null;\n }\n\n const profileId = sanitizeTrimmedSingleLineText(\n input.profileIdentity?.profileId\n );\n if (profileId) {\n const activeMatch = snapshot.agents.find(\n (member) =>\n member.status === \"active\" &&\n sanitizeTrimmedSingleLineText(member.profileId) === profileId\n );\n if (activeMatch) {\n return activeMatch;\n }\n }\n\n const profileName = resolveHumanProfileName(input.profileIdentity);\n if (!profileName) {\n return null;\n }\n\n return (\n snapshot.agents.find(\n (member) =>\n member.status === \"active\" &&\n areCaseInsensitiveMatches(member.profileName, profileName)\n ) ?? null\n );\n}\n\nfunction resolveHumanMemberRoleLabel(member: SpaceMemberHumanSnapshot): string {\n return member.memberSource === \"space_creator\" ? \"space creator\" : \"member\";\n}\n\nfunction resolveSpaceMemberSeenLabel(member: {\n lastSeenLabel?: string | null;\n liveNow?: boolean;\n}): string {\n const seenLabel = sanitizeTrimmedSingleLineText(member.lastSeenLabel);\n if (seenLabel) {\n const normalizedSeenLabel = seenLabel.toLowerCase();\n if (\n normalizedSeenLabel === \"left\" ||\n normalizedSeenLabel.startsWith(\"left \")\n ) {\n return \"\";\n }\n return normalizedSeenLabel;\n }\n return member.liveNow ? \"seen now\" : \"\";\n}\n\nfunction buildHumanRelatedAgentsLine(input: {\n profileIdentity: ProfileIdentityLike;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string | null {\n const snapshot = input.spaceMembersSnapshot;\n if (!snapshot) {\n return null;\n }\n\n const ownedAgents = snapshot.agents.filter(\n (agent) =>\n agent.status === \"active\" &&\n isAgentOwnedByHumanProfile(agent, input.profileIdentity)\n );\n if (ownedAgents.length > 0) {\n return `${pc.dim(\"owns: \")}${ownedAgents\n .map((agent) =>\n formatPlainRelatedAgentHandle(agent, input.spaceMembersSnapshot ?? null)\n )\n .join(pc.dim(\" · \"))}`;\n }\n\n const humanProfileId = sanitizeTrimmedSingleLineText(\n input.profileIdentity?.profileId\n );\n if (!humanProfileId) {\n return null;\n }\n\n const addedAgents = snapshot.agents.filter(\n (agent) =>\n agent.status === \"active\" &&\n sanitizeTrimmedSingleLineText(agent.addedByProfileId) === humanProfileId\n );\n if (addedAgents.length === 0) {\n return null;\n }\n\n return `${pc.dim(\"added: \")}${addedAgents\n .map((agent) =>\n formatRelatedAgentHandle(agent, input.spaceMembersSnapshot ?? null)\n )\n .join(pc.dim(\" · \"))}`;\n}\n\nfunction colorizeLiveNowLabel(): string {\n return renderPositiveAccentText(\"live now\");\n}\n\nfunction isAgentOwnedByHumanProfile(\n agent: SpaceMemberAgentSnapshot,\n profileIdentity: ProfileIdentityLike\n): boolean {\n const humanOwnerUserId = sanitizeTrimmedSingleLineText(\n profileIdentity?.ownerUserId\n );\n const agentOwnerUserId = sanitizeTrimmedSingleLineText(agent.ownerUserId);\n if (humanOwnerUserId && agentOwnerUserId) {\n return humanOwnerUserId === agentOwnerUserId;\n }\n\n const ownerName = sanitizeTrimmedSingleLineText(agent.ownerName);\n if (!ownerName) {\n return false;\n }\n\n const humanOwnerName = sanitizeTrimmedSingleLineText(\n profileIdentity?.ownerName\n );\n if (humanOwnerName) {\n return areCaseInsensitiveMatches(ownerName, humanOwnerName);\n }\n\n return areCaseInsensitiveMatches(\n ownerName,\n resolveHumanProfileName(profileIdentity)\n );\n}\n\nfunction resolveAgentAddedByDisplay(input: {\n agentSnapshot: SpaceMemberAgentSnapshot | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): {\n label: string;\n ownerUserId: string | null;\n ownerName: string | null;\n profileId: string | null;\n} | null {\n const addedByDisplay = sanitizeTrimmedSingleLineText(\n input.agentSnapshot?.addedByDisplayName\n );\n if (addedByDisplay) {\n return {\n label: addedByDisplay,\n ownerUserId: null,\n ownerName: null,\n profileId:\n sanitizeTrimmedSingleLineText(input.agentSnapshot?.addedByProfileId) ||\n null,\n };\n }\n\n const addedByProfileId = sanitizeTrimmedSingleLineText(\n input.agentSnapshot?.addedByProfileId\n );\n if (!(addedByProfileId && input.spaceMembersSnapshot)) {\n return null;\n }\n\n const humanSnapshot = input.spaceMembersSnapshot.humans.find(\n (member) =>\n member.status === \"active\" &&\n sanitizeTrimmedSingleLineText(member.profileId) === addedByProfileId\n );\n const label = sanitizeTrimmedSingleLineText(humanSnapshot?.profileName);\n if (!label) {\n return null;\n }\n return {\n label,\n ownerUserId: humanSnapshot?.ownerUserId ?? null,\n ownerName: humanSnapshot?.ownerName ?? null,\n profileId: humanSnapshot?.profileId ?? null,\n };\n}\n\nfunction areCaseInsensitiveMatches(\n left: string | number | null | undefined,\n right: string | number | null | undefined\n): boolean {\n const normalizedLeft = sanitizeTrimmedSingleLineText(left).toLowerCase();\n if (!normalizedLeft) {\n return false;\n }\n return normalizedLeft === sanitizeTrimmedSingleLineText(right).toLowerCase();\n}\n\nfunction formatRelatedAgentHandle(\n agent: SpaceMemberAgentSnapshot,\n spaceMembersSnapshot: SpaceMembersSnapshot | null\n): string {\n const token =\n resolvePrimarySpaceMentionLabel({\n profileId: agent.profileId,\n snapshot: spaceMembersSnapshot,\n }) ||\n sanitizeTrimmedSingleLineText(agent.profileName) ||\n sanitizeTrimmedSingleLineText(agent.profileId);\n if (!token) {\n return \"@unknown-agent\";\n }\n const handle = token.startsWith(\"@\") ? token : `@${token}`;\n return colorizeAgentLabel(\n handle,\n {\n agentControllerRef: agent.agentControllerRef,\n profileId: agent.profileId,\n profileName: agent.profileName,\n },\n {\n spaceMembersSnapshot,\n }\n );\n}\n\nfunction formatPlainRelatedAgentHandle(\n agent: SpaceMemberAgentSnapshot,\n spaceMembersSnapshot?: SpaceMembersSnapshot | null\n): string {\n const token =\n resolvePrimarySpaceMentionLabel({\n profileId: agent.profileId,\n snapshot: spaceMembersSnapshot ?? null,\n }) ||\n sanitizeTrimmedSingleLineText(agent.profileName) ||\n sanitizeTrimmedSingleLineText(agent.profileId);\n if (!token) {\n return \"@unknown-agent\";\n }\n return token.startsWith(\"@\") ? token : `@${token}`;\n}\n\nfunction resolveAgentViewProfileMetadata(\n profileIdentity: ProfileIdentityLike\n): string[] {\n if (!profileIdentity || typeof profileIdentity !== \"object\") {\n return [];\n }\n\n const record = profileIdentity as Record<string, unknown>;\n const metadata: string[] = [];\n const normalizedOwner = resolveNormalizedOwnerFields({\n ownerUserId: record.ownerUserId,\n ownerName: record.ownerName,\n owner: record.owner,\n });\n const preferredKeys = [\n \"kind\",\n \"profileName\",\n \"agentControllerRef\",\n \"agentControllerConversationId\",\n ] as const;\n const skippedKeys = new Set<string>([\"profileId\", \"owner\"]);\n\n for (const key of preferredKeys) {\n const formattedValue = formatAgentViewMetadataValue(record[key]);\n if (!formattedValue) {\n continue;\n }\n metadata.push(`${key}=${formattedValue}`);\n skippedKeys.add(key);\n }\n\n if (normalizedOwner.ownerName) {\n metadata.splice(2, 0, `ownerName=${normalizedOwner.ownerName}`);\n skippedKeys.add(\"ownerName\");\n skippedKeys.add(\"ownerUserId\");\n } else if (normalizedOwner.ownerUserId) {\n const recordOwnerUserId =\n typeof record.ownerUserId === \"string\" ? record.ownerUserId : undefined;\n const ownerLabel =\n typeof record.owner === \"string\" &&\n !sanitizeTrimmedSingleLineText(recordOwnerUserId)\n ? \"owner\"\n : \"ownerUserId\";\n metadata.splice(2, 0, `${ownerLabel}=${normalizedOwner.ownerUserId}`);\n skippedKeys.add(\"ownerUserId\");\n }\n\n const additionalKeys = Object.keys(record)\n .filter((key) => !skippedKeys.has(key))\n .sort((left, right) => left.localeCompare(right));\n for (const key of additionalKeys) {\n const formattedValue = formatAgentViewMetadataValue(record[key]);\n if (!formattedValue) {\n continue;\n }\n metadata.push(`${key}=${formattedValue}`);\n }\n\n return metadata;\n}\n\nfunction formatAgentViewMetadataValue(value: unknown): string {\n if (typeof value === \"string\") {\n const normalized = sanitizeTrimmedSingleLineText(value);\n return normalized.length > 0 ? normalized : \"\";\n }\n if (typeof value === \"number\" || typeof value === \"boolean\") {\n return String(value);\n }\n if (value === null || value === undefined) {\n return \"\";\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction resolveAgentControllerConversationId(\n profileIdentity: ProfileIdentityLike\n): string {\n if (resolveHumanProfileKind(profileIdentity) !== \"agent\") {\n return \"\";\n }\n const normalized =\n sanitizeTrimmedSingleLineText(\n profileIdentity?.agentControllerConversation\n ?.agentControllerConversationId\n ) ||\n sanitizeTrimmedSingleLineText(\n profileIdentity?.agentControllerConversationId\n );\n if (!normalized) {\n return \"\";\n }\n if (AGENT_CONTEXT_HIDDEN_TOKENS.has(normalized.toLowerCase())) {\n return \"\";\n }\n return normalized;\n}\n\nfunction resolveAgentControllerRef(\n profileIdentity: ProfileIdentityLike\n): string {\n if (resolveHumanProfileKind(profileIdentity) !== \"agent\") {\n return \"\";\n }\n return sanitizeTrimmedSingleLineText(profileIdentity?.agentControllerRef);\n}\n\nfunction resolveAgentOriginDisplay(input: {\n agentControllerRef: string;\n agentControllerConversationId?: string | null;\n model?: string | null;\n workingDirectory?: string | null;\n}): string {\n const model = sanitizeTrimmedSingleLineText(input.model);\n return sanitizeTrimmedSingleLineText(\n resolveRegistryOriginLaunchCommand({\n agentControllerRef: input.agentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n ...(model ? { model } : {}),\n workingDirectory: input.workingDirectory,\n }) ??\n input.agentControllerConversationId ??\n \"\"\n );\n}\n\nfunction resolveProfileModelId(profileIdentity: ProfileIdentityLike): string {\n if (resolveHumanProfileKind(profileIdentity) !== \"agent\") {\n return \"\";\n }\n return sanitizeTrimmedSingleLineText(\n profileIdentity?.modelSelection?.modelId\n );\n}\n\nfunction resolveWorkingDirectory(profileIdentity: ProfileIdentityLike): string {\n if (resolveHumanProfileKind(profileIdentity) !== \"agent\") {\n return \"\";\n }\n return (\n normalizeOptionalWorkingDirectory(profileIdentity?.workingDirectory) ?? \"\"\n );\n}\n\nfunction formatSignalTimestamp(ts: number): string {\n const date = new Date(ts);\n if (Number.isNaN(date.getTime())) {\n return pc.dim(\"00000000 00:00\");\n }\n const year = String(date.getFullYear());\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n const hour = String(date.getHours()).padStart(2, \"0\");\n const minute = String(date.getMinutes()).padStart(2, \"0\");\n return pc.dim(`${year}${month}${day} ${hour}:${minute}`);\n}\n","import { toStructuredApiClientFailure } from \"@openmeld/api-client\";\n\nexport function rethrowSpaceAddressingSnapshotLoadFailure(\n error: unknown\n): never {\n const failure = toStructuredApiClientFailure(error);\n if (failure.code || failure.status !== null) {\n throw error;\n }\n\n throw new Error(buildMembersSnapshotLoadFailureMessage(error), {\n cause: error,\n });\n}\n\nfunction buildMembersSnapshotLoadFailureMessage(error: unknown): string {\n const prefix = \"OpenMeld couldn't validate the selected recipients.\";\n const plainTextHint =\n \"Retry when Space members are available. To send without recipients, remove the recipient options.\";\n const failure = toStructuredApiClientFailure(error);\n const details: string[] = [];\n\n if (failure.message.trim().length > 0) {\n details.push(failure.message.trim());\n }\n if (failure.code) {\n details.push(`code: ${failure.code}`);\n }\n if (failure.requestId) {\n details.push(`request ID: ${failure.requestId}`);\n }\n if (failure.status !== null) {\n details.push(`status: ${String(failure.status)}`);\n }\n\n return details.length === 0\n ? `${prefix} ${plainTextHint}`\n : `${prefix} ${plainTextHint} Details: ${details.join(\"; \")}`;\n}\n","export const SPACE_QUIT_PRIMARY_TRIGGER = \"/quit\";\n\nexport const SPACE_QUIT_COMMAND_TOKENS = [\n SPACE_QUIT_PRIMARY_TRIGGER,\n \"/exit\",\n \"exit\",\n \":q\",\n] as const;\n\nconst SPACE_QUIT_COMMAND_SET = new Set(\n SPACE_QUIT_COMMAND_TOKENS.map((token) => token.toLowerCase())\n);\n\nexport function isSpaceQuitCommand(value: string): boolean {\n const normalized = value.trim().toLowerCase();\n return normalized.length > 0 && SPACE_QUIT_COMMAND_SET.has(normalized);\n}\n","import { isSpaceQuitCommand } from \"./quit-command\";\n\nexport type ComposeDraftState = {\n lines: string[];\n};\n\nexport type ComposeLineAction =\n | { kind: \"quit\" }\n | { kind: \"continue\"; nextDraft: ComposeDraftState }\n | { kind: \"send\"; nextDraft: ComposeDraftState; text: string };\n\nexport function consumeComposeInputLine(input: {\n line: string;\n draft: ComposeDraftState;\n}): ComposeLineAction {\n const rawLine = String(input.line ?? \"\");\n if (isSpaceQuitCommand(rawLine)) {\n return { kind: \"quit\" };\n }\n\n const continuation = parseContinuationLine(rawLine);\n if (continuation.continues) {\n return {\n kind: \"continue\",\n nextDraft: {\n lines: [...input.draft.lines, continuation.lineText],\n },\n };\n }\n\n const nextLines =\n input.draft.lines.length > 0\n ? [...input.draft.lines, continuation.lineText]\n : [continuation.lineText];\n\n return {\n kind: \"send\",\n nextDraft: emptyComposeDraft(),\n text: nextLines.join(\"\\n\"),\n };\n}\n\nexport function emptyComposeDraft(): ComposeDraftState {\n return { lines: [] };\n}\n\ntype ContinuationParseResult = {\n continues: boolean;\n lineText: string;\n};\n\nfunction parseContinuationLine(line: string): ContinuationParseResult {\n const trimmedEnd = line.replaceAll(/\\s+$/g, \"\");\n const trailingBackslashes = countTrailingBackslashes(trimmedEnd);\n if (trailingBackslashes !== 1) {\n return { continues: false, lineText: line };\n }\n return {\n continues: true,\n lineText: trimmedEnd.slice(0, -1),\n };\n}\n\nfunction countTrailingBackslashes(value: string): number {\n let count = 0;\n for (let index = value.length - 1; index >= 0; index -= 1) {\n if (value[index] !== \"\\\\\") {\n break;\n }\n count += 1;\n }\n return count;\n}\n","import type { SpacePanelKind } from \"../panel/space-panel-definition\";\nimport { SPACE_QUIT_PRIMARY_TRIGGER } from \"../quit-command\";\n\nexport type SpaceSlashCommandName =\n | \"help\"\n | \"space\"\n | \"members\"\n | \"logs\"\n | \"quit\";\n\nexport type SpaceControlCommandAction = \"quit\";\n\nexport type SpacePanelCommand = {\n name: SpacePanelKind;\n panelKind: SpacePanelKind;\n trigger: `/${SpacePanelKind}`;\n description: string;\n kind: \"panel\";\n};\n\nexport type SpaceControlCommand = {\n name: SpaceControlCommandAction;\n action: SpaceControlCommandAction;\n trigger: `/${SpaceControlCommandAction}`;\n description: string;\n kind: \"control\";\n};\n\nexport type SpaceSlashCommand = SpacePanelCommand | SpaceControlCommand;\n\nconst SPACE_SLASH_COMMANDS = [\n {\n name: \"help\",\n panelKind: \"help\",\n trigger: \"/help\",\n description: \"Show available Space composer commands\",\n kind: \"panel\",\n },\n {\n name: \"space\",\n panelKind: \"space\",\n trigger: \"/space\",\n description: \"Show current Space info\",\n kind: \"panel\",\n },\n {\n name: \"members\",\n panelKind: \"members\",\n trigger: \"/members\",\n description: \"Show current Space members\",\n kind: \"panel\",\n },\n {\n name: \"logs\",\n panelKind: \"logs\",\n trigger: \"/logs\",\n description: \"Show current Space logs\",\n kind: \"panel\",\n },\n {\n name: \"quit\",\n action: \"quit\",\n trigger: SPACE_QUIT_PRIMARY_TRIGGER,\n description: \"Leave the current Space session\",\n kind: \"control\",\n },\n] as const satisfies readonly SpaceSlashCommand[];\n\nconst SPACE_SLASH_COMMAND_BY_TRIGGER = new Map(\n SPACE_SLASH_COMMANDS.map((command) => [command.trigger, command] as const)\n);\n\nexport function listSpaceSlashCommands(): readonly SpaceSlashCommand[] {\n return SPACE_SLASH_COMMANDS;\n}\n\nexport function resolveSpaceSlashCommand(\n value: string\n): SpaceSlashCommand | null {\n const normalized = normalizeSpaceSlashCommandTrigger(value);\n if (!normalized) {\n return null;\n }\n return (\n SPACE_SLASH_COMMAND_BY_TRIGGER.get(\n normalized as SpaceSlashCommand[\"trigger\"]\n ) ?? null\n );\n}\n\nfunction normalizeSpaceSlashCommandTrigger(value: string): string | null {\n const normalized = value.trim().toLowerCase();\n if (!normalized.startsWith(\"/\")) {\n return null;\n }\n return normalized.length > 1 ? normalized : null;\n}\n","import { sanitizeText } from \"../../protocol/wire\";\nimport type { ComposeDraftState } from \"../compose-input\";\nimport { consumeComposeInputLine } from \"../compose-input\";\nimport { isSpaceQuitCommand } from \"../quit-command\";\nimport type { ComposerIntent } from \"./composer-contract\";\nimport { resolveSpaceSlashCommand } from \"./slash-command-registry\";\n\nexport class ComposerController {\n consumeLine(input: {\n line: string;\n draft: ComposeDraftState;\n }): ComposerIntent {\n const action = consumeComposeInputLine(input);\n\n switch (action.kind) {\n case \"quit\":\n return { kind: \"quit\" };\n\n case \"continue\":\n return {\n kind: \"buffer.updated\",\n nextBufferText: composeDraftToBufferText(action.nextDraft),\n };\n\n case \"send\":\n return this.consumeEditorSubmit({\n text: action.text,\n nextBufferText: composeDraftToBufferText(action.nextDraft),\n });\n\n default:\n return assertUnreachable(action);\n }\n }\n\n consumeLegacyLine(input: {\n line: string;\n bufferText: string;\n }): ComposerIntent {\n return this.consumeLine({\n line: input.line,\n draft: bufferTextToComposeDraft(input.bufferText),\n });\n }\n\n consumeEditorSubmit(input: {\n text: string;\n nextBufferText?: string;\n }): ComposerIntent {\n // PI-TUI editor submit treats \"\\\" as a literal character. Legacy\n // backslash-continuation only exists on line-based shells.\n const commandIntent = resolveLocalSlashCommandIntent({\n text: input.text,\n nextBufferText: input.nextBufferText ?? \"\",\n });\n if (commandIntent) {\n return commandIntent;\n }\n\n const sanitized = sanitizeText(input.text);\n if (!sanitized.ok) {\n return {\n kind: \"submit.rejected\",\n nextBufferText: input.nextBufferText ?? \"\",\n reason: sanitized.reason,\n };\n }\n return {\n kind: \"submit\",\n nextBufferText: input.nextBufferText ?? \"\",\n text: sanitized.value,\n };\n }\n}\n\nfunction assertUnreachable(value: never): never {\n throw new Error(`Unhandled compose action: ${JSON.stringify(value)}`);\n}\n\nfunction bufferTextToComposeDraft(bufferText: string): ComposeDraftState {\n if (!bufferText) {\n return { lines: [] };\n }\n return {\n lines: bufferText.split(\"\\n\"),\n };\n}\n\nfunction composeDraftToBufferText(draft: ComposeDraftState): string {\n return draft.lines.join(\"\\n\");\n}\n\nfunction resolveLocalSlashCommandIntent(input: {\n text: string;\n nextBufferText: string;\n}): ComposerIntent | null {\n if (isSpaceQuitCommand(input.text)) {\n return {\n kind: \"quit\",\n };\n }\n\n const command = resolveSpaceSlashCommand(input.text);\n if (command?.kind === \"panel\") {\n return {\n kind: \"command.panel.open\",\n panelKind: command.panelKind,\n nextBufferText: input.nextBufferText,\n };\n }\n\n switch (command?.action) {\n case \"quit\":\n return {\n kind: \"quit\",\n };\n default:\n return null;\n }\n}\n","import type {\n MessageMentionType,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport {\n createSpaceTargetCatalog,\n type PreparedSpaceComposerSubmission,\n prepareSpaceComposerSubmission,\n prepareSpaceFileOnlySubmission,\n type SpaceComposerReplyTarget,\n SpaceComposerSubmissionError,\n} from \"@openmeld/space\";\n\nexport type CliSpaceAddressingTarget = {\n primaryMentionLabel: string;\n profileId: string;\n relation: MessageMentionType;\n};\n\nexport type CliSpaceAddressingOptions = {\n wakeTargets?: readonly string[];\n referenceTargets?: readonly string[];\n mentionTargets?: readonly string[];\n};\n\nexport type PreparedCliSpaceComposerSubmission = {\n outboundMessageEnvelope?: NonNullable<\n PreparedSpaceComposerSubmission[\"messageEnvelope\"]\n >;\n outboundReplyTo?: SpaceComposerReplyTarget;\n outboundText: string;\n preparedSubmission: PreparedSpaceComposerSubmission;\n resolvedAddressingTargets: readonly CliSpaceAddressingTarget[];\n};\n\nexport async function prepareCliSpaceComposerSubmission(\n input: CliSpaceAddressingOptions & {\n missingSnapshotMessage: string;\n onMembersSnapshotLoaded?: (snapshot: SpaceMembersSnapshot) => void;\n onSnapshotLoadFailure?: (error: unknown) => void;\n replyTo?: SpaceComposerReplyTarget | null;\n loadMembersSnapshot?: () => Promise<SpaceMembersSnapshot | null>;\n authoredMentionsInTextOrder?: PreparedSpaceComposerSubmission[\"authoredMentionsInTextOrder\"];\n text: string;\n }\n): Promise<PreparedCliSpaceComposerSubmission> {\n const requested = (\n [\n [\"wake\", input.wakeTargets ?? []],\n [\"reference\", input.referenceTargets ?? []],\n [\"mention\", input.mentionTargets ?? []],\n ] as const\n ).flatMap(([relation, ids]) =>\n ids.map((profileId) => ({ profileId, relation }))\n );\n let snapshot: SpaceMembersSnapshot | null = null;\n if (\n requested.length > 0 ||\n (input.authoredMentionsInTextOrder?.length ?? 0) > 0\n ) {\n try {\n snapshot = (await input.loadMembersSnapshot?.()) ?? null;\n if (snapshot) {\n input.onMembersSnapshotLoaded?.(snapshot);\n }\n } catch (error) {\n input.onSnapshotLoadFailure?.(error);\n throw error;\n }\n if (!snapshot) {\n throw new SpaceComposerSubmissionError({\n code: \"addressing.members_snapshot_missing\",\n message: input.missingSnapshotMessage,\n });\n }\n }\n const { mentions, prefix, resolvedAddressingTargets } =\n resolveRequestedRecipients(snapshot, requested);\n const preparedSubmission =\n prefix.length === 0 && input.text.length === 0\n ? prepareSpaceFileOnlySubmission({ replyTo: input.replyTo })\n : prepareSpaceComposerSubmission({\n authoredMentionsInTextOrder: [\n ...mentions,\n ...(input.authoredMentionsInTextOrder ?? []).map((mention) => ({\n ...mention,\n start:\n mention.start === undefined\n ? undefined\n : mention.start + prefix.length,\n })),\n ],\n missingSnapshotMessage: input.missingSnapshotMessage,\n replyTo: input.replyTo,\n snapshot,\n text: prefix + input.text,\n });\n return {\n ...(preparedSubmission.messageEnvelope\n ? { outboundMessageEnvelope: preparedSubmission.messageEnvelope }\n : {}),\n ...(preparedSubmission.replyTo\n ? { outboundReplyTo: preparedSubmission.replyTo }\n : {}),\n outboundText: preparedSubmission.text,\n preparedSubmission,\n resolvedAddressingTargets,\n };\n}\n\nfunction resolveRequestedRecipients(\n snapshot: SpaceMembersSnapshot | null,\n requested: readonly { profileId: string; relation: MessageMentionType }[]\n) {\n const catalog = snapshot ? createSpaceTargetCatalog(snapshot) : null;\n const seen = new Map<string, MessageMentionType>();\n const resolvedAddressingTargets: CliSpaceAddressingTarget[] = [];\n const mentions: PreparedSpaceComposerSubmission[\"authoredMentionsInTextOrder\"][number][] =\n [];\n let prefix = \"\";\n for (const request of requested) {\n const profileId = request.profileId.trim();\n const target = catalog?.byProfileId.get(profileId);\n if (!target) {\n throw new SpaceComposerSubmissionError({\n code: \"addressing.target_not_in_current_space\",\n message: `No current Space member has Profile ID \"${profileId}\". Run openmeld space members and use the full Profile ID.`,\n });\n }\n const previous = seen.get(profileId);\n if (previous && previous !== request.relation) {\n throw new SpaceComposerSubmissionError({\n code: \"addressing.target_reused_across_relations\",\n message: `Choose one relation for Profile ID \"${profileId}\".`,\n });\n }\n if (previous) {\n continue;\n }\n seen.set(profileId, request.relation);\n const label = target.profileName || target.primaryMentionLabel;\n const text = `@${label}`;\n mentions.push({\n profileId,\n relation: request.relation,\n start: prefix.length,\n text,\n });\n prefix += `${text} `;\n resolvedAddressingTargets.push({\n primaryMentionLabel: label,\n profileId,\n relation: request.relation,\n });\n }\n return { mentions, prefix, resolvedAddressingTargets };\n}\n","import type { HelloAck, SignalEnvelope } from \"@openmeld/protocol\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../config/openmeld-request-context\";\nimport { parseIncoming } from \"../protocol/wire\";\nimport { createCliSpaceApi, type SpaceSignalsReadQuery } from \"./cli-space-api\";\nimport type { SpaceSessionProfileIdentity } from \"./session-profile\";\n\nconst CATCHUP_PAGE_LIMIT = 200;\nconst RECENT_HISTORY_DEFAULT_LIMIT = 100;\nconst RECENT_HISTORY_MAX_LIMIT = 500;\nconst CATCHUP_SEEN_SIGNAL_IDS_MAX = 50_000;\nconst LAST_SEEN_FUTURE_SKEW_TOLERANCE_MS = 30_000;\n\ntype ReplaySignalsInput = {\n seenSignalIds: Set<string>;\n onEvent: (event: SignalEnvelope | HelloAck) => void;\n};\n\ntype ShouldIgnoreIncomingSignalReason =\n | \"seen_replay_duplicate\"\n | \"older_than_live_floor\"\n | null;\n\ntype ShouldIgnoreIncomingSignalResult = {\n ignore: boolean;\n reason: ShouldIgnoreIncomingSignalReason;\n};\n\nexport function rememberSeenSignalId(\n seenSignalIds: Set<string>,\n signalId: string\n): void {\n if (seenSignalIds.has(signalId)) {\n return;\n }\n\n seenSignalIds.add(signalId);\n while (seenSignalIds.size > CATCHUP_SEEN_SIGNAL_IDS_MAX) {\n const oldestSignalId = seenSignalIds.values().next().value;\n if (typeof oldestSignalId !== \"string\") {\n return;\n }\n seenSignalIds.delete(oldestSignalId);\n }\n}\n\nfunction emitReplaySignals(\n input: ReplaySignalsInput,\n signals: readonly unknown[]\n): void {\n for (const item of signals) {\n const event = parseIncoming(item);\n if (!event || isServerErrorFrameMessage(event)) {\n continue;\n }\n if (!isSignalEnvelope(event)) {\n input.onEvent(event);\n continue;\n }\n if (input.seenSignalIds.has(event.id)) {\n continue;\n }\n input.onEvent(event);\n rememberSeenSignalId(input.seenSignalIds, event.id);\n }\n}\n\nfunction isSignalEnvelope(\n event: SignalEnvelope | HelloAck\n): event is SignalEnvelope {\n return \"id\" in event && typeof event.id === \"string\";\n}\n\nfunction isServerErrorFrameMessage(\n event: SignalEnvelope | HelloAck | { error: string }\n): event is { error: string; requestId?: string; clientMessageId?: string } {\n return typeof (event as { error?: unknown }).error === \"string\";\n}\n\nasync function fetchReplaySignals(input: {\n profileIdentity: SpaceSessionProfileIdentity;\n baseUrl: string;\n space: string;\n password?: string;\n query: SpaceSignalsReadQuery;\n}): Promise<readonly unknown[]> {\n const response = await createCliSpaceApi(input.baseUrl).listSignals({\n spaceId: input.space,\n requestContext: buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: input.profileIdentity,\n }),\n query: input.query,\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n });\n return response.signals;\n}\n\nexport async function replayMissedSignals(input: {\n profileIdentity: SpaceSessionProfileIdentity;\n baseUrl: string;\n space: string;\n password?: string;\n afterSignalId: string;\n seenSignalIds: Set<string>;\n onEvent: (event: SignalEnvelope | HelloAck) => void;\n}): Promise<void> {\n const afterSignalId = input.afterSignalId.trim();\n if (!afterSignalId) {\n throw new Error(\"afterSignalId is required for reconnect catch-up\");\n }\n\n // Known pagination gap: Core's GET /v1/spaces/:id/signals afterSignalId\n // branch always returns nextCursor: null. This helper requests\n // CATCHUP_PAGE_LIMIT (200) signals, while the shared query schema caps any\n // caller at 500, so a larger gap is silently truncated. This helper has no\n // production caller while the CLI Space connect flow has no automatic\n // reconnect loop. Before wiring it into one, drain full pages by advancing\n // afterSignalId, following Web's\n // drainSpaceUpdatesFromAnchor/readSpaceUpdates pattern, or add true\n // pagination to Core's anchor branch.\n const signals = await fetchReplaySignals({\n profileIdentity: input.profileIdentity,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n query: {\n afterSignalId,\n limit: CATCHUP_PAGE_LIMIT,\n },\n });\n emitReplaySignals(input, signals);\n}\n\nexport async function replayRecentSignals(input: {\n profileIdentity: SpaceSessionProfileIdentity;\n baseUrl: string;\n space: string;\n password?: string;\n limit: number;\n seenSignalIds: Set<string>;\n onEvent: (event: SignalEnvelope | HelloAck) => void;\n}): Promise<void> {\n if (input.limit <= 0) {\n return;\n }\n\n const signals = await fetchReplaySignals({\n profileIdentity: input.profileIdentity,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n query: {\n limit: Math.max(1, Math.min(input.limit, RECENT_HISTORY_MAX_LIMIT)),\n recent: true,\n },\n });\n emitReplaySignals(input, signals);\n}\n\nexport function normalizeRecentHistoryLimit(value: number | undefined): number {\n if (value === undefined) {\n return RECENT_HISTORY_DEFAULT_LIMIT;\n }\n if (!Number.isInteger(value) || value < 0) {\n throw new Error(\"history limit must be a non-negative integer\");\n }\n return Math.min(value, RECENT_HISTORY_MAX_LIMIT);\n}\n\nexport function resolveInitialLiveFloorTs(input: {\n lastSeenTs: number | null;\n nowMs: number;\n}): number {\n if (\n typeof input.lastSeenTs !== \"number\" ||\n !Number.isFinite(input.lastSeenTs)\n ) {\n return 0;\n }\n\n const normalizedLastSeenTs = Math.max(0, Math.trunc(input.lastSeenTs));\n const maxAllowedFloorTs = input.nowMs + LAST_SEEN_FUTURE_SKEW_TOLERANCE_MS;\n\n if (normalizedLastSeenTs > maxAllowedFloorTs) {\n return input.nowMs;\n }\n\n return normalizedLastSeenTs;\n}\n\nexport function shouldIgnoreIncomingSignal(input: {\n event: SignalEnvelope | HelloAck;\n liveFloorTs: number;\n seenSignalIds: Set<string>;\n selfProfileId?: string;\n}): ShouldIgnoreIncomingSignalResult {\n const { event, liveFloorTs, seenSignalIds } = input;\n if (!isSignalEnvelope(event)) {\n return { ignore: false, reason: null };\n }\n\n if (seenSignalIds.has(event.id)) {\n return { ignore: true, reason: \"seen_replay_duplicate\" };\n }\n\n const selfProfileId = String(input.selfProfileId ?? \"\").trim();\n const senderProfileId = String(event.profile?.profileId ?? \"\").trim();\n if (selfProfileId && senderProfileId === selfProfileId) {\n return { ignore: false, reason: null };\n }\n\n if (event.ts < liveFloorTs) {\n return { ignore: true, reason: \"older_than_live_floor\" };\n }\n\n return { ignore: false, reason: null };\n}\n\nexport function processIgnoredOlderThanLiveFloorSignal(input: {\n event: SignalEnvelope | HelloAck;\n seenSignalIds: Set<string>;\n onDispatchActivityEvent: (event: SignalEnvelope) => void;\n}): boolean {\n if (!isSignalEnvelope(input.event)) {\n return false;\n }\n rememberSeenSignalId(input.seenSignalIds, input.event.id);\n input.onDispatchActivityEvent(input.event);\n return true;\n}\n","import type { SignalEnvelope, SignalTextEnvelope } from \"@openmeld/protocol\";\nimport {\n AGENT_REPLY_PREVIEW_END_PURPOSE,\n AGENT_REPLY_PREVIEW_PURPOSE,\n AGENT_REPLYING_END_PURPOSE,\n AGENT_REPLYING_PURPOSE,\n CONVERSATION_CONTINUITY_WARNING_PURPOSE,\n DISPATCH_ACTIVITY_DISPATCHING_PURPOSE,\n DISPATCH_ACTIVITY_FAILED_PURPOSE,\n DISPATCH_ACTIVITY_RETRYING_PURPOSE,\n} from \"@openmeld/schemas\";\nimport stringWidth from \"string-width\";\nimport { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\nimport type { ComposerDispatchRowState } from \"./view/space-session-view-state\";\n\nconst REPLYING_HINT_FALLBACK_CLEAR_MS = 180_000;\nconst REPLYING_STATUS_SYSTEM_LABEL = \"📣 system\";\nconst REPLYING_STATUS_AGENT_LABEL = \"🤖\";\nconst PREVIEW_MAX_VISIBLE_CHARS = 240;\nconst PREVIEW_MIN_VISIBLE_CHARS = 24;\nconst PREVIEW_ELLIPSIS = \"...\";\nconst REPLYING_TARGET_LABEL_REGEX = /^(@[^\\s]+)\\s+is replying\\.\\.\\.$/u;\n\ntype DispatchActivityRowState = ComposerDispatchRowState;\n\ntype DispatchActivityEventIdentity = {\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetLabel: string;\n targetProfileId: string;\n};\n\ntype DispatchActivityEvent =\n | {\n kind: \"dispatching\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n targetLabel: string;\n text: string;\n }\n | {\n kind: \"retrying\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n targetLabel: string;\n text: string;\n }\n | {\n kind: \"replying_start\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n targetLabel: string;\n }\n | {\n kind: \"preview\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n targetLabel: string;\n previewText: string;\n }\n | {\n kind: \"preview_end\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n }\n | {\n kind: \"warning\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n targetLabel: string;\n text: string;\n preserveActivityMode: boolean;\n }\n | {\n kind: \"end\";\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n };\n\nexport function clearUnconfirmedPendingOutboundRows(\n rowsById: Map<string, DispatchActivityRowState>\n): boolean {\n let changed = false;\n for (const [rowId, row] of rowsById) {\n if (\n row.stage === \"sending\" &&\n row.dispatchId === null &&\n row.sourceEventId === null\n ) {\n rowsById.delete(rowId);\n changed = true;\n }\n }\n return changed;\n}\n\nexport function pruneExpiredDispatchRows(\n rowsById: Map<string, DispatchActivityRowState>,\n nowMs: number\n): boolean {\n let changed = false;\n for (const [rowId, row] of rowsById) {\n if (typeof row.expiresAtMs !== \"number\" || row.expiresAtMs > nowMs) {\n continue;\n }\n rowsById.delete(rowId);\n changed = true;\n }\n return changed;\n}\n\nexport function resolveNearestDispatchRowExpiryMs(\n rowsById: Map<string, DispatchActivityRowState>\n): number | null {\n let nearestExpiryMs: number | null = null;\n for (const row of rowsById.values()) {\n if (typeof row.expiresAtMs !== \"number\") {\n continue;\n }\n if (nearestExpiryMs === null || row.expiresAtMs < nearestExpiryMs) {\n nearestExpiryMs = row.expiresAtMs;\n }\n }\n return nearestExpiryMs;\n}\n\nexport function resolveDispatchRowStatusTexts(input: {\n rowsById: Map<string, DispatchActivityRowState>;\n terminalColumns: number | null;\n}): string[] {\n if (input.rowsById.size === 0) {\n return [];\n }\n return [...input.rowsById.values()]\n .sort((left, right) => right.updatedAtMs - left.updatedAtMs)\n .map((state) =>\n formatReplyingStatusText({\n state,\n terminalColumns: input.terminalColumns,\n })\n );\n}\n\nexport function toComposerDispatchRows(\n rowsById: Map<string, DispatchActivityRowState>\n): ComposerDispatchRowState[] {\n return [...rowsById.values()];\n}\n\nfunction toDispatchActivityEventIdentity(\n event: DispatchActivityEvent\n): DispatchActivityEventIdentity {\n return {\n dispatchId: event.dispatchId,\n sourceClientMessageId: event.sourceClientMessageId,\n sourceEventId: event.sourceEventId,\n targetLabel:\n \"targetLabel\" in event ? event.targetLabel : event.targetProfileId,\n targetProfileId: event.targetProfileId,\n };\n}\n\nfunction buildDispatchActivityRowId(input: {\n identity: DispatchActivityEventIdentity;\n}): string {\n return `dispatch:${input.identity.dispatchId}`;\n}\n\nfunction findMatchingDispatchActivityRowEntry(input: {\n identity: DispatchActivityEventIdentity;\n rowsById: Map<string, DispatchActivityRowState>;\n}): [string, DispatchActivityRowState] | null {\n for (const entry of input.rowsById) {\n if (entry[1].dispatchId === input.identity.dispatchId) {\n return entry;\n }\n }\n if (input.identity.sourceEventId && input.identity.targetProfileId) {\n for (const entry of input.rowsById) {\n if (\n entry[1].sourceEventId === input.identity.sourceEventId &&\n entry[1].targetProfileId === input.identity.targetProfileId\n ) {\n return entry;\n }\n }\n }\n if (input.identity.sourceClientMessageId && input.identity.targetProfileId) {\n for (const entry of input.rowsById) {\n if (\n entry[1].sourceClientMessageId ===\n input.identity.sourceClientMessageId &&\n entry[1].targetProfileId === input.identity.targetProfileId\n ) {\n return entry;\n }\n }\n }\n return null;\n}\n\nfunction mergeDispatchActivityIdentity(input: {\n event: DispatchActivityEvent;\n existing: DispatchActivityRowState | null;\n nowMs: number;\n rowId: string;\n}): DispatchActivityRowState {\n return {\n rowId: input.rowId,\n dispatchId: input.event.dispatchId,\n sourceEventId:\n input.event.sourceEventId ?? input.existing?.sourceEventId ?? null,\n sourceClientMessageId:\n input.event.sourceClientMessageId ??\n input.existing?.sourceClientMessageId ??\n null,\n sourceTextSnapshot: input.existing?.sourceTextSnapshot ?? null,\n targetProfileId:\n input.event.targetProfileId ?? input.existing?.targetProfileId ?? null,\n targetLabel:\n (\"targetLabel\" in input.event ? input.event.targetLabel : null) ??\n input.existing?.targetLabel ??\n input.event.targetProfileId,\n targetMentionLabel:\n (\"targetLabel\" in input.event ? input.event.targetLabel : null) ??\n input.existing?.targetMentionLabel ??\n null,\n stage: input.existing?.stage ?? \"dispatching\",\n createdAtMs: input.existing?.createdAtMs ?? input.nowMs,\n updatedAtMs: input.nowMs,\n expiresAtMs: input.existing?.expiresAtMs ?? null,\n latestPreviewText: input.existing?.latestPreviewText ?? \"\",\n latestPreviewUpdatedAtMs: input.existing?.latestPreviewUpdatedAtMs ?? null,\n statusText: input.existing?.statusText ?? \"\",\n warningText: input.existing?.warningText ?? \"\",\n };\n}\n\nexport function clearDispatchActivitiesForSignal(input: {\n rowsById: Map<string, DispatchActivityRowState>;\n event: SignalEnvelope;\n}): boolean {\n if (input.rowsById.size === 0) {\n return false;\n }\n const terminalSignal = resolveTerminalDispatchActivitySignal(input.event);\n if (!terminalSignal) {\n return false;\n }\n const { dispatchId, senderProfileId } = terminalSignal;\n if (dispatchId) {\n for (const [rowId, row] of input.rowsById) {\n if (row.dispatchId !== dispatchId) {\n continue;\n }\n input.rowsById.delete(rowId);\n return true;\n }\n }\n\n let latestRowId: string | null = null;\n let latestUpdatedAtMs = Number.NEGATIVE_INFINITY;\n for (const [rowId, row] of input.rowsById) {\n if (row.targetProfileId !== senderProfileId || row.stage === \"sending\") {\n continue;\n }\n if (row.updatedAtMs > latestUpdatedAtMs) {\n latestUpdatedAtMs = row.updatedAtMs;\n latestRowId = rowId;\n }\n }\n if (!latestRowId) {\n return false;\n }\n input.rowsById.delete(latestRowId);\n return true;\n}\n\nfunction resolveTerminalDispatchActivitySignal(event: SignalEnvelope): {\n dispatchId: string | null;\n senderProfileId: string | null;\n} | null {\n if (event.type === \"signal.text\") {\n if (!resolveNonTransientSignalText(event)) {\n return null;\n }\n return {\n dispatchId: resolveReplyingSignalDispatchId(event),\n senderProfileId: normalizeOptionalMetaText(event.profile?.profileId),\n };\n }\n\n if (event.type === \"signal.status\") {\n return {\n dispatchId: normalizeOptionalMetaText(event.data.dispatchId),\n senderProfileId: normalizeOptionalMetaText(event.data.actorProfileId),\n };\n }\n\n if (event.type === \"signal.system_notice\") {\n return {\n dispatchId: normalizeOptionalMetaText(event.data.dispatchId),\n senderProfileId: normalizeOptionalMetaText(event.data.actorProfileId),\n };\n }\n\n return null;\n}\n\nfunction upsertDispatchActivityStatusState(input: {\n rowsById: Map<string, DispatchActivityRowState>;\n event: DispatchActivityEvent;\n nowMs: number;\n}): boolean {\n const existingEntry = findMatchingDispatchActivityRowEntry({\n identity: toDispatchActivityEventIdentity(input.event),\n rowsById: input.rowsById,\n });\n const existing = existingEntry?.[1] ?? null;\n const rowId =\n existingEntry?.[0] ??\n buildDispatchActivityRowId({\n identity: toDispatchActivityEventIdentity(input.event),\n });\n\n switch (input.event.kind) {\n case \"end\":\n return existingEntry ? input.rowsById.delete(existingEntry[0]) : false;\n case \"preview_end\":\n return applyPreviewEndDispatchActivityState({\n existing,\n map: input.rowsById,\n rowId,\n nowMs: input.nowMs,\n });\n case \"warning\":\n return applyWarningDispatchActivityState({\n existing,\n event: input.event,\n map: input.rowsById,\n rowId,\n nowMs: input.nowMs,\n });\n case \"dispatching\":\n case \"retrying\":\n return applyStatusDispatchActivityState({\n existing,\n event: input.event,\n map: input.rowsById,\n rowId,\n nowMs: input.nowMs,\n });\n case \"replying_start\":\n return applyReplyingStartDispatchActivityState({\n existing,\n event: input.event,\n map: input.rowsById,\n rowId,\n nowMs: input.nowMs,\n });\n case \"preview\":\n return applyPreviewDispatchActivityState({\n existing,\n event: input.event,\n map: input.rowsById,\n rowId,\n nowMs: input.nowMs,\n });\n default:\n return false;\n }\n}\n\nfunction applyPreviewEndDispatchActivityState(input: {\n existing: DispatchActivityRowState | null;\n map: Map<string, DispatchActivityRowState>;\n rowId: string;\n nowMs: number;\n}): boolean {\n if (!input.existing) {\n return false;\n }\n input.map.set(input.rowId, {\n ...input.existing,\n updatedAtMs: input.nowMs,\n latestPreviewText: \"\",\n latestPreviewUpdatedAtMs: null,\n expiresAtMs: input.nowMs + REPLYING_HINT_FALLBACK_CLEAR_MS,\n warningText: \"\",\n });\n return true;\n}\n\nfunction applyWarningDispatchActivityState(input: {\n existing: DispatchActivityRowState | null;\n event: Extract<DispatchActivityEvent, { kind: \"warning\" }>;\n map: Map<string, DispatchActivityRowState>;\n rowId: string;\n nowMs: number;\n}): boolean {\n if (\n input.event.preserveActivityMode &&\n input.existing?.stage === \"replying\"\n ) {\n input.map.set(input.rowId, {\n ...input.existing,\n updatedAtMs: input.nowMs,\n expiresAtMs: input.nowMs + REPLYING_HINT_FALLBACK_CLEAR_MS,\n statusText: input.event.text,\n warningText: input.event.text,\n });\n return true;\n }\n\n input.map.set(input.rowId, {\n ...mergeDispatchActivityIdentity({\n event: input.event,\n existing: input.existing,\n nowMs: input.nowMs,\n rowId: input.rowId,\n }),\n stage: \"warning\",\n updatedAtMs: input.nowMs,\n latestPreviewText: \"\",\n latestPreviewUpdatedAtMs: null,\n expiresAtMs: input.nowMs + REPLYING_HINT_FALLBACK_CLEAR_MS,\n statusText: input.event.text,\n warningText: input.event.text,\n });\n return true;\n}\n\nfunction applyStatusDispatchActivityState(input: {\n existing: DispatchActivityRowState | null;\n event: Extract<DispatchActivityEvent, { kind: \"dispatching\" | \"retrying\" }>;\n map: Map<string, DispatchActivityRowState>;\n rowId: string;\n nowMs: number;\n}): boolean {\n input.map.set(input.rowId, {\n ...mergeDispatchActivityIdentity({\n event: input.event,\n existing: input.existing,\n nowMs: input.nowMs,\n rowId: input.rowId,\n }),\n stage: input.event.kind === \"dispatching\" ? \"dispatching\" : \"retrying\",\n updatedAtMs: input.nowMs,\n latestPreviewText: \"\",\n latestPreviewUpdatedAtMs: null,\n expiresAtMs: input.nowMs + REPLYING_HINT_FALLBACK_CLEAR_MS,\n statusText: input.event.text,\n warningText: \"\",\n });\n return true;\n}\n\nfunction applyReplyingStartDispatchActivityState(input: {\n existing: DispatchActivityRowState | null;\n event: Extract<DispatchActivityEvent, { kind: \"replying_start\" }>;\n map: Map<string, DispatchActivityRowState>;\n rowId: string;\n nowMs: number;\n}): boolean {\n input.map.set(input.rowId, {\n ...mergeDispatchActivityIdentity({\n event: input.event,\n existing: input.existing,\n nowMs: input.nowMs,\n rowId: input.rowId,\n }),\n stage: \"replying\",\n updatedAtMs: input.nowMs,\n latestPreviewText: input.existing?.latestPreviewText ?? \"\",\n latestPreviewUpdatedAtMs: input.existing?.latestPreviewUpdatedAtMs ?? null,\n expiresAtMs: input.nowMs + REPLYING_HINT_FALLBACK_CLEAR_MS,\n statusText: input.existing?.statusText ?? \"\",\n warningText: \"\",\n });\n return true;\n}\n\nfunction applyPreviewDispatchActivityState(input: {\n existing: DispatchActivityRowState | null;\n event: Extract<DispatchActivityEvent, { kind: \"preview\" }>;\n map: Map<string, DispatchActivityRowState>;\n rowId: string;\n nowMs: number;\n}): boolean {\n input.map.set(input.rowId, {\n ...mergeDispatchActivityIdentity({\n event: input.event,\n existing: input.existing,\n nowMs: input.nowMs,\n rowId: input.rowId,\n }),\n stage: \"replying\",\n updatedAtMs: input.nowMs,\n latestPreviewText: input.event.previewText,\n latestPreviewUpdatedAtMs: input.nowMs,\n expiresAtMs: input.nowMs + REPLYING_HINT_FALLBACK_CLEAR_MS,\n statusText: input.existing?.statusText ?? \"\",\n warningText: \"\",\n });\n return true;\n}\n\nexport function applyDispatchActivityEventToStatusMap(input: {\n rowsById: Map<string, DispatchActivityRowState>;\n event: SignalEnvelope;\n nowMs: number;\n}): boolean {\n const hintEvent = resolveDispatchActivityEvent(input.event);\n if (!hintEvent) {\n return false;\n }\n return upsertDispatchActivityStatusState({\n rowsById: input.rowsById,\n event: hintEvent,\n nowMs: input.nowMs,\n });\n}\n\nfunction formatReplyingStatusText(input: {\n state: DispatchActivityRowState;\n terminalColumns: number | null;\n}): string {\n if (input.state.stage === \"sending\") {\n return input.state.statusText || \"sending...\";\n }\n if (input.state.stage === \"warning\") {\n return input.state.warningText || input.state.statusText;\n }\n if (input.state.stage === \"dispatching\" || input.state.stage === \"retrying\") {\n return (\n input.state.statusText ||\n `${input.state.targetLabel} ${\n input.state.stage === \"dispatching\"\n ? \"is dispatching...\"\n : \"is retrying...\"\n }`\n );\n }\n if (input.state.warningText) {\n return input.state.warningText;\n }\n const previewText = input.state.latestPreviewText.trim();\n if (!previewText) {\n return `${input.state.targetLabel} is replying...`;\n }\n const previewPrefix = `${input.state.targetLabel} preview: `;\n const maxPreviewWidth = resolvePreviewContentWidth({\n previewPrefix,\n terminalColumns: input.terminalColumns,\n });\n const previewHead = truncatePreviewHead(previewText, maxPreviewWidth);\n return `${previewPrefix}${previewHead}`;\n}\n\nfunction isDispatchActivityPurpose(purpose: string): boolean {\n return (\n purpose === AGENT_REPLYING_PURPOSE ||\n purpose === AGENT_REPLYING_END_PURPOSE ||\n purpose === CONVERSATION_CONTINUITY_WARNING_PURPOSE ||\n purpose === AGENT_REPLY_PREVIEW_PURPOSE ||\n purpose === AGENT_REPLY_PREVIEW_END_PURPOSE ||\n purpose === DISPATCH_ACTIVITY_DISPATCHING_PURPOSE ||\n purpose === DISPATCH_ACTIVITY_RETRYING_PURPOSE ||\n purpose === DISPATCH_ACTIVITY_FAILED_PURPOSE\n );\n}\n\nfunction resolveDispatchActivityBase(event: SignalEnvelope): {\n event: SignalTextEnvelope;\n meta: Record<string, unknown>;\n purpose: string;\n dispatchId: string;\n sourceClientMessageId: string | null;\n sourceEventId: string | null;\n targetProfileId: string;\n} | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n\n const meta = resolveSignalTextMetaFromEnvelope(event);\n if (meta?.transient !== true) {\n return null;\n }\n\n const purpose = String(meta.purpose ?? \"\").trim();\n if (!isDispatchActivityPurpose(purpose)) {\n return null;\n }\n\n const dispatchId = String(meta.dispatchId ?? \"\").trim();\n if (!dispatchId) {\n return null;\n }\n\n const targetProfileId = String(meta.targetProfileId ?? \"\").trim();\n if (!targetProfileId) {\n return null;\n }\n\n return {\n event,\n meta,\n purpose,\n dispatchId,\n sourceClientMessageId: normalizeOptionalMetaText(\n meta.sourceClientMessageId\n ),\n sourceEventId: normalizeOptionalMetaText(meta.sourceEventId),\n targetProfileId,\n };\n}\n\nfunction resolveDispatchActivityTargetLabel(input: {\n event: SignalTextEnvelope;\n purpose: string;\n meta: Record<string, unknown>;\n targetProfileId: string;\n}): string {\n return (\n normalizeOptionalMetaText(input.meta.targetLabel) ??\n (input.purpose === AGENT_REPLYING_PURPOSE\n ? extractReplyingTargetLabelFromText(String(input.event.data?.text ?? \"\"))\n : null) ??\n normalizeOptionalMetaText(input.meta.targetProfileName) ??\n normalizeOptionalMetaText(input.event.profile?.profileName) ??\n input.targetProfileId\n );\n}\n\nfunction resolveContinuityWarningText(\n event: SignalTextEnvelope\n): string | null {\n const text = sanitizeTerminalDisplayText(\n event.data.text,\n \"single-line\"\n ).trim();\n return text || null;\n}\n\nexport function resolveDispatchActivityEvent(\n event: SignalEnvelope\n): DispatchActivityEvent | null {\n const base = resolveDispatchActivityBase(event);\n if (!base) {\n return null;\n }\n\n const {\n event: textEvent,\n dispatchId,\n meta,\n purpose,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n } = base;\n if (purpose === AGENT_REPLYING_END_PURPOSE) {\n return {\n kind: \"end\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n };\n }\n\n const targetLabel = resolveDispatchActivityTargetLabel({\n event: textEvent,\n purpose,\n meta,\n targetProfileId,\n });\n\n if (purpose === DISPATCH_ACTIVITY_DISPATCHING_PURPOSE) {\n const text = resolveContinuityWarningText(textEvent);\n if (!text) {\n return null;\n }\n return {\n kind: \"dispatching\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n targetLabel,\n text,\n };\n }\n\n if (purpose === DISPATCH_ACTIVITY_RETRYING_PURPOSE) {\n const text = resolveContinuityWarningText(textEvent);\n if (!text) {\n return null;\n }\n return {\n kind: \"retrying\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n targetLabel,\n text,\n };\n }\n\n if (purpose === AGENT_REPLY_PREVIEW_PURPOSE) {\n const previewText = normalizePreviewDisplayText(textEvent.data.text);\n if (!previewText) {\n return null;\n }\n return {\n kind: \"preview\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n targetLabel,\n previewText,\n };\n }\n\n if (purpose === AGENT_REPLY_PREVIEW_END_PURPOSE) {\n return {\n kind: \"preview_end\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n };\n }\n\n if (purpose === CONVERSATION_CONTINUITY_WARNING_PURPOSE) {\n const text = resolveContinuityWarningText(textEvent);\n if (!text) {\n return null;\n }\n return {\n kind: \"warning\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n targetLabel,\n text,\n preserveActivityMode: true,\n };\n }\n\n if (purpose === DISPATCH_ACTIVITY_FAILED_PURPOSE) {\n const text = resolveContinuityWarningText(textEvent);\n if (!text) {\n return null;\n }\n return {\n kind: \"warning\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n targetLabel,\n text,\n preserveActivityMode: false,\n };\n }\n\n return {\n kind: \"replying_start\",\n dispatchId,\n sourceClientMessageId,\n sourceEventId,\n targetProfileId,\n targetLabel,\n };\n}\n\nexport function resolveNonTransientSignalText(\n event: SignalEnvelope\n): string | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n const meta = resolveSignalTextMetaFromEnvelope(event);\n if (meta?.transient === true) {\n return null;\n }\n const text = sanitizeTerminalDisplayText(\n event.data.text,\n \"multi-line\"\n ).trim();\n return text || null;\n}\n\nexport function resolveSignalTextMetaFromEnvelope(\n event: SignalEnvelope\n): Record<string, unknown> | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n if (\n !event.data ||\n typeof event.data !== \"object\" ||\n Array.isArray(event.data)\n ) {\n return null;\n }\n const meta = (event.data as { meta?: unknown }).meta;\n if (!meta || typeof meta !== \"object\" || Array.isArray(meta)) {\n return null;\n }\n return meta as Record<string, unknown>;\n}\n\nexport function resolveSignalClientMessageId(\n event: SignalEnvelope\n): string | null {\n return normalizeOptionalMetaText(\n resolveSignalTextMetaFromEnvelope(event)?.clientMessageId\n );\n}\n\nfunction normalizePreviewDisplayText(value: string): string {\n return sanitizeTerminalDisplayText(value, \"single-line\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nexport function resolveReplyingStatusColumns(): number | null {\n if (!(process.stdout.isTTY && typeof process.stdout.columns === \"number\")) {\n return null;\n }\n const normalizedColumns = Math.trunc(process.stdout.columns);\n return normalizedColumns > 0 ? normalizedColumns : null;\n}\n\nfunction resolvePreviewContentWidth(input: {\n previewPrefix: string;\n terminalColumns: number | null;\n}): number {\n const prefixWidth = stringWidth(\n `* ${REPLYING_STATUS_SYSTEM_LABEL} · ${REPLYING_STATUS_AGENT_LABEL} ${input.previewPrefix}`\n );\n if (input.terminalColumns === null) {\n return PREVIEW_MAX_VISIBLE_CHARS;\n }\n const availableWidth = input.terminalColumns - prefixWidth;\n return Math.max(\n PREVIEW_MIN_VISIBLE_CHARS,\n Math.min(PREVIEW_MAX_VISIBLE_CHARS, availableWidth)\n );\n}\n\nfunction truncatePreviewHead(value: string, maxWidth: number): string {\n if (stringWidth(value) <= maxWidth) {\n return value;\n }\n const truncatedWidth = Math.max(0, maxWidth - stringWidth(PREVIEW_ELLIPSIS));\n let head = \"\";\n for (const char of value) {\n if (stringWidth(head) + stringWidth(char) > truncatedWidth) {\n break;\n }\n head += char;\n }\n return `${head}${PREVIEW_ELLIPSIS}`;\n}\n\nexport function countRenderedTerminalRows(text: string): number {\n const columns = resolveReplyingStatusColumns();\n const lines = text.split(\"\\n\");\n if (columns === null) {\n return Math.max(1, lines.length);\n }\n let totalRows = 0;\n for (const line of lines) {\n totalRows += Math.max(1, Math.ceil(stringWidth(line) / columns));\n }\n return Math.max(1, totalRows);\n}\n\nfunction normalizeOptionalMetaText(value: unknown): string | null {\n if (typeof value !== \"string\") {\n return null;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction extractReplyingTargetLabelFromText(text: string): string | null {\n const normalized = sanitizeTerminalDisplayText(text, \"single-line\").trim();\n const match = REPLYING_TARGET_LABEL_REGEX.exec(normalized);\n return match?.[1] ?? null;\n}\n\nfunction resolveReplyingSignalDispatchId(event: SignalEnvelope): string {\n const meta = resolveSignalTextMetaFromEnvelope(event);\n return String(meta?.dispatchId ?? \"\").trim();\n}\n","import type { Profile } from \"@openmeld/protocol\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport type { TranscriptSessionProfileIdentity } from \"./transcript/transcript-item-builder\";\nimport type { SpaceSessionContext } from \"./view/space-session-view-state\";\n\nexport type SpaceSessionProfileIdentity = TranscriptSessionProfileIdentity & {\n openMeldProfileId: string;\n profileHandle?: string;\n profileName: string;\n agentControllerRef?: string;\n agentControllerConversationId?: string;\n};\n\nexport function buildSpaceSessionProfileIdentity(input: {\n openMeldProfile: OpenMeldProfile;\n agentControllerConversationId?: string | null;\n}): SpaceSessionProfileIdentity {\n const { openMeldProfile } = input;\n const agentControllerConversationId = String(\n input.agentControllerConversationId ?? \"\"\n ).trim();\n\n return {\n kind: openMeldProfile.profileKind === \"agent\" ? \"agent\" : \"human\",\n openMeldProfileId: openMeldProfile.openMeldProfileId,\n profileHandle: openMeldProfile.profileHandle,\n profileName: openMeldProfile.profileName,\n ...(openMeldProfile.ownerUserId\n ? { ownerUserId: String(openMeldProfile.ownerUserId).trim() }\n : {}),\n ...(openMeldProfile.ownerName\n ? { ownerName: String(openMeldProfile.ownerName).trim() }\n : {}),\n ...(agentControllerConversationId ? { agentControllerConversationId } : {}),\n };\n}\n\nexport function buildSpaceSessionProfileContext(\n openMeldProfile: OpenMeldProfile\n): SpaceSessionContext[\"profile\"] {\n return {\n profileId: openMeldProfile.openMeldProfileId,\n profileName: openMeldProfile.profileName,\n kind: openMeldProfile.profileKind === \"agent\" ? \"agent\" : \"human\",\n ownerUserId: openMeldProfile.ownerUserId ?? null,\n ownerName: openMeldProfile.ownerName ?? null,\n };\n}\n\nexport function buildSpaceSessionProfileContextFromIdentity(input: {\n kind: \"human\" | \"agent\";\n ownerName?: string | null;\n ownerUserId?: string | null;\n openMeldProfileId: string;\n profileName: string;\n}): SpaceSessionContext[\"profile\"] {\n return {\n profileId: input.openMeldProfileId,\n profileName: input.profileName,\n kind: input.kind,\n ownerUserId: input.ownerUserId ?? null,\n ownerName: input.ownerName ?? null,\n };\n}\n\nexport function toProtocolProfile(\n identity: SpaceSessionProfileIdentity\n): Profile {\n return {\n kind: identity.kind,\n profileId: identity.openMeldProfileId,\n ...(identity.profileHandle\n ? { profileHandle: identity.profileHandle }\n : {}),\n profileName: identity.profileName,\n ...(identity.ownerUserId ? { owner: identity.ownerUserId } : {}),\n ...(identity.ownerName ? { ownerName: identity.ownerName } : {}),\n ...(identity.agentControllerRef\n ? { agentControllerRef: identity.agentControllerRef }\n : {}),\n ...(identity.agentControllerConversationId\n ? {\n agentControllerConversationId: identity.agentControllerConversationId,\n }\n : {}),\n };\n}\n\nexport function buildActiveSpaceSessionContext(input: {\n profile: SpaceSessionContext[\"profile\"];\n baseUrl: string;\n connectionMode: SpaceSessionContext[\"connectionMode\"];\n session: SpaceSessionContext[\"session\"];\n}): SpaceSessionContext {\n return {\n surface: \"active-session\",\n connectionMode: input.connectionMode,\n gatewayUrl: input.baseUrl,\n profile: input.profile,\n session: input.session,\n };\n}\n\nexport function rememberSessionOwnerDisplayName(\n ownerDisplayNameByUserId: Map<string, string>,\n openMeldProfile: OpenMeldProfile\n): void {\n rememberOwnerDisplayName(\n ownerDisplayNameByUserId,\n openMeldProfile.ownerUserId,\n openMeldProfile.ownerName\n );\n if (openMeldProfile.profileKind === \"human\") {\n rememberOwnerDisplayName(\n ownerDisplayNameByUserId,\n openMeldProfile.ownerUserId,\n openMeldProfile.profileName,\n { overwrite: false }\n );\n }\n}\n\nexport function rememberOwnerDisplayName(\n ownerDisplayNameByUserId: Map<string, string>,\n ownerUserIdRaw: string | null | undefined,\n ownerDisplayRaw: string | null | undefined,\n options?: {\n overwrite?: boolean;\n }\n): void {\n const ownerUserId = String(ownerUserIdRaw ?? \"\").trim();\n const ownerDisplay = String(ownerDisplayRaw ?? \"\").trim();\n if (!(ownerUserId && ownerDisplay)) {\n return;\n }\n if (\n options?.overwrite === false &&\n ownerDisplayNameByUserId.has(ownerUserId)\n ) {\n return;\n }\n ownerDisplayNameByUserId.set(ownerUserId, ownerDisplay);\n}\n\nexport function rememberMembersSnapshotOwnerDisplayNames(\n ownerDisplayNameByUserId: Map<string, string>,\n membersSnapshot: SpaceMembersSnapshot | null | undefined\n): void {\n for (const human of membersSnapshot?.humans ?? []) {\n rememberOwnerDisplayName(\n ownerDisplayNameByUserId,\n human.ownerUserId,\n human.ownerName ?? human.profileName\n );\n }\n for (const agent of membersSnapshot?.agents ?? []) {\n rememberOwnerDisplayName(\n ownerDisplayNameByUserId,\n agent.ownerUserId,\n agent.ownerName\n );\n }\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport {\n SPACE_MEMBER_JOIN_NOTICE_PURPOSE,\n SPACE_MEMBER_REMOVE_NOTICE_PURPOSE,\n} from \"@openmeld/schemas\";\nimport { sanitizeTerminalDisplayText } from \"../../ui/terminal-safe-text\";\nimport type { SpaceMembershipNotice } from \"../state/space-screen-state\";\n\nconst LEGACY_MENTION_LABEL_PREFIX_PATTERN = /^@+/u;\n\nexport function resolveMembershipNoticeFromSignalEnvelope(\n event: SignalEnvelope\n): SpaceMembershipNotice | null {\n if (event.type !== \"signal.text\") {\n return null;\n }\n\n const meta = resolveSignalTextMeta(event);\n if (!meta || meta.transient === true) {\n return null;\n }\n\n const action = resolveMembershipNoticeAction(\n readSignalMetaText(meta, \"purpose\")\n );\n if (!action) {\n return null;\n }\n\n const targetProfileKind = resolveMembershipTargetKind(\n readSignalMetaText(meta, \"targetProfileKind\")\n );\n if (!targetProfileKind) {\n return null;\n }\n\n const targetProfileId = readSignalMetaText(meta, \"targetProfileId\") || null;\n const targetProfileLabel =\n readSignalMetaText(meta, \"targetProfileName\") || targetProfileId || \"\";\n if (!targetProfileLabel) {\n return null;\n }\n const mentionLabel =\n readSignalMetaText(meta, \"targetMentionLabel\") ||\n // Legacy read-only seam: old stored notices may only have targetProfileHandle.\n // This fallback must not be treated as active mention truth for new producers.\n normalizeLegacyMentionLabel(\n readSignalMetaText(meta, \"targetProfileHandle\")\n ) ||\n null;\n\n const actorProfileId =\n readSignalMetaText(\n meta,\n action === \"member_added\" ? \"addedByProfileId\" : \"removedByProfileId\"\n ) ||\n sanitizeSingleLineText(event.profile?.profileId) ||\n \"\";\n const actorLabel =\n readSignalMetaText(\n meta,\n action === \"member_added\" ? \"addedByDisplayName\" : \"removedByDisplayName\"\n ) ||\n sanitizeSingleLineText(event.profile?.profileName) ||\n \"\";\n if (!actorLabel) {\n return null;\n }\n\n return {\n action,\n actorProfileId: actorProfileId || null,\n actorKind: resolveMembershipActorKind(event.profile?.kind),\n actorLabel,\n targetProfileId,\n targetProfileKind,\n targetProfileLabel,\n mentionLabel,\n ts: event.ts,\n };\n}\n\nfunction resolveMembershipNoticeAction(\n purpose: string\n): SpaceMembershipNotice[\"action\"] | null {\n if (purpose === SPACE_MEMBER_JOIN_NOTICE_PURPOSE) {\n return \"member_added\";\n }\n if (purpose === SPACE_MEMBER_REMOVE_NOTICE_PURPOSE) {\n return \"member_removed\";\n }\n return null;\n}\n\nfunction resolveSignalTextMeta(\n event: SignalEnvelope\n): Record<string, unknown> | null {\n if (\n !event.data ||\n typeof event.data !== \"object\" ||\n Array.isArray(event.data)\n ) {\n return null;\n }\n const meta = (event.data as { meta?: unknown }).meta;\n if (!meta || typeof meta !== \"object\" || Array.isArray(meta)) {\n return null;\n }\n return meta as Record<string, unknown>;\n}\n\nfunction readSignalMetaText(\n meta: Record<string, unknown>,\n key: string\n): string {\n const value = meta[key];\n return typeof value === \"string\" || typeof value === \"number\"\n ? sanitizeSingleLineText(value)\n : \"\";\n}\n\nfunction sanitizeSingleLineText(value: unknown): string {\n return sanitizeTerminalDisplayText(String(value ?? \"\"), \"single-line\").trim();\n}\n\nfunction normalizeLegacyMentionLabel(value: string): string {\n return value.replace(LEGACY_MENTION_LABEL_PREFIX_PATTERN, \"\").trim();\n}\n\nfunction resolveMembershipTargetKind(\n kind: string\n): SpaceMembershipNotice[\"targetProfileKind\"] | null {\n return kind === \"human\" || kind === \"agent\" ? kind : null;\n}\n\nfunction resolveMembershipActorKind(\n kind: unknown\n): SpaceMembershipNotice[\"actorKind\"] {\n return kind === \"human\" || kind === \"agent\" ? kind : \"unknown\";\n}\n","import type { HelloAck, SignalEnvelope } from \"@openmeld/protocol\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport { resolveNormalizedOwnerFields } from \"../agent-output-contract\";\n\ntype TranscriptOwnerEnrichmentSessionProfileIdentity = {\n kind: \"human\" | \"agent\";\n openMeldProfileId: string;\n ownerUserId?: string;\n ownerName?: string;\n};\n\ntype ResolvedOwnerDisplay = {\n ownerUserId: string;\n ownerName: string;\n};\n\nexport function resolveEnrichedTextRenderEvent(input: {\n event: SignalEnvelope | HelloAck;\n ownerDisplayNameByUserId: Map<string, string>;\n sessionProfileIdentity: TranscriptOwnerEnrichmentSessionProfileIdentity;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): SignalEnvelope | HelloAck {\n if (!isOwnerEnrichmentCandidate(input.event)) {\n return input.event;\n }\n\n const profile = input.event.profile;\n const currentOwner = resolveProfileOwnerDisplay(profile);\n cacheOwnerDisplayName(input.ownerDisplayNameByUserId, currentOwner);\n\n const mergedOwner = resolveMergedOwnerDisplay({\n currentOwner,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n sessionOwner: resolveSessionOwnerDisplay({\n profile,\n sessionProfileIdentity: input.sessionProfileIdentity,\n }),\n snapshotOwner: resolveSnapshotOwnerDisplay({\n profile,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }),\n });\n cacheOwnerDisplayName(input.ownerDisplayNameByUserId, mergedOwner);\n\n if (\n mergedOwner.ownerUserId === currentOwner.ownerUserId &&\n (!mergedOwner.ownerName || mergedOwner.ownerName === currentOwner.ownerName)\n ) {\n return input.event;\n }\n\n return {\n ...input.event,\n profile: {\n ...profile,\n ...(mergedOwner.ownerUserId\n ? { ownerUserId: mergedOwner.ownerUserId }\n : {}),\n ...(mergedOwner.ownerName ? { ownerName: mergedOwner.ownerName } : {}),\n ...(\"owner\" in profile ? { owner: undefined } : {}),\n },\n };\n}\n\nfunction isSignalEnvelope(\n event: SignalEnvelope | HelloAck\n): event is SignalEnvelope {\n return \"id\" in event && typeof event.id === \"string\";\n}\n\nfunction isOwnerEnrichmentCandidate(\n event: SignalEnvelope | HelloAck\n): event is SignalEnvelope & {\n profile: NonNullable<SignalEnvelope[\"profile\"]> & {\n kind: \"human\" | \"agent\";\n };\n} {\n return (\n isSignalEnvelope(event) &&\n (event.profile?.kind === \"human\" || event.profile?.kind === \"agent\")\n );\n}\n\nfunction resolveProfileOwnerDisplay(\n profile: NonNullable<SignalEnvelope[\"profile\"]>\n): ResolvedOwnerDisplay {\n const { ownerUserId, ownerName } = resolveNormalizedOwnerFields({\n ownerUserId: (profile as { ownerUserId?: unknown }).ownerUserId,\n ownerName: profile.ownerName,\n owner: (profile as { owner?: unknown }).owner,\n });\n return {\n ownerUserId: ownerUserId ?? \"\",\n ownerName: ownerName ?? \"\",\n };\n}\n\nfunction cacheOwnerDisplayName(\n ownerDisplayNameByUserId: Map<string, string>,\n ownerDisplay: ResolvedOwnerDisplay\n): void {\n if (!(ownerDisplay.ownerUserId && ownerDisplay.ownerName)) {\n return;\n }\n\n ownerDisplayNameByUserId.set(\n ownerDisplay.ownerUserId,\n ownerDisplay.ownerName\n );\n}\n\nfunction resolveSessionOwnerDisplay(input: {\n profile: NonNullable<SignalEnvelope[\"profile\"]> & {\n kind: \"human\" | \"agent\";\n };\n sessionProfileIdentity: TranscriptOwnerEnrichmentSessionProfileIdentity;\n}): ResolvedOwnerDisplay {\n if (\n input.profile.kind !== input.sessionProfileIdentity.kind ||\n input.profile.profileId !== input.sessionProfileIdentity.openMeldProfileId\n ) {\n return {\n ownerUserId: \"\",\n ownerName: \"\",\n };\n }\n\n return {\n ownerUserId: String(input.sessionProfileIdentity.ownerUserId ?? \"\").trim(),\n ownerName: String(input.sessionProfileIdentity.ownerName ?? \"\").trim(),\n };\n}\n\nfunction resolveSnapshotOwnerDisplay(input: {\n profile: NonNullable<SignalEnvelope[\"profile\"]> & {\n kind: \"human\" | \"agent\";\n };\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): ResolvedOwnerDisplay {\n const snapshot = input.spaceMembersSnapshot ?? null;\n const matchedSnapshot =\n input.profile.kind === \"human\"\n ? findMatchingHumanMemberSnapshot({\n profileId: input.profile.profileId,\n profileName: input.profile.profileName,\n snapshot,\n })\n : findMatchingAgentMemberSnapshot({\n profileId: input.profile.profileId,\n profileName: input.profile.profileName,\n snapshot,\n });\n\n return {\n ownerUserId: String(matchedSnapshot?.ownerUserId ?? \"\").trim(),\n ownerName: String(matchedSnapshot?.ownerName ?? \"\").trim(),\n };\n}\n\nfunction resolveMergedOwnerDisplay(input: {\n currentOwner: ResolvedOwnerDisplay;\n ownerDisplayNameByUserId: Map<string, string>;\n sessionOwner: ResolvedOwnerDisplay;\n snapshotOwner: ResolvedOwnerDisplay;\n}): ResolvedOwnerDisplay {\n const ownerUserId =\n input.currentOwner.ownerUserId ||\n input.sessionOwner.ownerUserId ||\n input.snapshotOwner.ownerUserId;\n const ownerName =\n input.currentOwner.ownerName ||\n input.sessionOwner.ownerName ||\n input.snapshotOwner.ownerName ||\n (ownerUserId\n ? String(input.ownerDisplayNameByUserId.get(ownerUserId) ?? \"\").trim()\n : \"\");\n\n return {\n ownerUserId,\n ownerName,\n };\n}\n\nfunction findMatchingHumanMemberSnapshot(input: {\n profileId?: string;\n profileName?: string;\n snapshot: SpaceMembersSnapshot | null;\n}) {\n if (!input.snapshot) {\n return null;\n }\n\n const profileId = String(input.profileId ?? \"\").trim();\n if (profileId) {\n const profileIdMatch = input.snapshot.humans.find(\n (member) => member.status === \"active\" && member.profileId === profileId\n );\n if (profileIdMatch) {\n return profileIdMatch;\n }\n }\n\n const profileName = String(input.profileName ?? \"\")\n .trim()\n .toLowerCase();\n if (!profileName) {\n return null;\n }\n\n return (\n input.snapshot.humans.find(\n (member) =>\n member.status === \"active\" &&\n String(member.profileName).trim().toLowerCase() === profileName\n ) ?? null\n );\n}\n\nfunction findMatchingAgentMemberSnapshot(input: {\n profileId?: string;\n profileName?: string;\n snapshot: SpaceMembersSnapshot | null;\n}) {\n if (!input.snapshot) {\n return null;\n }\n\n const profileId = String(input.profileId ?? \"\").trim();\n if (profileId) {\n const profileIdMatch = input.snapshot.agents.find(\n (member) => member.status === \"active\" && member.profileId === profileId\n );\n if (profileIdMatch) {\n return profileIdMatch;\n }\n }\n\n const profileName = String(input.profileName ?? \"\")\n .trim()\n .toLowerCase();\n if (!profileName) {\n return null;\n }\n\n return (\n input.snapshot.agents.find(\n (member) =>\n member.status === \"active\" &&\n String(member.profileName).trim().toLowerCase() === profileName\n ) ?? null\n );\n}\n","import type { SignalEnvelope, SignalTextReplyTo } from \"@openmeld/protocol\";\nimport { sanitizeTerminalDisplayText } from \"../../ui/terminal-safe-text\";\nimport type {\n SpaceTranscriptItem,\n SpaceTranscriptReplyRef,\n} from \"../state/space-screen-state\";\n\nexport function resolveTranscriptReplyRef(input: {\n event: SignalEnvelope;\n messageReadProjection: SpaceTranscriptItem[\"messageReadProjection\"] | null;\n}): SpaceTranscriptReplyRef | undefined {\n const replyToSignalId = input.messageReadProjection?.replyToSignalId ?? null;\n const replyToContext = input.messageReadProjection?.replyToContext ?? null;\n if (!(replyToSignalId && replyToContext)) {\n return undefined;\n }\n const signalId = sanitizeTranscriptReplyText(replyToSignalId);\n const profileId = sanitizeTranscriptReplyText(replyToContext.actorProfileId);\n const profileName = sanitizeTranscriptReplyText(\n replyToContext.actorDisplayName\n );\n if (!(signalId && (profileName || profileId))) {\n return undefined;\n }\n\n return {\n signalId,\n profileId,\n profileKind: resolveTranscriptReplyProfileKind({\n event: input.event,\n messageReadProjection: input.messageReadProjection,\n profileId,\n }),\n profileName,\n previewText: sanitizeTranscriptReplyText(replyToContext.previewText),\n };\n}\n\nfunction resolveSignalReplyToRecord(\n event: SignalEnvelope\n): SignalTextReplyTo | null {\n if (\n event.type !== \"signal.text\" &&\n event.type !== \"signal.status\" &&\n event.type !== \"signal.system_notice\"\n ) {\n return null;\n }\n const replyTo = event.data.replyTo;\n return replyTo && typeof replyTo === \"object\" ? replyTo : null;\n}\n\nfunction resolveTranscriptReplyProfileKind(input: {\n event: SignalEnvelope;\n messageReadProjection: SpaceTranscriptItem[\"messageReadProjection\"] | null;\n profileId: string;\n}): SpaceTranscriptReplyRef[\"profileKind\"] {\n const projectionProfileKind =\n input.messageReadProjection?.replyToContext?.actorProfileKind ?? null;\n if (projectionProfileKind) {\n return projectionProfileKind;\n }\n\n const replyToRecord = resolveSignalReplyToRecord(input.event);\n if (\n replyToRecord &&\n sanitizeTranscriptReplyText(replyToRecord.profileId) === input.profileId &&\n (replyToRecord.profileKind === \"human\" ||\n replyToRecord.profileKind === \"agent\" ||\n replyToRecord.profileKind === \"system\")\n ) {\n return replyToRecord.profileKind;\n }\n\n return null;\n}\n\nfunction sanitizeTranscriptReplyText(value: unknown): string {\n return sanitizeTerminalDisplayText(\n typeof value === \"string\" ? value : \"\",\n \"single-line\"\n )\n .replace(/\\s+/gu, \" \")\n .trim();\n}\n","import type { HelloAck, SignalEnvelope } from \"@openmeld/protocol\";\nimport {\n SPACE_MEMBER_JOIN_NOTICE_PURPOSE,\n SPACE_MEMBER_REMOVE_NOTICE_PURPOSE,\n} from \"@openmeld/schemas\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport {\n buildSignalMessageReadProjection,\n buildSignalReplyWorkflowProjection,\n type SpaceReplyWorkflowProjection,\n type SpaceSignalIndex,\n} from \"@openmeld/space\";\nimport { buildHumanFormattedMessage, formatTextEvent } from \"../../ui/output\";\nimport type { SpaceMentionHighlightIndex } from \"../../ui/space-mention-highlight\";\nimport { sanitizeTerminalDisplayText } from \"../../ui/terminal-safe-text\";\nimport { resolveNormalizedOwnerFields } from \"../agent-output-contract\";\nimport { isOpenMeldSystemProfileIdentity } from \"../openmeld-system-profile\";\nimport { buildHumanReplyContextLine } from \"../read-projection/human-message-read-display\";\nimport type {\n SpaceTranscriptFormattedMessage,\n SpaceTranscriptItem,\n SpaceTranscriptReplyRef,\n} from \"../state/space-screen-state\";\nimport { resolveMembershipNoticeFromSignalEnvelope } from \"./membership-notice\";\nimport { resolveEnrichedTextRenderEvent } from \"./transcript-owner-enrichment\";\nimport { resolveTranscriptReplyRef } from \"./transcript-reply-ref\";\n\nconst SYSTEM_MESSAGE_GROUP_KEY = \"system\";\nconst PRESENCE_HUMAN_AVATAR = \"👤\";\nconst PRESENCE_AGENT_AVATAR = \"🤖\";\n\nexport type TranscriptSessionProfileIdentity = {\n kind: \"human\" | \"agent\";\n openMeldProfileId: string;\n ownerUserId?: string;\n ownerName?: string;\n};\n\nexport type TranscriptThreadIndicator = {\n threadId: string;\n replyCount: number;\n};\n\n// Assemble transcript items from shared read/workflow projections plus\n// render-facing metadata. This file must not re-own shared semantics.\nexport function buildHumanTranscriptItemFromEvent(input: {\n event: SignalEnvelope | HelloAck;\n mentionHighlightIndex?: SpaceMentionHighlightIndex | null;\n ownerDisplayNameByUserId: Map<string, string>;\n selfProfileId: string;\n sessionProfileIdentity: TranscriptSessionProfileIdentity;\n signalIndex?: SpaceSignalIndex | null;\n spaceId?: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n threadSummary?: TranscriptThreadIndicator | null;\n}): SpaceTranscriptItem | null {\n const enrichedEvent = resolveEnrichedTextRenderEvent({\n event: input.event,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n sessionProfileIdentity: input.sessionProfileIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n const messageReadProjection = isSignalEnvelope(enrichedEvent)\n ? buildSignalMessageReadProjection({\n signal: enrichedEvent,\n membersSnapshot: input.spaceMembersSnapshot,\n signalIndex: input.signalIndex ?? null,\n })\n : null;\n const replyWorkflowProjection = isSignalEnvelope(enrichedEvent)\n ? buildSignalReplyWorkflowProjection({\n signal: enrichedEvent,\n membersSnapshot: input.spaceMembersSnapshot,\n signalIndex: input.signalIndex ?? null,\n })\n : null;\n const line = formatTextEvent(enrichedEvent, {\n view: \"human\",\n selfProfileId: input.selfProfileId,\n mentionHighlightIndex: input.mentionHighlightIndex,\n replyLine: buildHumanReplyContextLine(\n replyWorkflowProjection?.replyToContext ?? null\n ),\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n if (!line) {\n return null;\n }\n\n const formattedMessage = shouldBuildHumanFormattedMessage(enrichedEvent)\n ? buildHumanFormattedMessage({\n event: enrichedEvent,\n mentionHighlightIndex: input.mentionHighlightIndex,\n messageReadProjection,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n })\n : null;\n\n return buildSpaceTranscriptItem({\n event: enrichedEvent,\n line,\n formattedMessage: attachThreadIndicatorLine({\n formattedMessage,\n spaceId: input.spaceId,\n threadSummary: input.threadSummary ?? null,\n }),\n messageReadProjection,\n replyWorkflowProjection,\n });\n}\n\n// Attach a dimmed thread-indicator sub-line under a message that roots a\n// thread, e.g. \"↳ 3 replies · openmeld space thread <spaceId> <threadId>\". Rendered\n// as its own wrapped line below the message body (not joined into the meta\n// tags), so the full thread id survives narrow terminals.\nfunction attachThreadIndicatorLine(input: {\n formattedMessage: SpaceTranscriptFormattedMessage | null;\n spaceId: string | undefined;\n threadSummary: TranscriptThreadIndicator | null;\n}): SpaceTranscriptFormattedMessage | null {\n const { formattedMessage, spaceId, threadSummary } = input;\n if (!(formattedMessage && threadSummary && spaceId)) {\n return formattedMessage;\n }\n if (threadSummary.replyCount <= 0) {\n return formattedMessage;\n }\n const replyNoun = threadSummary.replyCount === 1 ? \"reply\" : \"replies\";\n const safeSpaceId = sanitizeTerminalDisplayText(spaceId);\n const safeThreadId = sanitizeTerminalDisplayText(threadSummary.threadId);\n const indicatorLine = `↳ ${String(threadSummary.replyCount)} ${replyNoun} · openmeld space thread ${safeSpaceId} ${safeThreadId}`;\n return {\n ...formattedMessage,\n threadIndicatorLine: indicatorLine,\n };\n}\n\nexport function resolveTextLineGroupKey(\n event: SignalEnvelope | HelloAck\n): string {\n if (isSystemRenderedHumanViewEvent(event)) {\n return SYSTEM_MESSAGE_GROUP_KEY;\n }\n return resolveProfileGroupKey(event.profile, event.type);\n}\n\nexport function buildSpaceTranscriptItem(input: {\n event: SignalEnvelope | HelloAck;\n line: string;\n formattedMessage?: SpaceTranscriptFormattedMessage | null;\n messageReadProjection?: SpaceTranscriptItem[\"messageReadProjection\"] | null;\n replyWorkflowProjection?: SpaceReplyWorkflowProjection | null;\n}): SpaceTranscriptItem {\n const groupKey = resolveTextLineGroupKey(input.event);\n const profile = buildTranscriptItemProfileSnapshot(input.event);\n const systemPurpose = resolveTranscriptItemSystemPurpose(input.event);\n const replyRef = isSignalEnvelope(input.event)\n ? resolveTranscriptReplyRef({\n event: input.event,\n messageReadProjection: input.messageReadProjection ?? null,\n })\n : undefined;\n if (isSignalEnvelope(input.event)) {\n return buildSignalEnvelopeTranscriptItem({\n event: input.event,\n formattedMessage: input.formattedMessage ?? undefined,\n groupKey,\n line: input.line,\n messageReadProjection: input.messageReadProjection ?? undefined,\n profile,\n replyWorkflowProjection: input.replyWorkflowProjection ?? undefined,\n replyRef,\n systemPurpose: systemPurpose ?? undefined,\n });\n }\n return {\n line: input.line,\n groupKey,\n kind: \"system_notice\",\n formattedMessage: input.formattedMessage ?? undefined,\n ...(input.messageReadProjection\n ? { messageReadProjection: input.messageReadProjection }\n : {}),\n ...(input.replyWorkflowProjection\n ? { replyWorkflowProjection: input.replyWorkflowProjection }\n : {}),\n profile,\n systemPurpose,\n };\n}\n\nfunction buildSignalEnvelopeTranscriptItem(input: {\n event: SignalEnvelope;\n formattedMessage?: SpaceTranscriptFormattedMessage;\n groupKey: string;\n line: string;\n messageReadProjection?: SpaceTranscriptItem[\"messageReadProjection\"];\n profile: SpaceTranscriptItem[\"profile\"];\n replyWorkflowProjection?: SpaceTranscriptItem[\"replyWorkflowProjection\"];\n replyRef?: SpaceTranscriptReplyRef;\n systemPurpose: string | undefined;\n}): SpaceTranscriptItem {\n const baseItem = buildSignalTranscriptItemBase(input);\n if (\n input.event.type === \"presence.join\" ||\n input.event.type === \"presence.quit\"\n ) {\n return {\n ...baseItem,\n kind: \"presence\",\n presenceAction: input.event.type === \"presence.join\" ? \"join\" : \"left\",\n actorProfileId: normalizeTranscriptActorProfileId(input.event.profile),\n actorKind: resolveTranscriptActorKind(input.event.profile?.kind),\n actorLabel: resolveTranscriptActorLabel(input.event.profile),\n actorAvatar: resolveTranscriptActorAvatar(input.event.profile?.kind),\n };\n }\n\n const membershipNotice = resolveMembershipNoticeFromSignalEnvelope(\n input.event\n );\n if (membershipNotice) {\n return {\n ...baseItem,\n kind: \"membership_notice\",\n membershipNotice,\n };\n }\n\n if (input.event.type === \"signal.system_notice\") {\n return {\n ...baseItem,\n kind: \"system_notice\",\n ...(input.replyRef ? { replyRef: input.replyRef } : {}),\n };\n }\n\n return {\n ...baseItem,\n kind:\n input.groupKey === SYSTEM_MESSAGE_GROUP_KEY ? \"system_notice\" : \"message\",\n ...(input.groupKey === SYSTEM_MESSAGE_GROUP_KEY || !input.replyRef\n ? {}\n : { replyRef: input.replyRef }),\n };\n}\n\nfunction buildSignalTranscriptItemBase(input: {\n event: SignalEnvelope;\n formattedMessage?: SpaceTranscriptFormattedMessage;\n groupKey: string;\n line: string;\n messageReadProjection?: SpaceTranscriptItem[\"messageReadProjection\"];\n profile: SpaceTranscriptItem[\"profile\"];\n replyWorkflowProjection?: SpaceTranscriptItem[\"replyWorkflowProjection\"];\n systemPurpose: string | undefined;\n}): Omit<SpaceTranscriptItem, \"kind\"> {\n return {\n line: input.line,\n groupKey: input.groupKey,\n formattedMessage: input.formattedMessage,\n ...(input.messageReadProjection\n ? { messageReadProjection: input.messageReadProjection }\n : {}),\n ...(input.replyWorkflowProjection\n ? { replyWorkflowProjection: input.replyWorkflowProjection }\n : {}),\n profile: input.profile,\n systemPurpose: input.systemPurpose,\n ts: input.event.ts,\n };\n}\n\nfunction isSignalEnvelope(\n event: SignalEnvelope | HelloAck\n): event is SignalEnvelope {\n return \"id\" in event && typeof event.id === \"string\";\n}\n\nfunction resolveProfileGroupKey(\n profile: SignalEnvelope[\"profile\"] | HelloAck[\"profile\"] | undefined,\n fallbackType: string\n): string {\n const profileId = String(profile?.profileId ?? \"\").trim();\n if (profileId) {\n return `profile-id:${profileId}`;\n }\n\n const profileName = String(profile?.profileName ?? \"\").trim();\n const profileKind = String(profile?.kind ?? \"\").trim();\n if (profileName || profileKind) {\n return `profile:${profileKind || \"unknown\"}:${profileName || \"unknown\"}`;\n }\n return `event:${fallbackType}`;\n}\n\nfunction isSystemRenderedHumanViewEvent(\n event: SignalEnvelope | HelloAck\n): boolean {\n if (event.type === \"system.hello.ack\") {\n return true;\n }\n if (!isSignalEnvelope(event)) {\n return false;\n }\n if (event.type === \"presence.join\" || event.type === \"presence.quit\") {\n return true;\n }\n return isSystemRenderedHumanViewSignalEvent(event);\n}\n\nfunction shouldBuildHumanFormattedMessage(\n event: SignalEnvelope | HelloAck\n): event is Extract<SignalEnvelope, { type: \"signal.text\" | \"signal.status\" }> {\n return (\n isSignalEnvelope(event) &&\n (event.type === \"signal.text\" || event.type === \"signal.status\") &&\n !isSystemRenderedHumanViewEvent(event)\n );\n}\n\nfunction isSystemRenderedHumanViewSignalEvent(event: SignalEnvelope): boolean {\n if (event.type === \"signal.status\") {\n return isOpenMeldSystemProfileIdentity(event.profile);\n }\n\n if (event.type !== \"signal.text\") {\n return false;\n }\n\n if (isOpenMeldSystemProfileIdentity(event.profile)) {\n return true;\n }\n const meta = resolveSignalTextMetaFromEnvelope(event);\n const purpose = String(meta?.purpose ?? \"\").trim();\n return (\n purpose === SPACE_MEMBER_JOIN_NOTICE_PURPOSE ||\n purpose === SPACE_MEMBER_REMOVE_NOTICE_PURPOSE\n );\n}\n\nfunction resolveSignalTextMetaFromEnvelope(\n event: SignalEnvelope\n): Record<string, unknown> | null {\n if (\n !event.data ||\n typeof event.data !== \"object\" ||\n Array.isArray(event.data)\n ) {\n return null;\n }\n const meta = (event.data as { meta?: unknown }).meta;\n if (!meta || typeof meta !== \"object\" || Array.isArray(meta)) {\n return null;\n }\n return meta as Record<string, unknown>;\n}\n\nfunction buildTranscriptItemProfileSnapshot(\n event: SignalEnvelope | HelloAck\n): SpaceTranscriptItem[\"profile\"] {\n const rawProfile = isSignalEnvelope(event) ? event.profile : null;\n const rawProfileRecord =\n rawProfile && typeof rawProfile === \"object\"\n ? (rawProfile as Record<string, unknown>)\n : null;\n const profileName = sanitizeTerminalDisplayText(\n rawProfile?.profileName,\n \"single-line\"\n ).trim();\n const normalizedOwner = resolveNormalizedOwnerFields({\n ownerUserId:\n typeof rawProfileRecord?.ownerUserId === \"string\"\n ? rawProfileRecord.ownerUserId\n : undefined,\n ownerName: rawProfile?.ownerName,\n owner:\n typeof rawProfileRecord?.owner === \"string\"\n ? rawProfileRecord.owner\n : undefined,\n });\n return {\n kind:\n rawProfile?.kind === \"human\" ||\n rawProfile?.kind === \"agent\" ||\n rawProfile?.kind === \"system\"\n ? rawProfile.kind\n : \"unknown\",\n profileId: normalizeTranscriptActorProfileId(rawProfile ?? undefined),\n profileName: profileName || \"unknown\",\n ownerUserId: normalizedOwner.ownerUserId ?? null,\n ownerName: normalizedOwner.ownerName ?? null,\n agentControllerRef:\n sanitizeTerminalDisplayText(\n typeof rawProfileRecord?.agentControllerRef === \"string\"\n ? rawProfileRecord.agentControllerRef\n : rawProfile?.agentControllerRef,\n \"single-line\"\n ).trim() || null,\n };\n}\n\nfunction resolveTranscriptItemSystemPurpose(\n event: SignalEnvelope | HelloAck\n): string | null {\n if (!isSignalEnvelope(event)) {\n return null;\n }\n if (event.type === \"signal.text\") {\n const meta = resolveSignalTextMetaFromEnvelope(event);\n return typeof meta?.purpose === \"string\" ? meta.purpose : null;\n }\n if (event.type === \"signal.system_notice\") {\n const noticeType =\n event.data && typeof event.data.noticeType === \"string\"\n ? event.data.noticeType.trim()\n : \"\";\n return noticeType\n ? `signal.system_notice:${noticeType}`\n : \"signal.system_notice\";\n }\n return null;\n}\n\nfunction resolveTranscriptActorKind(\n kind: unknown\n): SpaceTranscriptItem[\"actorKind\"] {\n return kind === \"human\" || kind === \"agent\" ? kind : \"unknown\";\n}\n\nfunction resolveTranscriptActorAvatar(kind: unknown): string {\n if (kind === \"agent\") {\n return PRESENCE_AGENT_AVATAR;\n }\n return PRESENCE_HUMAN_AVATAR;\n}\n\nfunction resolveTranscriptActorLabel(\n profileIdentity: SignalEnvelope[\"profile\"] | undefined\n): string {\n const label = sanitizeTerminalDisplayText(\n profileIdentity?.profileName,\n \"single-line\"\n ).trim();\n return label || \"unknown\";\n}\n\nfunction normalizeTranscriptActorProfileId(\n profileIdentity: SignalEnvelope[\"profile\"] | undefined\n): string {\n return sanitizeTerminalDisplayText(\n profileIdentity?.profileId,\n \"single-line\"\n ).trim();\n}\n","import type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport type { SpaceReplyWorkflowProjection } from \"@openmeld/space\";\nimport { sanitizeTerminalDisplayText } from \"../../ui/terminal-safe-text\";\nimport { buildHumanReplyCuePreview } from \"../reply-cue-preview\";\nimport type { SpaceTranscriptReplyRef } from \"../state/space-screen-state\";\nimport { buildHumanReplyContextLine } from \"./human-message-read-display\";\n\nconst TRANSCRIPT_REPLY_PREVIEW_MAX_VISIBLE_WIDTH = 32;\n\nexport function buildHumanReplyWorkflowTranscriptCueLine(input: {\n membersSnapshot: SpaceMembersSnapshot | null;\n replyRef?: SpaceTranscriptReplyRef;\n replyWorkflowProjection?: SpaceReplyWorkflowProjection | null;\n}): string | null {\n const semanticReplyLine = buildHumanReplyContextLine(\n input.replyWorkflowProjection?.replyToContext ?? null\n );\n if (semanticReplyLine) {\n return semanticReplyLine;\n }\n\n const replyRef = input.replyRef;\n if (!replyRef) {\n return null;\n }\n\n const profileLabel = resolveTranscriptReplyProfileLabel({\n membersSnapshot: input.membersSnapshot,\n replyRef,\n });\n const previewText = resolveTranscriptReplyPreviewText(replyRef.previewText);\n\n return previewText\n ? `reply to ${profileLabel} · ${previewText}`\n : `reply to ${profileLabel}`;\n}\n\nfunction resolveTranscriptReplyProfileLabel(input: {\n membersSnapshot: SpaceMembersSnapshot | null;\n replyRef: NonNullable<SpaceTranscriptReplyRef>;\n}): string {\n const profileId = sanitizeTranscriptReplyDisplayText(\n input.replyRef.profileId\n );\n if (profileId && input.membersSnapshot) {\n const humanMatch = input.membersSnapshot.humans.find(\n (member) => member.profileId === profileId\n );\n const agentMatch = input.membersSnapshot.agents.find(\n (member) => member.profileId === profileId\n );\n const snapshotName =\n humanMatch?.profileName?.trim() || agentMatch?.profileName?.trim() || \"\";\n if (snapshotName) {\n return snapshotName;\n }\n }\n\n return (\n sanitizeTranscriptReplyDisplayText(input.replyRef.profileName) ||\n profileId ||\n \"unknown\"\n );\n}\n\nfunction resolveTranscriptReplyPreviewText(value: string): string {\n return buildHumanReplyCuePreview(\n value,\n TRANSCRIPT_REPLY_PREVIEW_MAX_VISIBLE_WIDTH\n );\n}\n\nfunction sanitizeTranscriptReplyDisplayText(value: string): string {\n return sanitizeTerminalDisplayText(value, \"single-line\")\n .replace(/\\s+/gu, \" \")\n .trim();\n}\n","import {\n CONVERSATION_CONTINUITY_WARNING_PURPOSE,\n SPACE_MENTION_REJECT_NOTICE_PURPOSE,\n} from \"@openmeld/schemas\";\n\nconst LEGACY_SYSTEM_PREFIX_PATTERN = /^\\* 📣 system:\\s*/u;\n\nconst IMPORTANT_SYSTEM_NOTICE_PURPOSES = new Set<string>([\n CONVERSATION_CONTINUITY_WARNING_PURPOSE,\n SPACE_MENTION_REJECT_NOTICE_PURPOSE,\n]);\n\nconst IMPORTANT_SYSTEM_NOTICE_TEXT_PATTERNS = [\n \"not confirmed\",\n \"connection closed\",\n \"connection dropped\",\n \"policy violation\",\n \"permission\",\n \"unauthorized\",\n \"forbidden\",\n \"rejected\",\n \"denied\",\n \"internal error\",\n \"service is busy\",\n \"tls handshake\",\n \"password required\",\n \"password invalid\",\n \"password too short\",\n \"space not found\",\n \"space is not available\",\n \"space is unavailable\",\n \"couldn't connect\",\n \"could not connect\",\n \"cannot connect\",\n \"failed to connect\",\n] as const;\n\nexport function stripLegacySystemPrefix(line: string): string {\n return line.replace(LEGACY_SYSTEM_PREFIX_PATTERN, \"\").trim();\n}\n\nexport function isConnectedAsLegacySystemLine(line: string): boolean {\n return stripLegacySystemPrefix(line)\n .toLowerCase()\n .startsWith(\"connected as \");\n}\n\nexport function isImportantHumanSystemNotice(input: {\n line: string;\n purpose?: string | null;\n}): boolean {\n const purpose = String(input.purpose ?? \"\").trim();\n if (\n purpose === \"signal.system_notice\" ||\n purpose.startsWith(\"signal.system_notice:\")\n ) {\n return true;\n }\n if (purpose && IMPORTANT_SYSTEM_NOTICE_PURPOSES.has(purpose)) {\n return true;\n }\n return isImportantHumanSystemNoticeLine(input.line);\n}\n\nfunction isImportantHumanSystemNoticeLine(line: string): boolean {\n const normalized = stripLegacySystemPrefix(line).toLowerCase();\n if (!normalized) {\n return false;\n }\n if (isConnectedAsLegacySystemLine(line)) {\n return false;\n }\n return IMPORTANT_SYSTEM_NOTICE_TEXT_PATTERNS.some((pattern) =>\n normalized.includes(pattern)\n );\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport pc from \"picocolors\";\nimport stringWidth from \"string-width\";\nimport wrapAnsi from \"wrap-ansi\";\nimport {\n OPENMELD_COMPOSER_SURFACE_BG_RGB,\n renderOpenMeldBrandAccent,\n} from \"../../ui/brand\";\nimport { resolveControllerDisplayName } from \"../../ui/controller-display\";\nimport { renderPositiveAccentText } from \"../../ui/positive-accent\";\nimport {\n colorizeAgentLabel,\n colorizeDisplayProfileLabel,\n colorizePersonLabel,\n resolveAgentSurfaceRgb,\n} from \"../../ui/profile-label-color\";\nimport { resolvePrimarySpaceMentionLabel } from \"../mention-label-state\";\nimport { buildHumanReplyWorkflowTranscriptCueLine } from \"../read-projection/human-reply-workflow-transcript-display\";\nimport type { SpaceTranscriptItem } from \"../state/space-screen-state\";\nimport {\n isConnectedAsLegacySystemLine,\n isImportantHumanSystemNotice,\n} from \"./system-notice-importance\";\n\nexport type TranscriptBlockKind =\n | \"plain_text_group\"\n | \"system_group\"\n | \"presence_first_join_group\"\n | \"presence_trace_group\"\n | \"membership_trace_group\";\nexport type TranscriptBubbleSpeakerKind = \"human\" | \"agent\" | \"unknown\";\nexport type TranscriptBubbleHighlightKind =\n | \"self_human\"\n | \"owned_agent\"\n | \"neutral\";\n\nexport type TranscriptBubbleMessageViewState = {\n primaryLine: string;\n headerBaseLeading?: string;\n headerAuxLeading?: string | null;\n headerLeading: string;\n headerTypeBadge?: string | null;\n headerPresenceBadge?: \"live now\" | null;\n headerTrailing: string;\n replyLine?: string | null;\n relationLines: readonly string[];\n bodyLines: readonly string[];\n bodyDetailLines: readonly string[];\n metaLines: readonly string[];\n threadIndicatorLine?: string | null;\n detailLines: readonly string[];\n rawLines: readonly string[];\n};\n\nexport type TranscriptPlainTextBlockViewState = {\n kind: \"plain_text_group\";\n groupKey: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n speakerKind: TranscriptBubbleSpeakerKind;\n highlightKind: TranscriptBubbleHighlightKind;\n speakerProfileId: string | null;\n speakerProfileName: string;\n speakerOwnerUserId?: string | null;\n speakerOwnerName?: string | null;\n speakerAgentControllerRef?: string | null;\n speakerControllerDisplay?: string | null;\n speakerOwnerDisplay?: string | null;\n messages: readonly TranscriptBubbleMessageViewState[];\n};\n\nexport type TranscriptSystemBlockViewState = {\n kind: \"system_group\";\n groupKey: string;\n lines: readonly string[];\n purposes: readonly (string | null)[];\n sourceNoticeCount: number;\n};\n\nexport type TranscriptPresenceFirstJoinBlockViewState = {\n kind: \"presence_first_join_group\";\n groupKey: string;\n actorKey: string;\n actorProfileId: string | null;\n actorKind: TranscriptBubbleSpeakerKind;\n actorAvatar: string;\n actorLabel: string;\n actorOwnerUserId?: string | null;\n actorOwnerName?: string | null;\n ts: number;\n};\n\nexport type TranscriptPresenceTraceBlockViewState = {\n kind: \"presence_trace_group\";\n groupKey: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n actorKey: string;\n actorProfileId: string | null;\n actorKind: TranscriptBubbleSpeakerKind;\n actorAvatar: string;\n actorLabel: string;\n actorOwnerUserId?: string | null;\n actorOwnerName?: string | null;\n startTs: number;\n endTs: number;\n joinCount: number;\n leftCount: number;\n count: number;\n};\n\nexport type TranscriptMembershipTraceTargetViewState = {\n profileId: string | null;\n kind: \"human\" | \"agent\";\n label: string;\n mentionLabel: string | null;\n ownerUserId?: string | null;\n ownerName?: string | null;\n};\n\nexport type TranscriptMembershipTraceBlockViewState = {\n kind: \"membership_trace_group\";\n groupKey: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n action: \"member_added\" | \"member_removed\";\n actorKey: string;\n actorProfileId: string | null;\n actorKind: TranscriptBubbleSpeakerKind;\n actorAvatar: string;\n actorLabel: string;\n actorOwnerUserId?: string | null;\n actorOwnerName?: string | null;\n startTs: number;\n endTs: number;\n targets: readonly TranscriptMembershipTraceTargetViewState[];\n};\n\nexport type TranscriptBlockViewState =\n | TranscriptPlainTextBlockViewState\n | TranscriptSystemBlockViewState\n | TranscriptPresenceFirstJoinBlockViewState\n | TranscriptPresenceTraceBlockViewState\n | TranscriptMembershipTraceBlockViewState;\n\ntype TranscriptSystemClusterBlockViewState =\n | TranscriptSystemBlockViewState\n | TranscriptPresenceFirstJoinBlockViewState\n | TranscriptPresenceTraceBlockViewState\n | TranscriptMembershipTraceBlockViewState;\n\nexport type HumanLogsSectionKind = \"presence\" | \"membership\" | \"system\";\n\nexport type HumanLogsItemViewState = {\n id: string;\n lines: readonly string[];\n};\n\nexport type HumanLogsSectionViewState = {\n kind: HumanLogsSectionKind;\n items: readonly HumanLogsItemViewState[];\n title: string;\n lines: readonly string[];\n};\n\nexport type HumanTranscriptProjectionSummaryViewState = {\n hiddenPresenceCount: number;\n hiddenSystemNoticeCount: number;\n};\n\nexport type HumanTranscriptProjectionViewState = {\n hiddenSummary: HumanTranscriptProjectionSummaryViewState;\n logsSections: readonly HumanLogsSectionViewState[];\n transcriptBlocks: readonly TranscriptBlockViewState[];\n};\ntype TranscriptSessionProfile = {\n profileId: string;\n profileName: string;\n kind: \"human\" | \"agent\";\n ownerUserId?: string | null;\n ownerName?: string | null;\n};\ntype TranscriptSpeakerIdentity = {\n profileId: string | null;\n profileName: string;\n kind: TranscriptBubbleSpeakerKind;\n agentControllerRef?: string | null;\n controllerDisplay?: string | null;\n ownerDisplay?: string | null;\n ownerUserId?: string | null;\n ownerName?: string | null;\n};\ntype TranscriptRenderSection =\n | {\n kind: \"plain_text_group\";\n block: TranscriptPlainTextBlockViewState;\n }\n | {\n kind: \"system_cluster\";\n blocks: readonly TranscriptSystemClusterBlockViewState[];\n };\n\nconst SYSTEM_TRANSCRIPT_GROUP_KEY = \"system\";\nconst PRESENCE_TRACE_MAX_GAP_MS = 15 * 60 * 1000;\nconst PRESENCE_TRACE_MAX_SPAN_MS = 60 * 60 * 1000;\nconst MEMBERSHIP_TRACE_MAX_GAP_MS = 5 * 60 * 1000;\nconst TRANSCRIPT_GROUP_GAP_LINES = 2;\nconst TRANSCRIPT_BUBBLE_GAP_LINES = 1;\nconst TRANSCRIPT_BUBBLE_GROUP_INDENT = 0;\nconst TRANSCRIPT_BUBBLE_HORIZONTAL_PADDING = 1;\nconst TRANSCRIPT_BUBBLE_VERTICAL_PADDING = 1;\nconst TRANSCRIPT_BUBBLE_META_GAP_LINES = 1;\nconst TRANSCRIPT_BUBBLE_BODY_PREFIX = \"› \";\nconst TRANSCRIPT_BUBBLE_BODY_CONTINUATION_PREFIX = \" \";\nconst TRANSCRIPT_BUBBLE_REPLY_CONNECTED_BODY_PREFIX = \"╰─› \";\nconst TRANSCRIPT_BUBBLE_REPLY_CONNECTED_BODY_CONTINUATION_PREFIX = \" \";\nconst TRANSCRIPT_HUMAN_BUBBLE_BACKGROUND = buildAnsiBackgroundColor(\n OPENMELD_COMPOSER_SURFACE_BG_RGB\n);\nconst TRANSCRIPT_NEUTRAL_BUBBLE_BACKGROUND = \"\\u001B[48;2;33;33;33m\";\nconst ANSI_BACKGROUND_RESET = \"\\u001B[49m\";\nconst ANSI_ESCAPE_PATTERN = \"(?:\\\\u001B\\\\[[0-9;]*m)*\";\nconst TRANSCRIPT_GROUP_KIND_PATTERN = /^profile:(human|agent|unknown):/u;\nconst PROFILE_GROUP_KEY_PATTERN = /^profile:(human|agent|unknown):(.+)$/u;\nconst PRESENCE_TRACE_JOINED_LABEL = \"joined\";\nconst PRESENCE_TRACE_LEFT_LABEL = \"left\";\nconst PRESENCE_TRACE_JOIN_LABEL = \"join\";\nconst PRESENCE_TRACE_JOIN_LEFT_LABEL = \"join/left\";\nconst PRESENCE_FIRST_JOIN_LABEL = \"first joined\";\nconst MEMBERSHIP_TRACE_ADDED_LABEL = \"added\";\nconst MEMBERSHIP_TRACE_REMOVED_LABEL = \"removed\";\nconst TRANSCRIPT_PRIMARY_METADATA_LINE_PATTERN =\n /^(human(?:\\s·.*)?|agent(?:\\s+via\\s+.*|\\s·.*)?)/u;\nconst TRANSCRIPT_SECONDARY_METADATA_LINE_PATTERN =\n /^(owns:|added:|owner:|origin:)/u;\nconst TRANSCRIPT_BODY_PREFIX_COLON_PATTERN = /^\\s*:\\s*/u;\nconst TRANSCRIPT_AGENT_VIA_META_PREFIX_PATTERN = /^agent via [^·]+ · /u;\nconst TRANSCRIPT_ANSI_HEADER_PATTERN = new RegExp(\n `^(?<leading>.+?)\\\\s${ANSI_ESCAPE_PATTERN}(?<timestamp>\\\\d{8}\\\\s\\\\d{2}:\\\\d{2}(?::\\\\d{2})?)${ANSI_ESCAPE_PATTERN}:\\\\s*(?<body>.*)$`,\n \"u\"\n);\nexport function buildTranscriptBlocks(\n items: readonly SpaceTranscriptItem[],\n membersSnapshot?: SpaceMembersSnapshot | null,\n sessionProfile?: TranscriptSessionProfile | null\n): TranscriptBlockViewState[] {\n const blocks: TranscriptBlockViewState[] = [];\n\n for (const item of items) {\n const nextBlock = appendOrCreateTranscriptBlock({\n currentBlock: blocks.at(-1) ?? null,\n item,\n membersSnapshot,\n sessionProfile,\n });\n if (nextBlock.replaceCurrent) {\n blocks[blocks.length - 1] = nextBlock.block;\n continue;\n }\n blocks.push(nextBlock.block);\n }\n\n return coalescePresenceTraceBlocksAcrossSingleForeignPresence(blocks);\n}\n\nexport function buildHumanTranscriptProjection(input: {\n items: readonly SpaceTranscriptItem[];\n membersSnapshot?: SpaceMembersSnapshot | null;\n sessionProfile?: TranscriptSessionProfile | null;\n}): HumanTranscriptProjectionViewState {\n const allBlocks = buildTranscriptBlocks(\n input.items,\n input.membersSnapshot,\n input.sessionProfile\n );\n const firstJoinBlocks = buildPresenceFirstJoinBlocks(\n input.items,\n input.membersSnapshot ?? null\n );\n const transcriptBlocks = attachCurrentPresenceStatusToLastMessageCards(\n coalesceAdjacentHumanPlainTextBlocks(\n buildHumanTranscriptBlocks({\n allBlocks,\n firstJoinBlocks,\n })\n ),\n input.membersSnapshot ?? null,\n input.items\n );\n const transcriptSystemNoticeCount = countSystemNotices(transcriptBlocks);\n const allSystemNoticeCount = countSystemNotices(allBlocks);\n\n return {\n hiddenSummary: {\n hiddenPresenceCount: allBlocks.filter(\n (block) => block.kind === \"presence_trace_group\"\n ).length,\n hiddenSystemNoticeCount: Math.max(\n 0,\n allSystemNoticeCount - transcriptSystemNoticeCount\n ),\n },\n logsSections: buildHumanLogsSections({\n allBlocks,\n firstJoinBlocks,\n }),\n transcriptBlocks,\n };\n}\n\nfunction countSystemNotices(\n blocks: readonly TranscriptBlockViewState[]\n): number {\n return blocks.reduce((count, block) => {\n if (block.kind === \"system_group\") {\n return count + block.sourceNoticeCount;\n }\n return count;\n }, 0);\n}\n\nfunction appendOrCreateTranscriptBlock(input: {\n currentBlock: TranscriptBlockViewState | null;\n item: SpaceTranscriptItem;\n membersSnapshot?: SpaceMembersSnapshot | null;\n sessionProfile?: TranscriptSessionProfile | null;\n}): {\n block: TranscriptBlockViewState;\n replaceCurrent: boolean;\n} {\n const appendedBlock = tryAppendTranscriptBlock(\n input.currentBlock,\n input.item\n );\n if (appendedBlock) {\n return {\n block: appendedBlock,\n replaceCurrent: true,\n };\n }\n return {\n block: createTranscriptBlock({\n groupKey: input.item.groupKey,\n item: input.item,\n membersSnapshot: input.membersSnapshot,\n sessionProfile: input.sessionProfile,\n }),\n replaceCurrent: false,\n };\n}\n\nfunction tryAppendTranscriptBlock(\n currentBlock: TranscriptBlockViewState | null,\n item: SpaceTranscriptItem\n): TranscriptBlockViewState | null {\n if (!currentBlock) {\n return null;\n }\n if (isPresenceTranscriptItem(item)) {\n return appendTranscriptItemToPresenceBlock(currentBlock, item);\n }\n if (isMembershipNoticeTranscriptItem(item)) {\n return appendTranscriptItemToMembershipTraceBlock(currentBlock, item);\n }\n if (currentBlock.groupKey !== item.groupKey) {\n return null;\n }\n return appendTranscriptItemToBlock(currentBlock, item);\n}\n\nfunction coalescePresenceTraceBlocksAcrossSingleForeignPresence(\n blocks: readonly TranscriptBlockViewState[]\n): TranscriptBlockViewState[] {\n const coalescedBlocks: TranscriptBlockViewState[] = [];\n\n for (let index = 0; index < blocks.length; index += 1) {\n const currentBlock = blocks[index];\n const foreignPresenceBlock = blocks[index + 1];\n const nextSameActorBlock = blocks[index + 2];\n\n if (\n currentBlock &&\n foreignPresenceBlock &&\n nextSameActorBlock &&\n canCoalescePresenceTraceAcrossSingleForeignPresence({\n current: currentBlock,\n foreign: foreignPresenceBlock,\n next: nextSameActorBlock,\n })\n ) {\n const coalescedCurrentBlock =\n currentBlock as TranscriptPresenceTraceBlockViewState;\n const coalescedForeignBlock =\n foreignPresenceBlock as TranscriptPresenceTraceBlockViewState;\n const coalescedNextBlock =\n nextSameActorBlock as TranscriptPresenceTraceBlockViewState;\n coalescedBlocks.push(\n mergePresenceTraceBlocks(coalescedCurrentBlock, coalescedNextBlock)\n );\n coalescedBlocks.push(coalescedForeignBlock);\n index += 2;\n continue;\n }\n\n if (currentBlock) {\n coalescedBlocks.push(currentBlock);\n }\n }\n\n return coalescedBlocks;\n}\n\nfunction buildHumanTranscriptBlocks(input: {\n allBlocks: readonly TranscriptBlockViewState[];\n firstJoinBlocks: readonly TranscriptPresenceFirstJoinBlockViewState[];\n}): TranscriptBlockViewState[] {\n const transcriptBlocks: TranscriptBlockViewState[] = [];\n const firstJoinBlockByActorKey = new Map(\n input.firstJoinBlocks.map((block) => [block.actorKey, block] as const)\n );\n const emittedFirstJoinActorKeys = new Set<string>();\n\n for (const block of input.allBlocks) {\n if (block.kind === \"presence_trace_group\") {\n const firstJoinBlock = firstJoinBlockByActorKey.get(block.actorKey);\n if (firstJoinBlock && !emittedFirstJoinActorKeys.has(block.actorKey)) {\n transcriptBlocks.push(firstJoinBlock);\n emittedFirstJoinActorKeys.add(block.actorKey);\n }\n continue;\n }\n\n if (block.kind === \"membership_trace_group\") {\n transcriptBlocks.push(block);\n continue;\n }\n\n if (block.kind === \"system_group\") {\n const importantEntries = block.lines.flatMap((line, index) => {\n const purpose = block.purposes[index] ?? null;\n if (!isImportantSystemNoticeEntry({ line, purpose })) {\n return [];\n }\n return [{ line, purpose }] as const;\n });\n const importantLines = importantEntries.map((entry) => entry.line);\n if (importantLines.length > 0) {\n transcriptBlocks.push({\n ...block,\n lines: importantLines,\n purposes: importantEntries.map((entry) => entry.purpose),\n });\n }\n continue;\n }\n\n transcriptBlocks.push(block);\n }\n\n return transcriptBlocks;\n}\n\nfunction coalesceAdjacentHumanPlainTextBlocks(\n blocks: readonly TranscriptBlockViewState[]\n): TranscriptBlockViewState[] {\n const coalescedBlocks: TranscriptBlockViewState[] = [];\n\n for (const block of blocks) {\n const previousBlock = coalescedBlocks.at(-1);\n if (\n previousBlock?.kind === \"plain_text_group\" &&\n block.kind === \"plain_text_group\" &&\n canCoalesceAdjacentHumanPlainTextBlocks(previousBlock, block)\n ) {\n coalescedBlocks[coalescedBlocks.length - 1] = {\n ...previousBlock,\n messages: [...previousBlock.messages, ...block.messages],\n };\n continue;\n }\n coalescedBlocks.push(block);\n }\n\n return coalescedBlocks;\n}\n\nfunction canCoalesceAdjacentHumanPlainTextBlocks(\n previousBlock: TranscriptBlockViewState | undefined,\n nextBlock: TranscriptBlockViewState\n): previousBlock is TranscriptPlainTextBlockViewState {\n if (\n !(\n previousBlock?.kind === \"plain_text_group\" &&\n nextBlock.kind === \"plain_text_group\"\n )\n ) {\n return false;\n }\n\n return (\n previousBlock.groupKey === nextBlock.groupKey &&\n previousBlock.speakerProfileId === nextBlock.speakerProfileId &&\n previousBlock.speakerKind === nextBlock.speakerKind &&\n previousBlock.highlightKind === nextBlock.highlightKind\n );\n}\n\nfunction buildHumanLogsSections(input: {\n allBlocks: readonly TranscriptBlockViewState[];\n firstJoinBlocks: readonly TranscriptPresenceFirstJoinBlockViewState[];\n}): readonly HumanLogsSectionViewState[] {\n const presenceItems = [\n ...input.firstJoinBlocks.map((block, index) => ({\n id: `presence:first-join:${String(index)}`,\n lines: buildPresenceFirstJoinRows(block),\n })),\n ...input.allBlocks.flatMap((block, index) => {\n if (block.kind !== \"presence_trace_group\") {\n return [];\n }\n return [\n {\n id: `presence:trace:${String(index)}`,\n lines: [buildPresenceTraceRowText(block)],\n },\n ];\n }),\n ];\n const membershipItems = input.allBlocks.flatMap((block, index) => {\n if (block.kind !== \"membership_trace_group\") {\n return [];\n }\n return [\n {\n id: `membership:${String(index)}`,\n lines: buildMembershipTraceRows(block),\n },\n ];\n });\n const systemItems = input.allBlocks.flatMap((block, index) => {\n if (block.kind !== \"system_group\") {\n return [];\n }\n return [\n {\n id: `system:${String(index)}`,\n lines: buildSystemClusterRowsFromSystemLines(block.lines),\n },\n ];\n });\n\n return [\n buildHumanLogsSection(\"system\", \"System\", systemItems),\n buildHumanLogsSection(\"membership\", \"Membership\", membershipItems),\n buildHumanLogsSection(\"presence\", \"Presence\", presenceItems),\n ];\n}\n\nfunction buildHumanLogsSection(\n kind: HumanLogsSectionKind,\n title: string,\n items: readonly HumanLogsItemViewState[]\n): HumanLogsSectionViewState {\n return {\n kind,\n title,\n items,\n lines: items.flatMap((item) => item.lines),\n };\n}\n\nfunction buildPresenceFirstJoinBlocks(\n items: readonly SpaceTranscriptItem[],\n membersSnapshot: SpaceMembersSnapshot | null\n): TranscriptPresenceFirstJoinBlockViewState[] {\n const blocks: TranscriptPresenceFirstJoinBlockViewState[] = [];\n const seenActorKeys = new Set<string>();\n const actorKeysWithPriorTranscriptActivity = new Set<string>();\n\n for (const item of items) {\n const nextBlock = buildPresenceFirstJoinBlock({\n item,\n membersSnapshot,\n seenActorKeys,\n actorKeysWithPriorTranscriptActivity,\n });\n if (nextBlock) {\n blocks.push(nextBlock);\n }\n\n registerTranscriptActorActivity(item, actorKeysWithPriorTranscriptActivity);\n }\n\n return blocks;\n}\n\nfunction buildPresenceFirstJoinBlock(input: {\n item: SpaceTranscriptItem;\n membersSnapshot: SpaceMembersSnapshot | null;\n seenActorKeys: Set<string>;\n actorKeysWithPriorTranscriptActivity: ReadonlySet<string>;\n}): TranscriptPresenceFirstJoinBlockViewState | null {\n if (\n !(\n isPresenceTranscriptItem(input.item) &&\n input.item.presenceAction === \"join\"\n )\n ) {\n return null;\n }\n\n const actorKey = resolvePresenceActorKey(input.item);\n if (!actorKey || input.seenActorKeys.has(actorKey)) {\n return null;\n }\n\n input.seenActorKeys.add(actorKey);\n if (\n !shouldRenderPresenceFirstJoinBlock({\n item: input.item,\n actorKey,\n membersSnapshot: input.membersSnapshot,\n actorKeysWithPriorTranscriptActivity:\n input.actorKeysWithPriorTranscriptActivity,\n })\n ) {\n return null;\n }\n\n const actorIdentity = resolvePresenceActorIdentity(\n input.item,\n input.membersSnapshot\n );\n return {\n kind: \"presence_first_join_group\",\n groupKey: input.item.groupKey,\n actorKey,\n actorProfileId: input.item.actorProfileId?.trim() || null,\n actorKind: input.item.actorKind ?? \"unknown\",\n actorAvatar:\n input.item.actorAvatar?.trim() || resolvePresenceActorAvatar(input.item),\n actorLabel: input.item.actorLabel?.trim() || \"unknown\",\n actorOwnerUserId: actorIdentity.ownerUserId,\n actorOwnerName: actorIdentity.ownerName,\n ts: typeof input.item.ts === \"number\" ? input.item.ts : 0,\n };\n}\n\nfunction shouldRenderPresenceFirstJoinBlock(input: {\n item: SpaceTranscriptItem;\n actorKey: string;\n membersSnapshot: SpaceMembersSnapshot | null;\n actorKeysWithPriorTranscriptActivity: ReadonlySet<string>;\n}): boolean {\n if (input.actorKeysWithPriorTranscriptActivity.has(input.actorKey)) {\n return false;\n }\n\n const knownFirstEnteredAtMs = resolvePresenceActorFirstEnteredAtMs(\n input.item,\n input.membersSnapshot\n );\n if (knownFirstEnteredAtMs === null) {\n return true;\n }\n\n const joinTs = typeof input.item.ts === \"number\" ? input.item.ts : null;\n return joinTs !== null && joinTs === knownFirstEnteredAtMs;\n}\n\nfunction registerTranscriptActorActivity(\n item: SpaceTranscriptItem,\n actorKeys: Set<string>\n): void {\n for (const actorKey of resolveTranscriptActorActivityKeys(item)) {\n actorKeys.add(actorKey);\n }\n}\n\nfunction resolveTranscriptActorActivityKeys(\n item: SpaceTranscriptItem\n): readonly string[] {\n if (isPresenceTranscriptItem(item)) {\n const actorKey = resolvePresenceActorKey(item);\n return actorKey ? [actorKey] : [];\n }\n\n if (isMembershipNoticeTranscriptItem(item)) {\n const notice = resolveMembershipNoticePayload(item);\n if (!notice) {\n return [];\n }\n const actorKey = resolveMembershipActorKey(notice);\n return actorKey ? [actorKey] : [];\n }\n\n const actorKey = resolveTranscriptContentActorKey(item);\n return actorKey ? [actorKey] : [];\n}\n\nfunction resolveTranscriptContentActorKey(item: SpaceTranscriptItem): string {\n const itemProfileId = item.profile?.profileId?.trim();\n if (itemProfileId) {\n return itemProfileId;\n }\n\n const groupProfileId = resolveProfileIdFromGroupKey(item.groupKey);\n if (groupProfileId) {\n return groupProfileId;\n }\n\n const itemProfileName = item.profile?.profileName?.trim();\n if (\n (item.profile?.kind === \"human\" ||\n item.profile?.kind === \"agent\" ||\n item.profile?.kind === \"unknown\") &&\n itemProfileName\n ) {\n return `${item.profile.kind}:${itemProfileName}`;\n }\n\n const fallbackMatch = PROFILE_GROUP_KEY_PATTERN.exec(item.groupKey);\n if (!fallbackMatch) {\n return \"\";\n }\n\n return `${fallbackMatch[1]}:${fallbackMatch[2]}`;\n}\n\nfunction attachCurrentPresenceStatusToLastMessageCards(\n blocks: readonly TranscriptBlockViewState[],\n membersSnapshot: SpaceMembersSnapshot | null,\n items: readonly SpaceTranscriptItem[]\n): TranscriptBlockViewState[] {\n const lastMessageLocationByActorKey = new Map<\n string,\n { blockIndex: number; messageIndex: number }\n >();\n const currentStatusByActorKey = buildCurrentPresenceStatusByActorKey({\n items,\n membersSnapshot,\n });\n\n for (const [blockIndex, block] of blocks.entries()) {\n if (!(block.kind === \"plain_text_group\" && block.speakerProfileId)) {\n continue;\n }\n lastMessageLocationByActorKey.set(block.speakerProfileId, {\n blockIndex,\n messageIndex: block.messages.length - 1,\n });\n }\n\n return blocks.map((block, blockIndex) => {\n if (!(block.kind === \"plain_text_group\" && block.speakerProfileId)) {\n return block;\n }\n\n const lastMessageLocation = lastMessageLocationByActorKey.get(\n block.speakerProfileId\n );\n if (!lastMessageLocation || lastMessageLocation.blockIndex !== blockIndex) {\n return block;\n }\n\n const currentStatus =\n currentStatusByActorKey.get(block.speakerProfileId) ?? null;\n if (!currentStatus) {\n return block;\n }\n\n return {\n ...block,\n messages: block.messages.map((message, messageIndex) => ({\n ...message,\n headerPresenceBadge:\n messageIndex === lastMessageLocation.messageIndex &&\n !message.headerTypeBadge\n ? currentStatus\n : null,\n })),\n };\n });\n}\n\nfunction buildCurrentPresenceStatusByActorKey(input: {\n items: readonly SpaceTranscriptItem[];\n membersSnapshot: SpaceMembersSnapshot | null;\n}): Map<string, \"live now\"> {\n const statusByActorKey = new Map<string, \"live now\">();\n\n for (const human of input.membersSnapshot?.humans ?? []) {\n if (human.liveNow) {\n statusByActorKey.set(human.profileId, \"live now\");\n }\n }\n\n for (const agent of input.membersSnapshot?.agents ?? []) {\n if (agent.liveNow) {\n statusByActorKey.set(agent.profileId, \"live now\");\n }\n }\n\n const snapshotActorKeys = new Set(statusByActorKey.keys());\n\n for (const item of input.items) {\n if (!isPresenceTranscriptItem(item)) {\n continue;\n }\n const actorKey = resolvePresenceActorKey(item);\n if (!(actorKey && !snapshotActorKeys.has(actorKey))) {\n continue;\n }\n if (item.presenceAction === \"join\") {\n statusByActorKey.set(actorKey, \"live now\");\n }\n }\n\n return statusByActorKey;\n}\n\nfunction isImportantSystemNoticeEntry(input: {\n line: string;\n purpose?: string | null;\n}): boolean {\n return isImportantHumanSystemNotice(input);\n}\n\nfunction canCoalescePresenceTraceAcrossSingleForeignPresence(input: {\n current: TranscriptBlockViewState;\n foreign: TranscriptBlockViewState;\n next: TranscriptBlockViewState;\n}): input is {\n current: TranscriptPresenceTraceBlockViewState;\n foreign: TranscriptPresenceTraceBlockViewState;\n next: TranscriptPresenceTraceBlockViewState;\n} {\n if (\n !(\n input.current.kind === \"presence_trace_group\" &&\n input.foreign.kind === \"presence_trace_group\" &&\n input.next.kind === \"presence_trace_group\"\n )\n ) {\n return false;\n }\n\n if (input.current.actorKey !== input.next.actorKey) {\n return false;\n }\n\n if (input.current.actorKey === input.foreign.actorKey) {\n return false;\n }\n\n if (input.next.startTs < input.current.endTs) {\n return false;\n }\n\n if (input.next.startTs - input.current.endTs > PRESENCE_TRACE_MAX_GAP_MS) {\n return false;\n }\n\n if (input.next.endTs - input.current.startTs > PRESENCE_TRACE_MAX_SPAN_MS) {\n return false;\n }\n\n return true;\n}\n\nfunction mergePresenceTraceBlocks(\n current: TranscriptPresenceTraceBlockViewState,\n next: TranscriptPresenceTraceBlockViewState\n): TranscriptPresenceTraceBlockViewState {\n return {\n ...current,\n endTs: next.endTs,\n joinCount: current.joinCount + next.joinCount,\n leftCount: current.leftCount + next.leftCount,\n count: current.count + next.count,\n };\n}\n\nexport function renderTranscriptBlock(\n block: TranscriptBlockViewState,\n width: number\n): string[] {\n switch (block.kind) {\n case \"system_group\":\n return renderSystemClusterRowsFromSystemLines(block.lines, width);\n case \"presence_first_join_group\":\n return wrapBubbleLine(buildPresenceFirstJoinRowText(block), width);\n case \"presence_trace_group\":\n return renderPresenceTraceBlock(block, width);\n case \"membership_trace_group\":\n return renderMembershipTraceBlock(block, width);\n case \"plain_text_group\":\n return renderPlainTextBubbleGroup(block, width);\n default:\n return [];\n }\n}\n\nexport function renderTranscriptBlocks(\n blocks: readonly TranscriptBlockViewState[],\n width: number\n): string[] {\n const lines: string[] = [];\n const sections = buildTranscriptRenderSections(blocks);\n\n for (const [index, section] of sections.entries()) {\n const renderedSectionLines = renderTranscriptRenderSection(section, width);\n if (renderedSectionLines.length === 0) {\n continue;\n }\n if (lines.length > 0) {\n lines.push(\n ...renderTranscriptSectionGapLines({\n previous: sections[index - 1] ?? null,\n next: section,\n width,\n })\n );\n }\n lines.push(...renderedSectionLines);\n }\n\n return lines;\n}\n\nfunction buildTranscriptRenderSections(\n blocks: readonly TranscriptBlockViewState[]\n): TranscriptRenderSection[] {\n const sections: TranscriptRenderSection[] = [];\n\n for (const block of blocks) {\n if (block.kind === \"plain_text_group\") {\n sections.push({\n kind: \"plain_text_group\",\n block,\n });\n continue;\n }\n\n const currentSection = sections.at(-1);\n if (currentSection?.kind === \"system_cluster\") {\n sections[sections.length - 1] = {\n ...currentSection,\n blocks: [...currentSection.blocks, block],\n };\n continue;\n }\n\n sections.push({\n kind: \"system_cluster\",\n blocks: [block],\n });\n }\n\n return sections;\n}\n\nfunction renderTranscriptRenderSection(\n section: TranscriptRenderSection,\n width: number\n): string[] {\n if (section.kind === \"plain_text_group\") {\n return renderTranscriptBlock(section.block, width);\n }\n return renderTranscriptSystemCluster(section.blocks, width);\n}\n\nfunction resolveTranscriptSectionGapLines(input: {\n previous: TranscriptRenderSection | null;\n next: TranscriptRenderSection;\n}): number {\n if (\n input.previous?.kind === \"system_cluster\" ||\n input.next.kind === \"system_cluster\"\n ) {\n return 1;\n }\n return TRANSCRIPT_GROUP_GAP_LINES;\n}\n\nfunction renderTranscriptSectionGapLines(input: {\n previous: TranscriptRenderSection | null;\n next: TranscriptRenderSection;\n width: number;\n}): string[] {\n if (shouldRenderTranscriptSectionSeparator(input.previous, input.next)) {\n return [renderTranscriptSectionSeparatorLine(input.width)];\n }\n\n const gapLines: string[] = [];\n appendEmptyLines(\n gapLines,\n resolveTranscriptSectionGapLines({\n previous: input.previous,\n next: input.next,\n })\n );\n return gapLines;\n}\n\nfunction shouldRenderTranscriptSectionSeparator(\n previous: TranscriptRenderSection | null,\n next: TranscriptRenderSection\n): boolean {\n if (\n !(previous?.kind === \"plain_text_group\" && next.kind === \"plain_text_group\")\n ) {\n return false;\n }\n\n return previous.block.speakerProfileId !== next.block.speakerProfileId;\n}\n\nfunction renderTranscriptSectionSeparatorLine(width: number): string {\n const separator = pc.dim(\"-\");\n const availableWidth = Math.max(width, 1);\n const separatorWidth = stringWidth(\"-\");\n\n if (availableWidth <= separatorWidth) {\n return separator;\n }\n\n const leftPadding = Math.floor((availableWidth - separatorWidth) / 2);\n return `${\" \".repeat(leftPadding)}${separator}`;\n}\n\nfunction createTranscriptBlock(input: {\n groupKey: string;\n item: SpaceTranscriptItem;\n membersSnapshot?: SpaceMembersSnapshot | null;\n sessionProfile?: TranscriptSessionProfile | null;\n}): TranscriptBlockViewState {\n if (isPresenceTranscriptItem(input.item)) {\n return createTranscriptPresenceTraceBlock(\n input.item,\n input.membersSnapshot ?? null\n );\n }\n\n if (isMembershipNoticeTranscriptItem(input.item)) {\n return createTranscriptMembershipTraceBlock(\n input.item,\n input.membersSnapshot ?? null\n );\n }\n\n if (resolveTranscriptItemKind(input.item) === \"system_notice\") {\n const lines = splitTranscriptMultilineLines(input.item.line);\n return {\n kind: \"system_group\",\n groupKey: input.groupKey,\n lines,\n purposes: lines.map(() => input.item.systemPurpose ?? null),\n sourceNoticeCount: 1,\n };\n }\n\n const speakerKind = resolveTranscriptBubbleSpeakerKind({\n groupKey: input.groupKey,\n itemProfile: input.item.profile,\n membersSnapshot: input.membersSnapshot ?? null,\n sessionProfile: input.sessionProfile ?? null,\n });\n const speakerProfileIdentity = resolveTranscriptSpeakerIdentity({\n groupKey: input.groupKey,\n itemProfile: input.item.profile,\n membersSnapshot: input.membersSnapshot ?? null,\n speakerKind,\n sessionProfile: input.sessionProfile ?? null,\n });\n return {\n kind: \"plain_text_group\",\n groupKey: input.groupKey,\n spaceMembersSnapshot: input.membersSnapshot ?? null,\n speakerKind,\n highlightKind: resolveTranscriptBubbleHighlightKind({\n groupKey: input.groupKey,\n membersSnapshot: input.membersSnapshot ?? null,\n sessionProfile: input.sessionProfile ?? null,\n }),\n speakerProfileId: speakerProfileIdentity.profileId,\n speakerProfileName: speakerProfileIdentity.profileName,\n speakerOwnerUserId: speakerProfileIdentity.ownerUserId ?? null,\n speakerOwnerName: speakerProfileIdentity.ownerName ?? null,\n speakerAgentControllerRef:\n speakerProfileIdentity.agentControllerRef ?? null,\n speakerControllerDisplay: speakerProfileIdentity.controllerDisplay ?? null,\n speakerOwnerDisplay: speakerProfileIdentity.ownerDisplay ?? null,\n messages: [\n createTranscriptBubbleMessage({\n item: input.item,\n speakerIdentity: speakerProfileIdentity,\n spaceMembersSnapshot: input.membersSnapshot ?? null,\n }),\n ],\n };\n}\n\nfunction appendTranscriptItemToBlock(\n block: TranscriptBlockViewState,\n item: SpaceTranscriptItem\n): TranscriptBlockViewState | null {\n if (block.kind === \"system_group\") {\n if (resolveTranscriptItemKind(item) !== \"system_notice\") {\n return null;\n }\n return {\n ...block,\n lines: [...block.lines, ...splitTranscriptMultilineLines(item.line)],\n purposes: [\n ...block.purposes,\n ...splitTranscriptMultilineLines(item.line).map(\n () => item.systemPurpose ?? null\n ),\n ],\n sourceNoticeCount: block.sourceNoticeCount + 1,\n };\n }\n\n if (block.kind === \"plain_text_group\") {\n if (resolveTranscriptItemKind(item) !== \"message\") {\n return null;\n }\n return {\n ...block,\n messages: [\n ...block.messages,\n createTranscriptBubbleMessage({\n item,\n speakerIdentity: {\n profileId: block.speakerProfileId,\n profileName: block.speakerProfileName,\n kind: block.speakerKind,\n agentControllerRef: block.speakerAgentControllerRef ?? null,\n ownerUserId: block.speakerOwnerUserId ?? null,\n ownerName: block.speakerOwnerName ?? null,\n controllerDisplay: block.speakerControllerDisplay ?? null,\n ownerDisplay: block.speakerOwnerDisplay ?? null,\n },\n spaceMembersSnapshot: block.spaceMembersSnapshot ?? null,\n }),\n ],\n };\n }\n\n if (block.kind === \"membership_trace_group\") {\n return appendTranscriptItemToMembershipTraceBlock(block, item);\n }\n\n return appendTranscriptItemToPresenceBlock(block, item);\n}\n\nfunction appendTranscriptItemToPresenceBlock(\n block: TranscriptBlockViewState,\n item: SpaceTranscriptItem\n): TranscriptPresenceTraceBlockViewState | null {\n if (\n !(block.kind === \"presence_trace_group\" && isPresenceTranscriptItem(item))\n ) {\n return null;\n }\n const actorKey = resolvePresenceActorKey(item);\n if (!actorKey || actorKey !== block.actorKey) {\n return null;\n }\n if (typeof item.ts !== \"number\" || item.ts < block.endTs) {\n return null;\n }\n if (item.ts - block.endTs > PRESENCE_TRACE_MAX_GAP_MS) {\n return null;\n }\n if (item.ts - block.startTs > PRESENCE_TRACE_MAX_SPAN_MS) {\n return null;\n }\n return {\n ...block,\n endTs: item.ts,\n joinCount: block.joinCount + (item.presenceAction === \"join\" ? 1 : 0),\n leftCount: block.leftCount + (item.presenceAction === \"left\" ? 1 : 0),\n count: block.count + 1,\n };\n}\n\nfunction appendTranscriptItemToMembershipTraceBlock(\n block: TranscriptBlockViewState,\n item: SpaceTranscriptItem\n): TranscriptMembershipTraceBlockViewState | null {\n const notice = resolveMembershipNoticePayload(item);\n if (!(block.kind === \"membership_trace_group\" && notice)) {\n return null;\n }\n\n const actorKey = resolveMembershipActorKey(notice);\n if (!actorKey || actorKey !== block.actorKey) {\n return null;\n }\n if (notice.action !== block.action) {\n return null;\n }\n if (notice.ts < block.endTs) {\n return null;\n }\n if (notice.ts - block.endTs > MEMBERSHIP_TRACE_MAX_GAP_MS) {\n return null;\n }\n\n return {\n ...block,\n endTs: notice.ts,\n targets: [\n ...block.targets,\n buildTranscriptMembershipTraceTarget(\n notice,\n block.spaceMembersSnapshot ?? null\n ),\n ],\n };\n}\n\nfunction createTranscriptPresenceTraceBlock(\n item: SpaceTranscriptItem,\n membersSnapshot: SpaceMembersSnapshot | null\n): TranscriptPresenceTraceBlockViewState {\n const actorKey = resolvePresenceActorKey(item) || `presence:${item.line}`;\n const actorIdentity = resolvePresenceActorIdentity(item, membersSnapshot);\n const ts = typeof item.ts === \"number\" ? item.ts : 0;\n return {\n kind: \"presence_trace_group\",\n groupKey: item.groupKey,\n spaceMembersSnapshot: membersSnapshot,\n actorKey,\n actorProfileId: item.actorProfileId?.trim() || null,\n actorKind: item.actorKind ?? \"unknown\",\n actorAvatar: item.actorAvatar?.trim() || resolvePresenceActorAvatar(item),\n actorLabel: item.actorLabel?.trim() || \"unknown\",\n actorOwnerUserId: actorIdentity.ownerUserId,\n actorOwnerName: actorIdentity.ownerName,\n startTs: ts,\n endTs: ts,\n joinCount: item.presenceAction === \"join\" ? 1 : 0,\n leftCount: item.presenceAction === \"left\" ? 1 : 0,\n count: 1,\n };\n}\n\nfunction createTranscriptMembershipTraceBlock(\n item: SpaceTranscriptItem,\n membersSnapshot: SpaceMembersSnapshot | null\n): TranscriptMembershipTraceBlockViewState {\n const notice = resolveMembershipNoticePayload(item);\n if (!notice) {\n return {\n kind: \"membership_trace_group\",\n groupKey: item.groupKey,\n spaceMembersSnapshot: membersSnapshot,\n action: \"member_added\",\n actorKey: `membership:${item.line}`,\n actorProfileId: null,\n actorKind: \"unknown\",\n actorAvatar: \"👤\",\n actorLabel: \"unknown\",\n startTs: typeof item.ts === \"number\" ? item.ts : 0,\n endTs: typeof item.ts === \"number\" ? item.ts : 0,\n targets: [],\n };\n }\n\n const actorKey = resolveMembershipActorKey(notice);\n const actorIdentity = resolveMembershipActorIdentity(notice, membersSnapshot);\n return {\n kind: \"membership_trace_group\",\n groupKey: item.groupKey,\n spaceMembersSnapshot: membersSnapshot,\n action: notice.action,\n actorKey,\n actorProfileId: notice.actorProfileId?.trim() || null,\n actorKind: actorIdentity.actorKind,\n actorAvatar: actorIdentity.actorAvatar,\n actorLabel: actorIdentity.actorLabel,\n actorOwnerUserId: actorIdentity.ownerUserId,\n actorOwnerName: actorIdentity.ownerName,\n startTs: notice.ts,\n endTs: notice.ts,\n targets: [buildTranscriptMembershipTraceTarget(notice, membersSnapshot)],\n };\n}\n\nfunction buildTranscriptMembershipTraceTarget(\n notice: NonNullable<SpaceTranscriptItem[\"membershipNotice\"]>,\n membersSnapshot: SpaceMembersSnapshot | null\n): TranscriptMembershipTraceTargetViewState {\n if (!(notice.targetProfileId && membersSnapshot)) {\n return {\n profileId: notice.targetProfileId,\n kind: notice.targetProfileKind,\n label: notice.targetProfileLabel,\n mentionLabel: notice.mentionLabel,\n };\n }\n\n if (notice.targetProfileKind === \"agent\") {\n const agentSnapshot =\n membersSnapshot.agents.find(\n (member) => member.profileId === notice.targetProfileId\n ) ?? null;\n return {\n profileId: notice.targetProfileId,\n kind: notice.targetProfileKind,\n label: agentSnapshot?.profileName ?? notice.targetProfileLabel,\n mentionLabel:\n resolvePrimaryTranscriptMentionLabel({\n profileId: notice.targetProfileId,\n snapshot: membersSnapshot,\n }) ?? notice.mentionLabel,\n ownerUserId: agentSnapshot?.ownerUserId ?? null,\n ownerName: agentSnapshot?.ownerName ?? null,\n };\n }\n\n const humanSnapshot =\n membersSnapshot.humans.find(\n (member) => member.profileId === notice.targetProfileId\n ) ?? null;\n return {\n profileId: notice.targetProfileId,\n kind: notice.targetProfileKind,\n label: humanSnapshot?.profileName ?? notice.targetProfileLabel,\n mentionLabel: notice.mentionLabel,\n ownerUserId: humanSnapshot?.ownerUserId ?? null,\n ownerName: humanSnapshot?.ownerName ?? null,\n };\n}\n\nfunction createTranscriptBubbleMessage(input: {\n item: SpaceTranscriptItem;\n speakerIdentity: TranscriptSpeakerIdentity;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): TranscriptBubbleMessageViewState {\n const line = input.item.line;\n const rawLines = line.split(\"\\n\");\n const header = parseTranscriptBubbleHeader(rawLines[0] ?? \"\", input.item.ts);\n const structuredBodyLines = input.item.formattedMessage?.bodyLines ?? null;\n const structuredRelationLines =\n input.item.formattedMessage?.relationLines ?? null;\n const structuredMetaLines = input.item.formattedMessage?.metaLines ?? null;\n const detailLines = structuredBodyLines\n ? [...structuredBodyLines.slice(1), ...(structuredMetaLines ?? [])]\n : rawLines.slice(1);\n const { bodyDetailLines, metaLines } = structuredBodyLines\n ? {\n bodyDetailLines: [...structuredBodyLines.slice(1)],\n metaLines: [...(structuredMetaLines ?? [])],\n }\n : splitTranscriptBodyAndMetadataLines(detailLines);\n const bodyLines = structuredBodyLines\n ? [...structuredBodyLines]\n : [\n ...resolveTranscriptBubbleBodyLines({\n parsedBodyLine: header.bodyLine,\n primaryLine: rawLines[0] ?? \"\",\n speakerIdentity: input.speakerIdentity,\n }),\n ...bodyDetailLines,\n ];\n const headerBaseLeading = resolveTranscriptBubbleHeaderBaseLeading({\n parsedLeading: header.leading,\n speakerIdentity: input.speakerIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n const headerAuxLeading = buildTranscriptBubbleHeaderAuxLeading({\n speakerIdentity: input.speakerIdentity,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n const replyLine = resolveTranscriptBubbleReplyLine({\n replyRef: input.item.replyRef,\n replyWorkflowProjection: input.item.replyWorkflowProjection ?? null,\n membersSnapshot: input.spaceMembersSnapshot ?? null,\n });\n return {\n primaryLine: rawLines[0] ?? \"\",\n headerBaseLeading,\n headerAuxLeading,\n headerLeading: joinTranscriptBubbleHeaderLeading({\n baseLeading: headerBaseLeading,\n auxLeading: headerAuxLeading,\n typeBadge: input.item.formattedMessage?.headerBadge ?? null,\n presenceBadge: null,\n }),\n headerTypeBadge: input.item.formattedMessage?.headerBadge ?? null,\n headerPresenceBadge: null,\n headerTrailing: header.trailing,\n ...(replyLine ? { replyLine } : {}),\n relationLines: structuredRelationLines ? [...structuredRelationLines] : [],\n bodyLines,\n bodyDetailLines,\n metaLines,\n ...(input.item.formattedMessage?.threadIndicatorLine\n ? {\n threadIndicatorLine: input.item.formattedMessage.threadIndicatorLine,\n }\n : {}),\n detailLines,\n rawLines,\n };\n}\n\nfunction resolveTranscriptBubbleSpeakerKind(input: {\n groupKey: string;\n itemProfile?: SpaceTranscriptItem[\"profile\"];\n membersSnapshot: SpaceMembersSnapshot | null;\n sessionProfile: TranscriptSessionProfile | null;\n}): TranscriptBubbleSpeakerKind {\n if (\n input.itemProfile?.kind === \"human\" ||\n input.itemProfile?.kind === \"agent\"\n ) {\n return input.itemProfile.kind;\n }\n if (input.groupKey === SYSTEM_TRANSCRIPT_GROUP_KEY) {\n return \"unknown\";\n }\n\n const prefixedKind = resolveSpeakerKindFromGroupKey(input.groupKey);\n if (prefixedKind !== \"unknown\") {\n return prefixedKind;\n }\n\n const profileId = resolveProfileIdFromGroupKey(input.groupKey);\n if (!(profileId && input.membersSnapshot)) {\n if (profileId && input.sessionProfile?.profileId === profileId) {\n return input.sessionProfile.kind;\n }\n return \"unknown\";\n }\n if (\n input.membersSnapshot.humans.some(\n (member) => member.profileId === profileId\n )\n ) {\n return \"human\";\n }\n if (\n input.membersSnapshot.agents.some(\n (member) => member.profileId === profileId\n )\n ) {\n return \"agent\";\n }\n if (input.sessionProfile?.profileId === profileId) {\n return input.sessionProfile.kind;\n }\n return \"unknown\";\n}\n\nfunction resolveSpeakerKindFromGroupKey(\n groupKey: string\n): TranscriptBubbleSpeakerKind {\n const match = TRANSCRIPT_GROUP_KIND_PATTERN.exec(groupKey);\n return (match?.[1] as TranscriptBubbleSpeakerKind | undefined) ?? \"unknown\";\n}\n\nfunction resolveProfileIdFromGroupKey(groupKey: string): string {\n const prefix = \"profile-id:\";\n return groupKey.startsWith(prefix) ? groupKey.slice(prefix.length) : \"\";\n}\n\nfunction resolveTranscriptSpeakerIdentity(input: {\n groupKey: string;\n itemProfile?: SpaceTranscriptItem[\"profile\"];\n membersSnapshot: SpaceMembersSnapshot | null;\n speakerKind: TranscriptBubbleSpeakerKind;\n sessionProfile: TranscriptSessionProfile | null;\n}): TranscriptSpeakerIdentity {\n if (\n input.itemProfile &&\n input.itemProfile.kind !== \"unknown\" &&\n input.itemProfile.kind !== \"system\"\n ) {\n return {\n profileId: input.itemProfile.profileId,\n profileName: input.itemProfile.profileName,\n kind: input.itemProfile.kind,\n agentControllerRef: input.itemProfile.agentControllerRef,\n controllerDisplay: resolveControllerDisplayName(\n input.itemProfile.agentControllerRef\n ),\n ownerDisplay:\n input.itemProfile.kind === \"agent\"\n ? resolveAgentOwnerDisplay({\n ownerName: input.itemProfile.ownerName ?? null,\n ownerUserId: input.itemProfile.ownerUserId ?? null,\n profileName: input.itemProfile.profileName,\n })\n : null,\n ownerUserId: input.itemProfile.ownerUserId ?? null,\n ownerName: input.itemProfile.ownerName ?? null,\n };\n }\n const profileId = resolveProfileIdFromGroupKey(input.groupKey) || null;\n const humanSnapshot =\n input.membersSnapshot?.humans.find(\n (member) => member.profileId === profileId\n ) ?? null;\n const agentSnapshot =\n input.membersSnapshot?.agents.find(\n (member) => member.profileId === profileId\n ) ?? null;\n\n if (agentSnapshot) {\n return {\n profileId,\n profileName: agentSnapshot.profileName,\n kind: \"agent\",\n agentControllerRef: agentSnapshot.agentControllerRef,\n controllerDisplay: resolveControllerDisplayName(\n agentSnapshot.agentControllerRef\n ),\n ownerDisplay: resolveAgentOwnerDisplay(agentSnapshot),\n ownerUserId: agentSnapshot.ownerUserId,\n ownerName: agentSnapshot.ownerName,\n };\n }\n\n if (humanSnapshot) {\n return {\n profileId,\n profileName: humanSnapshot.profileName,\n kind: \"human\",\n ownerUserId: humanSnapshot.ownerUserId,\n ownerName: humanSnapshot.ownerName,\n };\n }\n\n if (profileId && input.sessionProfile?.profileId === profileId) {\n return {\n profileId,\n profileName: input.sessionProfile.profileName,\n kind: input.sessionProfile.kind,\n ownerUserId: input.sessionProfile.ownerUserId,\n ownerName: input.sessionProfile.ownerName,\n };\n }\n\n return {\n profileId,\n profileName: profileId || \"unknown\",\n kind: input.speakerKind,\n };\n}\n\nfunction renderPlainTextBubbleGroup(\n block: TranscriptPlainTextBlockViewState,\n width: number\n): string[] {\n const contentWidth = resolveBubbleContentWidth(width);\n const lines: string[] = [];\n\n for (const message of block.messages) {\n if (lines.length > 0) {\n appendEmptyLines(lines, TRANSCRIPT_BUBBLE_GAP_LINES);\n }\n lines.push(...renderTranscriptBubbleMessage(message, block, contentWidth));\n }\n\n return lines;\n}\n\nfunction renderTranscriptBubbleMessage(\n message: TranscriptBubbleMessageViewState,\n block: TranscriptPlainTextBlockViewState,\n contentWidth: number\n): string[] {\n const lines: string[] = [];\n appendBubblePaddingLines(\n lines,\n TRANSCRIPT_BUBBLE_VERTICAL_PADDING,\n block,\n contentWidth\n );\n\n const headerLines = renderTranscriptBubbleHeaderLines({\n leading: joinTranscriptBubbleHeaderLeading({\n baseLeading: message.headerBaseLeading ?? message.headerLeading,\n auxLeading: message.headerAuxLeading ?? null,\n typeBadge: message.headerTypeBadge ?? null,\n presenceBadge: message.headerPresenceBadge ?? null,\n }),\n trailing: message.headerTrailing,\n contentWidth,\n });\n appendRenderedBubbleLines(lines, headerLines, block, contentWidth);\n appendTranscriptBubbleReplyLines({\n block,\n contentWidth,\n headerLineCount: headerLines.length,\n lines,\n replyLine: message.replyLine,\n });\n appendTranscriptBubbleRelationLines({\n block,\n contentWidth,\n hasReplyLine: Boolean(message.replyLine),\n headerLineCount: headerLines.length,\n lines,\n relationLines: message.relationLines,\n });\n appendTranscriptBubbleBodyGap({\n block,\n bodyLineCount: message.bodyLines.length,\n contentWidth,\n hasReplyLine: Boolean(message.replyLine),\n hasRelationLines: message.relationLines.length > 0,\n headerLineCount: headerLines.length,\n lines,\n });\n appendTranscriptBubbleBodyLines({\n block,\n bodyLines: message.bodyLines,\n contentWidth,\n hasReplyLine: Boolean(message.replyLine),\n hasRelationLines: message.relationLines.length > 0,\n lines,\n });\n appendTranscriptBubbleMetaSection({\n block,\n contentWidth,\n lines,\n metaLines: buildTranscriptBubbleMetaLines(message.metaLines, block),\n });\n appendThreadIndicatorLine({\n block,\n contentWidth,\n lines,\n threadIndicatorLine: message.threadIndicatorLine,\n });\n\n appendBubblePaddingLines(\n lines,\n TRANSCRIPT_BUBBLE_VERTICAL_PADDING,\n block,\n contentWidth\n );\n return lines;\n}\n\nfunction appendRenderedBubbleLines(\n lines: string[],\n renderedLines: readonly string[],\n block: TranscriptPlainTextBlockViewState,\n contentWidth: number\n): void {\n for (const renderedLine of renderedLines) {\n lines.push(renderBubbleLine(renderedLine, block, contentWidth));\n }\n}\n\nfunction appendTranscriptBubbleReplyLines(input: {\n block: TranscriptPlainTextBlockViewState;\n contentWidth: number;\n headerLineCount: number;\n lines: string[];\n replyLine: string | null | undefined;\n}): void {\n if (!input.replyLine) {\n return;\n }\n\n if (input.headerLineCount > 0) {\n appendBubblePaddingLines(\n input.lines,\n TRANSCRIPT_BUBBLE_META_GAP_LINES,\n input.block,\n input.contentWidth\n );\n }\n\n appendWrappedBubbleLines(\n input.lines,\n [pc.dim(input.replyLine)],\n input.block,\n input.contentWidth\n );\n}\n\nfunction appendTranscriptBubbleBodyGap(input: {\n block: TranscriptPlainTextBlockViewState;\n bodyLineCount: number;\n contentWidth: number;\n hasReplyLine: boolean;\n hasRelationLines: boolean;\n headerLineCount: number;\n lines: string[];\n}): void {\n if (\n input.bodyLineCount === 0 ||\n input.headerLineCount === 0 ||\n input.hasReplyLine ||\n input.hasRelationLines\n ) {\n return;\n }\n\n appendBubblePaddingLines(\n input.lines,\n TRANSCRIPT_BUBBLE_META_GAP_LINES,\n input.block,\n input.contentWidth\n );\n}\n\nfunction appendTranscriptBubbleBodyLines(input: {\n block: TranscriptPlainTextBlockViewState;\n bodyLines: readonly string[];\n contentWidth: number;\n hasReplyLine: boolean;\n hasRelationLines: boolean;\n lines: string[];\n}): void {\n const bodyPrefixes = resolveTranscriptBubbleBodyPrefixes({\n hasReplyLine: input.hasReplyLine,\n hasRelationLines: input.hasRelationLines,\n });\n for (const [index, bodyLine] of input.bodyLines.entries()) {\n const wrappedBodyLines = wrapBubbleBodyLine({\n line: bodyLine,\n contentWidth: input.contentWidth,\n leadPrefix:\n index === 0\n ? bodyPrefixes.firstLinePrefix\n : bodyPrefixes.otherLinePrefix,\n continuationPrefix: bodyPrefixes.otherLinePrefix,\n });\n appendRenderedBubbleLines(\n input.lines,\n wrappedBodyLines,\n input.block,\n input.contentWidth\n );\n }\n}\n\nfunction appendTranscriptBubbleRelationLines(input: {\n block: TranscriptPlainTextBlockViewState;\n contentWidth: number;\n hasReplyLine: boolean;\n headerLineCount: number;\n lines: string[];\n relationLines: readonly string[];\n}): void {\n if (input.relationLines.length === 0) {\n return;\n }\n\n if (!input.hasReplyLine && input.headerLineCount > 0) {\n appendBubblePaddingLines(\n input.lines,\n TRANSCRIPT_BUBBLE_META_GAP_LINES,\n input.block,\n input.contentWidth\n );\n }\n\n appendWrappedBubbleLines(\n input.lines,\n input.relationLines.map((line) => pc.dim(line)),\n input.block,\n input.contentWidth\n );\n}\n\nfunction appendThreadIndicatorLine(input: {\n block: TranscriptPlainTextBlockViewState;\n contentWidth: number;\n lines: string[];\n threadIndicatorLine: string | null | undefined;\n}): void {\n if (!input.threadIndicatorLine) {\n return;\n }\n appendBubblePaddingLines(\n input.lines,\n TRANSCRIPT_BUBBLE_META_GAP_LINES,\n input.block,\n input.contentWidth\n );\n appendWrappedBubbleLines(\n input.lines,\n [pc.dim(input.threadIndicatorLine)],\n input.block,\n input.contentWidth\n );\n}\n\nfunction appendTranscriptBubbleMetaSection(input: {\n block: TranscriptPlainTextBlockViewState;\n contentWidth: number;\n lines: string[];\n metaLines: ReturnType<typeof buildTranscriptBubbleMetaLines>;\n}): void {\n if (\n input.metaLines.wrappedLines.length === 0 &&\n input.metaLines.unwrappedLines.length === 0\n ) {\n return;\n }\n\n appendBubblePaddingLines(\n input.lines,\n TRANSCRIPT_BUBBLE_META_GAP_LINES,\n input.block,\n input.contentWidth\n );\n appendWrappedBubbleLines(\n input.lines,\n input.metaLines.wrappedLines.map((line) => pc.dim(line)),\n input.block,\n input.contentWidth\n );\n appendRenderedBubbleLines(\n input.lines,\n input.metaLines.unwrappedLines.map((line) => pc.dim(line)),\n input.block,\n input.contentWidth\n );\n}\n\nfunction appendWrappedBubbleLines(\n lines: string[],\n sourceLines: readonly string[],\n block: TranscriptPlainTextBlockViewState,\n contentWidth: number\n): void {\n for (const sourceLine of sourceLines) {\n appendRenderedBubbleLines(\n lines,\n wrapBubbleLine(sourceLine, contentWidth),\n block,\n contentWidth\n );\n }\n}\n\nfunction renderTranscriptBubbleHeaderLines(input: {\n leading: string;\n trailing: string;\n contentWidth: number;\n}): string[] {\n if (!(input.leading || input.trailing)) {\n return [];\n }\n if (!input.trailing) {\n return wrapBubbleLine(input.leading, input.contentWidth);\n }\n if (!input.leading) {\n return [\n alignTranscriptBubbleHeaderTrailing(input.trailing, input.contentWidth),\n ];\n }\n\n const combinedWidth =\n measureVisibleWidth(input.leading) + measureVisibleWidth(input.trailing);\n if (combinedWidth <= input.contentWidth) {\n const spacingWidth = input.contentWidth - combinedWidth;\n return [`${input.leading}${\" \".repeat(spacingWidth)}${input.trailing}`];\n }\n\n return [\n ...wrapBubbleLine(input.leading, input.contentWidth),\n alignTranscriptBubbleHeaderTrailing(input.trailing, input.contentWidth),\n ];\n}\n\nfunction alignTranscriptBubbleHeaderTrailing(\n trailing: string,\n contentWidth: number\n): string {\n return `${\" \".repeat(Math.max(0, contentWidth - measureVisibleWidth(trailing)))}${trailing}`;\n}\n\nfunction buildTranscriptBubbleHeaderAuxLeading(input: {\n speakerIdentity: TranscriptSpeakerIdentity;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string | null {\n if (input.speakerIdentity.kind !== \"agent\") {\n return null;\n }\n\n const headerSegments: string[] = [];\n const controllerDisplay =\n input.speakerIdentity.controllerDisplay?.trim() || \"\";\n const ownerDisplay = input.speakerIdentity.ownerDisplay?.trim() || \"\";\n\n if (controllerDisplay) {\n headerSegments.push(\n pc.dim(\" · \"),\n colorizeAgentLabel(\n controllerDisplay,\n {\n agentControllerRef: input.speakerIdentity.agentControllerRef,\n profileId: input.speakerIdentity.profileId,\n profileName: input.speakerIdentity.profileName,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n )\n );\n }\n\n if (ownerDisplay) {\n headerSegments.push(\n pc.dim(\" · \"),\n pc.dim(\"by \"),\n colorizePersonLabel(\n ownerDisplay,\n {\n ownerUserId: input.speakerIdentity.ownerUserId,\n ownerName: input.speakerIdentity.ownerName,\n profileName: ownerDisplay,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n )\n );\n }\n\n return headerSegments.length > 0 ? headerSegments.join(\"\") : null;\n}\n\nfunction resolveTranscriptBubbleReplyLine(input: {\n replyRef?: SpaceTranscriptItem[\"replyRef\"];\n replyWorkflowProjection?:\n | SpaceTranscriptItem[\"replyWorkflowProjection\"]\n | null;\n membersSnapshot: SpaceMembersSnapshot | null;\n}): string | null {\n return buildHumanReplyWorkflowTranscriptCueLine({\n membersSnapshot: input.membersSnapshot,\n replyRef: input.replyRef,\n replyWorkflowProjection: input.replyWorkflowProjection ?? null,\n });\n}\n\nfunction joinTranscriptBubbleHeaderLeading(input: {\n baseLeading: string;\n auxLeading: string | null;\n typeBadge: TranscriptBubbleMessageViewState[\"headerTypeBadge\"];\n presenceBadge: TranscriptBubbleMessageViewState[\"headerPresenceBadge\"];\n}): string {\n const segments = [input.baseLeading];\n if (input.auxLeading) {\n segments.push(input.auxLeading);\n }\n if (input.typeBadge) {\n segments.push(\n pc.dim(\" · \"),\n renderTranscriptBubbleHeaderTypeBadge(input.typeBadge)\n );\n }\n if (input.presenceBadge) {\n segments.push(\n pc.dim(\" · \"),\n renderTranscriptBubbleHeaderPresenceBadge(input.presenceBadge)\n );\n }\n return segments.join(\"\");\n}\n\nfunction renderTranscriptBubbleHeaderTypeBadge(\n typeBadge: NonNullable<TranscriptBubbleMessageViewState[\"headerTypeBadge\"]>\n): string {\n return pc.cyan(typeBadge);\n}\n\nfunction renderTranscriptBubbleHeaderPresenceBadge(\n presenceBadge: NonNullable<\n TranscriptBubbleMessageViewState[\"headerPresenceBadge\"]\n >\n): string {\n return renderPositiveAccentText(presenceBadge);\n}\n\nfunction resolveTranscriptBubbleHeaderBaseLeading(input: {\n parsedLeading: string;\n speakerIdentity: TranscriptSpeakerIdentity;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string {\n if (input.speakerIdentity.kind === \"unknown\") {\n return input.parsedLeading;\n }\n\n const avatar = resolveTranscriptSpeakerAvatar(input.speakerIdentity.kind);\n const profileLabel =\n input.speakerIdentity.kind === \"agent\"\n ? colorizeAgentLabel(\n input.speakerIdentity.profileName,\n {\n agentControllerRef: input.speakerIdentity.agentControllerRef,\n profileId: input.speakerIdentity.profileId,\n profileName: input.speakerIdentity.profileName,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n )\n : colorizeDisplayProfileLabel({\n label: input.speakerIdentity.profileName,\n profileIdentity: {\n kind: \"human\",\n ownerName: input.speakerIdentity.ownerName,\n ownerUserId: input.speakerIdentity.ownerUserId,\n profileId: input.speakerIdentity.profileId,\n profileName: input.speakerIdentity.profileName,\n },\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n return avatar ? `${avatar} ${profileLabel}` : profileLabel;\n}\n\nfunction parseTranscriptBubbleHeader(\n line: string,\n ts?: number\n): {\n leading: string;\n trailing: string;\n bodyLine: string;\n} {\n const normalizedLine = normalizeTranscriptPrimaryLine(line);\n if (typeof ts === \"number\") {\n const timestamp = formatTranscriptBubbleTimestamp(ts);\n const timestampIndex = normalizedLine.lastIndexOf(timestamp);\n if (timestampIndex >= 0) {\n const leading = normalizedLine.slice(0, timestampIndex).trimEnd();\n const bodyLine = normalizedLine\n .slice(timestampIndex + timestamp.length)\n .replace(TRANSCRIPT_BODY_PREFIX_COLON_PATTERN, \"\");\n return {\n leading,\n trailing: pc.dim(timestamp),\n bodyLine,\n };\n }\n }\n const match = TRANSCRIPT_ANSI_HEADER_PATTERN.exec(normalizedLine);\n\n if (match?.groups) {\n return {\n leading: match.groups.leading ?? \"\",\n trailing: pc.dim(\n typeof ts === \"number\"\n ? formatTranscriptBubbleTimestamp(ts)\n : (match.groups.timestamp ?? \"\")\n ),\n bodyLine: match.groups.body ?? \"\",\n };\n }\n\n return {\n leading: \"\",\n trailing: ts ? pc.dim(formatTranscriptBubbleTimestamp(ts)) : \"\",\n bodyLine: normalizedLine,\n };\n}\n\nfunction resolveTranscriptBubbleBodyLines(input: {\n parsedBodyLine: string;\n primaryLine: string;\n speakerIdentity: TranscriptSpeakerIdentity;\n}): string[] {\n const normalizedBodyLine = input.parsedBodyLine.replace(\n TRANSCRIPT_BODY_PREFIX_COLON_PATTERN,\n \"\"\n );\n const strippedParsedBodyLine =\n input.speakerIdentity.kind === \"unknown\"\n ? normalizedBodyLine\n : stripTranscriptSpeakerHeaderFromBodyLine({\n line: normalizedBodyLine,\n speakerIdentity: input.speakerIdentity,\n });\n if (strippedParsedBodyLine) {\n return [strippedParsedBodyLine];\n }\n\n const normalizedPrimaryLine = normalizeTranscriptPrimaryLine(\n input.primaryLine\n );\n if (input.speakerIdentity.kind === \"unknown\") {\n return normalizedPrimaryLine ? [normalizedPrimaryLine] : [];\n }\n\n const strippedBodyLine = stripTranscriptSpeakerHeaderFromBodyLine({\n line: normalizedPrimaryLine,\n speakerIdentity: input.speakerIdentity,\n });\n return strippedBodyLine ? [strippedBodyLine] : [];\n}\n\nfunction stripTranscriptSpeakerHeaderFromBodyLine(input: {\n line: string;\n speakerIdentity: TranscriptSpeakerIdentity;\n}): string {\n const speakerHeaderPattern = buildTranscriptSpeakerHeaderPrefixPattern(\n input.speakerIdentity\n );\n const strippedLine = input.line.replace(speakerHeaderPattern, \"\");\n return strippedLine === input.line ? input.line : strippedLine;\n}\n\nfunction buildTranscriptSpeakerHeaderPrefixPattern(\n speakerIdentity: TranscriptSpeakerIdentity\n): RegExp {\n const timestampPattern = \"\\\\d{8}\\\\s\\\\d{2}:\\\\d{2}(?::\\\\d{2})?\";\n const avatar = resolveTranscriptSpeakerAvatar(speakerIdentity.kind);\n const avatarPattern = avatar ? `${escapeRegExp(avatar)}\\\\s+` : \"\";\n const profileNamePattern = `${ANSI_ESCAPE_PATTERN}${escapeRegExp(\n speakerIdentity.profileName\n )}${ANSI_ESCAPE_PATTERN}`;\n return new RegExp(\n `^${avatarPattern}${profileNamePattern}\\\\s+${ANSI_ESCAPE_PATTERN}${timestampPattern}${ANSI_ESCAPE_PATTERN}:\\\\s*`,\n \"u\"\n );\n}\n\nfunction resolveTranscriptSpeakerAvatar(\n kind: TranscriptBubbleSpeakerKind\n): string {\n if (kind === \"agent\") {\n return \"🤖\";\n }\n if (kind === \"human\") {\n return \"👤\";\n }\n return \"\";\n}\n\nfunction escapeRegExp(value: string): string {\n return value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\nfunction formatTranscriptBubbleTimestamp(ts: number): string {\n const date = new Date(ts);\n const year = String(date.getFullYear());\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n const hour = String(date.getHours()).padStart(2, \"0\");\n const minute = String(date.getMinutes()).padStart(2, \"0\");\n const second = String(date.getSeconds()).padStart(2, \"0\");\n return `${year}${month}${day} ${hour}:${minute}:${second}`;\n}\n\nfunction renderPresenceTraceBlock(\n block: TranscriptPresenceTraceBlockViewState,\n width: number\n): string[] {\n return wrapBubbleLine(buildPresenceTraceRowText(block), width);\n}\n\nfunction buildPresenceFirstJoinRows(\n block: TranscriptPresenceFirstJoinBlockViewState\n): string[] {\n return [buildPresenceFirstJoinRowText(block)];\n}\n\nfunction buildPresenceFirstJoinRowText(\n block: TranscriptPresenceFirstJoinBlockViewState\n): string {\n return [\n formatPresenceTraceDateTime(block.ts),\n \"·\",\n buildSystemActorLabel({\n actorAvatar: block.actorAvatar,\n actorLabel: block.actorLabel,\n actorKind: block.actorKind,\n actorProfileId: block.actorProfileId,\n actorOwnerUserId: block.actorOwnerUserId,\n actorOwnerName: block.actorOwnerName,\n spaceMembersSnapshot: null,\n }),\n \"·\",\n PRESENCE_FIRST_JOIN_LABEL,\n ].join(\" \");\n}\n\nfunction buildPresenceTraceRowText(\n block: TranscriptPresenceTraceBlockViewState\n): string {\n const timeLabel = resolvePresenceTraceTimeLabel(block);\n const actionLabel =\n block.count <= 1\n ? resolveSinglePresenceActionLabel(block)\n : `${resolvePresenceTraceSummaryActionLabel(block)} ×${block.count}`;\n return [\n timeLabel,\n \"·\",\n buildSystemActorLabel({\n actorAvatar: block.actorAvatar,\n actorLabel: block.actorLabel,\n actorKind: block.actorKind,\n actorProfileId: block.actorProfileId,\n actorOwnerUserId: block.actorOwnerUserId,\n actorOwnerName: block.actorOwnerName,\n spaceMembersSnapshot: block.spaceMembersSnapshot ?? null,\n }),\n \"·\",\n actionLabel,\n ].join(\" \");\n}\n\nfunction renderMembershipTraceBlock(\n block: TranscriptMembershipTraceBlockViewState,\n width: number\n): string[] {\n const lines = wrapBubbleLine(\n buildMembershipTraceSummaryRowText(block),\n width\n );\n const detailLine = buildMembershipTraceDetailLine(block);\n if (!detailLine) {\n return lines;\n }\n return [...lines, ...wrapBubbleLine(detailLine, width)];\n}\n\nfunction buildMembershipTraceSummaryRowText(\n block: TranscriptMembershipTraceBlockViewState\n): string {\n return [\n resolvePresenceTraceTimeLabel({\n startTs: block.startTs,\n endTs: block.endTs,\n count: block.targets.length,\n }),\n \"·\",\n buildSystemActorLabel({\n actorAvatar: block.actorAvatar,\n actorLabel: block.actorLabel,\n actorKind: block.actorKind,\n actorProfileId: block.actorProfileId,\n actorOwnerUserId: block.actorOwnerUserId,\n actorOwnerName: block.actorOwnerName,\n spaceMembersSnapshot: block.spaceMembersSnapshot ?? null,\n }),\n \"·\",\n buildMembershipTraceSummaryActionLabel(block.action, block.targets),\n ].join(\" \");\n}\n\nfunction buildMembershipTraceRows(\n block: TranscriptMembershipTraceBlockViewState\n): string[] {\n const lines = [buildMembershipTraceSummaryRowText(block)];\n const detailLine = buildMembershipTraceDetailLine(block);\n if (detailLine) {\n lines.push(detailLine);\n }\n return lines;\n}\n\nfunction buildMembershipTraceSummaryActionLabel(\n action: TranscriptMembershipTraceBlockViewState[\"action\"],\n targets: readonly TranscriptMembershipTraceTargetViewState[]\n): string {\n const actionLabel =\n action === \"member_removed\"\n ? MEMBERSHIP_TRACE_REMOVED_LABEL\n : MEMBERSHIP_TRACE_ADDED_LABEL;\n const count = targets.length;\n const humanCount = targets.filter((target) => target.kind === \"human\").length;\n const agentCount = targets.filter((target) => target.kind === \"agent\").length;\n\n if (count === 1) {\n if (agentCount === 1) {\n return `${actionLabel} 1 agent`;\n }\n if (humanCount === 1) {\n return `${actionLabel} 1 human`;\n }\n return `${actionLabel} 1 member`;\n }\n\n if (count > 1 && agentCount === count) {\n return `${actionLabel} ${String(count)} agents`;\n }\n if (count > 1 && humanCount === count) {\n return `${actionLabel} ${String(count)} humans`;\n }\n return `${actionLabel} ${String(count)} members`;\n}\n\nfunction buildMembershipTraceDetailLine(\n block: TranscriptMembershipTraceBlockViewState\n): string {\n const segments = block.targets\n .map((target) =>\n renderMembershipTraceTargetLabel(\n target,\n block.spaceMembersSnapshot ?? null\n )\n )\n .filter((segment) => segment.length > 0);\n return segments.join(\" · \");\n}\n\nfunction renderMembershipTraceTargetLabel(\n target: TranscriptMembershipTraceTargetViewState,\n _spaceMembersSnapshot: SpaceMembersSnapshot | null\n): string {\n if (target.kind === \"agent\" && target.mentionLabel) {\n return `@${target.label}`;\n }\n\n return target.label;\n}\n\nfunction resolvePrimaryTranscriptMentionLabel(input: {\n profileId: string | null;\n snapshot: SpaceMembersSnapshot | null;\n}): string | null {\n return resolvePrimarySpaceMentionLabel({\n profileId: input.profileId,\n snapshot: input.snapshot,\n });\n}\n\nfunction buildSystemActorLabel(input: {\n actorAvatar: string;\n actorLabel: string;\n actorKind: TranscriptBubbleSpeakerKind;\n actorProfileId: string | null;\n actorOwnerUserId?: string | null;\n actorOwnerName?: string | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot | null;\n}): string {\n const actorPrefix = input.actorAvatar ? `${input.actorAvatar} ` : \"\";\n return `${actorPrefix}${input.actorLabel}`;\n}\n\nfunction resolvePresenceTraceTimeLabel(block: {\n startTs: number;\n endTs: number;\n count?: number;\n}): string {\n const startDateLabel = formatPresenceTraceDate(block.startTs);\n const startClockLabel = formatPresenceTraceClock(block.startTs);\n const endDateLabel = formatPresenceTraceDate(block.endTs);\n const endClockLabel = formatPresenceTraceClock(block.endTs);\n\n if (\n (block.count ?? 1) <= 1 ||\n (startDateLabel === endDateLabel && startClockLabel === endClockLabel)\n ) {\n return `${startDateLabel} ${startClockLabel}`;\n }\n if (startDateLabel === endDateLabel) {\n return `${startDateLabel} ${startClockLabel}–${endClockLabel}`;\n }\n return `${startDateLabel} ${startClockLabel}–${endDateLabel} ${endClockLabel}`;\n}\n\nfunction formatPresenceTraceDateTime(ts: number): string {\n return `${formatPresenceTraceDate(ts)} ${formatPresenceTraceClock(ts)}`;\n}\n\nfunction formatPresenceTraceDate(ts: number): string {\n const date = new Date(ts);\n const year = `${date.getFullYear()}`;\n const month = `${date.getMonth() + 1}`.padStart(2, \"0\");\n const day = `${date.getDate()}`.padStart(2, \"0\");\n return `${year}${month}${day}`;\n}\n\nfunction formatPresenceTraceClock(ts: number): string {\n const date = new Date(ts);\n const hours = `${date.getHours()}`.padStart(2, \"0\");\n const minutes = `${date.getMinutes()}`.padStart(2, \"0\");\n return `${hours}:${minutes}`;\n}\n\nfunction resolveSinglePresenceActionLabel(\n block: TranscriptPresenceTraceBlockViewState\n): string {\n return block.leftCount > 0\n ? PRESENCE_TRACE_LEFT_LABEL\n : PRESENCE_TRACE_JOINED_LABEL;\n}\n\nfunction resolvePresenceTraceSummaryActionLabel(\n block: TranscriptPresenceTraceBlockViewState\n): string {\n if (block.joinCount > 0 && block.leftCount > 0) {\n return PRESENCE_TRACE_JOIN_LEFT_LABEL;\n }\n if (block.joinCount > 0) {\n return PRESENCE_TRACE_JOIN_LABEL;\n }\n return PRESENCE_TRACE_LEFT_LABEL;\n}\n\nfunction wrapBubbleLine(line: string, contentWidth: number): string[] {\n const wrapped = wrapAnsi(line, contentWidth, {\n hard: true,\n trim: false,\n wordWrap: true,\n });\n return wrapped.split(\"\\n\");\n}\n\nfunction wrapBubbleBodyLine(input: {\n line: string;\n contentWidth: number;\n leadPrefix: string;\n continuationPrefix: string;\n}): string[] {\n const leadPrefix =\n input.leadPrefix === TRANSCRIPT_BUBBLE_BODY_CONTINUATION_PREFIX ||\n input.leadPrefix ===\n TRANSCRIPT_BUBBLE_REPLY_CONNECTED_BODY_CONTINUATION_PREFIX\n ? input.leadPrefix\n : renderOpenMeldBrandAccent(input.leadPrefix);\n const prefixWidth = stringWidth(input.leadPrefix);\n const prefixedContentWidth = Math.max(1, input.contentWidth - prefixWidth);\n const wrapped = wrapAnsi(input.line, prefixedContentWidth, {\n hard: true,\n trim: false,\n wordWrap: true,\n }).split(\"\\n\");\n\n return wrapped.map((wrappedLine, index) =>\n index === 0\n ? `${leadPrefix}${wrappedLine}`\n : `${input.continuationPrefix}${wrappedLine}`\n );\n}\n\nfunction resolveTranscriptBubbleBodyPrefixes(input: {\n hasReplyLine: boolean;\n hasRelationLines: boolean;\n}): {\n firstLinePrefix: string;\n otherLinePrefix: string;\n} {\n return input.hasReplyLine && !input.hasRelationLines\n ? {\n firstLinePrefix: TRANSCRIPT_BUBBLE_REPLY_CONNECTED_BODY_PREFIX,\n otherLinePrefix:\n TRANSCRIPT_BUBBLE_REPLY_CONNECTED_BODY_CONTINUATION_PREFIX,\n }\n : {\n firstLinePrefix: TRANSCRIPT_BUBBLE_BODY_PREFIX,\n otherLinePrefix: TRANSCRIPT_BUBBLE_BODY_CONTINUATION_PREFIX,\n };\n}\n\nfunction renderBubbleLine(\n line: string,\n block: TranscriptPlainTextBlockViewState,\n contentWidth: number\n): string {\n const visibleWidth = measureVisibleWidth(line);\n const trailingPaddingWidth = Math.max(0, contentWidth - visibleWidth);\n const bubbleContent = ` ${line}${\" \".repeat(trailingPaddingWidth)} `;\n const bubbleBackground = resolveBubbleBackground(block);\n if (!bubbleBackground) {\n return `${resolveBubbleIndent()}${bubbleContent}`;\n }\n return `${resolveBubbleIndent()}${bubbleBackground}${bubbleContent}${ANSI_BACKGROUND_RESET}`;\n}\n\nfunction renderBubblePaddingLine(\n block: TranscriptPlainTextBlockViewState,\n contentWidth: number\n): string {\n return renderBubbleLine(\"\", block, contentWidth);\n}\n\nfunction appendBubblePaddingLines(\n lines: string[],\n count: number,\n block: TranscriptPlainTextBlockViewState,\n contentWidth: number\n): void {\n for (let index = 0; index < count; index += 1) {\n lines.push(renderBubblePaddingLine(block, contentWidth));\n }\n}\n\nfunction normalizeTranscriptPrimaryLine(line: string): string {\n return line.startsWith(\"- \") ? line.slice(2) : line;\n}\n\nfunction buildTranscriptBubbleMetaLines(\n detailLines: readonly string[],\n block: TranscriptPlainTextBlockViewState\n): {\n wrappedLines: readonly string[];\n unwrappedLines: readonly string[];\n} {\n const wrappedSegments: string[] = [];\n const unwrappedLines: string[] = [];\n\n for (const detailLine of detailLines) {\n const normalizedLine = stripTranscriptBubbleMetaSegment(detailLine, block);\n if (!normalizedLine) {\n continue;\n }\n if (isTranscriptOriginMetaLine(normalizedLine)) {\n unwrappedLines.push(normalizedLine);\n continue;\n }\n wrappedSegments.push(normalizedLine);\n }\n\n return {\n wrappedLines:\n wrappedSegments.length > 0 ? [wrappedSegments.join(\" · \")] : [],\n unwrappedLines,\n };\n}\n\nfunction stripTranscriptBubbleMetaSegment(\n line: string,\n block: TranscriptPlainTextBlockViewState\n): string {\n const normalizedLine = stripVTControlCharacters(line).trim();\n if (!normalizedLine) {\n return \"\";\n }\n\n const withoutAgentVia = normalizedLine.replace(\n TRANSCRIPT_AGENT_VIA_META_PREFIX_PATTERN,\n \"\"\n );\n if (block.speakerKind === \"human\" && withoutAgentVia.startsWith(\"owns:\")) {\n return \"\";\n }\n return withoutAgentVia;\n}\n\nfunction isTranscriptOriginMetaLine(line: string): boolean {\n return stripVTControlCharacters(line).trim().startsWith(\"origin:\");\n}\n\nfunction splitTranscriptBodyAndMetadataLines(detailLines: readonly string[]): {\n bodyDetailLines: readonly string[];\n metaLines: readonly string[];\n} {\n if (detailLines.length === 0) {\n return {\n bodyDetailLines: [],\n metaLines: [],\n };\n }\n\n const trailingMetaLines: string[] = [];\n let sawPrimaryMetadataLine = false;\n let boundaryIndex = detailLines.length;\n\n for (let index = detailLines.length - 1; index >= 0; index -= 1) {\n const line = detailLines[index] ?? \"\";\n if (isTranscriptSecondaryMetadataLine(line)) {\n trailingMetaLines.unshift(line);\n boundaryIndex = index;\n continue;\n }\n if (isTranscriptPrimaryMetadataLine(line)) {\n trailingMetaLines.unshift(line);\n boundaryIndex = index;\n sawPrimaryMetadataLine = true;\n continue;\n }\n break;\n }\n\n if (!sawPrimaryMetadataLine) {\n return {\n bodyDetailLines: [...detailLines],\n metaLines: [],\n };\n }\n\n return {\n bodyDetailLines: detailLines.slice(0, boundaryIndex),\n metaLines: trailingMetaLines,\n };\n}\n\nfunction isTranscriptPrimaryMetadataLine(line: string): boolean {\n const normalized = stripVTControlCharacters(line).trim();\n return TRANSCRIPT_PRIMARY_METADATA_LINE_PATTERN.test(normalized);\n}\n\nfunction isTranscriptSecondaryMetadataLine(line: string): boolean {\n const normalized = stripVTControlCharacters(line).trim();\n return TRANSCRIPT_SECONDARY_METADATA_LINE_PATTERN.test(normalized);\n}\n\nfunction resolveBubbleIndent(): string {\n return TRANSCRIPT_BUBBLE_GROUP_INDENT > 0\n ? \" \".repeat(TRANSCRIPT_BUBBLE_GROUP_INDENT)\n : \"\";\n}\n\nfunction resolveBubbleBackground(\n block: TranscriptPlainTextBlockViewState\n): string {\n if (block.speakerKind === \"human\") {\n return TRANSCRIPT_HUMAN_BUBBLE_BACKGROUND;\n }\n\n if (\n block.highlightKind === \"neutral\" ||\n block.highlightKind === \"self_human\"\n ) {\n return TRANSCRIPT_NEUTRAL_BUBBLE_BACKGROUND;\n }\n\n const surfaceColor = resolveAgentSurfaceRgb(\n block.speakerProfileName,\n {\n agentControllerRef: block.speakerAgentControllerRef,\n profileId: block.speakerProfileId,\n profileName: block.speakerProfileName,\n },\n {\n spaceMembersSnapshot: block.spaceMembersSnapshot ?? null,\n }\n );\n return buildAnsiBackgroundColor([\n surfaceColor.r,\n surfaceColor.g,\n surfaceColor.b,\n ]);\n}\n\nfunction resolveTranscriptBubbleHighlightKind(input: {\n groupKey: string;\n membersSnapshot: SpaceMembersSnapshot | null;\n sessionProfile: TranscriptSessionProfile | null;\n}): TranscriptBubbleHighlightKind {\n const profileId = resolveProfileIdFromGroupKey(input.groupKey);\n if (!(profileId && input.sessionProfile)) {\n return \"neutral\";\n }\n\n if (input.sessionProfile.kind === \"agent\") {\n return profileId === input.sessionProfile.profileId\n ? \"owned_agent\"\n : \"neutral\";\n }\n\n if (profileId === input.sessionProfile.profileId) {\n return \"self_human\";\n }\n\n const ownedAgent = resolveOwnedAgentSnapshot({\n membersSnapshot: input.membersSnapshot,\n profileId,\n sessionProfile: input.sessionProfile,\n });\n return ownedAgent ? \"owned_agent\" : \"neutral\";\n}\n\nfunction resolveOwnedAgentSnapshot(input: {\n membersSnapshot: SpaceMembersSnapshot | null;\n profileId: string;\n sessionProfile: TranscriptSessionProfile;\n}) {\n const agentSnapshot =\n input.membersSnapshot?.agents.find(\n (member) => member.profileId === input.profileId\n ) ?? null;\n if (!agentSnapshot) {\n return null;\n }\n\n const currentOwnerUserId = normalizeTranscriptOwnerValue(\n input.sessionProfile.ownerUserId\n );\n const agentOwnerUserId = normalizeTranscriptOwnerValue(\n agentSnapshot.ownerUserId\n );\n if (currentOwnerUserId && agentOwnerUserId) {\n return currentOwnerUserId === agentOwnerUserId ? agentSnapshot : null;\n }\n\n const currentOwnerName = normalizeTranscriptOwnerValue(\n input.sessionProfile.ownerName\n );\n const agentOwnerName = normalizeTranscriptOwnerValue(agentSnapshot.ownerName);\n if (currentOwnerName && agentOwnerName) {\n return currentOwnerName === agentOwnerName ? agentSnapshot : null;\n }\n\n return null;\n}\n\nfunction normalizeTranscriptOwnerValue(\n value: string | null | undefined\n): string {\n return value?.trim() ?? \"\";\n}\n\nfunction resolveAgentOwnerDisplay(agentSnapshot: {\n ownerName?: string | null;\n ownerUserId?: string | null;\n profileName?: string;\n}): string {\n return (\n agentSnapshot.ownerName?.trim() || agentSnapshot.ownerUserId?.trim() || \"\"\n );\n}\n\nfunction measureVisibleWidth(value: string): number {\n return stringWidth(stripVTControlCharacters(value));\n}\n\nfunction buildAnsiBackgroundColor(\n rgb: readonly [number, number, number]\n): string {\n const [red, green, blue] = rgb;\n return `\\u001B[48;2;${String(red)};${String(green)};${String(blue)}m`;\n}\n\nfunction resolveBubbleContentWidth(width: number): number {\n const normalizedWidth = Number.isFinite(width) && width > 0 ? width : 80;\n return Math.max(\n 1,\n normalizedWidth -\n TRANSCRIPT_BUBBLE_GROUP_INDENT -\n TRANSCRIPT_BUBBLE_HORIZONTAL_PADDING * 2\n );\n}\n\nfunction appendEmptyLines(lines: string[], count: number): void {\n for (let index = 0; index < count; index += 1) {\n lines.push(\"\");\n }\n}\n\nfunction resolveTranscriptItemKind(\n item: SpaceTranscriptItem\n): NonNullable<SpaceTranscriptItem[\"kind\"]> {\n if (item.kind) {\n return item.kind;\n }\n return item.groupKey === SYSTEM_TRANSCRIPT_GROUP_KEY\n ? \"system_notice\"\n : \"message\";\n}\n\nfunction isPresenceTranscriptItem(item: SpaceTranscriptItem): boolean {\n return resolveTranscriptItemKind(item) === \"presence\";\n}\n\nfunction isMembershipNoticeTranscriptItem(item: SpaceTranscriptItem): boolean {\n return (\n resolveTranscriptItemKind(item) === \"membership_notice\" &&\n resolveMembershipNoticePayload(item) !== null\n );\n}\n\nfunction resolveMembershipNoticePayload(\n item: SpaceTranscriptItem\n): NonNullable<SpaceTranscriptItem[\"membershipNotice\"]> | null {\n return item.membershipNotice ?? null;\n}\n\nfunction resolvePresenceActorAvatar(item: SpaceTranscriptItem): string {\n if (item.actorKind === \"agent\") {\n return \"🤖\";\n }\n if (item.actorKind === \"human\") {\n return \"👤\";\n }\n return item.actorAvatar?.trim() || \"👤\";\n}\n\nfunction resolvePresenceActorKey(item: SpaceTranscriptItem): string {\n if (item.actorProfileId?.trim()) {\n return item.actorProfileId.trim();\n }\n const label = item.actorLabel?.trim();\n if (label) {\n return `${item.actorKind ?? \"unknown\"}:${label}`;\n }\n return \"\";\n}\n\nfunction resolvePresenceActorIdentity(\n item: SpaceTranscriptItem,\n membersSnapshot: SpaceMembersSnapshot | null\n): {\n ownerUserId?: string | null;\n ownerName?: string | null;\n} {\n const matchedSnapshot = resolvePresenceActorMemberSnapshot(\n item,\n membersSnapshot\n );\n if (!matchedSnapshot) {\n return {};\n }\n\n return {\n ownerUserId: matchedSnapshot.ownerUserId,\n ownerName: matchedSnapshot.ownerName,\n };\n}\n\nfunction resolvePresenceActorFirstEnteredAtMs(\n item: SpaceTranscriptItem,\n membersSnapshot: SpaceMembersSnapshot | null\n): number | null {\n const firstEnteredAt =\n resolvePresenceActorMemberSnapshot(item, membersSnapshot)?.firstEnteredAt ??\n null;\n if (!firstEnteredAt) {\n return null;\n }\n\n const parsed = Date.parse(firstEnteredAt);\n return Number.isFinite(parsed) ? parsed : null;\n}\n\nfunction resolvePresenceActorMemberSnapshot(\n item: SpaceTranscriptItem,\n membersSnapshot: SpaceMembersSnapshot | null\n):\n | SpaceMembersSnapshot[\"humans\"][number]\n | SpaceMembersSnapshot[\"agents\"][number]\n | null {\n if (!membersSnapshot) {\n return null;\n }\n\n const actorProfileId = item.actorProfileId?.trim() || \"\";\n const actorLabel = item.actorLabel?.trim().toLowerCase() || \"\";\n\n if (item.actorKind === \"agent\") {\n return (\n membersSnapshot.agents.find(\n (member) =>\n member.profileId === actorProfileId ||\n (!actorProfileId &&\n actorLabel.length > 0 &&\n member.profileName.trim().toLowerCase() === actorLabel)\n ) ?? null\n );\n }\n\n if (item.actorKind === \"human\") {\n return (\n membersSnapshot.humans.find(\n (member) =>\n member.profileId === actorProfileId ||\n (!actorProfileId &&\n actorLabel.length > 0 &&\n member.profileName.trim().toLowerCase() === actorLabel)\n ) ?? null\n );\n }\n\n return null;\n}\n\nfunction resolveMembershipActorKey(\n notice: NonNullable<SpaceTranscriptItem[\"membershipNotice\"]>\n): string {\n if (notice.actorProfileId?.trim()) {\n return notice.actorProfileId.trim();\n }\n const label = notice.actorLabel.trim();\n if (label) {\n return `${notice.actorKind}:${label}`;\n }\n return \"\";\n}\n\nfunction resolveMembershipActorIdentity(\n notice: NonNullable<SpaceTranscriptItem[\"membershipNotice\"]>,\n membersSnapshot: SpaceMembersSnapshot | null\n): {\n actorKind: TranscriptBubbleSpeakerKind;\n actorAvatar: string;\n actorLabel: string;\n ownerUserId?: string | null;\n ownerName?: string | null;\n} {\n const actorProfileId = notice.actorProfileId?.trim();\n const actorLabel = notice.actorLabel.trim() || \"unknown\";\n\n if (actorProfileId && membersSnapshot) {\n if (notice.actorKind === \"agent\") {\n const agentSnapshot =\n membersSnapshot.agents.find(\n (member) => member.profileId === actorProfileId\n ) ?? null;\n if (agentSnapshot) {\n return {\n actorKind: \"agent\",\n actorAvatar: \"🤖\",\n actorLabel: agentSnapshot.profileName,\n ownerUserId: agentSnapshot.ownerUserId,\n ownerName: agentSnapshot.ownerName,\n };\n }\n }\n\n if (notice.actorKind === \"human\") {\n const humanSnapshot =\n membersSnapshot.humans.find(\n (member) => member.profileId === actorProfileId\n ) ?? null;\n if (humanSnapshot) {\n return {\n actorKind: \"human\",\n actorAvatar: \"👤\",\n actorLabel: humanSnapshot.profileName,\n ownerUserId: humanSnapshot.ownerUserId,\n ownerName: humanSnapshot.ownerName,\n };\n }\n }\n }\n\n return {\n actorKind: notice.actorKind,\n actorAvatar: notice.actorKind === \"agent\" ? \"🤖\" : \"👤\",\n actorLabel,\n };\n}\n\nfunction renderTranscriptSystemCluster(\n blocks: readonly TranscriptSystemClusterBlockViewState[],\n width: number\n): string[] {\n const contentWidth = resolveSystemClusterContentWidth(width);\n const renderedLines: string[] = [];\n\n for (const block of blocks) {\n const clusterRows = renderSystemClusterBlockRows(block, contentWidth);\n renderedLines.push(\n ...clusterRows.map((line) => renderSystemClusterLine(line, contentWidth))\n );\n }\n\n return renderedLines;\n}\n\nfunction renderSystemClusterBlockRows(\n block: TranscriptSystemClusterBlockViewState,\n contentWidth: number\n): string[] {\n if (block.kind === \"presence_first_join_group\") {\n return wrapBubbleLine(buildPresenceFirstJoinRowText(block), contentWidth);\n }\n if (block.kind === \"presence_trace_group\") {\n return wrapBubbleLine(buildPresenceTraceRowText(block), contentWidth);\n }\n if (block.kind === \"membership_trace_group\") {\n return renderMembershipTraceBlock(block, contentWidth);\n }\n return renderSystemClusterRowsFromSystemLines(block.lines, contentWidth);\n}\n\nfunction buildSystemClusterRowsFromSystemLines(\n lines: readonly string[]\n): string[] {\n const renderedLines: string[] = [];\n\n for (const line of lines) {\n const normalizedLines = splitTranscriptMultilineLines(line);\n for (const normalizedLine of normalizedLines) {\n if (isConnectedAsSystemLine(normalizedLine)) {\n continue;\n }\n renderedLines.push(stripVTControlCharacters(normalizedLine).trim());\n }\n }\n\n return renderedLines;\n}\n\nfunction renderSystemClusterRowsFromSystemLines(\n lines: readonly string[],\n contentWidth: number\n): string[] {\n return buildSystemClusterRowsFromSystemLines(lines).flatMap((line) =>\n wrapBubbleLine(line, contentWidth)\n );\n}\n\nfunction splitTranscriptMultilineLines(value: string): string[] {\n return stripVTControlCharacters(value)\n .split(\"\\n\")\n .map((line) => line.trimEnd())\n .filter((line) => line.trim().length > 0);\n}\n\nfunction isConnectedAsSystemLine(line: string): boolean {\n return isConnectedAsLegacySystemLine(stripVTControlCharacters(line));\n}\n\nfunction renderSystemClusterLine(line: string, contentWidth: number): string {\n const normalizedLine = stripVTControlCharacters(line).trim();\n if (normalizedLine.length === 0) {\n return \"\";\n }\n const visibleWidth = stringWidth(normalizedLine);\n const remainingWidth = Math.max(0, contentWidth - visibleWidth);\n const leadingPaddingWidth = Math.floor(remainingWidth / 2);\n const trailingPaddingWidth = remainingWidth - leadingPaddingWidth;\n return `${\" \".repeat(leadingPaddingWidth)}${pc.dim(normalizedLine)}${\" \".repeat(trailingPaddingWidth)}`;\n}\n\nfunction resolveSystemClusterContentWidth(width: number): number {\n const normalizedWidth = Number.isFinite(width) && width > 0 ? width : 80;\n return Math.max(1, normalizedWidth);\n}\n","import type { HelloAck, SignalEnvelope } from \"@openmeld/protocol\";\nimport { replayRecentSignals } from \"./connect-catchup\";\nimport type { SpaceJoinReadModelSeed } from \"./join-read-model-seed\";\nimport {\n buildSpaceSessionProfileContextFromIdentity,\n type SpaceSessionProfileIdentity,\n} from \"./session-profile\";\nimport type { SpaceTranscriptItem } from \"./state/space-screen-state\";\nimport { buildHumanTranscriptItemFromEvent } from \"./transcript/transcript-item-builder\";\nimport {\n buildHumanTranscriptProjection,\n renderTranscriptBlocks,\n} from \"./transcript/transcript-render\";\n\nexport type ConnectHistoryTranscriptBootstrapResult = {\n synced: boolean;\n latestReplayedSignalTs: number | null;\n lastTranscriptGroupKey: string | null;\n};\n\n// Neutral connect/runtime seam: owns initial replay bootstrap and shared\n// transcript-pipeline parity, without owning join handoff or read seed state.\nexport async function replayConnectInitialHistoryBootstrap(input: {\n profileIdentity: SpaceSessionProfileIdentity;\n baseUrl: string;\n space: string;\n password?: string;\n recentHistoryLimit: number;\n readModelSeed: Pick<\n SpaceJoinReadModelSeed,\n | \"rememberSignal\"\n | \"getMentionHighlightIndex\"\n | \"getMembersSnapshot\"\n | \"getSignalIndex\"\n >;\n ownerDisplayNameByUserId: Map<string, string>;\n seenSignalIds: Set<string>;\n onReplayEvent: (event: SignalEnvelope | HelloAck) => void;\n onError: (error: unknown) => void;\n onReplayTranscriptRendered?: (input: {\n lines: readonly string[];\n lastTranscriptGroupKey: string | null;\n }) => void;\n renderWidth?: number;\n}): Promise<ConnectHistoryTranscriptBootstrapResult> {\n let latestReplayedSignalTs: number | null = null;\n const replayedTranscriptItems: SpaceTranscriptItem[] = [];\n\n try {\n await replayRecentSignals({\n profileIdentity: input.profileIdentity,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n limit: input.recentHistoryLimit,\n seenSignalIds: input.seenSignalIds,\n onEvent: (event) => {\n if (isSignalEnvelope(event)) {\n input.readModelSeed.rememberSignal(event);\n latestReplayedSignalTs = Math.max(\n latestReplayedSignalTs ?? event.ts,\n event.ts\n );\n }\n\n if (input.onReplayTranscriptRendered) {\n emitHumanConnectTranscriptEvent({\n event,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n readModelSeed: input.readModelSeed,\n sessionProfileIdentity: input.profileIdentity,\n onTranscriptItem: (transcriptItem) => {\n replayedTranscriptItems.push(transcriptItem);\n },\n });\n }\n\n input.onReplayEvent(event);\n },\n });\n } catch (error) {\n input.onError(error);\n return {\n synced: false,\n latestReplayedSignalTs,\n lastTranscriptGroupKey: replayedTranscriptItems.at(-1)?.groupKey ?? null,\n };\n }\n\n if (input.onReplayTranscriptRendered) {\n const projection = buildHumanTranscriptProjection({\n items: replayedTranscriptItems,\n membersSnapshot: input.readModelSeed.getMembersSnapshot(),\n sessionProfile: buildSpaceSessionProfileContextFromIdentity({\n kind: input.profileIdentity.kind,\n openMeldProfileId: input.profileIdentity.openMeldProfileId,\n ownerName: input.profileIdentity.ownerName,\n ownerUserId: input.profileIdentity.ownerUserId,\n profileName: input.profileIdentity.profileName,\n }),\n });\n input.onReplayTranscriptRendered({\n lines: renderTranscriptBlocks(\n projection.transcriptBlocks,\n Math.max(input.renderWidth ?? process.stdout.columns ?? 100, 40)\n ),\n lastTranscriptGroupKey: replayedTranscriptItems.at(-1)?.groupKey ?? null,\n });\n }\n\n return {\n synced: true,\n latestReplayedSignalTs,\n lastTranscriptGroupKey: replayedTranscriptItems.at(-1)?.groupKey ?? null,\n };\n}\n\nexport function emitHumanConnectTranscriptEvent(input: {\n event: SignalEnvelope | HelloAck;\n ownerDisplayNameByUserId: Map<string, string>;\n readModelSeed: Pick<\n SpaceJoinReadModelSeed,\n \"getMentionHighlightIndex\" | \"getMembersSnapshot\" | \"getSignalIndex\"\n >;\n sessionProfileIdentity: SpaceSessionProfileIdentity;\n onTranscriptItem: (item: SpaceTranscriptItem) => void;\n}): SpaceTranscriptItem | null {\n const transcriptItem = buildHumanTranscriptItemFromEvent({\n event: input.event,\n mentionHighlightIndex: input.readModelSeed.getMentionHighlightIndex(),\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n selfProfileId: input.sessionProfileIdentity.openMeldProfileId,\n sessionProfileIdentity: input.sessionProfileIdentity,\n signalIndex: input.readModelSeed.getSignalIndex(),\n spaceMembersSnapshot: input.readModelSeed.getMembersSnapshot(),\n });\n if (!transcriptItem) {\n return null;\n }\n input.onTranscriptItem(transcriptItem);\n return transcriptItem;\n}\n\nfunction isSignalEnvelope(\n event: SignalEnvelope | HelloAck\n): event is SignalEnvelope {\n return \"id\" in event && typeof event.id === \"string\";\n}\n","import type { SpaceCursor, SpaceMeta } from \"@openmeld/protocol\";\nimport { resolveCustomMentionAliasOverride } from \"@openmeld/protocol\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\n\nconst MENTION_ALIAS_TOKEN_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\n\nfunction resolvePresentString(value: unknown): string | undefined {\n if (typeof value !== \"string\" || value.length === 0) {\n return undefined;\n }\n\n return value;\n}\n\nfunction resolveTrimmedPresentString(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n\n const normalized = value.trim();\n if (normalized.length === 0) {\n return undefined;\n }\n\n return normalized;\n}\n\nfunction resolveOptionalNumber(value: unknown): number | undefined {\n return typeof value === \"number\" ? value : undefined;\n}\n\nexport function resolveCreatorProfileId(creator: unknown): string | undefined {\n if (!creator || typeof creator !== \"object\") {\n return undefined;\n }\n const record = creator as { profileId?: unknown; profile?: unknown };\n if (\n typeof record.profileId === \"string\" &&\n record.profileId.trim().length > 0\n ) {\n return record.profileId.trim();\n }\n if (typeof record.profile === \"string\" && record.profile.trim().length > 0) {\n return record.profile.trim();\n }\n return undefined;\n}\n\nexport function resolveCreatorProfileName(\n creator: unknown\n): string | undefined {\n if (!creator || typeof creator !== \"object\") {\n return undefined;\n }\n const record = creator as { profileName?: unknown };\n return normalizeOptionalTrimmedText(record.profileName);\n}\n\nexport function resolveCreatorKind(\n kind: unknown\n): \"human\" | \"agent\" | \"system\" | undefined {\n if (kind === \"human\" || kind === \"agent\" || kind === \"system\") {\n return kind;\n }\n return undefined;\n}\n\nexport function normalizeOptionalTrimmedText(\n value: unknown\n): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\nexport function normalizeOptionalIsoDateTime(\n value: unknown\n): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim();\n if (normalized.length === 0) {\n return undefined;\n }\n const date = new Date(normalized);\n if (Number.isNaN(date.getTime())) {\n return undefined;\n }\n return normalized;\n}\n\nexport function resolveSessionMeta(\n requestedSpace: string,\n spaceMeta: SpaceMeta | null,\n fallbackName?: string,\n fallbackSpaceCreatedAt?: string\n): {\n accessMode?: SpaceMeta[\"accessMode\"];\n spaceId: string;\n spaceName?: string;\n spaceCreatedAt?: string;\n spaceCreatorName?: string;\n spaceCreatorId?: string;\n passwordProtected?: boolean;\n visibility?: SpaceMeta[\"visibility\"];\n storageUsedBytes?: number;\n storageSoftLimitBytes?: number;\n storageUsagePercent?: number;\n} {\n const spaceId = resolvePresentString(spaceMeta?.spaceId) ?? requestedSpace;\n const fallbackSpaceName = resolveTrimmedPresentString(fallbackName);\n const spaceName = resolvePresentString(spaceMeta?.name) ?? fallbackSpaceName;\n const fallbackCreatedAt = resolveTrimmedPresentString(fallbackSpaceCreatedAt);\n const spaceCreatedAt =\n resolvePresentString(spaceMeta?.createdAt) ?? fallbackCreatedAt;\n const spaceCreatorName = resolveCreatorProfileName(spaceMeta?.creator);\n const spaceCreatorId = resolveCreatorProfileId(spaceMeta?.creator);\n const passwordProtected =\n typeof spaceMeta?.passwordProtected === \"boolean\"\n ? spaceMeta.passwordProtected\n : undefined;\n const accessMode = spaceMeta?.accessMode;\n const visibility = spaceMeta?.visibility;\n const storageUsedBytes = resolveOptionalNumber(\n spaceMeta?.storageUsage?.usedBytes\n );\n const storageSoftLimitBytes = resolveOptionalNumber(\n spaceMeta?.storageUsage?.softLimitBytes\n );\n const storageUsagePercent = resolveOptionalNumber(\n spaceMeta?.storageUsage?.usagePercent\n );\n\n return {\n ...(accessMode ? { accessMode } : {}),\n spaceId,\n ...(spaceName ? { spaceName } : {}),\n ...(spaceCreatedAt ? { spaceCreatedAt } : {}),\n ...(spaceCreatorName ? { spaceCreatorName } : {}),\n ...(spaceCreatorId ? { spaceCreatorId } : {}),\n ...(typeof passwordProtected === \"boolean\" ? { passwordProtected } : {}),\n ...(visibility ? { visibility } : {}),\n ...(typeof storageUsedBytes === \"number\" ? { storageUsedBytes } : {}),\n ...(typeof storageSoftLimitBytes === \"number\"\n ? { storageSoftLimitBytes }\n : {}),\n ...(typeof storageUsagePercent === \"number\" ? { storageUsagePercent } : {}),\n };\n}\n\nexport function resolveSessionRoleContext(input: {\n inputRole?: string;\n localRole?: string;\n cloudRole?: string;\n}): { role?: string } {\n const role =\n normalizeRoleValue(input.inputRole) ??\n normalizeRoleValue(input.cloudRole) ??\n normalizeRoleValue(input.localRole);\n\n return {\n ...(role ? { role } : {}),\n };\n}\n\nexport function resolveSessionMentionAlias(input: {\n inputMentionAlias?: string;\n localMentionAlias?: string;\n cloudMentionAlias?: string;\n profileId?: string;\n profileName?: string;\n profileKind?: OpenMeldProfile[\"profileKind\"];\n}): string | undefined {\n const explicitMentionAlias = normalizeMentionAliasValue(\n input.inputMentionAlias\n );\n if (explicitMentionAlias) {\n return explicitMentionAlias;\n }\n\n return (\n normalizeStoredMentionAliasValue({\n mentionAlias: input.cloudMentionAlias,\n profileId: input.profileId,\n profileName: input.profileName,\n profileKind: input.profileKind,\n }) ??\n normalizeStoredMentionAliasValue({\n mentionAlias: input.localMentionAlias,\n profileId: input.profileId,\n profileName: input.profileName,\n profileKind: input.profileKind,\n })\n );\n}\n\nexport function buildSpaceCursorPatch(input: {\n lastSeenTs: number | null;\n shouldSyncRole: boolean;\n shouldSyncMentionAlias: boolean;\n role?: string;\n mentionAlias?: string;\n}): {\n lastSeenTs?: number;\n role?: string;\n mentionAlias?: string;\n} | null {\n const patch: {\n lastSeenTs?: number;\n role?: string;\n mentionAlias?: string;\n } = {};\n\n if (typeof input.lastSeenTs === \"number\") {\n patch.lastSeenTs = input.lastSeenTs;\n }\n if (input.shouldSyncRole && input.role) {\n patch.role = input.role;\n }\n if (input.shouldSyncMentionAlias && input.mentionAlias) {\n patch.mentionAlias = input.mentionAlias;\n }\n\n return Object.keys(patch).length > 0 ? patch : null;\n}\n\nexport function normalizeCursorLastSeenTs(\n cursor: SpaceCursor | null\n): number | null {\n const value = cursor?.lastSeenTs;\n if (typeof value !== \"number\" || !Number.isFinite(value) || value < 0) {\n return null;\n }\n return Math.trunc(value);\n}\n\nexport function normalizeRoleValue(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\nfunction normalizeMentionAliasValue(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim();\n if (normalized.length === 0) {\n return undefined;\n }\n return MENTION_ALIAS_TOKEN_REGEX.test(normalized) ? normalized : undefined;\n}\n\nexport function normalizeStoredMentionAliasValue(input: {\n mentionAlias: unknown;\n profileId?: string;\n profileName?: string;\n profileKind?: OpenMeldProfile[\"profileKind\"];\n}): string | undefined {\n const normalizedMentionAlias = normalizeMentionAliasValue(input.mentionAlias);\n if (!normalizedMentionAlias) {\n return undefined;\n }\n\n return (\n resolveCustomMentionAliasOverride({\n mentionAlias: normalizedMentionAlias,\n profileId: input.profileId,\n profileName: input.profileName,\n profileKind: input.profileKind,\n }) ?? undefined\n );\n}\n\nexport function resolveMaxLastSeenTs(\n localLastSeenTs: number | null,\n cloudLastSeenTs: number | null\n): number | null {\n if (\n typeof localLastSeenTs === \"number\" &&\n typeof cloudLastSeenTs === \"number\"\n ) {\n return Math.max(localLastSeenTs, cloudLastSeenTs);\n }\n if (typeof localLastSeenTs === \"number\") {\n return localLastSeenTs;\n }\n if (typeof cloudLastSeenTs === \"number\") {\n return cloudLastSeenTs;\n }\n return null;\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\nimport type { ComposerDispatchRowState } from \"./view/space-session-view-state\";\n\nexport function normalizePendingOutboundSourceText(\n value: string | null | undefined\n): string | null {\n const normalized = sanitizeTerminalDisplayText(\n String(value ?? \"\"),\n \"single-line\"\n )\n .replace(/\\s+/g, \" \")\n .trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nexport function confirmPendingOutboundRows(input: {\n rowsById: Map<string, ComposerDispatchRowState>;\n clientMessageId: string | null;\n}): boolean {\n if (!input.clientMessageId) {\n return false;\n }\n let changed = false;\n for (const [rowId, row] of input.rowsById) {\n if (row.sourceClientMessageId !== input.clientMessageId) {\n continue;\n }\n input.rowsById.delete(rowId);\n changed = true;\n }\n return changed;\n}\n\nexport function confirmPendingOutboundRowsForSignal(input: {\n rowsById: Map<string, ComposerDispatchRowState>;\n event: SignalEnvelope;\n selfProfileId: string;\n}): boolean {\n if (input.event.type !== \"signal.text\") {\n return false;\n }\n const profileId = normalizeOptionalText(input.event.profile?.profileId);\n if (!profileId || profileId !== input.selfProfileId) {\n return false;\n }\n const sourceEventId = normalizeOptionalText(input.event.id);\n if (!sourceEventId) {\n return false;\n }\n\n const clientMessageId = resolveSignalClientMessageId(input.event);\n if (\n confirmPendingOutboundRows({\n rowsById: input.rowsById,\n clientMessageId,\n })\n ) {\n return true;\n }\n\n const fallbackClientMessageId = resolveOldestPendingClientMessageIdByText({\n rowsById: input.rowsById,\n normalizedText: normalizePendingOutboundSourceText(input.event.data.text),\n });\n if (!fallbackClientMessageId) {\n return false;\n }\n\n return confirmPendingOutboundRows({\n rowsById: input.rowsById,\n clientMessageId: fallbackClientMessageId,\n });\n}\n\nfunction resolveOldestPendingClientMessageIdByText(input: {\n rowsById: Map<string, ComposerDispatchRowState>;\n normalizedText: string | null;\n}): string | null {\n if (!input.normalizedText) {\n return null;\n }\n\n const oldestCreatedAtByClientMessageId = new Map<string, number>();\n for (const row of input.rowsById.values()) {\n if (\n row.stage !== \"sending\" ||\n row.sourceEventId !== null ||\n row.sourceTextSnapshot !== input.normalizedText\n ) {\n continue;\n }\n const clientMessageId = normalizeOptionalText(row.sourceClientMessageId);\n if (!clientMessageId) {\n continue;\n }\n const previousCreatedAtMs =\n oldestCreatedAtByClientMessageId.get(clientMessageId);\n if (\n previousCreatedAtMs === undefined ||\n row.createdAtMs < previousCreatedAtMs\n ) {\n oldestCreatedAtByClientMessageId.set(clientMessageId, row.createdAtMs);\n }\n }\n\n let matchedClientMessageId: string | null = null;\n let matchedCreatedAtMs = Number.POSITIVE_INFINITY;\n for (const [\n clientMessageId,\n createdAtMs,\n ] of oldestCreatedAtByClientMessageId) {\n if (createdAtMs >= matchedCreatedAtMs) {\n continue;\n }\n matchedClientMessageId = clientMessageId;\n matchedCreatedAtMs = createdAtMs;\n }\n return matchedClientMessageId;\n}\n\nfunction resolveSignalClientMessageId(event: SignalEnvelope): string | null {\n const meta =\n event.data && typeof event.data === \"object\" && !Array.isArray(event.data)\n ? (event.data as { meta?: unknown }).meta\n : null;\n if (!(meta && typeof meta === \"object\") || Array.isArray(meta)) {\n return null;\n }\n return normalizeOptionalText(\n (meta as { clientMessageId?: unknown }).clientMessageId\n );\n}\n\nfunction normalizeOptionalText(value: unknown): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n","import stringWidth from \"string-width\";\nimport { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\n\nconst PREVIEW_MAX_VISIBLE_CHARS = 240;\nconst PREVIEW_MIN_VISIBLE_CHARS = 24;\nconst PREVIEW_ELLIPSIS = \"...\";\nconst STATUS_SYSTEM_PREFIX = \"* 📣 system · \";\nconst STATUS_PREVIEW_PREFIX = \"Sending: \";\n\nexport type PendingOutboundDispatchRowDraft = {\n statusText: string;\n targetLabel: string;\n targetMentionLabel: string | null;\n};\n\nexport function formatPendingOutboundStatusText(input: {\n pendingText: string;\n terminalColumns: number | null;\n}): string {\n const normalizedText = normalizePendingOutboundText(input.pendingText);\n if (!normalizedText) {\n return \"Sending...\";\n }\n\n const maxStatusWidth = resolvePendingOutboundPreviewWidth({\n terminalColumns: input.terminalColumns,\n });\n const statusHead = truncatePreviewHead(normalizedText, maxStatusWidth);\n return `${STATUS_PREVIEW_PREFIX}${statusHead}`;\n}\n\nexport function buildPendingOutboundDispatchRowDrafts(input: {\n pendingText: string;\n terminalColumns: number | null;\n}): PendingOutboundDispatchRowDraft[] {\n return [\n {\n statusText: formatPendingOutboundStatusText(input),\n targetLabel: \"\",\n targetMentionLabel: null,\n },\n ];\n}\n\nfunction normalizePendingOutboundText(value: string): string {\n return sanitizeTerminalDisplayText(value, \"single-line\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\nfunction resolvePendingOutboundPreviewWidth(input: {\n terminalColumns: number | null;\n}): number {\n const prefixWidth = stringWidth(\n `${STATUS_SYSTEM_PREFIX}${STATUS_PREVIEW_PREFIX}`\n );\n if (input.terminalColumns === null) {\n return PREVIEW_MAX_VISIBLE_CHARS;\n }\n const availableWidth = input.terminalColumns - prefixWidth;\n return Math.max(\n PREVIEW_MIN_VISIBLE_CHARS,\n Math.min(PREVIEW_MAX_VISIBLE_CHARS, availableWidth)\n );\n}\n\nfunction truncatePreviewHead(value: string, maxWidth: number): string {\n if (stringWidth(value) <= maxWidth) {\n return value;\n }\n const truncatedWidth = Math.max(0, maxWidth - stringWidth(PREVIEW_ELLIPSIS));\n let head = \"\";\n for (const char of value) {\n if (stringWidth(head) + stringWidth(char) > truncatedWidth) {\n break;\n }\n head += char;\n }\n return `${head}${PREVIEW_ELLIPSIS}`;\n}\n","import { normalizePendingOutboundSourceText } from \"./pending-outbound-confirmation\";\nimport {\n buildPendingOutboundDispatchRowDrafts,\n formatPendingOutboundStatusText,\n} from \"./pending-outbound-status\";\nimport type { ComposerDispatchRowState } from \"./view/space-session-view-state\";\n\nexport function buildPendingHumanSendRowId(clientMessageId: string): string {\n return `pending:${clientMessageId}`;\n}\n\nexport function upsertPendingHumanSendRow(input: {\n enableLocalEcho: boolean;\n rowsById: Map<string, ComposerDispatchRowState>;\n text: string;\n clientMessageId: string;\n terminalColumns: number | null;\n nowMs: number;\n maxPendingRows: number;\n}): boolean {\n if (!input.enableLocalEcho) {\n return false;\n }\n\n const draft =\n buildPendingOutboundDispatchRowDrafts({\n pendingText: input.text,\n terminalColumns: input.terminalColumns,\n })[0] ?? null;\n if (!draft) {\n return false;\n }\n\n const rowId = buildPendingHumanSendRowId(input.clientMessageId);\n input.rowsById.set(rowId, {\n rowId,\n dispatchId: null,\n sourceEventId: null,\n sourceClientMessageId: input.clientMessageId,\n sourceTextSnapshot: normalizePendingOutboundSourceText(input.text),\n targetProfileId: null,\n targetMentionLabel: null,\n targetLabel: \"\",\n stage: \"sending\",\n createdAtMs: input.nowMs,\n updatedAtMs: input.nowMs,\n expiresAtMs: null,\n latestPreviewText: \"\",\n latestPreviewUpdatedAtMs: null,\n statusText: draft.statusText,\n warningText: \"\",\n });\n trimPendingHumanSendRows(input.rowsById, input.maxPendingRows);\n return true;\n}\n\nexport function clearPendingHumanSendRowsByClientMessageId(input: {\n rowsById: Map<string, ComposerDispatchRowState>;\n clientMessageId: string | null;\n}): boolean {\n if (!input.clientMessageId) {\n return false;\n }\n\n const rowId = buildPendingHumanSendRowId(input.clientMessageId);\n if (!input.rowsById.has(rowId)) {\n return false;\n }\n input.rowsById.delete(rowId);\n return true;\n}\n\nexport function buildPendingHumanSendStatusText(input: {\n text: string;\n terminalColumns: number | null;\n}): string {\n return formatPendingOutboundStatusText({\n pendingText: input.text,\n terminalColumns: input.terminalColumns,\n });\n}\n\nfunction trimPendingHumanSendRows(\n rowsById: Map<string, ComposerDispatchRowState>,\n maxPendingRows: number\n): void {\n if (rowsById.size <= maxPendingRows) {\n return;\n }\n\n const removableRows = [...rowsById.values()]\n .filter(\n (row) =>\n row.stage === \"sending\" &&\n row.dispatchId === null &&\n row.sourceEventId === null\n )\n .sort((left, right) => left.createdAtMs - right.createdAtMs);\n\n while (rowsById.size > maxPendingRows && removableRows.length > 0) {\n const oldestRow = removableRows.shift();\n if (!oldestRow) {\n break;\n }\n rowsById.delete(oldestRow.rowId);\n }\n}\n","import type { MessageEnvelope } from \"@openmeld/schemas/types\";\nimport type {\n SpaceAuthoredMentionInTextOrder,\n SpaceResolvedStructuredTargetSet,\n} from \"@openmeld/space\";\nimport type { SpaceSessionSendReceipt } from \"./runtime/space-session-runtime\";\n\nexport type PreparedInteractiveOutboundText = {\n text: string;\n messageEnvelope: MessageEnvelope | null;\n mentionsInTextOrder: readonly SpaceAuthoredMentionInTextOrder[];\n resolvedStructuredTargets: SpaceResolvedStructuredTargetSet;\n};\n\nexport type InteractiveTextSubmitResult =\n | {\n status: \"not_queued\";\n text: string;\n mentionsInTextOrder: readonly SpaceAuthoredMentionInTextOrder[];\n resolvedStructuredTargets: SpaceResolvedStructuredTargetSet;\n }\n | {\n status: \"queued\";\n text: string;\n clientMessageId: string;\n mentionsInTextOrder: readonly SpaceAuthoredMentionInTextOrder[];\n resolvedStructuredTargets: SpaceResolvedStructuredTargetSet;\n };\n\nexport async function performInteractiveTextSubmit(input: {\n nextBufferText: string;\n submittedText: string;\n text: string;\n prepareOutboundText: (\n text: string\n ) => Promise<PreparedInteractiveOutboundText>;\n queueText: (input: {\n text: string;\n messageEnvelope?: MessageEnvelope;\n }) => SpaceSessionSendReceipt;\n applyComposerBuffer: (bufferText: string) => void;\n clearSubmittedInputLine: (text: string) => void;\n}): Promise<InteractiveTextSubmitResult> {\n const preparedSubmission = await input\n .prepareOutboundText(input.text)\n .catch((error) => {\n input.applyComposerBuffer(input.submittedText);\n throw error;\n });\n const outboundText = preparedSubmission.text;\n const sendReceipt = input.queueText({\n text: outboundText,\n ...(preparedSubmission.messageEnvelope\n ? { messageEnvelope: preparedSubmission.messageEnvelope }\n : {}),\n });\n if (!sendReceipt.queued) {\n input.applyComposerBuffer(input.submittedText);\n return {\n status: \"not_queued\",\n text: outboundText,\n mentionsInTextOrder: preparedSubmission.mentionsInTextOrder,\n resolvedStructuredTargets: preparedSubmission.resolvedStructuredTargets,\n };\n }\n\n input.applyComposerBuffer(input.nextBufferText);\n input.clearSubmittedInputLine(input.submittedText);\n return {\n status: \"queued\",\n text: outboundText,\n clientMessageId: sendReceipt.clientMessageId,\n mentionsInTextOrder: preparedSubmission.mentionsInTextOrder,\n resolvedStructuredTargets: preparedSubmission.resolvedStructuredTargets,\n };\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../config/openmeld-request-context\";\nimport { buildSpaceMentionHighlightIndex } from \"../ui/space-mention-highlight\";\nimport { createCliSpaceApi } from \"./cli-space-api\";\nimport {\n rememberOwnerDisplayName,\n type SpaceSessionProfileIdentity,\n} from \"./session-profile\";\n\nexport type SpaceJoinReadModelSeed = {\n ensureMembersSnapshotLoaded: () => Promise<SpaceMembersSnapshot | null>;\n refreshMembersSnapshot: () => Promise<SpaceMembersSnapshot | null>;\n getMembersSnapshot: () => SpaceMembersSnapshot | null;\n getMentionHighlightIndex: () => ReturnType<\n typeof buildSpaceMentionHighlightIndex\n > | null;\n getSignalIndex: () => ReadonlyMap<string, SignalEnvelope>;\n applyMembersSnapshot: (snapshot: SpaceMembersSnapshot | null) => void;\n rememberSignal: (event: SignalEnvelope) => void;\n};\n\nexport function resolveSpaceJoinReadModelSeed(input: {\n baseUrl: string;\n ownerDisplayNameByUserId: Map<string, string>;\n password?: string;\n profileIdentity: SpaceSessionProfileIdentity;\n space: string;\n}): SpaceJoinReadModelSeed {\n const spaceApi = createCliSpaceApi(input.baseUrl);\n const signalIndexById = new Map<string, SignalEnvelope>();\n let membersSnapshot: SpaceMembersSnapshot | null = null;\n let hasLoadedMembersSnapshot = false;\n let membersSnapshotLoadPromise: Promise<SpaceMembersSnapshot | null> | null =\n null;\n let mentionHighlightIndex: ReturnType<\n typeof buildSpaceMentionHighlightIndex\n > | null = null;\n\n const applyMembersSnapshot = (\n snapshot: SpaceMembersSnapshot | null\n ): void => {\n membersSnapshot = snapshot\n ? enrichSpaceMembersOwnerDisplayNames({\n snapshot,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n })\n : null;\n hasLoadedMembersSnapshot = true;\n mentionHighlightIndex = membersSnapshot\n ? buildSpaceMentionHighlightIndex(membersSnapshot)\n : null;\n };\n\n const fetchMembersSnapshot =\n async (): Promise<SpaceMembersSnapshot | null> => {\n const fetchedSnapshot = await spaceApi.getMembersSnapshot({\n spaceId: input.space,\n requestContext: buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: input.profileIdentity,\n }),\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n applyMembersSnapshot(fetchedSnapshot);\n return membersSnapshot;\n };\n\n return {\n async ensureMembersSnapshotLoaded(): Promise<SpaceMembersSnapshot | null> {\n if (hasLoadedMembersSnapshot) {\n return membersSnapshot;\n }\n if (!membersSnapshotLoadPromise) {\n membersSnapshotLoadPromise = fetchMembersSnapshot().finally(() => {\n membersSnapshotLoadPromise = null;\n });\n }\n return await membersSnapshotLoadPromise;\n },\n async refreshMembersSnapshot(): Promise<SpaceMembersSnapshot | null> {\n membersSnapshotLoadPromise = fetchMembersSnapshot().finally(() => {\n membersSnapshotLoadPromise = null;\n });\n return await membersSnapshotLoadPromise;\n },\n getMembersSnapshot(): SpaceMembersSnapshot | null {\n return membersSnapshot;\n },\n getMentionHighlightIndex() {\n return mentionHighlightIndex;\n },\n getSignalIndex(): ReadonlyMap<string, SignalEnvelope> {\n return signalIndexById;\n },\n applyMembersSnapshot,\n rememberSignal(event: SignalEnvelope): void {\n signalIndexById.set(event.id, event);\n },\n };\n}\n\nfunction enrichSpaceMembersOwnerDisplayNames(input: {\n snapshot: SpaceMembersSnapshot;\n ownerDisplayNameByUserId: Map<string, string>;\n}): SpaceMembersSnapshot {\n for (const human of input.snapshot.humans) {\n rememberOwnerDisplayName(\n input.ownerDisplayNameByUserId,\n human.ownerUserId,\n human.ownerName ?? human.profileName\n );\n }\n\n for (const agent of input.snapshot.agents) {\n rememberOwnerDisplayName(\n input.ownerDisplayNameByUserId,\n agent.ownerUserId,\n agent.ownerName\n );\n }\n\n let changed = false;\n const humans = input.snapshot.humans.map((human) => {\n const ownerName = resolveEnrichedOwnerName({\n ownerName: human.ownerName,\n ownerUserId: human.ownerUserId,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n });\n if (ownerName === human.ownerName) {\n return human;\n }\n\n changed = true;\n return {\n ...human,\n ownerName,\n };\n });\n const agents = input.snapshot.agents.map((agent) => {\n const ownerName = resolveEnrichedOwnerName({\n ownerName: agent.ownerName,\n ownerUserId: agent.ownerUserId,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n });\n if (ownerName === agent.ownerName) {\n return agent;\n }\n\n changed = true;\n return {\n ...agent,\n ownerName,\n };\n });\n\n if (!changed) {\n return input.snapshot;\n }\n\n return {\n ...input.snapshot,\n humans,\n agents,\n };\n}\n\nfunction resolveEnrichedOwnerName(input: {\n ownerName?: string | null;\n ownerUserId?: string | null;\n ownerDisplayNameByUserId: Map<string, string>;\n}): string | null {\n const ownerName = String(input.ownerName ?? \"\").trim();\n if (ownerName) {\n return ownerName;\n }\n\n const ownerUserId = String(input.ownerUserId ?? \"\").trim();\n if (!ownerUserId) {\n return null;\n }\n\n return input.ownerDisplayNameByUserId.get(ownerUserId) ?? null;\n}\n","const TRAILING_DECIMAL_ZERO_REGEX = /\\.0$/;\n\nexport function formatStorageBytesCompact(bytes: number): string {\n const normalizedBytes = Math.max(0, bytes);\n if (normalizedBytes === 0) {\n return \"0 KB\";\n }\n if (normalizedBytes < 1000) {\n return `${Math.floor(normalizedBytes)} B`;\n }\n\n const units = [\"KB\", \"MB\", \"GB\", \"TB\"] as const;\n let value = normalizedBytes / 1000;\n let unitIndex = 0;\n while (value >= 1000 && unitIndex < units.length - 1) {\n value /= 1000;\n unitIndex += 1;\n }\n\n const rounded = value >= 10 ? value.toFixed(0) : value.toFixed(1);\n return `${stripTrailingZeroes(rounded)} ${units[unitIndex]}`;\n}\n\nexport function formatStorageUsagePercentText(percent: number): string {\n return `${Math.round(percent)}% used`;\n}\n\nexport function formatStorageUsageSummaryText(input: {\n usedBytes: number | null;\n usagePercent: number | null;\n}): string | null {\n if (input.usedBytes === null || input.usagePercent === null) {\n return null;\n }\n\n return `${formatStorageBytesCompact(input.usedBytes)} ( ${formatStorageUsagePercentText(input.usagePercent)} )`;\n}\n\nexport function formatStorageUsageDetailText(input: {\n usedBytes: number | null;\n softLimitBytes: number | null;\n usagePercent: number | null;\n}): string | null {\n const { softLimitBytes, usedBytes, usagePercent } = input;\n const summaryText = formatStorageUsageSummaryText({\n usedBytes,\n usagePercent,\n });\n if (summaryText === null) {\n return null;\n }\n if (usedBytes === null || usagePercent === null) {\n return null;\n }\n if (softLimitBytes === null) {\n return summaryText;\n }\n\n return `${formatStorageBytesCompact(usedBytes)} / ${formatStorageBytesCompact(softLimitBytes)} ( ${formatStorageUsagePercentText(usagePercent)} )`;\n}\n\nfunction stripTrailingZeroes(value: string): string {\n return value.replace(TRAILING_DECIMAL_ZERO_REGEX, \"\");\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport pc from \"picocolors\";\nimport {\n buildSpaceInfoData,\n buildSpaceMembersLoadingPanelLines,\n buildSpaceMembersPanelLines,\n buildSpaceMembersPanelSource,\n type SpaceMembersPanelSectionSource,\n} from \"../../ui/output\";\nimport { listSpaceSlashCommands } from \"../composer/slash-command-registry\";\nimport type { HumanLogsSectionViewState } from \"../transcript/transcript-render\";\nimport type {\n PanelBodyBlockViewState,\n PanelFactItemViewState,\n SearchablePanelListViewState,\n SpaceSessionContext,\n} from \"../view/space-session-view-state\";\nimport { formatStorageUsageDetailText } from \"../view/space-storage-usage-text\";\n\nconst SPACE_INFO_FULL_WIDTH_LABELS = new Set([\"Space Name\", \"Space ID\"]);\nconst MEMBERS_SEARCH_LABEL = \"Type to search\";\nconst MEMBERS_SEARCH_PLACEHOLDER =\n \"Filter members by name, @wake, ID, or owner\";\nconst MEMBERS_NO_MATCHES_LINE = pc.dim(\"No matching members found.\");\nconst LOGS_SEARCH_LABEL = \"Type to search\";\nconst LOGS_SEARCH_PLACEHOLDER = \"Filter logs by actor, action, or text\";\nconst LOGS_NO_MATCHES_LINE = pc.dim(\"No matching logs found.\");\n\nexport function buildHelpPanelBlocks(): readonly PanelBodyBlockViewState[] {\n return buildPanelBodyBlocks([\n buildPanelLinesSection(\n listSpaceSlashCommands().map((command) => {\n return `${pc.cyan(command.trigger)} ${pc.dim(command.description)}`;\n })\n ),\n ]);\n}\n\nexport function buildSpacePanelBlocks(input: {\n context: SpaceSessionContext;\n membersSnapshot?: SpaceMembersSnapshot | null;\n}): readonly PanelBodyBlockViewState[] {\n const spaceInfo = buildSpaceInfoData({\n accessMode: input.context.session.accessMode ?? undefined,\n gatewayUrl: input.context.gatewayUrl,\n modeLabel: resolveConnectionModeLabel(input.context.connectionMode),\n passwordProtected: input.context.session.passwordProtected ?? undefined,\n spaceCreatedAt: input.context.session.spaceCreatedAt ?? undefined,\n spaceCreatorId: input.context.session.spaceCreatorId ?? undefined,\n spaceCreatorName: input.context.session.spaceCreatorName ?? undefined,\n spaceId: input.context.session.spaceId,\n spaceName: input.context.session.spaceName ?? undefined,\n spaceMembersSnapshot: input.membersSnapshot,\n visibility: input.context.session.visibility ?? undefined,\n });\n const factsWithStorage = buildSpaceInfoFactsFromData(\n spaceInfo,\n input.context\n );\n\n return buildPanelBodyBlocks([\n spaceInfo.publicWarningLines.length > 0\n ? buildPanelLinesSection(\n spaceInfo.publicWarningLines.map((line) => pc.yellow(line))\n )\n : null,\n buildPanelFactsSection(factsWithStorage),\n buildPanelLinesSection([\n pc.dim(\"Join command\"),\n pc.cyan(spaceInfo.joinCommand),\n ]),\n ]);\n}\n\nexport function buildMembersPanelBlocks(input: {\n refreshError?: string | null;\n snapshot: SpaceMembersSnapshot | null;\n}): readonly PanelBodyBlockViewState[] {\n return buildPanelBodyBlocks([\n buildPanelLinesSection(buildMembersPanelLines(input)),\n ]);\n}\n\nexport function buildLogsPanelBlocks(input: {\n sections: readonly HumanLogsSectionViewState[];\n}): readonly PanelBodyBlockViewState[] {\n const sections = input.sections\n .map((section) => buildLogsPanelSection(section))\n .filter((section): section is PanelBodyBlockViewState => section !== null);\n\n if (sections.length > 0) {\n return sections;\n }\n\n return buildPanelBodyBlocks([\n buildPanelLinesSection([pc.dim(\"No logs yet.\")]),\n ]);\n}\n\nexport function buildLogsSearchableListViewState(input: {\n activeItemId: string | null;\n query: string;\n sections: readonly HumanLogsSectionViewState[];\n}): SearchablePanelListViewState {\n const normalizedQuery = normalizeSearchQuery(input.query);\n const filteredSections = filterLogsSections(input.sections, normalizedQuery);\n const activeItemId = resolveLogsSearchableActiveItemId({\n preferredActiveItemId: input.activeItemId,\n query: input.query,\n sections: input.sections,\n });\n\n return {\n activeItemId,\n control: {\n label: LOGS_SEARCH_LABEL,\n placeholder: LOGS_SEARCH_PLACEHOLDER,\n query: input.query,\n },\n emptyLines: resolveLogsEmptyLines(filteredSections.length, normalizedQuery),\n sections: filteredSections.map((section) => ({\n id: section.id,\n title: section.title,\n items: section.items.map((item) => ({\n id: item.id,\n lines: item.lines,\n })),\n })),\n };\n}\n\nexport function buildMembersSearchableListViewState(input: {\n activeItemId: string | null;\n query: string;\n refreshError?: string | null;\n snapshot: SpaceMembersSnapshot | null;\n}): SearchablePanelListViewState {\n const normalizedQuery = normalizeSearchQuery(input.query);\n if (!input.snapshot) {\n return {\n activeItemId: null,\n control: {\n label: MEMBERS_SEARCH_LABEL,\n placeholder: MEMBERS_SEARCH_PLACEHOLDER,\n query: input.query,\n },\n emptyLines: input.refreshError\n ? [\n \"Couldn't load the current Space members.\",\n pc.dim(\"Try /members again in a few seconds.\"),\n ]\n : buildSpaceMembersLoadingPanelLines(),\n sections: [],\n };\n }\n\n const source = buildSpaceMembersPanelSource(input.snapshot);\n const filteredSections = filterMembersPanelSections(\n source.sections,\n normalizedQuery\n );\n const activeItemId = resolveMembersSearchableActiveItemId({\n preferredActiveItemId: input.activeItemId,\n query: input.query,\n snapshot: input.snapshot,\n });\n\n let emptyLines: readonly string[] = [];\n if (filteredSections.length === 0) {\n emptyLines = normalizedQuery\n ? [MEMBERS_NO_MATCHES_LINE]\n : [pc.dim(\"No members yet.\")];\n }\n\n return {\n activeItemId,\n control: {\n label: MEMBERS_SEARCH_LABEL,\n placeholder: MEMBERS_SEARCH_PLACEHOLDER,\n query: input.query,\n },\n emptyLines,\n sections: filteredSections.map((section) => ({\n id: section.id,\n title: section.title,\n items: section.items.map((item) => ({\n id: item.id,\n lines: item.renderedLines,\n })),\n })),\n };\n}\n\nexport function resolveMembersSearchableActiveItemId(input: {\n preferredActiveItemId: string | null;\n query: string;\n snapshot: SpaceMembersSnapshot | null;\n}): string | null {\n if (!input.snapshot) {\n return null;\n }\n\n const normalizedQuery = normalizeSearchQuery(input.query);\n const filteredSections = filterMembersPanelSections(\n buildSpaceMembersPanelSource(input.snapshot).sections,\n normalizedQuery\n );\n const itemIds = filteredSections.flatMap((section) =>\n section.items.map((item) => item.id)\n );\n if (itemIds.length === 0) {\n return null;\n }\n return itemIds.includes(input.preferredActiveItemId ?? \"\")\n ? input.preferredActiveItemId\n : (itemIds[0] ?? null);\n}\n\nexport function resolveLogsSearchableActiveItemId(input: {\n preferredActiveItemId: string | null;\n query: string;\n sections: readonly HumanLogsSectionViewState[];\n}): string | null {\n const filteredSections = filterLogsSections(\n input.sections,\n normalizeSearchQuery(input.query)\n );\n const itemIds = filteredSections.flatMap((section) =>\n section.items.map((item) => item.id)\n );\n if (itemIds.length === 0) {\n return null;\n }\n return itemIds.includes(input.preferredActiveItemId ?? \"\")\n ? input.preferredActiveItemId\n : (itemIds[0] ?? null);\n}\n\nexport function buildSpaceInfoPanelFacts(input: {\n context: SpaceSessionContext;\n membersSnapshot?: SpaceMembersSnapshot | null;\n}): readonly PanelFactItemViewState[] {\n return buildSpaceInfoFactsFromData(\n buildSpaceInfoData({\n accessMode: input.context.session.accessMode ?? undefined,\n gatewayUrl: input.context.gatewayUrl,\n modeLabel: resolveConnectionModeLabel(input.context.connectionMode),\n passwordProtected: input.context.session.passwordProtected ?? undefined,\n spaceCreatedAt: input.context.session.spaceCreatedAt ?? undefined,\n spaceCreatorId: input.context.session.spaceCreatorId ?? undefined,\n spaceCreatorName: input.context.session.spaceCreatorName ?? undefined,\n spaceId: input.context.session.spaceId,\n spaceName: input.context.session.spaceName ?? undefined,\n spaceMembersSnapshot: input.membersSnapshot,\n visibility: input.context.session.visibility ?? undefined,\n }),\n input.context\n );\n}\n\nfunction buildMembersPanelLines(input: {\n refreshError?: string | null;\n snapshot: SpaceMembersSnapshot | null;\n}): string[] {\n if (!input.snapshot) {\n if (input.refreshError) {\n return [\n \"Couldn't load the current Space members.\",\n pc.dim(\"Try /members again in a few seconds.\"),\n ];\n }\n return buildSpaceMembersLoadingPanelLines();\n }\n\n return buildSpaceMembersPanelLines(input.snapshot);\n}\n\nfunction buildLogsPanelSection(\n section: HumanLogsSectionViewState\n): PanelBodyBlockViewState | null {\n if (section.items.length === 0) {\n return null;\n }\n\n return buildPanelLinesSection([\n pc.bold(section.title),\n ...section.items.flatMap((item) => item.lines),\n ]);\n}\n\nfunction filterLogsSections(\n sections: readonly HumanLogsSectionViewState[],\n normalizedQuery: string\n): Array<{\n id: string;\n title: string | null;\n items: Array<{\n id: string;\n lines: readonly string[];\n searchKey: string;\n }>;\n}> {\n const sourceSections = sections.map((section) => ({\n id: section.kind,\n title: section.title,\n items: section.items.map((item) => ({\n id: item.id,\n lines: item.lines,\n searchKey: buildLogsSearchKey(section.title, item.lines),\n })),\n }));\n if (!normalizedQuery) {\n return sourceSections;\n }\n return sourceSections\n .map((section) => ({\n ...section,\n items: section.items.filter((item) =>\n item.searchKey.includes(normalizedQuery)\n ),\n }))\n .filter((section) => section.items.length > 0);\n}\n\nfunction filterMembersPanelSections(\n sections: readonly SpaceMembersPanelSectionSource[],\n normalizedQuery: string\n): SpaceMembersPanelSectionSource[] {\n if (!normalizedQuery) {\n return [...sections];\n }\n\n return sections\n .map((section) => ({\n id: section.id,\n title: section.title,\n items: section.items\n .filter((item) => item.searchKey.includes(normalizedQuery))\n .map((item) => ({ ...item })),\n }))\n .filter((section) => section.items.length > 0);\n}\n\nfunction normalizeSearchQuery(query: string): string {\n return query.trim().toLowerCase();\n}\n\nfunction resolveLogsEmptyLines(\n sectionCount: number,\n normalizedQuery: string\n): readonly string[] {\n if (sectionCount > 0) {\n return [];\n }\n return normalizedQuery ? [LOGS_NO_MATCHES_LINE] : [pc.dim(\"No logs yet.\")];\n}\n\nfunction buildLogsSearchKey(title: string, lines: readonly string[]): string {\n return normalizeSearchQuery(\n [title, ...lines].map((line) => stripVTControlCharacters(line)).join(\" \")\n );\n}\n\nfunction resolveConnectionModeLabel(\n connectionMode: SpaceSessionContext[\"connectionMode\"]\n): string {\n if (connectionMode === \"watch\") {\n return \"watch-only stream\";\n }\n if (connectionMode === \"history\") {\n return \"history viewer\";\n }\n return \"interactive chat\";\n}\n\nfunction buildPanelBodyBlocks(\n sections: readonly (PanelBodyBlockViewState | null)[]\n): readonly PanelBodyBlockViewState[] {\n return sections.filter((section): section is PanelBodyBlockViewState => {\n if (!section) {\n return false;\n }\n\n return section.kind === \"facts\"\n ? section.items.length > 0\n : section.lines.length > 0;\n });\n}\n\nfunction buildSpaceInfoFactsFromData(\n spaceInfo: ReturnType<typeof buildSpaceInfoData>,\n context?: SpaceSessionContext\n): readonly PanelFactItemViewState[] {\n const facts = spaceInfo.facts.map<PanelFactItemViewState>((fact) => ({\n label: fact.label,\n value: fact.value,\n span: SPACE_INFO_FULL_WIDTH_LABELS.has(fact.label) ? \"full\" : \"column\",\n }));\n\n const storageValue =\n context === undefined\n ? null\n : formatStorageUsageDetailText({\n usedBytes: context.session.storageUsedBytes ?? null,\n softLimitBytes: context.session.storageSoftLimitBytes ?? null,\n usagePercent: context.session.storageUsagePercent ?? null,\n });\n\n return storageValue\n ? [\n ...facts,\n {\n label: \"Storage\",\n value: storageValue,\n span: \"column\",\n },\n ]\n : facts;\n}\n\nfunction buildPanelFactsSection(\n items: readonly PanelFactItemViewState[]\n): PanelBodyBlockViewState {\n return {\n kind: \"facts\",\n items: [...items],\n };\n}\n\nfunction buildPanelLinesSection(\n lines: readonly string[]\n): PanelBodyBlockViewState {\n return {\n kind: \"lines\",\n lines: [...lines],\n };\n}\n","import pc from \"picocolors\";\n\nexport function renderTextInputCursor(): string {\n return pc.white(\"█\");\n}\n","export type SpacePanelKind = \"help\" | \"space\" | \"members\" | \"logs\";\n\nexport type SpacePanelMode = \"readonly\" | \"searchable_list\";\n\nexport type SpacePanelLayout = \"centered_modal\";\n\nexport type SpacePanelContentAlign = \"left\" | \"centered_block\";\n\nexport type SpacePanelSurfaceVariant = \"dark\" | \"light\";\n\nexport type PanelInstruction = {\n id: string;\n keys: readonly string[];\n label: string;\n};\n\nexport type PanelInstructionPreset = \"readonly-close\" | \"searchable-list-close\";\n\nexport type SpacePanelDefinition = {\n contentAlign: SpacePanelContentAlign;\n kind: SpacePanelKind;\n layout: SpacePanelLayout;\n mode: SpacePanelMode;\n surfaceVariant: SpacePanelSurfaceVariant;\n title: string;\n instructionPreset: PanelInstructionPreset;\n};\n\nconst SPACE_PANEL_DEFINITIONS = [\n {\n contentAlign: \"left\",\n kind: \"help\",\n title: \"Space Commands\",\n mode: \"readonly\",\n layout: \"centered_modal\",\n surfaceVariant: \"dark\",\n instructionPreset: \"readonly-close\",\n },\n {\n contentAlign: \"left\",\n kind: \"space\",\n title: \"🛰️ Space Info\",\n mode: \"readonly\",\n layout: \"centered_modal\",\n surfaceVariant: \"dark\",\n instructionPreset: \"readonly-close\",\n },\n {\n contentAlign: \"left\",\n kind: \"members\",\n title: \"👥 Space Members\",\n mode: \"searchable_list\",\n layout: \"centered_modal\",\n surfaceVariant: \"dark\",\n instructionPreset: \"searchable-list-close\",\n },\n {\n contentAlign: \"left\",\n kind: \"logs\",\n title: \"🗒️ Space Logs\",\n mode: \"searchable_list\",\n layout: \"centered_modal\",\n surfaceVariant: \"dark\",\n instructionPreset: \"searchable-list-close\",\n },\n] as const satisfies readonly SpacePanelDefinition[];\n\nconst SPACE_PANEL_DEFINITION_BY_KIND = new Map(\n SPACE_PANEL_DEFINITIONS.map(\n (definition) => [definition.kind, definition] as const\n )\n);\n\nconst PANEL_INSTRUCTION_PRESETS = {\n \"readonly-close\": [\n {\n id: \"close\",\n keys: [\"Esc\"],\n label: \"close\",\n },\n ],\n \"searchable-list-close\": [\n {\n id: \"close\",\n keys: [\"Esc\"],\n label: \"close\",\n },\n ],\n} as const satisfies Record<\n PanelInstructionPreset,\n readonly PanelInstruction[]\n>;\n\nexport function getSpacePanelDefinition(\n kind: SpacePanelKind\n): SpacePanelDefinition {\n const definition = SPACE_PANEL_DEFINITION_BY_KIND.get(kind);\n if (!definition) {\n throw new Error(`Unknown space panel kind: ${kind}`);\n }\n return definition;\n}\n\nexport function listSpacePanelInstructions(\n preset: PanelInstructionPreset\n): readonly PanelInstruction[] {\n return PANEL_INSTRUCTION_PRESETS[preset];\n}\n\nexport function formatPanelInstructionsLine(\n instructions: readonly PanelInstruction[]\n): string {\n if (instructions.length === 0) {\n return \"\";\n }\n\n if (\n instructions.length === 1 &&\n instructions[0]?.id === \"close\" &&\n matchesInstructionKeys(instructions[0].keys, [\"Esc\"])\n ) {\n return \"Press Esc to close.\";\n }\n\n return instructions\n .map((instruction) => `${instruction.keys.join(\"/\")}: ${instruction.label}`)\n .join(\" · \");\n}\n\nfunction matchesInstructionKeys(\n actual: readonly string[],\n expected: readonly string[]\n): boolean {\n if (actual.length !== expected.length) {\n return false;\n }\n return actual.every((value, index) => value === expected[index]);\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport pc from \"picocolors\";\nimport stringWidth from \"string-width\";\nimport { renderPositiveAccentText } from \"../../ui/positive-accent\";\nimport { renderTextInputCursor } from \"../../ui/text-input-cursor\";\nimport type {\n PanelBodyBlockViewState,\n PanelFactItemViewState,\n PanelViewState,\n SearchablePanelItemViewState,\n} from \"../view/space-session-view-state\";\nimport { formatPanelInstructionsLine } from \"./space-panel-definition\";\n\nconst PANEL_COLUMN_GAP = 4;\nconst PANEL_TWO_COLUMN_MIN_WIDTH = 88;\nconst WHITESPACE_SPLIT_REGEX = /\\s+/u;\n\nexport type PanelDisplaySections = {\n bodyAnchorLineIndex: number | null;\n bodyItemAnchors: readonly PanelDisplayBodyItemAnchor[];\n bodyLines: readonly string[];\n controlLines: readonly string[];\n footerLines: readonly string[];\n headerLines: readonly string[];\n};\n\nexport type PanelDisplayBodyItemAnchor = {\n id: string;\n lineIndex: number;\n};\n\nexport function buildPanelDisplayLines(input: {\n includeControls?: boolean;\n panel: PanelViewState;\n contentWidth?: number;\n}): string[] {\n return joinPanelDisplaySections(\n buildPanelDisplaySections({\n contentWidth: input.contentWidth,\n includeControls: input.includeControls,\n panel: input.panel,\n })\n );\n}\n\nexport function buildPanelDisplaySections(input: {\n includeControls?: boolean;\n panel: PanelViewState;\n contentWidth?: number;\n}): PanelDisplaySections {\n const contentWidth = input.contentWidth ?? 0;\n const title = input.panel.title.trim();\n const headerMetaText = input.panel.headerMetaText?.trim() ?? \"\";\n const includeControls = input.includeControls ?? true;\n const searchableDisplay =\n input.panel.mode === \"searchable_list\" && includeControls\n ? renderSearchablePanelDisplay(input.panel.searchableList)\n : null;\n const controlLines =\n searchableDisplay?.controlLines ??\n (input.panel.mode === \"searchable_list\" && includeControls\n ? buildSearchableControlLines(input.panel.searchableList)\n : []);\n const bodyLines = alignPanelBodyLines(\n searchableDisplay?.bodyLines ??\n renderPanelBodyBlocks(input.panel.body.blocks, contentWidth),\n contentWidth,\n input.panel.contentAlign\n );\n const instructionLine = renderPanelInstructionText(input.panel);\n return {\n bodyAnchorLineIndex: searchableDisplay?.activeLineIndex ?? null,\n bodyItemAnchors: searchableDisplay?.itemAnchors ?? [],\n bodyLines,\n controlLines,\n footerLines: instructionLine ? [instructionLine] : [],\n headerLines: buildPanelHeaderLines({\n contentWidth,\n headerMetaText,\n title,\n }),\n };\n}\n\nfunction renderPanelInstructionText(panel: PanelViewState): string {\n const instructionLine = formatPanelInstructionsLine(panel.instructions);\n if (!instructionLine) {\n return \"\";\n }\n const closeInstruction = `${pc.dim(\"Press \")}Esc${pc.dim(\" to close.\")}`;\n if (panel.mode === \"searchable_list\") {\n return `${closeInstruction}${pc.dim(\" Type to search.\")}`;\n }\n return closeInstruction;\n}\n\nexport function formatPanelOverflowHintLine(input: {\n hiddenAfter: number;\n hiddenBefore: number;\n}): string | null {\n if (input.hiddenBefore === 0 && input.hiddenAfter === 0) {\n return null;\n }\n\n const parts: string[] = [];\n if (input.hiddenBefore > 0) {\n parts.push(\n renderPositiveAccentText(`↑ ${String(input.hiddenBefore)} more`)\n );\n }\n if (input.hiddenAfter > 0) {\n parts.push(renderPositiveAccentText(`↓ ${String(input.hiddenAfter)} more`));\n }\n return parts.join(pc.dim(\" · \"));\n}\n\nexport function joinPanelDisplaySections(\n sections: PanelDisplaySections\n): string[] {\n const renderedSections = [\n [...sections.headerLines],\n [...sections.controlLines],\n [...sections.bodyLines],\n [...sections.footerLines],\n ].filter((lines) => lines.length > 0);\n\n return renderedSections.flatMap((lines, index) => {\n if (index === 0) {\n return lines;\n }\n return [\"\", ...lines];\n });\n}\n\nfunction alignPanelBodyLines(\n lines: readonly string[],\n width: number,\n contentAlign: PanelViewState[\"contentAlign\"]\n): string[] {\n if (contentAlign !== \"centered_block\" || lines.length === 0) {\n return [...lines];\n }\n\n const blockWidth = lines.reduce((maxWidth, line) => {\n return Math.max(maxWidth, stringWidth(line));\n }, 0);\n const leftPadding = Math.max(0, Math.floor((width - blockWidth) / 2));\n const padding = \" \".repeat(leftPadding);\n\n return lines.map((line) => {\n if (!line.trim()) {\n return line;\n }\n return `${padding}${line}`;\n });\n}\n\nfunction buildPanelHeaderLines(input: {\n contentWidth: number;\n headerMetaText: string;\n title: string;\n}): string[] {\n if (!(input.title || input.headerMetaText)) {\n return [];\n }\n\n if (!input.title) {\n return [pc.dim(input.headerMetaText)];\n }\n\n if (!input.headerMetaText) {\n return [input.title];\n }\n\n const titleWidth = stringWidth(stripVTControlCharacters(input.title));\n const headerMetaWidth = stringWidth(input.headerMetaText);\n const minimumGapWidth = 2;\n\n if (\n input.contentWidth > 0 &&\n titleWidth + minimumGapWidth + headerMetaWidth <= input.contentWidth\n ) {\n const gapWidth = Math.max(\n minimumGapWidth,\n input.contentWidth - titleWidth - headerMetaWidth\n );\n return [\n `${input.title}${\" \".repeat(gapWidth)}${pc.dim(input.headerMetaText)}`,\n ];\n }\n\n if (input.contentWidth > 0) {\n return [\n input.title,\n padVisibleStart(pc.dim(input.headerMetaText), input.contentWidth),\n ];\n }\n\n return [input.title, pc.dim(input.headerMetaText)];\n}\n\nfunction renderPanelBodyBlocks(\n blocks: readonly PanelBodyBlockViewState[],\n contentWidth: number\n): string[] {\n const renderedBlocks = blocks\n .map((block) => renderPanelBodyBlock(block, contentWidth))\n .filter((lines) => lines.length > 0);\n\n return renderedBlocks.flatMap((lines, index) => {\n if (index === 0) {\n return lines;\n }\n return [\"\", ...lines];\n });\n}\n\nfunction renderPanelBodyBlock(\n block: PanelBodyBlockViewState,\n contentWidth: number\n): string[] {\n switch (block.kind) {\n case \"facts\":\n return renderFactsBlock(block.items, contentWidth);\n case \"lines\":\n return [...block.lines];\n default:\n return assertUnreachable(block);\n }\n}\n\nfunction buildSearchableControlLines(\n searchableList: PanelViewState[\"searchableList\"]\n): string[] {\n if (!searchableList) {\n return [];\n }\n\n const controlLabel = pc.dim(searchableList.control.label);\n const controlValue = renderSearchableControlValue(searchableList.control);\n return [`${controlLabel} ${controlValue}`];\n}\n\nfunction renderSearchableControlValue(\n control: NonNullable<PanelViewState[\"searchableList\"]>[\"control\"]\n): string {\n if (control.query.length > 0) {\n return `${control.query}${renderTextInputCursor()}`;\n }\n return `${renderTextInputCursor()} ${pc.dim(control.placeholder)}`;\n}\n\nfunction renderSearchablePanelDisplay(\n searchableList: PanelViewState[\"searchableList\"]\n): {\n activeLineIndex: number | null;\n bodyLines: readonly string[];\n controlLines: readonly string[];\n itemAnchors: readonly PanelDisplayBodyItemAnchor[];\n} | null {\n if (!searchableList) {\n return null;\n }\n\n const itemAnchors: PanelDisplayBodyItemAnchor[] = [];\n const lines: string[] = [];\n const sections = searchableList.sections.filter(\n (section) => section.items.length > 0\n );\n\n if (sections.length === 0) {\n return {\n activeLineIndex: null,\n bodyLines: searchableList.emptyLines,\n controlLines: buildSearchableControlLines(searchableList),\n itemAnchors: [],\n };\n }\n\n let activeLineIndex: number | null = null;\n for (const [sectionIndex, section] of sections.entries()) {\n if (sectionIndex > 0) {\n lines.push(\"\");\n }\n if (section.title) {\n lines.push(pc.bold(section.title));\n }\n\n for (const item of section.items) {\n const itemLineIndex = lines.length;\n itemAnchors.push({\n id: item.id,\n lineIndex: itemLineIndex,\n });\n if (item.id === searchableList.activeItemId && activeLineIndex === null) {\n activeLineIndex = itemLineIndex;\n }\n lines.push(\n ...renderSearchablePanelItemLines(\n item,\n item.id === searchableList.activeItemId\n )\n );\n }\n }\n\n return {\n activeLineIndex,\n bodyLines: lines,\n controlLines: buildSearchableControlLines(searchableList),\n itemAnchors,\n };\n}\n\nfunction renderSearchablePanelItemLines(\n item: SearchablePanelItemViewState,\n active: boolean\n): string[] {\n return item.lines.map((line, lineIndex) => {\n let prefix = \" \";\n if (lineIndex === 0) {\n prefix = active ? pc.cyan(\"❯ \") : \" \";\n }\n return `${prefix}${line}`;\n });\n}\n\nfunction renderFactsBlock(\n items: readonly PanelFactItemViewState[],\n contentWidth: number\n): string[] {\n const fullWidthFacts = items.filter((item) => item.span === \"full\");\n const columnFacts = items.filter((item) => item.span === \"column\");\n const lines: string[] = [];\n\n for (const item of fullWidthFacts) {\n lines.push(renderInlineFact(item));\n }\n\n if (fullWidthFacts.length > 0 && columnFacts.length > 0) {\n lines.push(\"\");\n }\n\n if (columnFacts.length > 0) {\n lines.push(...renderColumnFacts(columnFacts, contentWidth));\n }\n\n return lines;\n}\n\nfunction renderInlineFact(item: PanelFactItemViewState): string {\n return `${pc.dim(item.label)} ${item.value}`;\n}\n\nfunction renderColumnFacts(\n items: readonly PanelFactItemViewState[],\n contentWidth: number\n): string[] {\n if (contentWidth < PANEL_TWO_COLUMN_MIN_WIDTH) {\n return renderStackedFacts(items);\n }\n\n const columnWidth = Math.max(\n 1,\n Math.floor((contentWidth - PANEL_COLUMN_GAP) / 2)\n );\n const lines: string[] = [];\n\n for (let index = 0; index < items.length; index += 2) {\n const left = items[index];\n if (!left) {\n continue;\n }\n const right = items[index + 1];\n const leftLines = buildFactCellLines(left, columnWidth);\n const rightLines = right ? buildFactCellLines(right, columnWidth) : [];\n const rowHeight = Math.max(leftLines.length, rightLines.length);\n\n for (let lineIndex = 0; lineIndex < rowHeight; lineIndex += 1) {\n const leftLine = leftLines[lineIndex] ?? \"\";\n if (!right) {\n lines.push(leftLine);\n continue;\n }\n const rightLine = rightLines[lineIndex] ?? \"\";\n lines.push(\n `${padVisibleEnd(leftLine, columnWidth)}${\" \".repeat(\n PANEL_COLUMN_GAP\n )}${rightLine}`\n );\n }\n\n if (index + 2 < items.length) {\n lines.push(\"\");\n }\n }\n\n return lines;\n}\n\nfunction renderStackedFacts(\n items: readonly PanelFactItemViewState[]\n): string[] {\n const lines: string[] = [];\n\n for (const [index, item] of items.entries()) {\n lines.push(pc.dim(item.label));\n lines.push(item.value);\n if (index < items.length - 1) {\n lines.push(\"\");\n }\n }\n\n return lines;\n}\n\nfunction buildFactCellLines(\n item: PanelFactItemViewState,\n width: number\n): string[] {\n return [pc.dim(item.label), ...wrapText(item.value, width)];\n}\n\nfunction wrapText(value: string, width: number): string[] {\n const normalized = value.trim();\n if (!normalized) {\n return [\"\"];\n }\n\n const words = normalized.split(WHITESPACE_SPLIT_REGEX);\n const lines: string[] = [];\n let currentLine = \"\";\n\n for (const word of words) {\n const wordWidth = stringWidth(word);\n if (wordWidth > width) {\n if (currentLine) {\n lines.push(currentLine);\n currentLine = \"\";\n }\n lines.push(...splitLongToken(word, width));\n continue;\n }\n\n const nextLine = currentLine ? `${currentLine} ${word}` : word;\n if (stringWidth(nextLine) <= width) {\n currentLine = nextLine;\n continue;\n }\n\n lines.push(currentLine);\n currentLine = word;\n }\n\n if (currentLine) {\n lines.push(currentLine);\n }\n\n return lines.length > 0 ? lines : [normalized];\n}\n\nfunction splitLongToken(value: string, width: number): string[] {\n const segments: string[] = [];\n let currentSegment = \"\";\n\n for (const character of Array.from(value)) {\n const nextSegment = `${currentSegment}${character}`;\n if (stringWidth(nextSegment) <= width) {\n currentSegment = nextSegment;\n continue;\n }\n\n if (currentSegment) {\n segments.push(currentSegment);\n }\n currentSegment = character;\n }\n\n if (currentSegment) {\n segments.push(currentSegment);\n }\n\n return segments;\n}\n\nfunction padVisibleEnd(value: string, width: number): string {\n const visibleWidth = stringWidth(stripVTControlCharacters(value));\n return `${value}${\" \".repeat(Math.max(0, width - visibleWidth))}`;\n}\n\nfunction padVisibleStart(value: string, width: number): string {\n const visibleWidth = stringWidth(stripVTControlCharacters(value));\n return `${\" \".repeat(Math.max(0, width - visibleWidth))}${value}`;\n}\n\nfunction assertUnreachable(value: never): never {\n throw new Error(`Unknown panel body block: ${JSON.stringify(value)}`);\n}\n","import {\n resolveAuthenticationGuidance,\n resolveAuthenticationGuidanceFromError,\n} from \"../auth/auth-guidance\";\nimport { resolveAuthRequestCompatibility } from \"../config/auth-request-compatibility\";\nimport {\n type AuthSessionState,\n getAuthSessionState,\n} from \"../config/auth-session\";\nimport type { DaemonServiceRuntimeStatus } from \"../config/daemon-state\";\nimport {\n isOpenMeldLockError,\n resolveOpenMeldOrphanedLockIssue,\n} from \"../config/lock\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { resolveOpenMeldEnvPreset } from \"../config/paths\";\nimport { buildDaemonServiceRepairGuidance } from \"../local-service/lifecycle/daemon-service-repair-guidance\";\nimport type { DeviceRuntimeStateSyncResult } from \"../local-service/reporting/device-runtime-state-sync\";\nimport {\n formatInlineOpenMeldCliCommands,\n formatOpenMeldCliCommand,\n formatOpenMeldCliCommands,\n formatProfileAwareOpenMeldCliCommand,\n} from \"../runtime/cli-entry-command\";\nimport type { Presenter } from \"../runtime/presenter/types\";\nimport { resolveCurrentReplyReadinessSnapshot } from \"../system/current-reply-readiness-snapshot\";\nimport {\n classifyGatewayChainFailure,\n resolveGatewayChainRetryGuidance,\n} from \"../system/gateway-chain-readiness\";\nimport {\n type AgentReplyReadinessStatus,\n type DeviceReplyReadinessStatus,\n formatReplyReadinessSummary,\n type ReplyReadinessReasonCode,\n} from \"../system/reply-readiness\";\nimport {\n formatServiceParticipationReadinessLabel,\n formatServiceRuntimeHeadline,\n resolveServiceParticipationReadiness,\n type ServiceParticipationReadinessSummary,\n} from \"../system/service-participation-readiness\";\nimport { renderInfoCard } from \"../ui/info-card\";\nimport { resolveSpaceRequestTimeoutMsForDiagnostics } from \"./fetch-with-timeout\";\nimport { parseHttpFailure } from \"./http-failure\";\n\ntype SpaceCommandName =\n | \"create\"\n | \"join\"\n | \"send\"\n | \"add_members\"\n | \"remove_members\"\n | \"leave\";\n\ntype HumanServiceGuidanceMode = \"show\" | \"suppress\";\n\ntype SpacePreflightPayload = {\n command: SpaceCommandName;\n actionRequirements: {\n localService: \"not_required\" | \"required_for_local_agent_participation\";\n localServiceSummary: string;\n };\n auth: {\n state: AuthSessionState;\n ready: boolean;\n compatibleWithBaseUrl: boolean;\n authBaseUrl: string | null;\n gatewayUrl: string;\n };\n profile: {\n profileId: string;\n profileName: string;\n profileKind: OpenMeldProfile[\"profileKind\"];\n };\n agentReplyReadiness?: {\n reasonCodes: ReplyReadinessReasonCode[];\n reasonText: string;\n replyReadiness: \"blocked\" | \"degraded\" | \"ready\" | \"unknown\";\n } | null;\n services?: {\n daemon: {\n installed: boolean;\n version: string | null;\n runtimeStatus: DaemonServiceRuntimeStatus[\"status\"];\n runtimeReason: string | null;\n };\n };\n env: {\n baseUrl: string;\n requestTimeoutMs: number;\n };\n serviceRepairGuidance?: {\n reason:\n | \"service_needs_repair\"\n | \"service_update_available\"\n | \"service_not_running\"\n | \"service_not_installed\"\n | \"service_unknown\";\n summary: string;\n nextSteps: string[];\n } | null;\n};\n\nexport type SpaceSessionDiagnostics = {\n openMeldServiceLabel: string;\n canWakeLocalAgentsLabel: string;\n};\n\nexport type SpaceFailureGuidance = {\n reason:\n | \"auth_required\"\n | \"space_join_locked\"\n | \"space_password_required\"\n | \"space_password_invalid\"\n | \"space_password_too_short\"\n | \"space_send_timeout_uncertain\"\n | \"service_unavailable\"\n | \"local_dev_session_missing\"\n | \"binding_store_unavailable\"\n | \"daemon_control_contract_mismatch\"\n | \"daemon_control_endpoint_missing\";\n summary: string;\n steps: string[];\n};\n\nexport type SpaceCommandPreflightResult = {\n deviceReplyReadiness: DeviceReplyReadinessStatus;\n payload: SpacePreflightPayload;\n serviceParticipationReadiness: ServiceParticipationReadinessSummary;\n};\n\nconst SPACE_PASSWORD_REQUIRED_RE = /\\bspace[.\\s]+password[.\\s]+required\\b/i;\nconst SPACE_PASSWORD_INVALID_RE = /\\bspace[.\\s]+password[.\\s]+invalid\\b/i;\nconst SPACE_PASSWORD_TOO_SHORT_RE = /\\bpassword\\b.*\\btoo short\\b/i;\nconst SPACE_PASSWORD_MIN_LENGTH_RE = /\\bat least\\s+6\\s+characters?\\b/i;\nconst SPACE_LOCKED_RE = /^space is locked \\(/i;\nconst LOCAL_AGENT_BINDING_LOOKUP_FAILED_CODE =\n \"controller.binding.lookup_failed\";\n\nexport async function resolveSpaceSessionDiagnostics(input: {\n baseUrl: string;\n profile: OpenMeldProfile;\n}): Promise<SpaceSessionDiagnostics> {\n const snapshot = await resolveCurrentReplyReadinessSnapshot({\n baseUrl: input.baseUrl,\n ownerUserId: input.profile.ownerUserId,\n profile: input.profile,\n });\n\n const serviceParticipationReadiness = resolveServiceParticipationReadiness({\n deviceReplyReadiness: snapshot.deviceReplyReadiness,\n inventory: snapshot.inventory,\n runtimeStatus:\n snapshot.displayRuntimeStatus ?? snapshot.runtimeStatus ?? null,\n });\n\n return {\n openMeldServiceLabel:\n serviceParticipationReadiness.summaryText.toLowerCase(),\n canWakeLocalAgentsLabel: resolveCanWakeLocalAgentsLabel({\n agentReplyReadiness: snapshot.agentReplyReadiness,\n serviceParticipationReadiness,\n }),\n };\n}\n\nexport async function emitSpaceCommandPreflight(input: {\n presenter: Presenter;\n command: SpaceCommandName;\n profile: OpenMeldProfile;\n baseUrl: string;\n resolvedView: \"human\" | \"agent\";\n humanServiceGuidanceMode?: HumanServiceGuidanceMode;\n emitOutput?: boolean;\n runtimeProjection?: DeviceRuntimeStateSyncResult | null;\n}): Promise<SpaceCommandPreflightResult> {\n const actionRequirements = resolveSpacePreflightActionRequirements(\n input.command\n );\n const authState = await getAuthSessionState({ validateRemote: false });\n if (actionRequirements.localService === \"not_required\") {\n const preflight = buildLocalServiceNotRequiredPreflight({\n actionRequirements,\n authState,\n baseUrl: input.baseUrl,\n command: input.command,\n profile: input.profile,\n });\n if (shouldEmitSpaceCommandPreflightOutput(input.emitOutput)) {\n emitResolvedSpaceCommandPreflight({\n presenter: input.presenter,\n command: input.command,\n resolvedView: input.resolvedView,\n humanServiceGuidanceMode: input.humanServiceGuidanceMode ?? \"show\",\n preflight,\n });\n }\n return preflight;\n }\n\n const replyReadinessSnapshot = await resolveCurrentReplyReadinessSnapshot({\n baseUrl: input.baseUrl,\n checkGatewayChain: input.command === \"join\",\n ownerUserId: input.profile.ownerUserId,\n profile: input.profile,\n runtimeProjection: input.runtimeProjection,\n });\n const serviceParticipationReadiness = resolveServiceParticipationReadiness({\n deviceReplyReadiness: replyReadinessSnapshot.deviceReplyReadiness,\n inventory: replyReadinessSnapshot.inventory,\n runtimeStatus:\n replyReadinessSnapshot.displayRuntimeStatus ??\n replyReadinessSnapshot.runtimeStatus,\n });\n const payload: SpacePreflightPayload = {\n command: input.command,\n auth: {\n state: authState.state,\n ready: resolvePreflightAuthReadiness({\n authState,\n baseUrl: input.baseUrl,\n }),\n compatibleWithBaseUrl: resolvePreflightAuthCompatibility({\n authState,\n baseUrl: input.baseUrl,\n }),\n authBaseUrl:\n authState.state === \"valid\" && authState.session\n ? authState.session.authBaseUrl\n : null,\n gatewayUrl: input.baseUrl,\n },\n profile: {\n profileId: input.profile.openMeldProfileId,\n profileName: input.profile.profileName,\n profileKind: input.profile.profileKind,\n },\n actionRequirements,\n agentReplyReadiness: toSpacePreflightAgentReplyReadiness({\n command: input.command,\n readiness: replyReadinessSnapshot.agentReplyReadiness,\n }),\n services: {\n daemon: {\n installed: replyReadinessSnapshot.daemonStatus.installed,\n version: replyReadinessSnapshot.daemonStatus.installed\n ? replyReadinessSnapshot.daemonStatus.state.daemonVersion\n : null,\n runtimeStatus:\n replyReadinessSnapshot.displayRuntimeStatus?.status ??\n replyReadinessSnapshot.runtimeStatus?.status ??\n \"unknown\",\n runtimeReason:\n replyReadinessSnapshot.displayRuntimeStatus?.reason ??\n replyReadinessSnapshot.runtimeStatus?.reason ??\n null,\n },\n },\n env: {\n baseUrl: input.baseUrl,\n requestTimeoutMs: resolveSpaceRequestTimeoutMsForDiagnostics(),\n },\n serviceRepairGuidance: resolveSpacePreflightRepairGuidance({\n command: input.command,\n serviceParticipationReadiness,\n }),\n };\n\n if (!shouldEmitSpaceCommandPreflightOutput(input.emitOutput)) {\n return {\n deviceReplyReadiness: replyReadinessSnapshot.deviceReplyReadiness,\n payload,\n serviceParticipationReadiness,\n };\n }\n\n emitResolvedSpaceCommandPreflight({\n presenter: input.presenter,\n command: input.command,\n resolvedView: input.resolvedView,\n humanServiceGuidanceMode: input.humanServiceGuidanceMode ?? \"show\",\n preflight: {\n deviceReplyReadiness: replyReadinessSnapshot.deviceReplyReadiness,\n payload,\n serviceParticipationReadiness,\n },\n });\n\n return {\n deviceReplyReadiness: replyReadinessSnapshot.deviceReplyReadiness,\n payload,\n serviceParticipationReadiness,\n };\n}\n\nfunction buildLocalServiceNotRequiredPreflight(input: {\n actionRequirements: SpacePreflightPayload[\"actionRequirements\"];\n authState: Awaited<ReturnType<typeof getAuthSessionState>>;\n baseUrl: string;\n command: SpaceCommandName;\n profile: OpenMeldProfile;\n}): SpaceCommandPreflightResult {\n const deviceReplyReadiness: DeviceReplyReadinessStatus = {\n reasonCodes: [],\n reasonText: input.actionRequirements.localServiceSummary,\n replyReadiness: \"unknown\",\n updatedAt: new Date().toISOString(),\n wakeableRouteCount: 0,\n };\n const serviceParticipationReadiness: ServiceParticipationReadinessSummary = {\n serviceReadiness: \"unknown\",\n serviceReadinessState: \"unknown\",\n summaryText: \"not required\",\n detailText: input.actionRequirements.localServiceSummary,\n nextStepSummary: null,\n nextSteps: [],\n runtimeHeadline: \"unknown\",\n };\n const payload: SpacePreflightPayload = {\n command: input.command,\n auth: {\n state: input.authState.state,\n ready: resolvePreflightAuthReadiness({\n authState: input.authState,\n baseUrl: input.baseUrl,\n }),\n compatibleWithBaseUrl: resolvePreflightAuthCompatibility({\n authState: input.authState,\n baseUrl: input.baseUrl,\n }),\n authBaseUrl:\n input.authState.state === \"valid\" && input.authState.session\n ? input.authState.session.authBaseUrl\n : null,\n gatewayUrl: input.baseUrl,\n },\n profile: {\n profileId: input.profile.openMeldProfileId,\n profileName: input.profile.profileName,\n profileKind: input.profile.profileKind,\n },\n actionRequirements: input.actionRequirements,\n agentReplyReadiness: null,\n env: {\n baseUrl: input.baseUrl,\n requestTimeoutMs: resolveSpaceRequestTimeoutMsForDiagnostics(),\n },\n serviceRepairGuidance: null,\n };\n\n return {\n deviceReplyReadiness,\n payload,\n serviceParticipationReadiness,\n };\n}\n\nexport function emitResolvedSpaceCommandPreflight(input: {\n presenter: Presenter;\n command: SpaceCommandName;\n resolvedView: \"human\" | \"agent\";\n humanServiceGuidanceMode?: HumanServiceGuidanceMode;\n preflight: SpaceCommandPreflightResult;\n}): void {\n const { payload, serviceParticipationReadiness } = input.preflight;\n\n if (input.resolvedView === \"human\") {\n const authLabel = buildHumanPreflightAuthLabel(payload.auth);\n emitHumanSpaceCommandPreflight({\n presenter: input.presenter,\n command: input.command,\n authReady: payload.auth.ready,\n authLabel,\n profileName: payload.profile.profileName,\n guidance: payload.serviceRepairGuidance,\n serviceParticipationReadiness,\n humanServiceGuidanceMode: input.humanServiceGuidanceMode ?? \"show\",\n });\n return;\n }\n\n input.presenter.line({\n code: `space.${input.command}.preflight`,\n text: buildAgentSpaceCommandPreflightText({\n payload,\n serviceParticipationReadiness,\n }),\n data: payload,\n });\n emitSpacePreflightRepairGuidance({\n presenter: input.presenter,\n command: input.command,\n guidance: payload.serviceRepairGuidance,\n mode: shouldSurfaceServiceRepairGuidanceInPreflight(input.command)\n ? \"show\"\n : \"suppress\",\n });\n}\n\nfunction emitHumanSpaceCommandPreflight(input: {\n presenter: Presenter;\n command: SpaceCommandName;\n authReady: boolean;\n authLabel: string;\n profileName: string;\n guidance: SpacePreflightPayload[\"serviceRepairGuidance\"];\n serviceParticipationReadiness: ServiceParticipationReadinessSummary;\n humanServiceGuidanceMode: HumanServiceGuidanceMode;\n}): void {\n if (input.command === \"join\") {\n renderInfoCard({\n presenter: input.presenter,\n title: \"🔎 Join Quick Check\",\n codePrefix: \"space.join.preflight.card\",\n rows: [\n {\n label: input.authReady ? \"✅ Auth\" : \"⚠️ Auth\",\n value: input.authLabel,\n },\n {\n label: \"👤 Profile\",\n value: input.profileName,\n },\n {\n label: \"🧩 Local Service Link\",\n value: formatServiceParticipationReadinessLabel(\n input.serviceParticipationReadiness\n ),\n },\n {\n label: \"⚙️ OpenMeld Service Runtime\",\n value: formatServiceRuntimeHeadline(\n input.serviceParticipationReadiness.runtimeHeadline\n ),\n },\n ],\n sanitize: true,\n minContentWidth: 52,\n });\n emitSpacePreflightRepairGuidance({\n presenter: input.presenter,\n command: input.command,\n guidance: input.guidance,\n mode: input.humanServiceGuidanceMode,\n });\n return;\n }\n\n input.presenter.line({\n code: `space.${input.command}.preflight`,\n text: buildHumanSpaceCommandPreflightText({\n authLabel: input.authLabel,\n command: input.command,\n profileName: input.profileName,\n serviceParticipationReadiness: input.serviceParticipationReadiness,\n }),\n });\n emitSpacePreflightRepairGuidance({\n presenter: input.presenter,\n command: input.command,\n guidance: input.guidance,\n mode: input.humanServiceGuidanceMode,\n });\n}\n\nfunction shouldSurfaceServiceRepairGuidanceInPreflight(\n command: SpaceCommandName\n): boolean {\n return (\n resolveSpacePreflightActionRequirements(command).localService ===\n \"required_for_local_agent_participation\"\n );\n}\n\nfunction buildAgentSpaceCommandPreflightText(input: {\n payload: SpacePreflightPayload;\n serviceParticipationReadiness: ServiceParticipationReadinessSummary;\n}): string {\n if (input.payload.actionRequirements.localService === \"not_required\") {\n return `preflight ${input.payload.command}: auth=${input.payload.auth.state}, profile=${input.payload.profile.profileId}, local_service=not_required`;\n }\n\n return `preflight ${input.payload.command}: auth=${input.payload.auth.state}, profile=${input.payload.profile.profileId}, daemon=${input.payload.services?.daemon.runtimeStatus ?? \"unknown\"}, local_service_link=${input.serviceParticipationReadiness.serviceReadiness}, service_state=${input.serviceParticipationReadiness.serviceReadinessState}`;\n}\n\nfunction buildHumanSpaceCommandPreflightText(input: {\n authLabel: string;\n command: SpaceCommandName;\n profileName: string;\n serviceParticipationReadiness: ServiceParticipationReadinessSummary;\n}): string {\n const actionRequirements = resolveSpacePreflightActionRequirements(\n input.command\n );\n if (actionRequirements.localService === \"not_required\") {\n return `Quick check before ${input.command}: ${input.authLabel}, profile ${input.profileName}. ${actionRequirements.localServiceSummary}`;\n }\n\n return `Quick check before ${input.command}: ${input.authLabel}, profile ${input.profileName}, local service link: ${input.serviceParticipationReadiness.summaryText}.`;\n}\n\nfunction resolveSpacePreflightActionRequirements(\n command: SpaceCommandName\n): SpacePreflightPayload[\"actionRequirements\"] {\n if (command === \"create\") {\n return {\n localService: \"not_required\",\n localServiceSummary:\n \"OpenMeld Service is not required to create a Space.\",\n };\n }\n\n if (command === \"send\") {\n return {\n localService: \"not_required\",\n localServiceSummary:\n \"OpenMeld Service is not required to send a Space message.\",\n };\n }\n\n if (command === \"remove_members\" || command === \"leave\") {\n return {\n localService: \"not_required\",\n localServiceSummary:\n \"OpenMeld Service is not required for this Space command.\",\n };\n }\n\n return {\n localService: \"required_for_local_agent_participation\",\n localServiceSummary:\n \"OpenMeld Service is checked only for local agent participation from this computer.\",\n };\n}\n\nfunction resolveCanWakeLocalAgentsLabel(input: {\n agentReplyReadiness: AgentReplyReadinessStatus | null;\n serviceParticipationReadiness: ServiceParticipationReadinessSummary;\n}): string {\n if (input.agentReplyReadiness) {\n return formatReplyReadinessSummary({\n reasonCodes: input.agentReplyReadiness.reasonCodes,\n reasonText: input.agentReplyReadiness.reasonText,\n replyReadiness: input.agentReplyReadiness.replyReadiness,\n });\n }\n\n switch (input.serviceParticipationReadiness.serviceReadiness) {\n case \"ready\":\n return \"likely available\";\n case \"needs_repair\":\n return \"needs repair\";\n case \"not_running\":\n case \"not_installed\":\n return \"unavailable\";\n default:\n return \"unknown\";\n }\n}\n\nfunction resolvePreflightAuthReadiness(input: {\n authState: Awaited<ReturnType<typeof getAuthSessionState>>;\n baseUrl: string;\n}): boolean {\n if (input.authState.state !== \"valid\") {\n return false;\n }\n if (!input.authState.session) {\n return true;\n }\n\n return resolveAuthRequestCompatibility({\n session: input.authState.session,\n requestUrl: input.baseUrl,\n }).compatible;\n}\n\nfunction resolvePreflightAuthCompatibility(input: {\n authState: Awaited<ReturnType<typeof getAuthSessionState>>;\n baseUrl: string;\n}): boolean {\n if (input.authState.state !== \"valid\") {\n return false;\n }\n if (!input.authState.session) {\n return true;\n }\n\n return resolveAuthRequestCompatibility({\n session: input.authState.session,\n requestUrl: input.baseUrl,\n }).compatible;\n}\n\nfunction buildHumanPreflightAuthLabel(\n auth: SpacePreflightPayload[\"auth\"]\n): string {\n if (auth.ready) {\n return \"signed in\";\n }\n if (auth.state === \"valid\" && !auth.compatibleWithBaseUrl) {\n return `signed in to another OpenMeld environment (${auth.authBaseUrl ?? \"unknown\"}), not this gateway`;\n }\n return \"not signed in\";\n}\n\nfunction resolveSpacePreflightRepairGuidance(input: {\n command: SpaceCommandName;\n serviceParticipationReadiness: ServiceParticipationReadinessSummary;\n}): SpacePreflightPayload[\"serviceRepairGuidance\"] {\n if (\n resolveSpacePreflightActionRequirements(input.command).localService ===\n \"not_required\"\n ) {\n return null;\n }\n\n if (input.serviceParticipationReadiness.nextSteps.length === 0) {\n return null;\n }\n\n const nextSteps = input.serviceParticipationReadiness.nextSteps;\n if (\n nextSteps.length < 1 ||\n !input.serviceParticipationReadiness.nextStepSummary\n ) {\n return null;\n }\n\n return {\n reason: resolveSpacePreflightRepairReason(\n input.serviceParticipationReadiness\n ),\n summary: input.serviceParticipationReadiness.nextStepSummary,\n nextSteps,\n };\n}\n\nfunction resolveSpacePreflightRepairReason(\n serviceParticipationReadiness: ServiceParticipationReadinessSummary\n): NonNullable<SpacePreflightPayload[\"serviceRepairGuidance\"]>[\"reason\"] {\n if (\n serviceParticipationReadiness.serviceReadinessState === \"update_available\"\n ) {\n return \"service_update_available\";\n }\n switch (serviceParticipationReadiness.serviceReadiness) {\n case \"needs_repair\":\n return \"service_needs_repair\";\n case \"not_running\":\n return \"service_not_running\";\n case \"not_installed\":\n return \"service_not_installed\";\n default:\n return \"service_unknown\";\n }\n}\n\nfunction toSpacePreflightAgentReplyReadiness(input: {\n command: SpaceCommandName;\n readiness: AgentReplyReadinessStatus | null;\n}): SpacePreflightPayload[\"agentReplyReadiness\"] {\n if (!shouldIncludeWakeReadinessInSpacePreflight(input.command)) {\n return null;\n }\n if (!input.readiness) {\n return null;\n }\n\n return {\n reasonCodes: input.readiness.reasonCodes,\n reasonText: input.readiness.reasonText,\n replyReadiness: input.readiness.replyReadiness,\n };\n}\n\nfunction shouldIncludeWakeReadinessInSpacePreflight(\n command: SpaceCommandName\n): boolean {\n return command === \"join\";\n}\n\nfunction emitSpacePreflightRepairGuidance(input: {\n presenter: Presenter;\n command: SpaceCommandName;\n guidance: SpacePreflightPayload[\"serviceRepairGuidance\"];\n mode?: HumanServiceGuidanceMode;\n}): void {\n if (!input.guidance || input.mode === \"suppress\") {\n return;\n }\n\n input.presenter.line({\n code: `space.${input.command}.preflight.next_step`,\n text: `Next step: ${input.guidance.summary}`,\n data: {\n reason: input.guidance.reason,\n steps: input.guidance.nextSteps,\n },\n });\n}\n\nfunction shouldEmitSpaceCommandPreflightOutput(emitOutput?: boolean): boolean {\n return emitOutput !== false;\n}\n\nexport function emitSpaceFailureNextStep(input: {\n presenter: Presenter;\n command: SpaceCommandName;\n error: unknown;\n profileId?: string | null;\n resolvedView?: \"human\" | \"agent\" | string;\n}): void {\n const guidance = resolveSpaceFailureGuidance(input.error, {\n command: input.command,\n profileId: input.profileId,\n resolvedView: input.resolvedView,\n });\n if (!guidance) {\n return;\n }\n\n input.presenter.line({\n code: `space.${input.command}.next_step`,\n text: `Next step: ${guidance.summary}`,\n data: {\n reason: guidance.reason,\n steps: guidance.steps,\n },\n });\n}\n\nexport function resolveSpaceFailureGuidance(\n error: unknown,\n options: {\n command?: SpaceCommandName;\n profileId?: string | null;\n resolvedView?: \"human\" | \"agent\" | string;\n } = {}\n): SpaceFailureGuidance | null {\n const message = toErrorMessage(error);\n const lowered = message.toLowerCase();\n const localErrorCode = readErrorCode(error);\n const parsedHttpError = parseHttpFailure(error);\n const status = parsedHttpError?.status ?? null;\n const code = parsedHttpError?.code ?? \"\";\n const passwordRequiredByMessage = SPACE_PASSWORD_REQUIRED_RE.test(message);\n const passwordInvalidByMessage = SPACE_PASSWORD_INVALID_RE.test(message);\n const passwordTooShortByMessage =\n SPACE_PASSWORD_TOO_SHORT_RE.test(message) ||\n SPACE_PASSWORD_MIN_LENGTH_RE.test(message);\n const lockGuidance = resolveSpaceLockFailureGuidance(error, message);\n if (lockGuidance) {\n return lockGuidance;\n }\n\n if (code === \"space.password_required\" || passwordRequiredByMessage) {\n const whoamiCommand = formatSpaceFailureCliCommand(\n \"openmeld whoami\",\n options\n );\n const listSpacesCommand = formatSpaceFailureCliCommand(\n \"openmeld space list\",\n options\n );\n const joinWithPasswordCommand = formatSpaceFailureCliCommand(\n \"openmeld space join <space-id> --password <value>\",\n options\n );\n return {\n reason: \"space_password_required\",\n summary:\n \"this OpenMeld account has not joined this protected Space yet; join once with the Space password or switch to a profile that has access.\",\n steps: [whoamiCommand, listSpacesCommand, joinWithPasswordCommand],\n };\n }\n\n if (code === \"space.password_invalid\" || passwordInvalidByMessage) {\n const whoamiCommand = formatSpaceFailureCliCommand(\n \"openmeld whoami\",\n options\n );\n const listSpacesCommand = formatSpaceFailureCliCommand(\n \"openmeld space list\",\n options\n );\n const joinWithPasswordCommand = formatSpaceFailureCliCommand(\n \"openmeld space join <space-id> --password <value>\",\n options\n );\n return {\n reason: \"space_password_invalid\",\n summary:\n \"the provided Space password is invalid; confirm it or ask a Space member to add this profile.\",\n steps: [whoamiCommand, listSpacesCommand, joinWithPasswordCommand],\n };\n }\n\n if (code === \"space.password_too_short\" || passwordTooShortByMessage) {\n const listSpacesCommand = formatSpaceFailureCliCommand(\n \"openmeld space list\",\n options\n );\n const createWithPasswordCommand = formatSpaceFailureCliCommand(\n \"openmeld space create --name <name> --visibility <public|private> --password <value>\",\n options\n );\n const passwordUpdateCommand = formatSpaceFailureCliCommand(\n \"openmeld space password <space-id> --password <new-password>\",\n options\n );\n return {\n reason: \"space_password_too_short\",\n summary: \"password must be at least 6 characters.\",\n steps: [\n listSpacesCommand,\n createWithPasswordCommand,\n passwordUpdateCommand,\n ],\n };\n }\n\n if (\n status === 401 ||\n status === 403 ||\n lowered.includes(\"auth.unauthenticated\") ||\n lowered.includes(\"authentication required\")\n ) {\n const authGuidance =\n resolveAuthenticationGuidanceFromError(error) ??\n resolveAuthenticationGuidance({\n reason: \"required\",\n });\n return {\n reason: \"auth_required\",\n summary: authGuidance.errorNextStep,\n steps: formatOpenMeldCliCommands([\n \"openmeld login\",\n \"openmeld auth status --view agent\",\n ]),\n };\n }\n\n if (\n isBindingStoreUnavailableFailure({\n localErrorCode,\n message,\n parsedHttpError,\n })\n ) {\n const repairCommand = formatOpenMeldCliCommand(\"openmeld doctor --repair\");\n const migrateCommand = \"pnpm db:migrate:dev\";\n return {\n reason: \"binding_store_unavailable\",\n summary: `run \\`${migrateCommand}\\`, then \\`${repairCommand}\\`, then retry.`,\n steps: [migrateCommand, repairCommand],\n };\n }\n\n if (localErrorCode === \"daemon.control.contract_mismatch\") {\n const guidance = buildDaemonServiceRepairGuidance();\n return {\n reason: \"daemon_control_contract_mismatch\",\n summary: guidance.summary,\n steps: guidance.nextSteps,\n };\n }\n\n if (localErrorCode === \"daemon.control.endpoint_missing\") {\n const guidance = buildDaemonServiceRepairGuidance();\n return {\n reason: \"daemon_control_endpoint_missing\",\n summary: guidance.summary,\n steps: guidance.nextSteps,\n };\n }\n\n if (\n lowered.includes(\"network.timeout\") ||\n lowered.includes(\"timed out\") ||\n lowered.includes(\"upstream_unreachable\") ||\n lowered.includes(\"gateway is unreachable\") ||\n lowered.includes(\"can't reach the gateway\")\n ) {\n return resolveGatewayUnavailableFailureGuidance({\n code,\n command: options.command,\n message,\n parsedHttpError,\n status,\n });\n }\n\n return null;\n}\n\nfunction resolveSpaceLockFailureGuidance(\n error: unknown,\n message: string\n): SpaceFailureGuidance | null {\n if (!(isOpenMeldLockError(error) || SPACE_LOCKED_RE.test(message.trim()))) {\n return null;\n }\n const orphanedIssue = resolveOpenMeldOrphanedLockIssue(error);\n if (orphanedIssue) {\n return {\n reason: \"space_join_locked\",\n summary: orphanedIssue.summary,\n steps: orphanedIssue.primaryAction ? [orphanedIssue.primaryAction] : [],\n };\n }\n return {\n reason: \"space_join_locked\",\n summary: \"This profile has already joined this space.\",\n steps: [\n formatInlineOpenMeldCliCommands(\n \"Stop the other terminal session running `openmeld space join`.\"\n ),\n formatOpenMeldCliCommand(\"openmeld space join <space-id>\"),\n formatOpenMeldCliCommand(\"openmeld doctor --repair\"),\n ],\n };\n}\n\nfunction formatSpaceFailureCliCommand(\n command: string,\n options: {\n profileId?: string | null;\n resolvedView?: \"human\" | \"agent\" | string;\n }\n): string {\n if (options.profileId || options.resolvedView === \"agent\") {\n return formatProfileAwareOpenMeldCliCommand(command, {\n profileId: options.profileId,\n resolvedView: options.resolvedView,\n });\n }\n return formatOpenMeldCliCommand(command);\n}\n\nfunction resolveGatewayUnavailableFailureGuidance(input: {\n code: string;\n command?: SpaceCommandName;\n message: string;\n parsedHttpError: ReturnType<typeof parseHttpFailure>;\n status: number | null;\n}): SpaceFailureGuidance {\n if (input.command === \"send\") {\n return {\n reason: \"space_send_timeout_uncertain\",\n summary:\n \"the send request timed out before OpenMeld could confirm the result. Check recent text history before retrying so you do not duplicate a message.\",\n steps: [\n formatOpenMeldCliCommand(\n \"openmeld space history <space-id> --kind text --limit 20 --view agent\"\n ),\n ],\n };\n }\n const failureKind = classifyGatewayChainFailure({\n code: input.code,\n message: resolveGatewayFailureMessage(input),\n status: input.status,\n });\n if (failureKind === \"local_dev_session_missing\") {\n const guidance = resolveGatewayChainRetryGuidance({\n failureKind,\n lane: resolveOpenMeldEnvPreset(),\n });\n return {\n reason: \"local_dev_session_missing\",\n summary: guidance.summary,\n steps: guidance.nextSteps,\n };\n }\n return {\n reason: \"service_unavailable\",\n summary:\n \"OpenMeld Cloud service is temporarily unavailable. Try again after OpenMeld is reachable.\",\n steps: [],\n };\n}\n\nfunction resolveGatewayFailureMessage(input: {\n message: string;\n parsedHttpError: ReturnType<typeof parseHttpFailure>;\n}): string {\n return [input.parsedHttpError?.message ?? \"\", input.message]\n .filter((value) => value.length > 0)\n .join(\" \");\n}\n\nfunction isBindingStoreUnavailableFailure(input: {\n message: string;\n localErrorCode: string;\n parsedHttpError: ReturnType<typeof parseHttpFailure>;\n}): boolean {\n if (input.localErrorCode === LOCAL_AGENT_BINDING_LOOKUP_FAILED_CODE) {\n return true;\n }\n\n if (\n input.parsedHttpError?.upstreamCode ===\n LOCAL_AGENT_BINDING_LOOKUP_FAILED_CODE ||\n input.parsedHttpError?.code === LOCAL_AGENT_BINDING_LOOKUP_FAILED_CODE\n ) {\n return true;\n }\n\n const lowered = input.message.toLowerCase();\n return lowered.includes(\"openmeld_profiles unavailable\");\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n\nfunction readErrorCode(error: unknown): string {\n let current: unknown = error;\n const visited = new Set<object>();\n\n while (current && typeof current === \"object\") {\n if (visited.has(current)) {\n break;\n }\n visited.add(current);\n\n const record = current as {\n cause?: unknown;\n code?: unknown;\n };\n if (typeof record.code === \"string\") {\n return record.code;\n }\n current = record.cause;\n }\n\n return \"\";\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport type {\n DispatchResult,\n SpaceIdentityDirectory,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport {\n buildDispatchResultMessageReadProjection,\n buildSignalMessageReadProjection,\n type SpaceMessageReadProjection,\n type SpaceSignalIndex,\n} from \"@openmeld/space\";\nimport { formatOpenMeldCliCommand } from \"../../runtime/cli-entry-command\";\nimport type { DispatchExecutionEvidence } from \"./dispatch-execution-evidence\";\n\n// CLI adapter layer: decorate shared read truth onto command payloads without\n// owning read-projection or workflow semantics.\nexport type SpaceSignalThreadReplyPreview = {\n actorProfileId: string | null;\n actorProfileName: string | null;\n text: string | null;\n};\n\nexport type SpaceSignalThreadSummary = {\n threadId: string;\n replyCount: number;\n replyPreviews: SpaceSignalThreadReplyPreview[];\n};\n\nexport type FormalSignalReadPayload = SignalEnvelope & {\n diagnostics?: FormalSignalDiagnostics;\n dispatchExecution?: DispatchExecutionEvidence | null;\n messageReadProjection?: SpaceMessageReadProjection;\n thread?: SpaceSignalThreadSummary | null;\n};\n\nexport type FormalSignalDiagnostics = {\n summary: string;\n traceCommands: string[];\n};\n\nexport type FormalDispatchResultReadPayload = DispatchResult & {\n messageReadProjection: SpaceMessageReadProjection;\n};\n\nexport function buildFormalSignalReadPayload(input: {\n dispatchExecution?: DispatchExecutionEvidence | null;\n signal: SignalEnvelope;\n identityDirectory?: SpaceIdentityDirectory | null;\n membersSnapshot?: SpaceMembersSnapshot | null;\n signalIndex?: SpaceSignalIndex | null;\n thread?: SpaceSignalThreadSummary | null;\n}): FormalSignalReadPayload {\n if (!isMessageSemanticSignal(input.signal)) {\n return input.signal;\n }\n\n const messageReadProjection = buildSignalMessageReadProjection({\n signal: input.signal,\n identityDirectory: input.identityDirectory ?? null,\n membersSnapshot: input.membersSnapshot ?? null,\n signalIndex: input.signalIndex ?? null,\n });\n\n return {\n ...buildOptionalDispatchExecutionDecoration(input.dispatchExecution),\n ...buildOptionalSignalDiagnostics({\n messageReadProjection,\n signal: input.signal,\n }),\n ...input.signal,\n ...(input.thread ? { thread: input.thread } : {}),\n messageReadProjection,\n };\n}\n\nexport function buildFormalDispatchResultReadPayload(input: {\n result: DispatchResult;\n identityDirectory?: SpaceIdentityDirectory | null;\n membersSnapshot?: SpaceMembersSnapshot | null;\n signalIndex?: SpaceSignalIndex | null;\n}): FormalDispatchResultReadPayload {\n return {\n ...input.result,\n messageReadProjection: buildDispatchResultMessageReadProjection({\n result: input.result,\n identityDirectory: input.identityDirectory ?? null,\n membersSnapshot: input.membersSnapshot ?? null,\n signalIndex: input.signalIndex ?? null,\n }),\n };\n}\n\nfunction buildOptionalDispatchExecutionDecoration(\n dispatchExecution: DispatchExecutionEvidence | null | undefined\n): { dispatchExecution?: DispatchExecutionEvidence | null } {\n return dispatchExecution === undefined ? {} : { dispatchExecution };\n}\n\nfunction buildOptionalSignalDiagnostics(input: {\n messageReadProjection: SpaceMessageReadProjection;\n signal: SignalEnvelope;\n}): { diagnostics?: FormalSignalDiagnostics } {\n const traceCommands = buildSignalTraceCommands(input);\n if (traceCommands.length === 0) {\n return {};\n }\n return {\n diagnostics: {\n summary:\n \"Use a trace command to inspect dispatch, Wake execution authority, runtime execution, and result evidence for this message.\",\n traceCommands,\n },\n };\n}\n\nfunction buildSignalTraceCommands(input: {\n messageReadProjection: SpaceMessageReadProjection;\n signal: SignalEnvelope;\n}): string[] {\n const signalMeta = readObjectField(input.signal.data, \"meta\");\n const dispatchId =\n readStringField(input.signal.data, \"dispatchId\") ??\n readStringField(signalMeta, \"dispatchId\");\n if (dispatchId) {\n return [\n formatOpenMeldCliCommand(\n `openmeld service trace --space ${input.signal.spaceId} --dispatch ${dispatchId} --view agent`\n ),\n ];\n }\n\n const clientMessageId = readStringField(signalMeta, \"clientMessageId\");\n if (!clientMessageId) {\n return [];\n }\n\n return input.messageReadProjection.wakeTargets.map((target) =>\n formatOpenMeldCliCommand(\n `openmeld service trace --space ${input.signal.spaceId} --client-message ${clientMessageId} --target-profile ${target.profileId} --view agent`\n )\n );\n}\n\nfunction readObjectField(\n value: unknown,\n field: string\n): Record<string, unknown> | null {\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const nested = (value as Record<string, unknown>)[field];\n return nested && typeof nested === \"object\"\n ? (nested as Record<string, unknown>)\n : null;\n}\n\nfunction readStringField(value: unknown, field: string): string | null {\n if (!(value && typeof value === \"object\")) {\n return null;\n }\n const raw = (value as Record<string, unknown>)[field];\n if (typeof raw !== \"string\") {\n return null;\n }\n const normalized = raw.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction isMessageSemanticSignal(\n signal: SignalEnvelope\n): signal is\n | Extract<SignalEnvelope, { type: \"signal.text\" }>\n | Extract<SignalEnvelope, { type: \"signal.status\" }>\n | Extract<SignalEnvelope, { type: \"signal.system_notice\" }> {\n return (\n signal.type === \"signal.text\" ||\n signal.type === \"signal.status\" ||\n signal.type === \"signal.system_notice\"\n );\n}\n","import type { Profile } from \"@openmeld/protocol\";\nimport {\n parseOptionalClientMessageId,\n toCompatibleSpaceAddressingRequestWireValue,\n} from \"@openmeld/schemas\";\nimport type {\n MessageEnvelope,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport {\n makeHello,\n makeTextSignal,\n parseIncoming,\n parseServerErrorFrame,\n} from \"../../protocol/wire\";\nimport { connectWebSocket, type WsClient } from \"../../transport/ws\";\nimport { normalizePendingOutboundSourceText } from \"../pending-outbound-confirmation\";\nimport type {\n SpaceRuntimeEvent,\n SpaceRuntimeMessage,\n} from \"./space-runtime-events\";\n\nconst DEFAULT_BUFFERED_LIVE_EVENT_LIMIT = 2000;\nconst DEFAULT_PENDING_SEND_LIMIT = 200;\n\nexport type SpaceSessionRuntimeStartResult = {\n closed: Promise<void>;\n};\n\ntype SpaceSessionRuntimeInput = {\n wsUrl: string;\n wsHeaders: Record<string, string>;\n helloProfile: Profile;\n selfProfileId: string;\n loadMembers: () => Promise<SpaceMembersSnapshot | null>;\n replayHistory: (\n onEvent: (event: SpaceRuntimeMessage) => void\n ) => Promise<{ synced: boolean }>;\n formatError: (error: unknown) => string;\n scheduleDeferredWork?: (work: () => void) => void;\n bufferedLiveEventLimit?: number;\n pendingSendLimit?: number;\n};\n\ntype SpaceRuntimeListener = (event: SpaceRuntimeEvent) => void;\ntype PendingSentMessage = {\n clientMessageId: string;\n normalizedText: string | null;\n text: string;\n};\n\nexport type SpaceSessionSendReceipt =\n | {\n queued: true;\n clientMessageId: string;\n }\n | {\n queued: false;\n };\n\nexport class SpaceSessionRuntime {\n readonly #input: SpaceSessionRuntimeInput;\n readonly #listeners = new Set<SpaceRuntimeListener>();\n readonly #bufferedLiveEvents: SpaceRuntimeMessage[] = [];\n readonly #pendingSentMessages: PendingSentMessage[] = [];\n\n #ws: WsClient | null = null;\n #started = false;\n #stopRequested = false;\n #replayFinished = false;\n #bufferLiveEventsUntilReplayComplete = true;\n #closeEventDispatched = false;\n #forceTerminateTimer: NodeJS.Timeout | null = null;\n #historyLoadedReason: \"replay_error\" | \"live_buffer_overflow\" | null = null;\n\n constructor(input: SpaceSessionRuntimeInput) {\n this.#input = input;\n }\n\n subscribe(listener: SpaceRuntimeListener): () => void {\n this.#listeners.add(listener);\n return () => {\n this.#listeners.delete(listener);\n };\n }\n\n async start(): Promise<SpaceSessionRuntimeStartResult> {\n if (this.#started) {\n throw new Error(\"SpaceSessionRuntime.start() can only be called once\");\n }\n this.#started = true;\n\n const ws = await connectWebSocket(this.#input.wsUrl, {\n headers: this.#input.wsHeaders,\n });\n this.#ws = ws;\n\n ws.onMessage((raw) => {\n if (this.#stopRequested) {\n return;\n }\n const parsed = safeJsonParse(raw);\n const serverError = parseServerErrorFrame(parsed);\n if (serverError) {\n this.#maybeEmitSendFailed(serverError);\n return;\n }\n const event = parseIncoming(parsed);\n if (!event) {\n return;\n }\n this.#handleLiveEvent(event);\n });\n ws.onClose((code, reason) => {\n this.#emitConnectionClosed({\n source: \"close\",\n code,\n reason,\n });\n });\n ws.onError((error) => {\n this.#emitConnectionClosed({\n source: \"error\",\n reason: this.#input.formatError(error),\n error,\n });\n });\n\n const membersSnapshot = await this.#input.loadMembers();\n this.#emit({\n type: \"members.updated\",\n snapshot: membersSnapshot,\n });\n\n ws.send(JSON.stringify(makeHello(this.#input.helloProfile)));\n this.#emit({ type: \"connected\" });\n\n const scheduleDeferredWork =\n this.#input.scheduleDeferredWork ??\n ((work: () => void) => setImmediate(work));\n scheduleDeferredWork(() => {\n this.#startReplayAndDrain().catch(() => undefined);\n });\n\n return {\n closed: ws.waitUntilClosed(),\n };\n }\n\n stop(reason = \"stop requested\"): void {\n this.#stopRequested = true;\n if (!this.#ws) {\n return;\n }\n this.#ws.close(1000, reason);\n this.#forceTerminateTimer = setTimeout(() => {\n this.#ws?.terminate();\n }, 800);\n this.#ws\n .waitUntilClosed()\n .finally(() => {\n if (!this.#forceTerminateTimer) {\n return;\n }\n clearTimeout(this.#forceTerminateTimer);\n this.#forceTerminateTimer = null;\n })\n .catch(() => undefined);\n }\n\n sendText(input: {\n text: string;\n messageEnvelope?: MessageEnvelope;\n }): SpaceSessionSendReceipt {\n const text = input.text;\n if (!this.#ws) {\n this.#emit({\n type: \"send.failed\",\n clientMessageId: \"unknown-client-message\",\n text,\n error: \"space connection is not started\",\n });\n return {\n queued: false,\n };\n }\n\n const clientMessageId = crypto.randomUUID();\n try {\n this.#ws.send(\n JSON.stringify(\n toCompatibleSpaceAddressingRequestWireValue(\n makeTextSignal(text, {\n ...(input.messageEnvelope\n ? { messageEnvelope: input.messageEnvelope }\n : {}),\n meta: {\n clientMessageId,\n },\n })\n )\n )\n );\n this.#rememberPendingSentMessage({\n clientMessageId,\n normalizedText: normalizePendingOutboundSourceText(text),\n text,\n });\n this.#emit({\n type: \"send.queued\",\n clientMessageId,\n text,\n });\n return {\n queued: true,\n clientMessageId,\n };\n } catch (error) {\n this.#emit({\n type: \"send.failed\",\n clientMessageId,\n text,\n error: this.#input.formatError(error),\n });\n return {\n queued: false,\n };\n }\n }\n\n #emit(event: SpaceRuntimeEvent): void {\n for (const listener of this.#listeners) {\n listener(event);\n }\n }\n\n #handleLiveEvent(event: SpaceRuntimeMessage): void {\n if (this.#bufferLiveEventsUntilReplayComplete) {\n if (\n this.#bufferedLiveEvents.length <\n (this.#input.bufferedLiveEventLimit ??\n DEFAULT_BUFFERED_LIVE_EVENT_LIMIT)\n ) {\n this.#bufferedLiveEvents.push(event);\n return;\n }\n\n this.#historyLoadedReason = \"live_buffer_overflow\";\n this.#bufferLiveEventsUntilReplayComplete = false;\n this.#drainBufferedLiveEvents();\n }\n\n this.#emitSignalReceived(event, \"live\");\n }\n\n async #startReplayAndDrain(): Promise<void> {\n if (this.#replayFinished || this.#stopRequested) {\n return;\n }\n\n const replayState = await this.#input.replayHistory((event) => {\n this.#emitSignalReceived(event, \"history\");\n });\n if (this.#stopRequested) {\n this.#replayFinished = true;\n this.#bufferLiveEventsUntilReplayComplete = false;\n this.#bufferedLiveEvents.length = 0;\n return;\n }\n\n this.#replayFinished = true;\n this.#bufferLiveEventsUntilReplayComplete = false;\n const historyLoadedReason = resolveHistoryLoadedReason({\n replaySynced: replayState.synced,\n historyLoadedReason: this.#historyLoadedReason,\n });\n this.#emit({\n type: \"history.loaded\",\n synced: historyLoadedReason === null,\n ...(historyLoadedReason ? { reason: historyLoadedReason } : {}),\n });\n this.#drainBufferedLiveEvents();\n }\n\n #drainBufferedLiveEvents(): void {\n if (this.#bufferedLiveEvents.length === 0) {\n return;\n }\n const bufferedEvents = this.#bufferedLiveEvents.splice(0);\n for (const event of bufferedEvents) {\n this.#emitSignalReceived(event, \"live\");\n }\n }\n\n #emitSignalReceived(\n event: SpaceRuntimeMessage,\n source: \"history\" | \"live\"\n ): void {\n if (source === \"live\") {\n this.#maybeEmitSendConfirmed(event);\n }\n\n this.#emit({\n type: \"signal.received\",\n event,\n source,\n });\n }\n\n #rememberPendingSentMessage(message: PendingSentMessage): void {\n const pendingLimit =\n this.#input.pendingSendLimit ?? DEFAULT_PENDING_SEND_LIMIT;\n if (this.#pendingSentMessages.length >= pendingLimit) {\n this.#pendingSentMessages.shift();\n }\n this.#pendingSentMessages.push(message);\n }\n\n #maybeEmitSendConfirmed(event: SpaceRuntimeMessage): void {\n if (event.type !== \"signal.text\") {\n return;\n }\n const profileId = String(event.profile?.profileId ?? \"\").trim();\n if (!profileId || profileId !== this.#input.selfProfileId) {\n return;\n }\n const text = typeof event.data?.text === \"string\" ? event.data.text : \"\";\n const clientMessageId = resolveClientMessageId(event);\n if (clientMessageId) {\n const matchingIndex = this.#pendingSentMessages.findIndex(\n (message) => message.clientMessageId === clientMessageId\n );\n if (matchingIndex < 0) {\n return;\n }\n this.#pendingSentMessages.splice(matchingIndex, 1);\n this.#emit({\n type: \"send.confirmed\",\n clientMessageId,\n text,\n event,\n });\n return;\n }\n\n if (\n this.#pendingSentMessages[0]?.normalizedText !==\n normalizePendingOutboundSourceText(text)\n ) {\n return;\n }\n const pendingMessage = this.#pendingSentMessages.shift() ?? null;\n this.#emit({\n type: \"send.confirmed\",\n clientMessageId: pendingMessage?.clientMessageId ?? null,\n text,\n event,\n });\n }\n\n #maybeEmitSendFailed(input: {\n error: string;\n requestId?: string;\n clientMessageId?: string;\n }): void {\n if (this.#pendingSentMessages.length === 0) {\n return;\n }\n\n let matchingIndex = -1;\n const clientMessageId =\n typeof input.clientMessageId === \"string\" &&\n input.clientMessageId.trim().length > 0\n ? input.clientMessageId.trim()\n : null;\n if (clientMessageId) {\n matchingIndex = this.#pendingSentMessages.findIndex(\n (message) => message.clientMessageId === clientMessageId\n );\n }\n const failedMessage =\n matchingIndex >= 0\n ? (this.#pendingSentMessages.splice(matchingIndex, 1)[0] ?? null)\n : (this.#pendingSentMessages.shift() ?? null);\n if (!failedMessage) {\n return;\n }\n\n this.#emit({\n type: \"send.failed\",\n clientMessageId: failedMessage.clientMessageId,\n text: failedMessage.text,\n error: formatServerSendError(input),\n });\n }\n\n #emitConnectionClosed(input: {\n source: \"close\" | \"error\";\n reason: string;\n code?: number;\n error?: unknown;\n }): void {\n if (this.#closeEventDispatched) {\n return;\n }\n this.#closeEventDispatched = true;\n this.#emit({\n type: \"connection.closed\",\n source: input.source,\n reason: input.reason,\n ...(typeof input.code === \"number\" ? { code: input.code } : {}),\n ...(input.error === undefined ? {} : { error: input.error }),\n });\n }\n}\n\nfunction resolveHistoryLoadedReason(input: {\n replaySynced: boolean;\n historyLoadedReason: \"replay_error\" | \"live_buffer_overflow\" | null;\n}): \"replay_error\" | \"live_buffer_overflow\" | null {\n if (input.historyLoadedReason) {\n return input.historyLoadedReason;\n }\n if (!input.replaySynced) {\n return \"replay_error\";\n }\n return null;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\nfunction resolveClientMessageId(event: { data?: unknown }): string | null {\n const meta =\n event.data && typeof event.data === \"object\" && !Array.isArray(event.data)\n ? (event.data as { meta?: unknown }).meta\n : null;\n if (!(meta && typeof meta === \"object\") || Array.isArray(meta)) {\n return null;\n }\n return parseOptionalClientMessageId(\n (meta as { clientMessageId?: unknown }).clientMessageId\n );\n}\n\nfunction formatServerSendError(input: {\n error: string;\n requestId?: string;\n}): string {\n const error = String(input.error ?? \"\").trim() || \"unknown_error\";\n const requestId =\n typeof input.requestId === \"string\" ? input.requestId.trim() : \"\";\n if (!requestId) {\n return error;\n }\n return `${error} (requestId: ${requestId})`;\n}\n","export const INTERACTIVE_SPACE_SHELL_ENV_NAME =\n \"OPENMELD_SPACE_INTERACTIVE_SHELL\";\n\nexport type InteractiveHumanShellKind = \"legacy\" | \"pi-tui\";\n\nexport function resolveInteractiveHumanShellKind(): InteractiveHumanShellKind {\n const override = process.env[INTERACTIVE_SPACE_SHELL_ENV_NAME]\n ?.trim()\n .toLowerCase();\n if (override === \"legacy\" || override === \"pi-tui\") {\n return override;\n }\n if (!(process.stdin.isTTY === true && process.stdout.isTTY === true)) {\n return \"legacy\";\n }\n return \"pi-tui\";\n}\n","import {\n clearLine,\n createInterface,\n cursorTo,\n moveCursor,\n} from \"node:readline\";\nimport pc from \"picocolors\";\nimport stringWidth from \"string-width\";\nimport type { SpaceTranscriptItem } from \"../state/space-screen-state\";\nimport type { SpaceSessionViewState } from \"../view/space-session-view-state\";\nimport type { InteractiveSpaceShell } from \"./interactive-space-shell\";\n\nconst REPLYING_STATUS_PROMPT_GAP_LINES = 1;\nconst CHAT_GROUP_DIVIDER_MARGIN = 2;\nconst CHAT_GROUP_DIVIDER_MIN_WIDTH = 24;\nconst CHAT_GROUP_DIVIDER_MAX_WIDTH = 120;\nconst CHAT_GROUP_DIVIDER_CHAR = \"╌\";\nconst CHAT_GROUP_DIVIDER_SIDE_GAP_LINES = 1;\n\ntype LegacyInteractiveSpaceShellInput = {\n composePromptPrefix?: string;\n onLine: (line: string) => void;\n onClose: () => void;\n};\n\nexport class LegacyInteractiveSpaceShell implements InteractiveSpaceShell {\n readonly #composePromptPrefix: string;\n readonly #onLine: (line: string) => void;\n readonly #onClose: () => void;\n\n #readline: ReturnType<typeof createInterface> | null = null;\n #lastRenderedTranscriptCount = 0;\n #hasPrintedTextLine = false;\n #lastPrintedTextLineGroupKey: string | null = null;\n #nextDividerGapPlacement: \"top\" | \"bottom\" = \"top\";\n #visibleOverlayLine = \"\";\n #visibleOverlayLineRows = 0;\n #latestViewState: SpaceSessionViewState | null = null;\n #composerVisible = true;\n\n constructor(input: LegacyInteractiveSpaceShellInput) {\n this.#composePromptPrefix = input.composePromptPrefix ?? pc.dim(\"[draft] \");\n this.#onLine = input.onLine;\n this.#onClose = input.onClose;\n }\n\n start(): void {\n if (this.#readline) {\n return;\n }\n const readline = createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: process.stdout.isTTY === true,\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n this.#readline = readline;\n readline.on(\"line\", (line) => {\n if (!this.#composerVisible) {\n if (line.trim() === \"q\") {\n this.#onClose();\n }\n return;\n }\n this.#onLine(line);\n });\n readline.on(\"close\", () => {\n if (this.#readline === readline) {\n this.#readline = null;\n }\n this.#onClose();\n });\n if (this.#composerVisible) {\n readline.setPrompt(this.#resolvePrompt());\n readline.prompt();\n }\n }\n\n render(viewState: SpaceSessionViewState): void {\n this.#latestViewState = viewState;\n this.#composerVisible = viewState.composer.visible;\n this.#renderNewTranscriptItems(viewState.transcript.items);\n this.#syncOverlayLine(viewState.status.overlayLine);\n this.#refreshPrompt();\n }\n\n stop(): void {\n if (!this.#readline) {\n return;\n }\n const currentReadline = this.#readline;\n this.#readline = null;\n currentReadline.removeAllListeners(\"line\");\n currentReadline.removeAllListeners(\"close\");\n currentReadline.close();\n }\n\n clearSubmittedInputLine(line: string): void {\n if (!process.stdout.isTTY) {\n return;\n }\n this.#clearInteractiveOverlay({\n submittedInputText: line,\n });\n }\n\n prepareExternalWrite(): void {\n this.#clearInteractiveOverlay();\n }\n\n #renderNewTranscriptItems(items: readonly SpaceTranscriptItem[]): void {\n if (items.length <= this.#lastRenderedTranscriptCount) {\n return;\n }\n const nextItems = items.slice(this.#lastRenderedTranscriptCount);\n for (const item of nextItems) {\n this.#emitTranscriptItem(item);\n }\n this.#lastRenderedTranscriptCount = items.length;\n }\n\n #emitTranscriptItem(item: SpaceTranscriptItem): void {\n this.prepareExternalWrite();\n const isGroupBoundary =\n this.#hasPrintedTextLine &&\n this.#lastPrintedTextLineGroupKey !== item.groupKey;\n if (isGroupBoundary) {\n this.#emitTextGroupDivider();\n }\n process.stdout.write(`${item.line}\\n`);\n this.#hasPrintedTextLine = true;\n this.#lastPrintedTextLineGroupKey = item.groupKey;\n if (item.refreshPrompt !== false && this.#readline) {\n process.stdout.write(\"\\n\");\n }\n }\n\n #emitTextGroupDivider(): void {\n const dividerLine = buildChatGroupDividerLine();\n if (!dividerLine) {\n process.stdout.write(\"\\n\");\n return;\n }\n const useTopGap = this.#nextDividerGapPlacement === \"top\";\n const topGapLines = useTopGap ? CHAT_GROUP_DIVIDER_SIDE_GAP_LINES : 0;\n const bottomGapLines = useTopGap ? 0 : CHAT_GROUP_DIVIDER_SIDE_GAP_LINES;\n process.stdout.write(\n `${\"\\n\".repeat(topGapLines)}${dividerLine}\\n${\"\\n\".repeat(bottomGapLines)}`\n );\n this.#nextDividerGapPlacement = useTopGap ? \"bottom\" : \"top\";\n }\n\n #syncOverlayLine(nextOverlayLine: string): void {\n const normalizedText = nextOverlayLine.trim();\n if (!normalizedText) {\n this.#clearVisibleOverlayLine();\n return;\n }\n if (!(process.stdout.isTTY && this.#readline)) {\n return;\n }\n if (this.#visibleOverlayLine === normalizedText) {\n return;\n }\n if (this.#visibleOverlayLine.length > 0) {\n this.#clearVisibleOverlayLine();\n } else {\n this.prepareExternalWrite();\n }\n process.stdout.write(\n `${pc.dim(normalizedText)}${\"\\n\".repeat(REPLYING_STATUS_PROMPT_GAP_LINES + 1)}`\n );\n this.#visibleOverlayLine = normalizedText;\n this.#visibleOverlayLineRows = countRenderedTerminalRows(normalizedText);\n }\n\n #clearVisibleOverlayLine(): void {\n if (!(process.stdout.isTTY && this.#readline)) {\n return;\n }\n if (this.#visibleOverlayLine.length === 0) {\n return;\n }\n this.#clearInteractiveOverlay({\n includeVisibleOverlayLine: true,\n });\n }\n\n #clearInteractiveOverlay(input?: {\n submittedInputText?: string;\n includeVisibleOverlayLine?: boolean;\n }): void {\n if (!(this.#readline && process.stdout.isTTY)) {\n return;\n }\n const promptRowsAboveCurrent =\n typeof input?.submittedInputText === \"string\"\n ? this.#countPromptDisplayRows(input.submittedInputText)\n : this.#resolvePromptCursorRows();\n const visibleOverlayRowsAbovePrompt =\n input?.includeVisibleOverlayLine === true &&\n this.#visibleOverlayLine.length > 0\n ? REPLYING_STATUS_PROMPT_GAP_LINES + this.#visibleOverlayLineRows\n : 0;\n const rowsAboveCurrent =\n promptRowsAboveCurrent + visibleOverlayRowsAbovePrompt;\n clearLine(process.stdout, 0);\n cursorTo(process.stdout, 0);\n for (let rowOffset = 0; rowOffset < rowsAboveCurrent; rowOffset += 1) {\n moveCursor(process.stdout, 0, -1);\n clearLine(process.stdout, 0);\n cursorTo(process.stdout, 0);\n }\n if (input?.includeVisibleOverlayLine === true) {\n this.#visibleOverlayLine = \"\";\n this.#visibleOverlayLineRows = 0;\n }\n }\n\n #resolvePrompt(): string {\n if (!this.#composerVisible) {\n return \"\";\n }\n const basePrompt = this.#latestViewState?.composer.basePrompt ?? \"\";\n if (this.#latestViewState?.composer.hasDraft) {\n return `${this.#composePromptPrefix}${basePrompt}`;\n }\n return basePrompt;\n }\n\n #refreshPrompt(): void {\n const readline = this.#readline;\n if (!readline) {\n return;\n }\n if (!this.#composerVisible) {\n return;\n }\n try {\n readline.setPrompt(this.#resolvePrompt());\n readline.prompt(true);\n } catch {\n this.#readline = null;\n }\n }\n\n #resolvePromptCursorRows(): number {\n if (!(this.#readline && process.stdout.isTTY)) {\n return 0;\n }\n try {\n const rows = this.#readline.getCursorPos().rows;\n return Number.isInteger(rows) && rows > 0 ? rows : 0;\n } catch {\n return 0;\n }\n }\n\n #countPromptDisplayRows(inputText: string): number {\n const columns = resolveTerminalColumns();\n const promptWidth = stringWidth(this.#resolvePrompt());\n const inputWidth = stringWidth(inputText);\n const totalWidth = Math.max(1, promptWidth + inputWidth);\n return Math.max(1, Math.ceil(totalWidth / columns));\n }\n}\n\nfunction countRenderedTerminalRows(text: string): number {\n const columns = resolveTerminalColumns();\n const renderedRows = text.split(\"\\n\").reduce((rowCount, line) => {\n return (\n rowCount +\n Math.max(1, Math.ceil(Math.max(1, stringWidth(line)) / columns))\n );\n }, 0);\n return Math.max(1, renderedRows);\n}\n\nfunction buildChatGroupDividerLine(): string {\n if (process.stdout.isTTY !== true) {\n return \"\";\n }\n const columns = resolveTerminalColumns();\n const width = clampNumber(\n columns - CHAT_GROUP_DIVIDER_MARGIN * 2,\n CHAT_GROUP_DIVIDER_MIN_WIDTH,\n CHAT_GROUP_DIVIDER_MAX_WIDTH\n );\n const margin = \" \".repeat(CHAT_GROUP_DIVIDER_MARGIN);\n return pc.dim(pc.gray(`${margin}${CHAT_GROUP_DIVIDER_CHAR.repeat(width)}`));\n}\n\nfunction resolveTerminalColumns(): number {\n const rawColumns = process.stdout.columns;\n if (!Number.isInteger(rawColumns) || rawColumns < 1) {\n return 80;\n }\n return rawColumns;\n}\n\nfunction clampNumber(value: number, min: number, max: number): number {\n if (value < min) {\n return min;\n }\n if (value > max) {\n return max;\n }\n return value;\n}\n","import type { PanelViewState } from \"../view/space-session-view-state\";\nimport {\n getSpacePanelDefinition,\n listSpacePanelInstructions,\n type SpacePanelKind,\n} from \"./space-panel-definition\";\n\nexport function buildSpacePanelViewState(input: {\n bodyByKind: Record<SpacePanelKind, PanelViewState[\"body\"][\"blocks\"]>;\n headerMetaTextByKind?: Partial<Record<SpacePanelKind, string | null>>;\n kind: SpacePanelKind | \"none\";\n searchableListByKind?: Partial<\n Record<SpacePanelKind, NonNullable<PanelViewState[\"searchableList\"]>>\n >;\n}): PanelViewState | null {\n if (input.kind === \"none\") {\n return null;\n }\n\n const definition = getSpacePanelDefinition(input.kind);\n return {\n body: {\n blocks: input.bodyByKind[input.kind],\n },\n contentAlign: definition.contentAlign,\n headerMetaText: input.headerMetaTextByKind?.[input.kind] ?? null,\n kind: definition.kind,\n instructions: listSpacePanelInstructions(definition.instructionPreset),\n layout: definition.layout,\n mode: definition.mode,\n searchableList: input.searchableListByKind?.[input.kind] ?? null,\n surfaceVariant: definition.surfaceVariant,\n title: definition.title,\n visible: true,\n };\n}\n","import type { SpacePanelKind } from \"./panel/space-panel-definition\";\n\nexport const JOIN_MODE_SUMMARY_HINT = \"type /members to check\";\nexport const READONLY_MODE_SUMMARY_HINT =\n \"press m for members · l for logs · s for space\";\n\nconst WATCH_MODE_EXIT_HINT =\n \"Watch-only mode · m members · l logs · s space · Ctrl+D/Ctrl+C/q quit.\";\nconst HISTORY_VIEW_EXIT_HINT =\n \"History view · m members · l logs · s space · Ctrl+D/Ctrl+C/q quit.\";\n\nexport function resolveReadonlyOverlayShortcut(\n data: string\n): SpacePanelKind | null {\n if (data === \"/\" || data === \"?\") {\n return \"help\";\n }\n if (data === \"s\") {\n return \"space\";\n }\n if (data === \"m\") {\n return \"members\";\n }\n if (data === \"l\") {\n return \"logs\";\n }\n return null;\n}\n\nexport function resolveSessionHeaderSummaryHint(\n connectionMode: \"join\" | \"watch\" | \"history\"\n): string {\n switch (connectionMode) {\n case \"join\":\n return JOIN_MODE_SUMMARY_HINT;\n case \"watch\":\n case \"history\":\n return READONLY_MODE_SUMMARY_HINT;\n default:\n return JOIN_MODE_SUMMARY_HINT;\n }\n}\n\nexport function resolveReadonlySessionFooterText(\n connectionMode: \"watch\" | \"history\"\n): string {\n switch (connectionMode) {\n case \"watch\":\n return WATCH_MODE_EXIT_HINT;\n case \"history\":\n return HISTORY_VIEW_EXIT_HINT;\n default:\n return WATCH_MODE_EXIT_HINT;\n }\n}\n","import type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport type {\n ComposerActivityRowViewState,\n ComposerActivityViewState,\n ComposerDispatchRowState,\n DispatchActivityActorViewState,\n} from \"./space-session-view-state\";\n\nexport type ComposerActivitySource = {\n nowMs: number;\n rows: readonly ComposerDispatchRowState[];\n};\n\ntype ComposerActivityRowCandidate = ComposerActivityRowViewState & {\n previewUpdatedAtMs: number;\n startedAtMs: number;\n updatedAtMs: number;\n};\n\nconst MAX_COMPOSER_ACTIVITY_ROWS = 2;\n\nexport function buildComposerActivityViewState(\n source: ComposerActivitySource,\n spaceMembersSnapshot?: SpaceMembersSnapshot | null\n): ComposerActivityViewState {\n const rowCandidates = buildComposerActivityRowCandidates({\n nowMs: source.nowMs,\n rows: source.rows,\n });\n const visibleRows = selectVisibleRows(rowCandidates);\n const leadRow = visibleRows.at(-1) ?? null;\n const actors = visibleRows.flatMap((row) => row.actors);\n const overflowCount = Math.max(0, rowCandidates.length - visibleRows.length);\n\n if (!leadRow) {\n return {\n visible: false,\n mode: \"idle\",\n rows: [],\n overflowCount: 0,\n actors: [],\n leadActor: null,\n elapsedSeconds: null,\n previewText: \"\",\n hint: null,\n spaceMembersSnapshot: spaceMembersSnapshot ?? null,\n };\n }\n\n return {\n visible: true,\n mode: leadRow.mode,\n rows: visibleRows,\n overflowCount,\n actors,\n leadActor: leadRow.leadActor,\n elapsedSeconds: leadRow.elapsedSeconds,\n previewText: leadRow.previewText,\n hint: leadRow.hint,\n spaceMembersSnapshot: spaceMembersSnapshot ?? null,\n };\n}\n\nfunction buildComposerActivityRowCandidates(input: {\n nowMs: number;\n rows: readonly ComposerDispatchRowState[];\n}): ComposerActivityRowCandidate[] {\n return input.rows.map((row) =>\n toComposerActivityRowCandidate({\n nowMs: input.nowMs,\n row,\n })\n );\n}\n\nfunction toComposerActivityRowCandidate(input: {\n nowMs: number;\n row: ComposerDispatchRowState;\n}): ComposerActivityRowCandidate {\n const actor = toDispatchActivityActor(input.row);\n if (input.row.stage === \"replying\") {\n const previewText = input.row.latestPreviewText.trim();\n return {\n key: input.row.rowId,\n mode: previewText ? \"streaming\" : \"replying\",\n targetLabel: input.row.targetLabel,\n actors: actor ? [actor] : [],\n leadActor: actor,\n elapsedSeconds: Math.max(\n 0,\n Math.floor((input.nowMs - input.row.createdAtMs) / 1000)\n ),\n previewText,\n hint: null,\n previewUpdatedAtMs:\n input.row.latestPreviewUpdatedAtMs ?? Number.NEGATIVE_INFINITY,\n startedAtMs: input.row.createdAtMs,\n updatedAtMs: input.row.updatedAtMs,\n };\n }\n\n if (input.row.stage === \"sending\") {\n return {\n key: input.row.rowId,\n mode: \"sending\",\n targetLabel: input.row.targetLabel,\n actors: [],\n leadActor: null,\n elapsedSeconds: Math.max(\n 0,\n Math.floor((input.nowMs - input.row.createdAtMs) / 1000)\n ),\n previewText: \"\",\n hint: input.row.statusText || \"sending...\",\n previewUpdatedAtMs: Number.NEGATIVE_INFINITY,\n startedAtMs: input.row.createdAtMs,\n updatedAtMs: input.row.updatedAtMs,\n };\n }\n\n let mode: ComposerActivityRowViewState[\"mode\"] = \"warning\";\n if (input.row.stage === \"dispatching\") {\n mode = \"dispatching\";\n } else if (input.row.stage === \"retrying\") {\n mode = \"retrying\";\n }\n return {\n key: input.row.rowId,\n mode,\n targetLabel: input.row.targetLabel,\n actors: actor ? [actor] : [],\n leadActor: actor,\n elapsedSeconds: Math.max(\n 0,\n Math.floor((input.nowMs - input.row.createdAtMs) / 1000)\n ),\n previewText: \"\",\n hint:\n input.row.warningText ||\n input.row.statusText ||\n resolveDispatchActivityHintFallback(input.row),\n previewUpdatedAtMs: Number.NEGATIVE_INFINITY,\n startedAtMs: input.row.createdAtMs,\n updatedAtMs: input.row.updatedAtMs,\n };\n}\n\nfunction selectVisibleRows(\n rowCandidates: readonly ComposerActivityRowCandidate[]\n): ComposerActivityRowViewState[] {\n const latestRows = [...rowCandidates]\n .sort(compareComposerActivityRowsByRecencyDesc)\n .slice(0, MAX_COMPOSER_ACTIVITY_ROWS)\n .sort(compareComposerActivityRowsByRenderOrderAsc);\n return latestRows.map(\n ({ previewUpdatedAtMs, startedAtMs, updatedAtMs, ...row }) => row\n );\n}\n\nfunction compareComposerActivityRowsByRecencyDesc(\n left: ComposerActivityRowCandidate,\n right: ComposerActivityRowCandidate\n): number {\n if (right.updatedAtMs !== left.updatedAtMs) {\n return right.updatedAtMs - left.updatedAtMs;\n }\n if (right.previewUpdatedAtMs !== left.previewUpdatedAtMs) {\n return right.previewUpdatedAtMs - left.previewUpdatedAtMs;\n }\n if (right.startedAtMs !== left.startedAtMs) {\n return right.startedAtMs - left.startedAtMs;\n }\n return left.key.localeCompare(right.key);\n}\n\nfunction compareComposerActivityRowsByRenderOrderAsc(\n left: ComposerActivityRowCandidate,\n right: ComposerActivityRowCandidate\n): number {\n if (left.updatedAtMs !== right.updatedAtMs) {\n return left.updatedAtMs - right.updatedAtMs;\n }\n if (left.previewUpdatedAtMs !== right.previewUpdatedAtMs) {\n return left.previewUpdatedAtMs - right.previewUpdatedAtMs;\n }\n if (left.startedAtMs !== right.startedAtMs) {\n return left.startedAtMs - right.startedAtMs;\n }\n return left.key.localeCompare(right.key);\n}\n\nfunction toDispatchActivityActor(\n row: ComposerDispatchRowState\n): DispatchActivityActorViewState | null {\n if (!row.targetProfileId) {\n return null;\n }\n return {\n profileId: row.targetProfileId,\n label: row.targetLabel,\n startedAtMs: row.createdAtMs,\n updatedAtMs: row.updatedAtMs,\n latestPreviewText: row.latestPreviewText,\n latestPreviewUpdatedAtMs: row.latestPreviewUpdatedAtMs,\n };\n}\n\nfunction resolveDispatchActivityHintFallback(\n row: ComposerDispatchRowState\n): string {\n if (row.stage === \"dispatching\") {\n return `${row.targetLabel} is dispatching...`;\n }\n if (row.stage === \"retrying\") {\n return `${row.targetLabel} is retrying...`;\n }\n return `${row.targetLabel} couldn't reply right now`;\n}\n","import type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport { resolveLinkAccessLabel } from \"../access-presentation\";\nimport type {\n SpaceSessionContext,\n SpaceSummaryFactsViewState,\n SpaceSummaryPreset,\n SpaceSummarySegmentKey,\n SpaceSummarySegmentViewState,\n SpaceSummaryViewState,\n} from \"./space-session-view-state\";\nimport { formatStorageUsageSummaryText } from \"./space-storage-usage-text\";\n\nexport function buildSpaceSummaryViewState(input: {\n context: SpaceSessionContext;\n membersSnapshot: SpaceMembersSnapshot | null;\n}): SpaceSummaryViewState {\n const facts = buildSpaceSummaryFactsViewState(input);\n return {\n facts,\n composerFooterSegments: selectSpaceSummarySegments({\n facts,\n preset: \"composer-footer\",\n }),\n sessionSummarySegments: selectSpaceSummarySegments({\n facts,\n preset: \"session-summary\",\n }),\n };\n}\n\nexport function buildSpaceSummaryFactsViewState(input: {\n context: SpaceSessionContext;\n membersSnapshot: SpaceMembersSnapshot | null;\n}): SpaceSummaryFactsViewState {\n const { context, membersSnapshot } = input;\n return {\n spaceId: context.session.spaceId.trim(),\n spaceName: normalizeNullableText(context.session.spaceName),\n accessLabel: resolveSpaceSummaryAccessLabel(context.session),\n membersCount: membersSnapshot\n ? membersSnapshot.humans.length + membersSnapshot.agents.length\n : null,\n liveHumanCount: membersSnapshot\n ? membersSnapshot.humans.filter((member) => member.liveNow).length\n : null,\n liveAgentCount: membersSnapshot\n ? membersSnapshot.agents.filter((member) => member.liveNow).length\n : null,\n storageUsedBytes: normalizeNullableNumber(context.session.storageUsedBytes),\n storageSoftLimitBytes: normalizeNullableNumber(\n context.session.storageSoftLimitBytes\n ),\n storageUsagePercent: normalizeNullableNumber(\n context.session.storageUsagePercent\n ),\n };\n}\n\nexport function selectSpaceSummarySegments(input: {\n facts: SpaceSummaryFactsViewState;\n preset: SpaceSummaryPreset;\n}): SpaceSummarySegmentViewState[] {\n const segmentOrder = resolveSpaceSummarySegmentOrder(input.preset);\n const segments: SpaceSummarySegmentViewState[] = [];\n for (const key of segmentOrder) {\n const text = resolveSegmentText(input.facts, key);\n if (!text) {\n continue;\n }\n segments.push({ key, text });\n }\n return segments;\n}\n\nfunction resolveSpaceSummaryAccessLabel(\n session: SpaceSessionContext[\"session\"]\n): string | null {\n const label = resolveLinkAccessLabel({\n accessMode: session.accessMode ?? undefined,\n passwordProtected: session.passwordProtected ?? undefined,\n visibility: session.visibility ?? undefined,\n });\n return label === \"unknown\" ? null : label;\n}\n\nfunction normalizeNullableText(\n value: string | null | undefined\n): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizeNullableNumber(\n value: number | null | undefined\n): number | null {\n return typeof value === \"number\" && Number.isFinite(value) ? value : null;\n}\n\nfunction resolveSpaceSummarySegmentOrder(\n preset: SpaceSummaryPreset\n): readonly SpaceSummarySegmentKey[] {\n switch (preset) {\n case \"composer-footer\":\n return [\n \"spaceName\",\n \"accessLabel\",\n \"membersCount\",\n \"liveHumanCount\",\n \"liveAgentCount\",\n \"storageUsage\",\n ];\n case \"session-summary\":\n return [\n \"spaceName\",\n \"accessLabel\",\n \"membersCount\",\n \"liveHumanCount\",\n \"liveAgentCount\",\n ];\n default:\n return [];\n }\n}\n\nfunction resolveSegmentText(\n facts: SpaceSummaryFactsViewState,\n key: SpaceSummarySegmentKey\n): string {\n switch (key) {\n case \"spaceName\":\n return facts.spaceName ?? \"\";\n case \"accessLabel\":\n return facts.accessLabel ?? \"\";\n case \"membersCount\":\n return renderCountText(facts.membersCount, (count) =>\n formatCountLabel(count, \"member\", \"members\")\n );\n case \"liveHumanCount\":\n return renderCountText(\n facts.liveHumanCount,\n (count) =>\n `${count} live ${pluralizeCountLabel(count, \"human\", \"humans\")}`\n );\n case \"liveAgentCount\":\n return renderCountText(\n facts.liveAgentCount,\n (count) =>\n `${count} live ${pluralizeCountLabel(count, \"agent\", \"agents\")}`\n );\n case \"storageUsage\":\n return (\n formatStorageUsageSummaryText({\n usedBytes: facts.storageUsedBytes,\n usagePercent: facts.storageUsagePercent,\n }) ?? \"\"\n );\n default:\n return \"\";\n }\n}\n\nfunction renderCountText(\n value: number | null,\n render: (value: number) => string\n): string {\n if (typeof value !== \"number\" || value <= 0) {\n return \"\";\n }\n return render(value);\n}\n\nfunction formatCountLabel(\n count: number,\n singular: string,\n plural: string\n): string {\n return `${count} ${pluralizeCountLabel(count, singular, plural)}`;\n}\n\nfunction pluralizeCountLabel(\n count: number,\n singular: string,\n plural: string\n): string {\n return count === 1 ? singular : plural;\n}\n","import type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport pc from \"picocolors\";\nimport { getCliVersionInfo } from \"../../runtime/cli-version\";\nimport { renderOpenMeldLogo } from \"../../ui/brand\";\nimport { formatInputPrompt } from \"../../ui/output\";\nimport { colorizeDisplayProfileLabel } from \"../../ui/profile-label-color\";\nimport { buildSpacePanelViewState } from \"../panel/build-space-panel-view-state\";\nimport {\n buildHelpPanelBlocks,\n buildLogsPanelBlocks,\n buildLogsSearchableListViewState,\n buildMembersPanelBlocks,\n buildMembersSearchableListViewState,\n buildSpacePanelBlocks,\n} from \"../panel/space-panel-content\";\nimport { resolveSessionHeaderSummaryHint } from \"../readonly-session-shortcuts\";\nimport type { SpaceScreenState } from \"../state/space-screen-state\";\nimport { buildHumanTranscriptProjection } from \"../transcript/transcript-render\";\nimport {\n buildComposerActivityViewState,\n type ComposerActivitySource,\n} from \"./build-composer-activity-view-state\";\nimport { buildSpaceSummaryViewState } from \"./build-space-summary-view-state\";\nimport type {\n SpaceSessionContext,\n SpaceSessionDiagnosticsViewState,\n SpaceSessionViewState,\n} from \"./space-session-view-state\";\n\nconst SPACE_SESSION_HEADER_PRODUCT_LABEL = \"OPENMELD • https://openmeld.ai\";\nconst SPACE_SESSION_HEADER_TAGLINE =\n \"Connect with any agents and humans in real time\";\nexport function buildSpaceSessionViewState(input: {\n context: SpaceSessionContext;\n resources?: {\n composerActivity?: ComposerActivitySource;\n sessionDiagnostics?: SpaceSessionDiagnosticsViewState;\n };\n screenState: SpaceScreenState;\n}): SpaceSessionViewState {\n const { context, resources, screenState } = input;\n const activeSessionVisible = context.surface === \"active-session\";\n const composerVisible =\n activeSessionVisible && context.connectionMode === \"join\";\n const statusOverlayLine = screenState.status.overlayLine.trim();\n const sessionDiagnostics = resources?.sessionDiagnostics ?? {\n openMeldServiceLabel: \"unknown\",\n canWakeLocalAgentsLabel: \"unknown\",\n };\n const helpBlocks = buildHelpPanelBlocks();\n const spaceBlocks = buildSpacePanelBlocks({\n context,\n membersSnapshot: screenState.members.snapshot,\n });\n const humanTranscriptProjection = buildHumanTranscriptProjection({\n items: screenState.transcript.items,\n membersSnapshot: screenState.members.snapshot,\n sessionProfile: context.profile,\n });\n const logsBlocks = buildLogsPanelBlocks({\n sections: humanTranscriptProjection.logsSections,\n });\n const logsSearchableList = buildLogsSearchableListViewState({\n activeItemId: screenState.overlay.interaction.activeItemId,\n query: screenState.overlay.interaction.query,\n sections: humanTranscriptProjection.logsSections,\n });\n const membersBlocks = buildMembersPanelBlocks({\n snapshot: screenState.members.snapshot,\n refreshError: screenState.members.refreshError,\n });\n const membersSearchableList = buildMembersSearchableListViewState({\n activeItemId: screenState.overlay.interaction.activeItemId,\n query: screenState.overlay.interaction.query,\n refreshError: screenState.members.refreshError,\n snapshot: screenState.members.snapshot,\n });\n const overlayPanel = buildSpacePanelViewState({\n kind: screenState.overlay.kind,\n bodyByKind: {\n help: helpBlocks,\n logs: logsBlocks,\n members: membersBlocks,\n space: spaceBlocks,\n },\n headerMetaTextByKind: {\n members: buildMembersPanelUpdatedAtLabel(screenState.members.updatedAtMs),\n },\n searchableListByKind: {\n logs: logsSearchableList,\n members: membersSearchableList,\n },\n });\n const transcriptBlocks = humanTranscriptProjection.transcriptBlocks;\n const spaceSummary = buildSpaceSummaryViewState({\n context,\n membersSnapshot: screenState.members.snapshot,\n });\n const composerActivity = buildComposerActivityViewState(\n resources?.composerActivity ?? {\n nowMs: Date.now(),\n rows: [],\n },\n screenState.members.snapshot\n );\n const visibleComposerActivity = composerVisible\n ? composerActivity\n : {\n ...composerActivity,\n visible: false,\n };\n\n return {\n surface: context.surface,\n context,\n spaceSummary,\n transcript: {\n items: screenState.transcript.items,\n blocks: transcriptBlocks,\n visible: activeSessionVisible,\n },\n sessionDocument: {\n blocks: [\n {\n kind: \"session_header\",\n productLabel: SPACE_SESSION_HEADER_PRODUCT_LABEL,\n tagline: SPACE_SESSION_HEADER_TAGLINE,\n versionLabel: `v ${getCliVersionInfo().version}`,\n logoLines: renderOpenMeldLogo().split(\"\\n\"),\n summaryFacts: spaceSummary.facts,\n summaryHintText: resolveSessionHeaderSummaryHint(\n context.connectionMode\n ),\n },\n {\n kind: \"transcript\",\n blocks: transcriptBlocks,\n },\n ],\n visible: activeSessionVisible,\n },\n status: {\n overlayLine: statusOverlayLine,\n lines: statusOverlayLine ? statusOverlayLine.split(\"\\n\") : [],\n visible: activeSessionVisible && statusOverlayLine.length > 0,\n },\n composerActivity: visibleComposerActivity,\n composer: {\n bufferText: screenState.composer.bufferText,\n basePrompt: formatInputPrompt(\n {\n profileId: context.profile.profileId,\n profileName: context.profile.profileName,\n kind: context.profile.kind,\n ownerUserId: context.profile.ownerUserId ?? undefined,\n ownerName: context.profile.ownerName ?? undefined,\n },\n {\n spaceMembersSnapshot: screenState.members.snapshot,\n }\n ),\n helperText: buildComposerHelperText(\n context,\n screenState.members.snapshot\n ),\n hasDraft: screenState.composer.bufferText.length > 0,\n placeholderText: \"Message the space...\",\n showPlaceholder: screenState.composer.bufferText.length === 0,\n visible: composerVisible,\n },\n overlay: {\n kind: screenState.overlay.kind,\n panel: overlayPanel,\n visible: activeSessionVisible && screenState.overlay.kind !== \"none\",\n },\n resources: {\n membersSnapshot: screenState.members.snapshot,\n sessionDiagnostics,\n },\n };\n}\n\nfunction buildComposerHelperText(\n context: SpaceSessionContext,\n membersSnapshot?: SpaceMembersSnapshot | null\n): string {\n const coloredProfileName = colorizeDisplayProfileLabel({\n label: context.profile.profileName,\n profileIdentity: {\n kind: context.profile.kind,\n ownerUserId: context.profile.ownerUserId ?? undefined,\n ownerName: context.profile.ownerName ?? undefined,\n profileId: context.profile.profileId,\n profileName: context.profile.profileName,\n },\n spaceMembersSnapshot: membersSnapshot,\n });\n return `${pc.dim(\"connected as \")}${coloredProfileName}${pc.dim(\" · Enter sends · Shift+Enter newline · / commands · @ mentions\")}`;\n}\n\nfunction buildMembersPanelUpdatedAtLabel(\n updatedAtMs: number | null\n): string | null {\n if (!(typeof updatedAtMs === \"number\" && Number.isFinite(updatedAtMs))) {\n return null;\n }\n\n const date = new Date(updatedAtMs);\n const year = String(date.getFullYear());\n const month = String(date.getMonth() + 1).padStart(2, \"0\");\n const day = String(date.getDate()).padStart(2, \"0\");\n const hour = String(date.getHours()).padStart(2, \"0\");\n const minute = String(date.getMinutes()).padStart(2, \"0\");\n\n return `UpdatedAt ${year}${month}${day} ${hour}:${minute}`;\n}\n","import type { SpaceScreenStore } from \"../../state/space-screen-store\";\nimport type { ComposerActivitySource } from \"../../view/build-composer-activity-view-state\";\nimport { buildSpaceSessionViewState } from \"../../view/build-space-session-view-state\";\nimport type {\n SpaceSessionContext,\n SpaceSessionDiagnosticsViewState,\n} from \"../../view/space-session-view-state\";\nimport type { PiTuiInteractiveSpaceShell } from \"./pi-tui-interactive-space-shell\";\n\ntype PiTuiSessionResources = {\n composerActivity?: ComposerActivitySource;\n sessionDiagnostics?: SpaceSessionDiagnosticsViewState;\n};\n\nexport function mountPiTuiSessionShell(input: {\n context: SpaceSessionContext;\n getResources?: () => PiTuiSessionResources;\n shell: PiTuiInteractiveSpaceShell;\n store: SpaceScreenStore;\n}): {\n removeStoreListener: () => void;\n refreshViewState: () => void;\n} {\n const refreshViewState = (): void => {\n input.shell.render(\n buildSpaceSessionViewState({\n context: input.context,\n resources: input.getResources?.(),\n screenState: input.store.getState(),\n })\n );\n };\n\n const removeStoreListener = input.store.subscribe(() => {\n refreshViewState();\n });\n refreshViewState();\n\n return {\n removeStoreListener,\n refreshViewState,\n };\n}\n","import type { EditorTheme, SelectListTheme } from \"@mariozechner/pi-tui\";\nimport pc from \"picocolors\";\nimport type { SpacePanelSurfaceVariant } from \"../../panel/space-panel-definition\";\n\ntype RgbTriplet = readonly [number, number, number];\nconst ANSI_RESET_FOREGROUND = \"\\x1B[39m\";\nconst ANSI_RESET_BACKGROUND = \"\\x1B[49m\";\n\nconst selectListTheme: SelectListTheme = {\n selectedPrefix: (text) => pc.cyan(text),\n selectedText: (text) => pc.cyan(text),\n description: (text) => pc.dim(text),\n scrollInfo: (text) => pc.dim(text),\n noMatch: (text) => pc.dim(text),\n};\n\nexport const spacePiTuiEditorTheme: EditorTheme = {\n borderColor: (text) => pc.dim(text),\n selectList: selectListTheme,\n};\n\nconst panelSurfaceThemes = {\n dark: {\n // Keep panel border and surface on the same background tone so the\n // full-width top/bottom rows do not read as a thicker frame than the sides.\n panelBorderBg: [38, 38, 38],\n panelAccentText: [245, 245, 245],\n panelInstructionText: [245, 245, 245],\n panelPrimaryText: [245, 245, 245],\n panelSecondaryText: [245, 245, 245],\n panelSurfaceBg: [38, 38, 38],\n },\n light: {\n panelBorderBg: [245, 245, 245],\n panelAccentText: [30, 34, 40],\n panelInstructionText: [100, 105, 112],\n panelPrimaryText: [34, 38, 44],\n panelSecondaryText: [84, 89, 96],\n panelSurfaceBg: [245, 245, 245],\n },\n} as const satisfies Record<\n SpacePanelSurfaceVariant,\n {\n panelBorderBg: RgbTriplet;\n panelAccentText: RgbTriplet;\n panelInstructionText: RgbTriplet;\n panelPrimaryText: RgbTriplet;\n panelSecondaryText: RgbTriplet;\n panelSurfaceBg: RgbTriplet;\n }\n>;\n\ntype PanelTextTone = \"accent\" | \"instruction\" | \"primary\" | \"secondary\";\n\nexport const spacePiTuiTheme = {\n accentText: (text: string) => pc.cyan(text),\n transcriptText: (text: string) => text,\n statusText: (text: string) => pc.dim(text),\n composerLabel: (text: string) => pc.dim(text),\n dimText: (text: string) => pc.dim(text),\n resolvePanelBorderBg(\n surfaceVariant: SpacePanelSurfaceVariant\n ): (text: string) => string {\n const panelTheme = panelSurfaceThemes[surfaceVariant];\n const rgb = panelTheme.panelBorderBg;\n const backgroundOpen = buildAnsiColorOpen(\"48\", rgb);\n return (text: string) => `${backgroundOpen}${text}${ANSI_RESET_BACKGROUND}`;\n },\n resolvePanelSurfaceBg(\n surfaceVariant: SpacePanelSurfaceVariant\n ): (text: string) => string {\n const panelTheme = panelSurfaceThemes[surfaceVariant];\n const backgroundOpen = buildAnsiColorOpen(\"48\", panelTheme.panelSurfaceBg);\n return (text: string) => `${backgroundOpen}${text}${ANSI_RESET_BACKGROUND}`;\n },\n renderPanelTextLine(input: {\n surfaceVariant: SpacePanelSurfaceVariant;\n text: string;\n tone: PanelTextTone;\n }): string {\n const panelTheme = panelSurfaceThemes[input.surfaceVariant];\n const fg = resolvePanelTextTone(panelTheme, input.tone);\n return renderAnsiStyledText({ fg, text: input.text });\n },\n};\n\nfunction resolvePanelTextTone(\n panelTheme: (typeof panelSurfaceThemes)[SpacePanelSurfaceVariant],\n tone: PanelTextTone\n): RgbTriplet {\n switch (tone) {\n case \"accent\":\n return panelTheme.panelAccentText;\n case \"instruction\":\n return panelTheme.panelInstructionText;\n case \"primary\":\n return panelTheme.panelPrimaryText;\n case \"secondary\":\n return panelTheme.panelSecondaryText;\n default:\n return panelTheme.panelPrimaryText;\n }\n}\n\nfunction renderAnsiStyledText(input: {\n fg?: RgbTriplet;\n text: string;\n}): string {\n const fgOpen = input.fg ? buildAnsiColorOpen(\"38\", input.fg) : \"\";\n if (!fgOpen) {\n return input.text;\n }\n return `${fgOpen}${input.text}${ANSI_RESET_FOREGROUND}`;\n}\n\nfunction buildAnsiColorOpen(prefix: \"38\" | \"48\", rgb: RgbTriplet): string {\n const [red, green, blue] = rgb;\n return `\\x1B[${prefix};2;${red};${green};${blue}m`;\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport type { Component, TUI } from \"@mariozechner/pi-tui\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport pc from \"picocolors\";\nimport stringWidth from \"string-width\";\nimport wrapAnsi from \"wrap-ansi\";\nimport { colorizeAgentLabel } from \"../../../../ui/profile-label-color\";\nimport { buildSpacePrimaryMentionLabelByProfileId } from \"../../../mention-label-state\";\nimport type {\n ComposerActivityRowViewState,\n ComposerActivityViewState,\n} from \"../../../view/space-session-view-state\";\nimport { spacePiTuiTheme } from \"../theme\";\n\nconst STRIP_SPINNER_FRAMES = [\n \"⠋\",\n \"⠙\",\n \"⠹\",\n \"⠸\",\n \"⠼\",\n \"⠴\",\n \"⠦\",\n \"⠧\",\n \"⠇\",\n \"⠏\",\n] as const;\nconst STRIP_TICK_MS = 150;\nconst STATUS_LABEL_CYCLE_SECONDS = 3;\nconst STATUS_LABELS = [\"replying\", \"thinking\", \"working\"] as const;\nconst STATUS_TRAILING_DOT_FRAMES = [\".\", \"..\", \"...\"] as const;\nconst PREVIEW_GAP = \" \";\nconst ACTIVITY_TARGET_LABEL_PREFIX_REGEX = /^@/u;\nconst mentionLabelsBySnapshot = new WeakMap<\n SpaceMembersSnapshot,\n ReadonlyMap<string, string>\n>();\n\nexport class ComposerActivityStrip implements Component {\n readonly #tui: TUI;\n #activity: ComposerActivityViewState = {\n visible: false,\n mode: \"idle\",\n rows: [],\n overflowCount: 0,\n actors: [],\n leadActor: null,\n elapsedSeconds: null,\n previewText: \"\",\n hint: null,\n };\n #activityBaseSetAtMs = Date.now();\n #tick = 0;\n #timer: NodeJS.Timeout | null = null;\n\n constructor(tui: TUI) {\n this.#tui = tui;\n }\n\n setActivity(activity: ComposerActivityViewState): void {\n const wasWaiting = isWaitingComposerActivity(this.#activity);\n const isWaiting = isWaitingComposerActivity(activity);\n if (!wasWaiting && isWaiting) {\n this.#tick = 0;\n }\n this.#activity = activity;\n this.#activityBaseSetAtMs = Date.now();\n this.#syncTimer();\n this.#tui.requestRender();\n }\n\n stop(): void {\n if (!this.#timer) {\n return;\n }\n clearInterval(this.#timer);\n this.#timer = null;\n }\n\n invalidate(): void {\n // No child components to invalidate; requestRender is driven by timer/setActivity.\n }\n\n render(width: number): string[] {\n if (!shouldRenderComposerActivity(this.#activity)) {\n return [];\n }\n\n const inlineLines = buildActivityLines({\n activity: this.#activity,\n tick: this.#tick,\n elapsedDeltaSeconds: this.#resolveElapsedDeltaSeconds(),\n width,\n });\n return [\"\", ...inlineLines];\n }\n\n #syncTimer(): void {\n if (shouldAnimateComposerActivity(this.#activity)) {\n if (this.#timer) {\n return;\n }\n this.#timer = setInterval(() => {\n this.#tick += 1;\n this.#tui.requestRender();\n }, STRIP_TICK_MS);\n return;\n }\n this.stop();\n }\n\n #resolveElapsedDeltaSeconds(): number {\n if (!shouldRenderComposerActivity(this.#activity)) {\n return 0;\n }\n return Math.max(\n 0,\n Math.floor((Date.now() - this.#activityBaseSetAtMs) / 1000)\n );\n }\n}\n\nfunction shouldRenderComposerActivity(\n activity: ComposerActivityViewState\n): boolean {\n return (\n activity.visible && activity.mode !== \"idle\" && activity.rows.length > 0\n );\n}\n\nfunction shouldAnimateComposerActivity(\n activity: ComposerActivityViewState\n): boolean {\n return (\n shouldRenderComposerActivity(activity) &&\n activity.rows.some((row) => row.mode !== \"warning\")\n );\n}\n\nfunction isWaitingComposerActivity(\n activity: ComposerActivityViewState\n): boolean {\n return (\n shouldRenderComposerActivity(activity) &&\n activity.rows.some(\n (row) => row.mode !== \"warning\" && row.previewText.trim().length === 0\n )\n );\n}\n\nfunction buildReplyingStatusLine(input: {\n row: ComposerActivityRowViewState;\n spaceMembersSnapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"];\n elapsedSeconds: number;\n tick: number;\n}): string {\n const actors = input.row.actors\n .map((actor) => {\n const matchingAgent =\n input.spaceMembersSnapshot?.agents.find(\n (candidate) => candidate.profileId === actor.profileId\n ) ?? null;\n return colorizeAgentLabel(\n actor.label,\n {\n agentControllerRef: matchingAgent?.agentControllerRef,\n profileId: actor.profileId,\n profileName: actor.label,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n );\n })\n .join(pc.dim(\", \"));\n const linkingVerb = input.row.actors.length > 1 ? \"are\" : \"is\";\n const modeLabel = resolveStatusModeLabel({\n elapsedSeconds: input.elapsedSeconds,\n previewText: input.row.previewText,\n });\n const modeSuffix =\n input.row.previewText.trim().length > 0\n ? \"\"\n : resolveAnimatedStatusDots(input.tick);\n return `${actors} ${pc.dim(linkingVerb)} ${pc.dim(`${modeLabel}${modeSuffix}`)}`;\n}\n\nfunction buildActivityLines(input: {\n activity: ComposerActivityViewState;\n tick: number;\n elapsedDeltaSeconds: number;\n width: number;\n}): string[] {\n const lines: string[] = [];\n if (input.activity.overflowCount > 0) {\n lines.push(pc.dim(`+${input.activity.overflowCount} more active`));\n }\n\n for (const row of input.activity.rows) {\n const inlineLine = buildActivityRowLine({\n row,\n spaceMembersSnapshot: input.activity.spaceMembersSnapshot,\n tick: input.tick,\n elapsedSeconds: resolveRowElapsedSeconds({\n row,\n elapsedDeltaSeconds: input.elapsedDeltaSeconds,\n }),\n width: input.width,\n });\n const wrappedLines = wrapAnsi(inlineLine, Math.max(1, input.width), {\n hard: true,\n trim: false,\n wordWrap: true,\n }).split(\"\\n\");\n lines.push(...wrappedLines);\n }\n\n return lines;\n}\n\nfunction buildActivityRowLine(input: {\n row: ComposerActivityRowViewState;\n spaceMembersSnapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"];\n tick: number;\n elapsedSeconds: number;\n width: number;\n}): string {\n const spinner =\n STRIP_SPINNER_FRAMES[input.tick % STRIP_SPINNER_FRAMES.length] ?? \"⠋\";\n if (input.row.mode === \"sending\") {\n return buildSendingStatusLine({\n row: input.row,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n spinner,\n });\n }\n\n if (\n input.row.mode === \"dispatching\" ||\n input.row.mode === \"retrying\" ||\n input.row.mode === \"warning\"\n ) {\n const glyph =\n input.row.mode === \"warning\"\n ? pc.yellow(\"!\")\n : spacePiTuiTheme.accentText(spinner);\n const elapsedLabel =\n input.row.mode === \"warning\"\n ? pc.dim(\"now\")\n : pc.dim(`${input.elapsedSeconds}s`);\n return buildStatusHintLine({\n glyph,\n elapsedLabel,\n row: input.row,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n });\n }\n\n const statusLine = [\n spacePiTuiTheme.accentText(spinner),\n pc.dim(`${input.elapsedSeconds}s`),\n buildReplyingStatusLine({\n row: input.row,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n elapsedSeconds: input.elapsedSeconds,\n tick: input.tick,\n }),\n ].join(` ${pc.dim(\"·\")} `);\n\n const previewText = input.row.previewText.trim();\n if (!previewText) {\n return statusLine;\n }\n\n const separator = ` ${pc.dim(\"·\")} `;\n const availableWidth = Math.max(\n 0,\n input.width -\n stringWidth(stripVTControlCharacters(statusLine)) -\n stringWidth(stripVTControlCharacters(separator))\n );\n if (availableWidth <= 0) {\n return statusLine;\n }\n const windowText = selectPreviewWindow({\n text: previewText,\n tick: input.tick,\n width: availableWidth,\n });\n return `${statusLine}${separator}${pc.dim(windowText)}`;\n}\n\nfunction buildSendingStatusLine(input: {\n row: ComposerActivityRowViewState;\n spaceMembersSnapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"];\n spinner: string;\n}): string {\n const sendingText = input.row.hint || \"sending...\";\n return [\n spacePiTuiTheme.accentText(input.spinner),\n formatHintWithColoredTargetLabel({\n hint: sendingText,\n targetLabel: input.row.targetLabel,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }),\n ].join(` ${pc.dim(\"·\")} `);\n}\n\nfunction buildStatusHintLine(input: {\n glyph: string;\n elapsedLabel: string;\n row: ComposerActivityRowViewState;\n spaceMembersSnapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"];\n}): string {\n return [\n input.glyph,\n input.elapsedLabel,\n formatHintWithColoredTargetLabel({\n hint: input.row.hint ?? \"\",\n targetLabel: input.row.targetLabel,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }),\n ].join(` ${pc.dim(\"·\")} `);\n}\n\nfunction formatHintWithColoredTargetLabel(input: {\n hint: string;\n targetLabel: string | null;\n spaceMembersSnapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"];\n}): string {\n const targetLabel = input.targetLabel?.trim() ?? \"\";\n if (!(targetLabel && input.hint.includes(targetLabel))) {\n return pc.white(input.hint);\n }\n\n const coloredTargetLabel = resolveColoredTargetLabel({\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n targetLabel,\n });\n const [prefix, suffix = \"\"] = input.hint.split(targetLabel, 2);\n return `${pc.white(prefix)}${coloredTargetLabel}${pc.white(suffix)}`;\n}\n\nfunction resolveColoredTargetLabel(input: {\n spaceMembersSnapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"];\n targetLabel: string;\n}): string {\n const normalizedTargetLabel = normalizeActivityTargetLabel(input.targetLabel);\n const mentionLabels = resolveMentionLabelsForSnapshot(\n input.spaceMembersSnapshot ?? null\n );\n const matchingAgent =\n input.spaceMembersSnapshot?.agents.find((candidate) => {\n const mentionLabel = mentionLabels?.get(candidate.profileId) ?? null;\n return [mentionLabel, candidate.profileName, candidate.profileId].some(\n (value) => normalizeActivityTargetLabel(value) === normalizedTargetLabel\n );\n }) ?? null;\n\n return colorizeAgentLabel(\n input.targetLabel,\n {\n agentControllerRef: matchingAgent?.agentControllerRef,\n profileId: matchingAgent?.profileId,\n profileName:\n matchingAgent?.profileName ||\n normalizedTargetLabel ||\n input.targetLabel,\n },\n {\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n }\n );\n}\n\nfunction resolveMentionLabelsForSnapshot(\n snapshot: ComposerActivityViewState[\"spaceMembersSnapshot\"]\n): ReadonlyMap<string, string> | null {\n if (!snapshot) {\n return null;\n }\n const cachedLabels = mentionLabelsBySnapshot.get(snapshot);\n if (cachedLabels) {\n return cachedLabels;\n }\n const resolvedLabels = buildSpacePrimaryMentionLabelByProfileId(snapshot);\n mentionLabelsBySnapshot.set(snapshot, resolvedLabels);\n return resolvedLabels;\n}\n\nfunction normalizeActivityTargetLabel(\n value: string | null | undefined\n): string {\n return stripVTControlCharacters(String(value ?? \"\"))\n .trim()\n .replace(ACTIVITY_TARGET_LABEL_PREFIX_REGEX, \"\");\n}\n\nfunction resolveRowElapsedSeconds(input: {\n row: ComposerActivityRowViewState;\n elapsedDeltaSeconds: number;\n}): number {\n return (input.row.elapsedSeconds ?? 0) + input.elapsedDeltaSeconds;\n}\n\nfunction resolveStatusModeLabel(input: {\n elapsedSeconds: number;\n previewText: string;\n}): string {\n if (input.previewText.trim().length > 0) {\n return \"streaming\";\n }\n const cycleIndex =\n Math.floor(input.elapsedSeconds / STATUS_LABEL_CYCLE_SECONDS) %\n STATUS_LABELS.length;\n return STATUS_LABELS[cycleIndex] ?? STATUS_LABELS[0];\n}\n\nfunction resolveAnimatedStatusDots(tick: number): string {\n return (\n STATUS_TRAILING_DOT_FRAMES[tick % STATUS_TRAILING_DOT_FRAMES.length] ?? \".\"\n );\n}\n\nfunction selectPreviewWindow(input: {\n text: string;\n tick: number;\n width: number;\n}): string {\n if (stringWidth(input.text) <= input.width) {\n return input.text;\n }\n\n const content = `${input.text}${PREVIEW_GAP}`;\n const characters = Array.from(content);\n const offset = input.tick % characters.length;\n const rotated = [...characters.slice(offset), ...characters.slice(0, offset)];\n let visibleWidth = 0;\n let rendered = \"\";\n\n for (const character of rotated) {\n const characterWidth = stringWidth(character);\n if (visibleWidth + characterWidth > input.width) {\n break;\n }\n rendered += character;\n visibleWidth += characterWidth;\n }\n\n return rendered || input.text;\n}\n","import {\n getEditorKeybindings,\n type SelectListTheme,\n} from \"@mariozechner/pi-tui\";\nimport { colorizeAgentLabel } from \"../../../ui/profile-label-color\";\nimport type { PiTuiComposerAutocompleteItem } from \"./pi-tui-composer-autocomplete-provider\";\n\ntype SelectListInternals = {\n filteredItems: PiTuiComposerAutocompleteItem[];\n items: PiTuiComposerAutocompleteItem[];\n maxVisible: number;\n onCancel?: (() => void) | undefined;\n onSelect?: ((item: PiTuiComposerAutocompleteItem) => void) | undefined;\n onSelectionChange?:\n | ((item: PiTuiComposerAutocompleteItem) => void)\n | undefined;\n selectedIndex: number;\n theme: SelectListTheme;\n getSelectedItem: () => PiTuiComposerAutocompleteItem | null;\n handleInput: (keyData: string) => void;\n notifySelectionChange: () => void;\n render: (width: number) => string[];\n setSelectedIndex: (index: number) => void;\n openMeldMentionAutocompleteDecorated?: boolean;\n};\n\ntype MentionSelectListItem = PiTuiComposerAutocompleteItem;\ntype MemberRowPieceTone =\n | \"agent-accent\"\n | \"description\"\n | \"plain\"\n | \"selected-prefix\";\ntype MemberRowTextPiece = {\n text: string;\n tone: MemberRowPieceTone;\n};\n\nexport function decorateMentionAutocompleteSelectList(\n list: SelectListInternals\n): void {\n if (\n list.openMeldMentionAutocompleteDecorated ||\n !hasPresentationRows(list.items)\n ) {\n return;\n }\n\n list.openMeldMentionAutocompleteDecorated = true;\n const originalSetSelectedIndex = list.setSelectedIndex.bind(list);\n\n list.setSelectedIndex = (index: number): void => {\n const nextIndex = findNearestSelectableIndex(list.filteredItems, index);\n if (nextIndex === null) {\n originalSetSelectedIndex(0);\n return;\n }\n originalSetSelectedIndex(nextIndex);\n };\n\n list.getSelectedItem = (): MentionSelectListItem | null => {\n const selectedIndex = findNearestSelectableIndex(\n list.filteredItems,\n list.selectedIndex\n );\n if (selectedIndex === null) {\n return null;\n }\n return list.filteredItems[selectedIndex] ?? null;\n };\n\n list.notifySelectionChange = (): void => {\n const selectedItem = list.getSelectedItem();\n if (selectedItem && list.onSelectionChange) {\n list.onSelectionChange(selectedItem);\n }\n };\n\n list.handleInput = (keyData: string): void => {\n const keybindings = getEditorKeybindings();\n\n if (keybindings.matches(keyData, \"selectUp\")) {\n moveSelection(list, -1);\n return;\n }\n\n if (keybindings.matches(keyData, \"selectDown\")) {\n moveSelection(list, 1);\n return;\n }\n\n if (keybindings.matches(keyData, \"selectConfirm\")) {\n const selectedItem = list.getSelectedItem();\n if (selectedItem && list.onSelect) {\n list.onSelect(selectedItem);\n }\n return;\n }\n\n if (keybindings.matches(keyData, \"selectCancel\")) {\n list.onCancel?.();\n }\n };\n\n list.render = (width: number): string[] => {\n const items = list.filteredItems;\n if (items.length === 0) {\n return [list.theme.noMatch(\" No matching commands\")];\n }\n\n const selectedIndex = findNearestSelectableIndex(items, list.selectedIndex);\n if (selectedIndex !== null && selectedIndex !== list.selectedIndex) {\n list.selectedIndex = selectedIndex;\n }\n\n const safeSelectedIndex = selectedIndex ?? 0;\n let startIndex = Math.max(\n 0,\n Math.min(\n safeSelectedIndex - Math.floor(list.maxVisible / 2),\n items.length - list.maxVisible\n )\n );\n startIndex = expandWindowForSectionContext(\n items,\n startIndex,\n safeSelectedIndex\n );\n const endIndex = Math.min(startIndex + list.maxVisible, items.length);\n const visibleItems = items.slice(startIndex, endIndex);\n const lines = visibleItems.map((item, offset) =>\n renderMentionAutocompleteRow({\n item,\n isSelected: startIndex + offset === safeSelectedIndex,\n theme: list.theme,\n width,\n })\n );\n\n if (startIndex > 0 || endIndex < items.length) {\n const selectableCount = items.filter(isSelectableItem).length;\n const selectedSelectableIndex = countSelectableItemsBefore(\n items,\n safeSelectedIndex\n );\n lines.push(\n list.theme.scrollInfo(\n truncateText(\n ` (${selectedSelectableIndex + 1}/${selectableCount})`,\n Math.max(0, width - 2)\n )\n )\n );\n }\n\n return lines;\n };\n\n list.setSelectedIndex(list.selectedIndex);\n}\n\nfunction hasPresentationRows(items: MentionSelectListItem[]): boolean {\n return items.some((item) => item.mentionPresentation !== undefined);\n}\n\nfunction moveSelection(list: SelectListInternals, direction: -1 | 1): void {\n const items = list.filteredItems;\n if (items.length === 0) {\n return;\n }\n\n const currentIndex =\n findNearestSelectableIndex(items, list.selectedIndex) ?? 0;\n let nextIndex = currentIndex;\n\n for (const _item of items) {\n nextIndex =\n (nextIndex + direction + items.length) % Math.max(1, items.length);\n if (isSelectableItem(items[nextIndex])) {\n list.selectedIndex = nextIndex;\n list.notifySelectionChange();\n return;\n }\n }\n}\n\nfunction renderMentionAutocompleteRow(input: {\n item: MentionSelectListItem;\n isSelected: boolean;\n theme: SelectListTheme;\n width: number;\n}): string {\n const { item, isSelected, theme, width } = input;\n\n switch (item.mentionPresentation) {\n case \"relation_header\":\n case \"section_header\":\n return theme.selectedPrefix(\n ` ${truncateText(item.label ?? \"\", width - 2)}`\n );\n case \"spacer\":\n return \"\";\n default:\n return renderMemberRow({\n isSelected,\n item,\n theme,\n width,\n });\n }\n}\n\nfunction renderMemberRow(input: {\n isSelected: boolean;\n item: MentionSelectListItem;\n theme: SelectListTheme;\n width: number;\n}): string {\n const prefix = input.isSelected ? \"→ \" : \" \";\n const label =\n normalizeSingleLineText(input.item.label || input.item.value) ?? \"\";\n const description = buildMemberDescriptionText(input.item);\n const maxWidth = Math.max(0, input.width - prefix.length - 2);\n\n if (!description || input.width <= 40) {\n return renderMemberRowPieces({\n isSelected: input.isSelected,\n item: input.item,\n pieces: [\n {\n text: prefix,\n tone: input.isSelected ? \"selected-prefix\" : \"plain\",\n },\n createMemberLabelPiece(input.item, truncateText(label, maxWidth)),\n ],\n theme: input.theme,\n });\n }\n\n const maxLabelWidth = Math.min(\n 30,\n Math.max(0, input.width - prefix.length - 4)\n );\n const truncatedLabel = truncateText(label, maxLabelWidth);\n const spacing = \" \".repeat(Math.max(1, 32 - truncatedLabel.length));\n const descriptionStart =\n prefix.length + truncatedLabel.length + spacing.length;\n const remainingWidth = Math.max(0, input.width - descriptionStart - 2);\n\n if (remainingWidth <= 10) {\n return renderMemberRowPieces({\n isSelected: input.isSelected,\n item: input.item,\n pieces: [\n {\n text: prefix,\n tone: input.isSelected ? \"selected-prefix\" : \"plain\",\n },\n createMemberLabelPiece(input.item, truncateText(label, maxWidth)),\n ],\n theme: input.theme,\n });\n }\n\n return renderMemberRowPieces({\n isSelected: input.isSelected,\n item: input.item,\n pieces: [\n {\n text: prefix,\n tone: input.isSelected ? \"selected-prefix\" : \"plain\",\n },\n createMemberLabelPiece(input.item, truncatedLabel),\n { text: spacing, tone: \"description\" },\n ...buildMemberDescriptionPieces({\n item: input.item,\n maxWidth: remainingWidth,\n }),\n ],\n theme: input.theme,\n });\n}\n\nfunction expandWindowForSectionContext(\n items: MentionSelectListItem[],\n startIndex: number,\n selectedIndex: number\n): number {\n let nextStartIndex = startIndex;\n const previousItem = items[selectedIndex - 1];\n const previousPreviousItem = items[selectedIndex - 2];\n\n if (previousItem?.mentionPresentation === \"section_header\") {\n nextStartIndex = Math.min(nextStartIndex, Math.max(0, selectedIndex - 1));\n }\n\n if (\n previousItem?.mentionPresentation === \"spacer\" &&\n previousPreviousItem?.mentionPresentation === \"section_header\"\n ) {\n nextStartIndex = Math.min(nextStartIndex, Math.max(0, selectedIndex - 2));\n }\n\n return nextStartIndex;\n}\n\nfunction findNearestSelectableIndex(\n items: MentionSelectListItem[],\n index: number\n): number | null {\n if (items.length === 0) {\n return null;\n }\n\n const clampedIndex = Math.max(0, Math.min(index, items.length - 1));\n if (isSelectableItem(items[clampedIndex])) {\n return clampedIndex;\n }\n\n for (let offset = 1; offset < items.length; offset += 1) {\n const nextIndex = clampedIndex + offset;\n if (nextIndex < items.length && isSelectableItem(items[nextIndex])) {\n return nextIndex;\n }\n const previousIndex = clampedIndex - offset;\n if (previousIndex >= 0 && isSelectableItem(items[previousIndex])) {\n return previousIndex;\n }\n }\n\n return null;\n}\n\nfunction countSelectableItemsBefore(\n items: MentionSelectListItem[],\n index: number\n): number {\n let count = 0;\n for (let currentIndex = 0; currentIndex <= index; currentIndex += 1) {\n if (isSelectableItem(items[currentIndex])) {\n count += 1;\n }\n }\n return Math.max(0, count - 1);\n}\n\nfunction isSelectableItem(item: MentionSelectListItem | undefined): boolean {\n return (\n item?.mentionPresentation === \"back_choice\" ||\n item?.mentionPresentation === \"relation_choice\" ||\n item?.mentionPresentation === \"target_choice\"\n );\n}\n\nfunction buildMemberDescriptionText(\n item: MentionSelectListItem\n): string | null {\n return normalizeSingleLineText(item.description);\n}\n\nfunction createMemberLabelPiece(\n item: MentionSelectListItem,\n label: string\n): MemberRowTextPiece {\n if (shouldColorizeAgentMentionItem(item)) {\n return { text: label, tone: \"agent-accent\" };\n }\n\n return { text: label, tone: \"plain\" };\n}\n\nfunction buildMemberDescriptionPieces(input: {\n item: MentionSelectListItem;\n maxWidth: number;\n}): MemberRowTextPiece[] {\n const description = buildMemberDescriptionText(input.item);\n if (!description) {\n return [];\n }\n\n const controllerDisplay = normalizeSingleLineText(\n input.item.mentionControllerDisplay\n );\n const controllerShown = Boolean(\n controllerDisplay && description.startsWith(controllerDisplay)\n );\n\n if (!(controllerShown && controllerDisplay)) {\n return truncateMemberRowPieces(\n [{ text: description, tone: \"description\" }],\n input.maxWidth\n );\n }\n\n const descriptionTail = description.slice(controllerDisplay.length);\n const pieces: MemberRowTextPiece[] = [\n {\n text: controllerDisplay,\n tone: shouldColorizeAgentMentionItem(input.item)\n ? \"agent-accent\"\n : \"description\",\n },\n ];\n\n if (descriptionTail) {\n pieces.push({ text: descriptionTail, tone: \"description\" });\n }\n\n return truncateMemberRowPieces(pieces, input.maxWidth);\n}\n\nfunction truncateMemberRowPieces(\n pieces: MemberRowTextPiece[],\n maxWidth: number\n): MemberRowTextPiece[] {\n let remainingWidth = maxWidth;\n const truncatedPieces: MemberRowTextPiece[] = [];\n\n for (const piece of pieces) {\n if (remainingWidth <= 0) {\n break;\n }\n\n const truncatedText = truncateText(piece.text, remainingWidth);\n if (!truncatedText) {\n continue;\n }\n\n truncatedPieces.push({\n ...piece,\n text: truncatedText,\n });\n remainingWidth -= measureTextWidth(truncatedText);\n }\n\n return truncatedPieces;\n}\n\nfunction renderMemberRowPieces(input: {\n isSelected: boolean;\n item: MentionSelectListItem;\n pieces: MemberRowTextPiece[];\n theme: SelectListTheme;\n}): string {\n return input.pieces\n .map((piece) => renderMemberRowPiece(piece, input.item, input.theme))\n .join(\"\");\n}\n\nfunction renderMemberRowPiece(\n piece: MemberRowTextPiece,\n item: MentionSelectListItem,\n theme: SelectListTheme\n): string {\n switch (piece.tone) {\n case \"agent-accent\":\n return colorizeMentionAgentText(piece.text, item);\n case \"description\":\n return theme.description(piece.text);\n case \"selected-prefix\":\n return theme.selectedPrefix(piece.text);\n default:\n return piece.text;\n }\n}\n\nfunction colorizeMentionAgentText(\n text: string,\n item: MentionSelectListItem\n): string {\n const agentControllerRef = normalizeSingleLineText(\n item.mentionAgentControllerRef\n );\n if (!(text && agentControllerRef && item.mentionProfileKind === \"agent\")) {\n return text;\n }\n\n return colorizeAgentLabel(text, {\n agentControllerRef,\n profileId: normalizeSingleLineText(item.mentionProfileId) ?? undefined,\n profileName:\n normalizeSingleLineText(item.mentionProfileName) ??\n normalizeSingleLineText(item.label || item.value) ??\n undefined,\n });\n}\n\nfunction shouldColorizeAgentMentionItem(item: MentionSelectListItem): boolean {\n return Boolean(\n item.mentionPresentation === \"target_choice\" &&\n item.mentionProfileKind === \"agent\" &&\n normalizeSingleLineText(item.mentionAgentControllerRef)\n );\n}\n\nfunction normalizeSingleLineText(\n text: string | number | null | undefined\n): string | null {\n const normalized = String(text ?? \"\")\n .replace(/[\\r\\n]+/g, \" \")\n .trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction measureTextWidth(text: string): number {\n return Array.from(text).length;\n}\n\nfunction truncateText(text: string, maxWidth: number): string {\n if (maxWidth <= 0) {\n return \"\";\n }\n return Array.from(text).slice(0, maxWidth).join(\"\");\n}\n","import type {\n AutocompleteItem,\n AutocompleteProvider,\n} from \"@mariozechner/pi-tui\";\nimport type { MessageMentionType } from \"@openmeld/schemas\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport type {\n MentionPickerState,\n MentionPickerTarget,\n SpaceMentionSuggestion,\n SpaceSendTargetAllowedRelations,\n SpaceSendTargetProjectionEntry,\n SpaceSendTargetWakeAvailability,\n} from \"@openmeld/space\";\nimport {\n closeMentionPickerState,\n enterRelationPickerState,\n extractMentionAuthoringPrefix,\n isRelationPickerState,\n isTargetPickerState,\n listSpaceMentionRelationChoices,\n listSpaceMentionSuggestions,\n openTargetPickerState,\n returnToTargetPickerState,\n} from \"@openmeld/space\";\nimport { listSpaceSlashCommands } from \"../../composer/slash-command-registry\";\n\nconst MENTION_SECTION_ITEM_VALUE = \"__mention_section__\";\nconst MENTION_SPACER_ITEM_VALUE = \"__mention_spacer__\";\nconst MENTION_RELATION_HEADER_ITEM_VALUE = \"__mention_relation_header__\";\nconst MENTION_BACK_ITEM_VALUE = \"__mention_back__\";\n\nexport type PiTuiMentionAutocompleteItemPresentation =\n | \"back_choice\"\n | \"relation_choice\"\n | \"relation_header\"\n | \"section_header\"\n | \"spacer\"\n | \"target_choice\";\n\nexport type PiTuiComposerAutocompleteItem = AutocompleteItem & {\n mentionAllowedRelations?: SpaceSendTargetAllowedRelations;\n mentionControllerDisplay?: string | null;\n mentionAgentControllerRef?: string | null;\n mentionOwnerDisplay?: string | null;\n mentionPresentation?: PiTuiMentionAutocompleteItemPresentation;\n mentionProfileId?: string;\n mentionProfileKind?: \"human\" | \"agent\";\n mentionProfileName?: string;\n mentionRelation?: MessageMentionType;\n mentionPrimaryLabel?: string;\n mentionLabelSource?: SpaceSendTargetProjectionEntry[\"labelSource\"];\n mentionWakeAvailability?: SpaceSendTargetWakeAvailability;\n};\n\nexport class PiTuiComposerAutocompleteProvider implements AutocompleteProvider {\n readonly #onMentionSelected?: (input: {\n text: string;\n start: number;\n profileId: string;\n relation: MessageMentionType;\n mentionText: string;\n }) => void;\n readonly #getMembersSnapshot: () => SpaceMembersSnapshot | null;\n readonly #getRecentMentionProfileIds: () => readonly string[];\n\n #mentionPickerState: MentionPickerState = closeMentionPickerState();\n #resetRelationSelectionOnNextSync = false;\n\n constructor(input: {\n onMentionSelected?: (input: {\n text: string;\n start: number;\n profileId: string;\n relation: MessageMentionType;\n mentionText: string;\n }) => void;\n getMembersSnapshot: () => SpaceMembersSnapshot | null;\n getRecentMentionProfileIds?: () => readonly string[];\n }) {\n this.#getMembersSnapshot = input.getMembersSnapshot;\n this.#onMentionSelected = input.onMentionSelected;\n this.#getRecentMentionProfileIds =\n input.getRecentMentionProfileIds ?? (() => []);\n }\n\n getSuggestions(lines: string[], cursorLine: number, cursorCol: number) {\n const currentLine = lines[cursorLine] ?? \"\";\n const textBeforeCursor = currentLine.slice(0, cursorCol);\n\n const slashSuggestions = this.#getSlashSuggestions(textBeforeCursor);\n if (slashSuggestions) {\n return slashSuggestions;\n }\n\n const mentionSuggestions = this.#getMentionSuggestions(textBeforeCursor);\n if (mentionSuggestions) {\n return mentionSuggestions;\n }\n\n return null;\n }\n\n applyCompletion(\n lines: string[],\n cursorLine: number,\n cursorCol: number,\n item: AutocompleteItem,\n prefix: string\n ) {\n if (prefix.startsWith(\"/\")) {\n const currentLine = lines[cursorLine] ?? \"\";\n const beforePrefix = currentLine.slice(0, cursorCol - prefix.length);\n const afterCursor = currentLine.slice(cursorCol);\n const nextLines = [...lines];\n\n nextLines[cursorLine] = `${beforePrefix}/${item.value} ${afterCursor}`;\n return {\n lines: nextLines,\n cursorLine,\n cursorCol: beforePrefix.length + item.value.length + 2,\n };\n }\n\n const mentionItem = asMentionAutocompleteItem(item);\n if (\n !(mentionItem && isSelectableMentionAutocompleteItem(mentionItem)) ||\n mentionItem.mentionPresentation !== \"relation_choice\"\n ) {\n return {\n lines: [...lines],\n cursorLine,\n cursorCol,\n };\n }\n\n const currentLine = lines[cursorLine] ?? \"\";\n const beforePrefix = currentLine.slice(0, cursorCol - prefix.length);\n const afterCursor = currentLine.slice(cursorCol);\n const nextLines = [...lines];\n\n this.resetMentionPicker();\n nextLines[cursorLine] =\n `${beforePrefix}${mentionItem.value} ${afterCursor}`;\n if (mentionItem.mentionProfileId && mentionItem.mentionRelation) {\n this.#onMentionSelected?.({\n text: nextLines.join(\"\\n\"),\n start:\n nextLines\n .slice(0, cursorLine)\n .reduce((length, line) => length + line.length + 1, 0) +\n beforePrefix.length,\n profileId: mentionItem.mentionProfileId,\n relation: mentionItem.mentionRelation,\n mentionText: mentionItem.value,\n });\n }\n return {\n lines: nextLines,\n cursorLine,\n cursorCol: beforePrefix.length + mentionItem.value.length + 1,\n };\n }\n\n enterRelationPicker(item: AutocompleteItem, prefix: string): boolean {\n const mentionItem = asMentionAutocompleteItem(item);\n if (\n mentionItem?.mentionPresentation !== \"target_choice\" ||\n !prefix.startsWith(\"@\")\n ) {\n return false;\n }\n\n const target = buildMentionPickerTargetFromItem(mentionItem);\n if (!target) {\n return false;\n }\n\n this.#mentionPickerState = enterRelationPickerState({\n query: prefix,\n target,\n });\n this.#resetRelationSelectionOnNextSync = true;\n return true;\n }\n\n isRelationPickerOpen(): boolean {\n return isRelationPickerState(this.#mentionPickerState);\n }\n\n prepareForEditableInput(): boolean {\n return this.returnToTargetPicker();\n }\n\n resetMentionPicker(): void {\n this.#mentionPickerState = closeMentionPickerState();\n this.#resetRelationSelectionOnNextSync = false;\n }\n\n returnToTargetPicker(): boolean {\n if (!isRelationPickerState(this.#mentionPickerState)) {\n return false;\n }\n\n this.#mentionPickerState = returnToTargetPickerState(\n this.#mentionPickerState\n );\n this.#resetRelationSelectionOnNextSync = false;\n return true;\n }\n\n syncAutocompleteSelection(input: {\n items: readonly PiTuiComposerAutocompleteItem[];\n setSelectedIndex: (index: number) => void;\n }): void {\n if (\n isRelationPickerState(this.#mentionPickerState) &&\n this.#resetRelationSelectionOnNextSync\n ) {\n const firstRelationIndex = input.items.findIndex(\n (item) => item.mentionPresentation === \"relation_choice\"\n );\n if (firstRelationIndex >= 0) {\n input.setSelectedIndex(firstRelationIndex);\n }\n this.#resetRelationSelectionOnNextSync = false;\n return;\n }\n\n if (!isTargetPickerState(this.#mentionPickerState)) {\n return;\n }\n\n const selectedProfileId = this.#mentionPickerState.selectedProfileId;\n if (!selectedProfileId) {\n return;\n }\n\n const selectedIndex = input.items.findIndex(\n (item) =>\n item.mentionPresentation === \"target_choice\" &&\n item.mentionProfileId === selectedProfileId\n );\n if (selectedIndex >= 0) {\n input.setSelectedIndex(selectedIndex);\n }\n }\n\n #getSlashSuggestions(textBeforeCursor: string): {\n items: AutocompleteItem[];\n prefix: string;\n } | null {\n if (!textBeforeCursor.startsWith(\"/\")) {\n return null;\n }\n if (textBeforeCursor.includes(\" \")) {\n return null;\n }\n const query = textBeforeCursor.slice(1).trim().toLowerCase();\n const items = listSpaceSlashCommands()\n .filter((command) =>\n query ? command.name.toLowerCase().startsWith(query) : true\n )\n .map((command) => ({\n value: command.name,\n label: command.trigger,\n description: command.description,\n }));\n if (items.length === 0) {\n return null;\n }\n return {\n items,\n prefix: textBeforeCursor,\n };\n }\n\n #getMentionSuggestions(textBeforeCursor: string): {\n items: PiTuiComposerAutocompleteItem[];\n prefix: string;\n } | null {\n const prefix = extractMentionAuthoringPrefix(textBeforeCursor);\n if (!prefix) {\n this.resetMentionPicker();\n return null;\n }\n\n if (\n isRelationPickerState(this.#mentionPickerState) &&\n this.#mentionPickerState.query === prefix\n ) {\n return {\n items: buildRelationPickerItems(this.#mentionPickerState.target),\n prefix,\n };\n }\n\n const suggestions = listSpaceMentionSuggestions({\n query: prefix,\n snapshot: this.#getMembersSnapshot(),\n recentProfileIds: this.#getRecentMentionProfileIds(),\n });\n const selectedProfileId = resolveSelectedProfileId(\n this.#mentionPickerState\n );\n this.#mentionPickerState = openTargetPickerState({\n query: prefix,\n selectedProfileId,\n });\n\n const items = buildGroupedTargetAutocompleteItems(suggestions);\n if (items.length === 0) {\n return null;\n }\n\n return {\n items,\n prefix,\n };\n }\n}\n\nexport function isSelectableMentionAutocompleteItem(\n item: AutocompleteItem\n): boolean {\n return (\n !(\"mentionPresentation\" in item) ||\n item.mentionPresentation === undefined ||\n item.mentionPresentation === \"back_choice\" ||\n item.mentionPresentation === \"relation_choice\" ||\n item.mentionPresentation === \"target_choice\"\n );\n}\n\nfunction asMentionAutocompleteItem(\n item: AutocompleteItem\n): PiTuiComposerAutocompleteItem | null {\n return item as PiTuiComposerAutocompleteItem | null;\n}\n\nfunction resolveSelectedProfileId(state: MentionPickerState): string | null {\n if (isRelationPickerState(state)) {\n return state.target.profileId;\n }\n\n if (isTargetPickerState(state)) {\n return state.selectedProfileId;\n }\n\n return null;\n}\n\nfunction buildGroupedTargetAutocompleteItems(\n suggestions: SpaceMentionSuggestion[]\n): PiTuiComposerAutocompleteItem[] {\n const agentItems = suggestions\n .filter((suggestion) => suggestion.profileKind === \"agent\")\n .map((suggestion) => buildTargetItem(suggestion));\n const humanItems = suggestions\n .filter((suggestion) => suggestion.profileKind === \"human\")\n .map((suggestion) => buildTargetItem(suggestion));\n const items: PiTuiComposerAutocompleteItem[] = [];\n\n if (agentItems.length > 0) {\n items.push(buildSectionHeaderItem(\"agent\"));\n items.push(...agentItems);\n }\n\n if (humanItems.length > 0 && agentItems.length > 0) {\n items.push(buildSpacerItem());\n }\n\n if (humanItems.length > 0) {\n items.push(buildSectionHeaderItem(\"human\"));\n items.push(...humanItems);\n }\n\n return items;\n}\n\nfunction buildTargetItem(\n suggestion: SpaceMentionSuggestion\n): PiTuiComposerAutocompleteItem {\n return {\n value: suggestion.primaryMentionLabel,\n label: suggestion.profileName,\n description: buildTargetChoiceDescription(suggestion),\n mentionAllowedRelations: suggestion.allowedRelations,\n mentionControllerDisplay: suggestion.controllerDisplay,\n mentionAgentControllerRef: suggestion.agentControllerRef,\n mentionOwnerDisplay: suggestion.ownerDisplay,\n mentionPresentation: \"target_choice\",\n mentionProfileId: suggestion.profileId,\n mentionProfileKind: suggestion.profileKind,\n mentionProfileName: suggestion.profileName,\n mentionPrimaryLabel: suggestion.primaryMentionLabel,\n mentionLabelSource: suggestion.labelSource,\n mentionWakeAvailability: suggestion.wakeAvailability,\n };\n}\n\nfunction buildTargetChoiceDescription(\n suggestion: SpaceMentionSuggestion\n): string {\n const baseDescription = suggestion.description.trim();\n if (suggestion.primaryMentionLabel === suggestion.profileName) {\n return baseDescription;\n }\n\n return [\n `Use @${suggestion.primaryMentionLabel}`,\n baseDescription.length > 0 ? baseDescription : null,\n ]\n .filter((segment): segment is string => Boolean(segment))\n .join(\" · \");\n}\n\nfunction buildRelationPickerItems(\n target: MentionPickerTarget\n): PiTuiComposerAutocompleteItem[] {\n const items: PiTuiComposerAutocompleteItem[] = [\n {\n value: `${MENTION_RELATION_HEADER_ITEM_VALUE}:${target.profileId}`,\n label: target.profileName,\n mentionAllowedRelations: target.allowedRelations,\n mentionControllerDisplay: target.controllerDisplay,\n mentionAgentControllerRef: target.agentControllerRef,\n mentionOwnerDisplay: target.ownerDisplay,\n mentionPresentation: \"relation_header\",\n mentionProfileId: target.profileId,\n mentionProfileKind: target.profileKind,\n mentionProfileName: target.profileName,\n mentionPrimaryLabel: target.primaryMentionLabel,\n mentionLabelSource: target.labelSource,\n mentionWakeAvailability: target.wakeAvailability,\n },\n ];\n\n for (const relationChoice of listSpaceMentionRelationChoices(target)) {\n items.push({\n value: `@${target.profileName}`,\n label: relationChoice.label,\n description: relationChoice.description,\n mentionAllowedRelations: target.allowedRelations,\n mentionControllerDisplay: target.controllerDisplay,\n mentionAgentControllerRef: target.agentControllerRef,\n mentionOwnerDisplay: target.ownerDisplay,\n mentionPresentation: \"relation_choice\",\n mentionProfileId: target.profileId,\n mentionProfileKind: target.profileKind,\n mentionProfileName: target.profileName,\n mentionRelation: relationChoice.relation,\n mentionPrimaryLabel: target.primaryMentionLabel,\n mentionLabelSource: target.labelSource,\n mentionWakeAvailability: target.wakeAvailability,\n });\n }\n\n items.push({\n value: `${MENTION_BACK_ITEM_VALUE}:${target.profileId}`,\n label: \"Back\",\n description: \"Go back\",\n mentionAllowedRelations: target.allowedRelations,\n mentionControllerDisplay: target.controllerDisplay,\n mentionAgentControllerRef: target.agentControllerRef,\n mentionOwnerDisplay: target.ownerDisplay,\n mentionPresentation: \"back_choice\",\n mentionProfileId: target.profileId,\n mentionProfileKind: target.profileKind,\n mentionProfileName: target.profileName,\n mentionPrimaryLabel: target.primaryMentionLabel,\n mentionLabelSource: target.labelSource,\n mentionWakeAvailability: target.wakeAvailability,\n });\n\n return items;\n}\n\nfunction buildMentionPickerTargetFromItem(\n item: PiTuiComposerAutocompleteItem\n): MentionPickerTarget | null {\n const allowedRelations = item.mentionAllowedRelations;\n const profileId = item.mentionProfileId;\n const profileKind = item.mentionProfileKind;\n const profileName = item.mentionProfileName;\n\n if (!(allowedRelations && profileId && profileKind && profileName)) {\n return null;\n }\n\n const primaryMentionLabel = item.mentionPrimaryLabel;\n const labelSource = item.mentionLabelSource;\n const wakeAvailability = item.mentionWakeAvailability;\n if (!(primaryMentionLabel && labelSource && wakeAvailability)) {\n return null;\n }\n\n return {\n allowedRelations,\n controllerDisplay: item.mentionControllerDisplay ?? null,\n agentControllerRef: item.mentionAgentControllerRef ?? null,\n description: item.description ?? \"\",\n ownerDisplay: item.mentionOwnerDisplay ?? null,\n profileId,\n profileKind,\n profileName,\n labelSource,\n primaryMentionLabel,\n wakeAvailability,\n };\n}\n\nfunction buildSectionHeaderItem(\n profileKind: \"human\" | \"agent\"\n): PiTuiComposerAutocompleteItem {\n return {\n value: `${MENTION_SECTION_ITEM_VALUE}:${profileKind}`,\n label: profileKind === \"human\" ? \"👤\" : \"🤖\",\n mentionPresentation: \"section_header\",\n mentionProfileKind: profileKind,\n };\n}\n\nfunction buildSpacerItem(): PiTuiComposerAutocompleteItem {\n return {\n value: MENTION_SPACER_ITEM_VALUE,\n label: \"\",\n mentionPresentation: \"spacer\",\n };\n}\n","import {\n Editor,\n type EditorTheme,\n getEditorKeybindings,\n Key,\n matchesKey,\n type TUI,\n} from \"@mariozechner/pi-tui\";\nimport { decorateMentionAutocompleteSelectList } from \"./mention-autocomplete-select-list\";\nimport {\n type PiTuiComposerAutocompleteItem,\n PiTuiComposerAutocompleteProvider,\n} from \"./pi-tui-composer-autocomplete-provider\";\n\ntype SelectListInternals = {\n openMeldMentionAutocompleteDecorated?: boolean;\n filteredItems: PiTuiComposerAutocompleteItem[];\n getSelectedItem: () => PiTuiComposerAutocompleteItem | null;\n setSelectedIndex: (index: number) => void;\n};\n\ntype EditorInternals = {\n autocompleteList?: SelectListInternals;\n autocompletePrefix: string;\n autocompleteProvider?: unknown;\n disableSubmit: boolean;\n forceFileAutocomplete: (explicitTab?: boolean) => void;\n handleInput: (data: string) => void;\n shouldSubmitOnBackslashEnter: (data: string, kb: unknown) => boolean;\n state: {\n cursorCol: number;\n cursorLine: number;\n lines: string[];\n };\n submitValue: () => void;\n tryTriggerAutocomplete: (explicitTab?: boolean) => void;\n updateAutocomplete: () => void;\n};\n\nexport function createSpaceComposerEditor(\n tui: TUI,\n theme: EditorTheme,\n options?: {\n autocompleteMaxVisible?: number;\n paddingX?: number;\n }\n): Editor {\n const editor = new Editor(tui, theme, options);\n disableBackslashContinuation(editor);\n return editor;\n}\n\nfunction disableBackslashContinuation(editor: Editor): void {\n const editorInternals = editor as unknown as EditorInternals;\n const originalHandleInput = editorInternals.handleInput.bind(editorInternals);\n const originalTryTriggerAutocomplete =\n editorInternals.tryTriggerAutocomplete.bind(editorInternals);\n const originalForceFileAutocomplete =\n editorInternals.forceFileAutocomplete.bind(editorInternals);\n const originalUpdateAutocomplete =\n editorInternals.updateAutocomplete.bind(editorInternals);\n\n editorInternals.shouldSubmitOnBackslashEnter = () => false;\n editorInternals.handleInput = (data: string): void => {\n if (handleNestedMentionPickerInput(editorInternals, data)) {\n return;\n }\n if (shouldSubmitLiteralBackslash(editorInternals, data)) {\n if (!editorInternals.disableSubmit) {\n editorInternals.submitValue();\n }\n return;\n }\n originalHandleInput(data);\n };\n editorInternals.tryTriggerAutocomplete = (explicitTab?: boolean): void => {\n originalTryTriggerAutocomplete(explicitTab);\n decorateMentionAutocomplete(editorInternals);\n };\n editorInternals.forceFileAutocomplete = (explicitTab?: boolean): void => {\n originalForceFileAutocomplete(explicitTab);\n decorateMentionAutocomplete(editorInternals);\n };\n editorInternals.updateAutocomplete = (): void => {\n originalUpdateAutocomplete();\n decorateMentionAutocomplete(editorInternals);\n };\n}\n\nfunction shouldSubmitLiteralBackslash(\n editor: EditorInternals,\n data: string\n): boolean {\n if (!matchesKey(data, Key.enter)) {\n return false;\n }\n const currentLine = editor.state.lines[editor.state.cursorLine] ?? \"\";\n return (\n editor.state.cursorCol > 0 &&\n currentLine[editor.state.cursorCol - 1] === \"\\\\\"\n );\n}\n\nfunction decorateMentionAutocomplete(editor: EditorInternals): void {\n if (!(editor.autocompleteList && editor.autocompletePrefix.startsWith(\"@\"))) {\n return;\n }\n\n const autocompleteList = editor.autocompleteList as SelectListInternals &\n Parameters<typeof decorateMentionAutocompleteSelectList>[0];\n decorateMentionAutocompleteSelectList(autocompleteList);\n\n const mentionProvider = getMentionAutocompleteProvider(editor);\n mentionProvider?.syncAutocompleteSelection({\n items: autocompleteList.filteredItems,\n setSelectedIndex: (index) => {\n autocompleteList.setSelectedIndex(index);\n },\n });\n}\n\nfunction handleNestedMentionPickerInput(\n editor: EditorInternals,\n data: string\n): boolean {\n if (!(editor.autocompleteList && editor.autocompletePrefix.startsWith(\"@\"))) {\n return false;\n }\n\n const mentionProvider = getMentionAutocompleteProvider(editor);\n if (!mentionProvider) {\n return false;\n }\n\n const keybindings = getEditorKeybindings();\n const selectedItem = editor.autocompleteList.getSelectedItem();\n const confirmsSelection =\n keybindings.matches(data, \"selectConfirm\") ||\n keybindings.matches(data, \"tab\");\n\n if (\n confirmsSelection &&\n selectedItem?.mentionPresentation === \"target_choice\" &&\n mentionProvider.enterRelationPicker(selectedItem, editor.autocompletePrefix)\n ) {\n editor.updateAutocomplete();\n return true;\n }\n\n if (!mentionProvider.isRelationPickerOpen()) {\n return false;\n }\n\n if (\n selectedItem?.mentionPresentation === \"back_choice\" &&\n confirmsSelection\n ) {\n mentionProvider.returnToTargetPicker();\n editor.updateAutocomplete();\n return true;\n }\n\n if (\n keybindings.matches(data, \"cursorLeft\") ||\n keybindings.matches(data, \"selectCancel\")\n ) {\n mentionProvider.returnToTargetPicker();\n editor.updateAutocomplete();\n return true;\n }\n\n if (shouldResumeTargetPickerSearch(data)) {\n mentionProvider.prepareForEditableInput();\n }\n\n return false;\n}\n\nfunction getMentionAutocompleteProvider(\n editor: EditorInternals\n): PiTuiComposerAutocompleteProvider | null {\n if (\n editor.autocompleteProvider instanceof PiTuiComposerAutocompleteProvider\n ) {\n return editor.autocompleteProvider;\n }\n return null;\n}\n\nfunction shouldResumeTargetPickerSearch(data: string): boolean {\n const keybindings = getEditorKeybindings();\n if (\n keybindings.matches(data, \"deleteCharBackward\") ||\n keybindings.matches(data, \"deleteCharForward\") ||\n keybindings.matches(data, \"deleteWordBackward\") ||\n keybindings.matches(data, \"deleteWordForward\") ||\n keybindings.matches(data, \"deleteToLineStart\") ||\n keybindings.matches(data, \"deleteToLineEnd\")\n ) {\n return true;\n }\n\n return isPrintableEditorInput(data);\n}\n\nfunction isPrintableEditorInput(data: string): boolean {\n if (!data) {\n return false;\n }\n\n if (\n matchesKey(data, Key.backspace) ||\n matchesKey(data, Key.delete) ||\n matchesKey(data, Key.enter) ||\n matchesKey(data, Key.escape) ||\n matchesKey(data, Key.tab)\n ) {\n return false;\n }\n\n if (data.startsWith(\"\\u001b\")) {\n return false;\n }\n\n for (const character of data) {\n const code = character.charCodeAt(0);\n if ((code >= 0 && code <= 31) || code === 127) {\n return false;\n }\n }\n\n return true;\n}\n","import pc from \"picocolors\";\nimport wrapAnsi from \"wrap-ansi\";\nimport type { SpaceSummarySegmentViewState } from \"../../../view/space-session-view-state\";\n\nexport function renderSpaceSummaryLines(input: {\n segments: readonly SpaceSummarySegmentViewState[];\n tone?: \"default\" | \"muted\";\n width: number;\n}): string[] {\n const text = joinSpaceSummarySegments(input.segments);\n if (!text) {\n return [];\n }\n const styledText =\n input.tone === \"muted\" ? pc.dim(text) : renderDefaultSummaryText(text);\n return wrapAnsi(styledText, Math.max(1, input.width), {\n hard: true,\n trim: false,\n wordWrap: true,\n }).split(\"\\n\");\n}\n\nfunction joinSpaceSummarySegments(\n segments: readonly SpaceSummarySegmentViewState[]\n): string {\n return segments\n .map((segment) => segment.text.trim())\n .filter((segment) => segment.length > 0)\n .join(pc.dim(\" · \"));\n}\n\nfunction renderDefaultSummaryText(text: string): string {\n return text;\n}\n","import {\n type Component,\n Container,\n type Editor,\n type EditorTheme,\n type TUI,\n} from \"@mariozechner/pi-tui\";\nimport stringWidth from \"string-width\";\nimport wrapAnsi from \"wrap-ansi\";\nimport {\n OPENMELD_COMPOSER_SURFACE_BG_RGB,\n renderOpenMeldBrandAccent,\n} from \"../../../../ui/brand\";\nimport { renderTextInputCursor } from \"../../../../ui/text-input-cursor\";\nimport type { SpaceSummarySegmentViewState } from \"../../../view/space-session-view-state\";\nimport { createSpaceComposerEditor } from \"../space-composer-editor\";\nimport { renderSpaceSummaryLines } from \"./render-space-summary-lines\";\n\nconst COMPOSER_INPUT_BACKGROUND = `\\u001B[48;2;${String(OPENMELD_COMPOSER_SURFACE_BG_RGB[0])};${String(OPENMELD_COMPOSER_SURFACE_BG_RGB[1])};${String(OPENMELD_COMPOSER_SURFACE_BG_RGB[2])}m`;\nconst COMPOSER_INPUT_BACKGROUND_RESET = \"\\u001B[49m\";\nconst COMPOSER_PLACEHOLDER_FOREGROUND = \"\\u001B[38;2;122;122;122m\";\nconst COMPOSER_PLACEHOLDER_FOREGROUND_RESET = \"\\u001B[39m\";\nconst COMPOSER_INPUT_PREFIX = \" › \";\nconst COMPOSER_INPUT_CONTINUATION_PREFIX = \" \";\nconst COMPOSER_INPUT_PREFIX_WIDTH = stringWidth(COMPOSER_INPUT_PREFIX);\nconst COMPOSER_BORDER_PATTERN = /^─+$/u;\nconst COMPOSER_SCROLL_BORDER_PATTERN = /^─── [↑↓] \\d+ more ─*$/u;\nconst COMPOSER_INPUT_VERTICAL_PADDING_LINES = 1;\nconst ANSI_SGR_PATTERN = new RegExp(\n `${String.fromCharCode(27)}\\\\[[0-9;]*m`,\n \"g\"\n);\n\nexport class ComposerPanel implements Component {\n readonly #container = new Container();\n readonly editor: Editor;\n #helperText = \"\";\n #leadingBlankLines = 1;\n #placeholderText = \"\";\n #showPlaceholder = false;\n #summarySegments: readonly SpaceSummarySegmentViewState[] = [];\n #visible = true;\n\n constructor(tui: TUI, theme: EditorTheme) {\n this.editor = createSpaceComposerEditor(tui, theme, {\n paddingX: 0,\n autocompleteMaxVisible: 6,\n });\n this.#container.addChild(this.editor);\n }\n\n invalidate(): void {\n this.#container.invalidate();\n }\n\n setHelperText(text: string): void {\n if (this.#helperText === text) {\n return;\n }\n this.#helperText = text;\n this.#container.invalidate();\n }\n\n setLeadingBlankLines(count: number): void {\n const normalizedCount = Math.max(0, Math.trunc(count));\n if (this.#leadingBlankLines === normalizedCount) {\n return;\n }\n this.#leadingBlankLines = normalizedCount;\n this.#container.invalidate();\n }\n\n setPlaceholderText(text: string): void {\n if (this.#placeholderText === text) {\n return;\n }\n this.#placeholderText = text;\n this.#container.invalidate();\n }\n\n setShowPlaceholder(visible: boolean): void {\n if (this.#showPlaceholder === visible) {\n return;\n }\n this.#showPlaceholder = visible;\n this.#container.invalidate();\n }\n\n setSummarySegments(segments: readonly SpaceSummarySegmentViewState[]): void {\n this.#summarySegments = segments;\n this.#container.invalidate();\n }\n\n setVisible(visible: boolean): void {\n if (this.#visible === visible) {\n return;\n }\n this.#visible = visible;\n this.#container.invalidate();\n }\n\n render(width: number): string[] {\n if (!this.#visible) {\n return [];\n }\n const editorRenderWidth = Math.max(1, width - COMPOSER_INPUT_PREFIX_WIDTH);\n const composerLines = styleComposerEditorLines({\n lines: this.#container.render(editorRenderWidth),\n placeholderText: this.#placeholderText,\n showPlaceholder: this.#showPlaceholder,\n width,\n });\n return [\n ...Array.from({ length: this.#leadingBlankLines }, () => \"\"),\n ...renderComposerHelperLines(this.#helperText, width),\n ...composerLines,\n ...renderSpaceSummaryLines({\n segments: this.#summarySegments,\n tone: \"muted\",\n width,\n }),\n ];\n }\n}\n\nfunction renderComposerHelperLines(text: string, width: number): string[] {\n const normalizedText = text.trim();\n if (!normalizedText) {\n return [];\n }\n const wrapped = wrapAnsi(normalizedText, Math.max(1, width), {\n hard: true,\n trim: false,\n wordWrap: true,\n });\n return wrapped.split(\"\\n\");\n}\n\nfunction styleComposerEditorLines(input: {\n lines: readonly string[];\n placeholderText: string;\n showPlaceholder: boolean;\n width: number;\n}): string[] {\n const sections = splitComposerEditorRenderLines(input.lines);\n const bodyLines = sections.bodyLines.length > 0 ? sections.bodyLines : [\"\"];\n const topPaddingLines = Array.from(\n { length: COMPOSER_INPUT_VERTICAL_PADDING_LINES },\n () => renderComposerInputPaddingLine(input.width)\n );\n const styledBodyLines = bodyLines.map((line, index) =>\n renderComposerInputLine({\n line,\n placeholderText: index === 0 ? input.placeholderText : \"\",\n width: input.width,\n prefix:\n index === 0\n ? COMPOSER_INPUT_PREFIX\n : COMPOSER_INPUT_CONTINUATION_PREFIX,\n showPlaceholder: index === 0 && input.showPlaceholder,\n })\n );\n const bottomPaddingLines = Array.from(\n { length: COMPOSER_INPUT_VERTICAL_PADDING_LINES },\n () => renderComposerInputPaddingLine(input.width)\n );\n const footerLines = sections.footerLines.map((line) =>\n indentComposerFooterLine(line, input.width)\n );\n return [\n ...topPaddingLines,\n ...styledBodyLines,\n ...bottomPaddingLines,\n ...footerLines,\n ];\n}\n\nfunction splitComposerEditorRenderLines(lines: readonly string[]): {\n bodyLines: readonly string[];\n footerLines: readonly string[];\n} {\n const topBorderIndex = lines.findIndex(isComposerBorderLine);\n const bottomBorderIndex = findLastComposerBorderLineIndex(lines);\n if (topBorderIndex === -1 || bottomBorderIndex <= topBorderIndex) {\n return {\n bodyLines: [...lines],\n footerLines: [],\n };\n }\n return {\n bodyLines: lines.slice(topBorderIndex + 1, bottomBorderIndex),\n footerLines: lines.slice(bottomBorderIndex + 1),\n };\n}\n\nfunction findLastComposerBorderLineIndex(lines: readonly string[]): number {\n for (let index = lines.length - 1; index >= 0; index -= 1) {\n if (isComposerBorderLine(lines[index] ?? \"\")) {\n return index;\n }\n }\n return -1;\n}\n\nfunction isComposerBorderLine(line: string): boolean {\n const normalized = line.replaceAll(ANSI_SGR_PATTERN, \"\").trim();\n return (\n COMPOSER_BORDER_PATTERN.test(normalized) ||\n COMPOSER_SCROLL_BORDER_PATTERN.test(normalized)\n );\n}\n\nfunction renderComposerInputLine(input: {\n line: string;\n placeholderText: string;\n prefix: string;\n showPlaceholder: boolean;\n width: number;\n}): string {\n const combinedLine =\n input.showPlaceholder && input.placeholderText\n ? renderComposerPlaceholderLine(input.prefix, input.placeholderText)\n : `${input.prefix}${input.line}`;\n const visibleWidth = stringWidth(combinedLine);\n const trailingPadding = \" \".repeat(Math.max(0, input.width - visibleWidth));\n return applyComposerInputBackground(`${combinedLine}${trailingPadding}`);\n}\n\nfunction renderComposerInputPaddingLine(width: number): string {\n return applyComposerInputBackground(\" \".repeat(Math.max(0, width)));\n}\n\nfunction applyComposerInputBackground(line: string): string {\n const normalizedLine = line.replaceAll(\n \"\\u001B[0m\",\n `\\u001B[0m${COMPOSER_INPUT_BACKGROUND}`\n );\n return `${COMPOSER_INPUT_BACKGROUND}${normalizedLine}${COMPOSER_INPUT_BACKGROUND_RESET}`;\n}\n\nfunction indentComposerFooterLine(line: string, width: number): string {\n const indentedLine = `${COMPOSER_INPUT_CONTINUATION_PREFIX}${line}`;\n const visibleWidth = stringWidth(indentedLine);\n return `${indentedLine}${\" \".repeat(Math.max(0, width - visibleWidth))}`;\n}\n\nfunction renderComposerPlaceholderLine(\n prefix: string,\n placeholderText: string\n): string {\n return `${renderOpenMeldBrandAccent(prefix)}${renderTextInputCursor()}${COMPOSER_PLACEHOLDER_FOREGROUND} ${placeholderText}${COMPOSER_PLACEHOLDER_FOREGROUND_RESET}`;\n}\n","import { Key, matchesKey } from \"@mariozechner/pi-tui\";\nimport {\n clampNumber,\n resolveAnchoredVisibleWindow,\n resolveOffsetVisibleWindow,\n} from \"../../../../ui/visible-window\";\nimport { formatPanelOverflowHintLine } from \"../../../panel/space-panel-display\";\n\nexport const READONLY_VIEWPORT_SCROLL_HINT_LINE =\n \"↑↓ scroll · PgUp/PgDn page · Home/End jump\";\n\nexport type ReadonlyViewportRow = {\n text: string;\n};\n\nexport type ReadonlyViewportScrollMode =\n | {\n kind: \"anchor\";\n }\n | {\n kind: \"offset\";\n offset: number;\n };\n\nexport type ReadonlyViewportState = {\n canScroll: boolean;\n footerLines: readonly string[];\n hiddenAfter: number;\n hiddenBefore: number;\n maxOffset: number;\n offset: number;\n visibleBodyLines: readonly string[];\n visibleBodyRowCount: number;\n};\n\nexport function buildReadonlyRuntimeFooterLines(input: {\n alwaysShowScrollHint?: boolean;\n canScroll: boolean;\n hiddenAfter: number;\n hiddenBefore: number;\n scrollHintLine?: string;\n}): string[] {\n const overflowSummaryLine = formatPanelOverflowHintLine({\n hiddenAfter: input.hiddenAfter,\n hiddenBefore: input.hiddenBefore,\n });\n const lines: string[] = [];\n\n if (overflowSummaryLine) {\n lines.push(overflowSummaryLine);\n }\n if (input.canScroll || input.alwaysShowScrollHint) {\n lines.push(input.scrollHintLine ?? READONLY_VIEWPORT_SCROLL_HINT_LINE);\n }\n\n return lines;\n}\n\nexport function resolveReadonlyViewportState(input: {\n bodyAnchorRowIndex: number | null;\n bodyAnchorRowRange: { end: number; start: number } | null;\n bodyRows: readonly ReadonlyViewportRow[];\n controlRows: readonly ReadonlyViewportRow[];\n footerRows: readonly ReadonlyViewportRow[];\n headerRows: readonly ReadonlyViewportRow[];\n maxDisplayRows: number;\n runtimeFooter?: {\n alwaysShowScrollHint?: boolean;\n scrollHintLine?: string;\n wrapLines?: (lines: readonly string[]) => readonly ReadonlyViewportRow[];\n };\n scrollMode: ReadonlyViewportScrollMode;\n}): ReadonlyViewportState {\n const wrapRuntimeFooterLines =\n input.runtimeFooter?.wrapLines ?? mapLinesToRows;\n\n if (input.bodyRows.length === 0) {\n const runtimeFooterRows = wrapRuntimeFooterLines(\n buildReadonlyRuntimeFooterLines({\n alwaysShowScrollHint: input.runtimeFooter?.alwaysShowScrollHint,\n canScroll: false,\n hiddenAfter: 0,\n hiddenBefore: 0,\n scrollHintLine: input.runtimeFooter?.scrollHintLine,\n })\n );\n return {\n canScroll: false,\n footerLines: [...runtimeFooterRows, ...input.footerRows].map(\n (row) => row.text\n ),\n hiddenAfter: 0,\n hiddenBefore: 0,\n maxOffset: 0,\n offset: 0,\n visibleBodyLines: [],\n visibleBodyRowCount: 0,\n };\n }\n\n const baseVisibleBodyRowCount = resolveVisibleBodyRowCount({\n bodyPresent: true,\n controlLineCount: input.controlRows.length,\n footerLineCount: input.footerRows.length,\n headerLineCount: input.headerRows.length,\n maxDisplayRows: input.maxDisplayRows,\n });\n\n let visibleBodyRowCount = baseVisibleBodyRowCount;\n let visibleWindow = resolveVisibleWindow({\n anchorIndex: input.bodyAnchorRowIndex,\n anchorRange: input.bodyAnchorRowRange,\n bodyRowCount: input.bodyRows.length,\n maxVisible: baseVisibleBodyRowCount,\n scrollMode: input.scrollMode,\n });\n let footerRows = input.footerRows;\n\n for (let iteration = 0; iteration < 3; iteration += 1) {\n const hiddenBefore = visibleWindow.start;\n const hiddenAfter = Math.max(0, input.bodyRows.length - visibleWindow.end);\n const runtimeFooterRows = wrapRuntimeFooterLines(\n buildReadonlyRuntimeFooterLines({\n alwaysShowScrollHint: input.runtimeFooter?.alwaysShowScrollHint,\n canScroll: input.bodyRows.length > visibleBodyRowCount,\n hiddenAfter,\n hiddenBefore,\n scrollHintLine: input.runtimeFooter?.scrollHintLine,\n })\n );\n const nextFooterRows = [...runtimeFooterRows, ...input.footerRows];\n const nextVisibleBodyRowCount = resolveVisibleBodyRowCount({\n bodyPresent: true,\n controlLineCount: input.controlRows.length,\n footerLineCount: nextFooterRows.length,\n headerLineCount: input.headerRows.length,\n maxDisplayRows: input.maxDisplayRows,\n });\n const nextVisibleWindow = resolveVisibleWindow({\n anchorIndex: input.bodyAnchorRowIndex,\n anchorRange: input.bodyAnchorRowRange,\n bodyRowCount: input.bodyRows.length,\n maxVisible: nextVisibleBodyRowCount,\n scrollMode: input.scrollMode,\n });\n const footerStable =\n nextFooterRows.length === footerRows.length &&\n nextFooterRows.every(\n (row, index) => row.text === footerRows[index]?.text\n );\n const windowStable =\n nextVisibleBodyRowCount === visibleBodyRowCount &&\n nextVisibleWindow.start === visibleWindow.start &&\n nextVisibleWindow.end === visibleWindow.end;\n\n footerRows = nextFooterRows;\n visibleBodyRowCount = nextVisibleBodyRowCount;\n visibleWindow = nextVisibleWindow;\n\n if (footerStable && windowStable) {\n break;\n }\n }\n\n const hiddenBefore = visibleWindow.start;\n const hiddenAfter = Math.max(0, input.bodyRows.length - visibleWindow.end);\n const maxOffset = Math.max(0, input.bodyRows.length - visibleBodyRowCount);\n\n return {\n canScroll: input.bodyRows.length > visibleBodyRowCount,\n footerLines: footerRows.map((row) => row.text),\n hiddenAfter,\n hiddenBefore,\n maxOffset,\n offset: visibleWindow.start,\n visibleBodyLines: input.bodyRows\n .slice(visibleWindow.start, visibleWindow.end)\n .map((row) => row.text),\n visibleBodyRowCount,\n };\n}\n\nexport function resolveNextReadonlyViewportOffset(input: {\n canScroll: boolean;\n currentOffset: number;\n data: string;\n maxOffset: number;\n visibleBodyRowCount: number;\n}): number {\n if (!input.canScroll) {\n return input.currentOffset;\n }\n\n const pageStep = Math.max(1, input.visibleBodyRowCount);\n if (matchesKey(input.data, Key.up)) {\n return Math.max(0, input.currentOffset - 1);\n }\n if (matchesKey(input.data, Key.down)) {\n return Math.min(input.maxOffset, input.currentOffset + 1);\n }\n if (matchesKey(input.data, Key.pageUp)) {\n return Math.max(0, input.currentOffset - pageStep);\n }\n if (matchesKey(input.data, Key.pageDown)) {\n return Math.min(input.maxOffset, input.currentOffset + pageStep);\n }\n if (matchesKey(input.data, Key.home)) {\n return 0;\n }\n if (matchesKey(input.data, Key.end)) {\n return input.maxOffset;\n }\n\n return input.currentOffset;\n}\n\nfunction mapLinesToRows(lines: readonly string[]): ReadonlyViewportRow[] {\n return lines.map((text) => ({ text }));\n}\n\nfunction resolveVisibleWindow(input: {\n anchorIndex: number | null;\n anchorRange: { end: number; start: number } | null;\n bodyRowCount: number;\n maxVisible: number;\n scrollMode: ReadonlyViewportScrollMode;\n}): { end: number; start: number } {\n if (input.scrollMode.kind === \"anchor\") {\n if (input.anchorRange) {\n return resolveAnchoredItemVisibleWindow({\n anchorEndIndex: input.anchorRange.end,\n anchorStartIndex: input.anchorRange.start,\n itemCount: input.bodyRowCount,\n maxVisible: input.maxVisible,\n });\n }\n return resolveAnchoredVisibleWindow({\n anchorIndex: input.anchorIndex,\n itemCount: input.bodyRowCount,\n maxVisible: input.maxVisible,\n });\n }\n\n return resolveOffsetVisibleWindow({\n itemCount: input.bodyRowCount,\n maxVisible: input.maxVisible,\n offset: input.scrollMode.offset,\n });\n}\n\nfunction resolveVisibleBodyRowCount(input: {\n bodyPresent: boolean;\n controlLineCount: number;\n footerLineCount: number;\n headerLineCount: number;\n maxDisplayRows: number;\n}): number {\n const headerControlSeparator =\n input.headerLineCount > 0 && input.controlLineCount > 0 ? 1 : 0;\n const bodySeparator =\n input.bodyPresent &&\n (input.headerLineCount > 0 || input.controlLineCount > 0)\n ? 1\n : 0;\n const footerSeparator =\n input.footerLineCount > 0 &&\n (input.bodyPresent ||\n input.headerLineCount > 0 ||\n input.controlLineCount > 0)\n ? 1\n : 0;\n const visibleBodyRowCount =\n input.maxDisplayRows -\n input.headerLineCount -\n input.controlLineCount -\n input.footerLineCount -\n headerControlSeparator -\n bodySeparator -\n footerSeparator;\n\n return Math.max(1, visibleBodyRowCount);\n}\n\nfunction resolveAnchoredItemVisibleWindow(input: {\n anchorEndIndex: number;\n anchorStartIndex: number;\n itemCount: number;\n maxVisible: number;\n}): { end: number; start: number } {\n if (input.itemCount <= input.maxVisible) {\n return {\n end: input.itemCount,\n start: 0,\n };\n }\n\n const maxStart = Math.max(0, input.itemCount - input.maxVisible);\n const clampedStartIndex = clampNumber(\n input.anchorStartIndex,\n 0,\n input.itemCount - 1\n );\n const clampedEndIndex = clampNumber(\n input.anchorEndIndex,\n clampedStartIndex,\n input.itemCount - 1\n );\n const itemHeight = clampedEndIndex - clampedStartIndex + 1;\n\n if (itemHeight >= input.maxVisible) {\n const start = clampNumber(clampedStartIndex, 0, maxStart);\n return {\n end: Math.min(input.itemCount, start + input.maxVisible),\n start,\n };\n }\n\n const freeRows = input.maxVisible - itemHeight;\n const centeredStart = clampedStartIndex - Math.floor(freeRows / 2);\n let start = clampNumber(centeredStart, 0, maxStart);\n if (start > clampedStartIndex) {\n start = clampedStartIndex;\n }\n if (start + input.maxVisible <= clampedEndIndex) {\n start = clampNumber(clampedEndIndex - input.maxVisible + 1, 0, maxStart);\n }\n return {\n end: Math.min(input.itemCount, start + input.maxVisible),\n start,\n };\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport { Box, Text } from \"@mariozechner/pi-tui\";\nimport wrapAnsi from \"wrap-ansi\";\nimport type { SpacePanelSurfaceVariant } from \"../../../panel/space-panel-definition\";\nimport { spacePiTuiTheme } from \"../theme\";\nimport {\n type ReadonlyViewportRow,\n type ReadonlyViewportScrollMode,\n type ReadonlyViewportState,\n resolveReadonlyViewportState,\n} from \"./readonly-viewport\";\n\nconst PANEL_HORIZONTAL_PADDING = 2;\nconst PANEL_VERTICAL_PADDING = 0;\nconst PANEL_BORDER_BOTTOM = 1;\nconst PANEL_BORDER_LEFT = 1;\nconst PANEL_BORDER_RIGHT = 1;\nconst PANEL_BORDER_TOP = 1;\n\nexport type ReadonlyOverlayChrome = {\n borderBgFn: (text: string) => string;\n surfaceBox: Box;\n text: Text;\n};\n\nexport type ReadonlyOverlaySections = {\n bodyLines: readonly string[];\n controlLines: readonly string[];\n footerLines: readonly string[];\n headerLines: readonly string[];\n};\n\nexport type ReadonlyOverlayViewportSections<\n Row extends ReadonlyViewportRow = ReadonlyViewportRow,\n> = {\n bodyAnchorRowIndex: number | null;\n bodyAnchorRowRange: { end: number; start: number } | null;\n bodyRows: readonly Row[];\n controlRows: readonly Row[];\n footerRows: readonly Row[];\n headerRows: readonly Row[];\n};\n\nexport type ReadonlyOverlayRenderResult<\n Row extends ReadonlyViewportRow = ReadonlyViewportRow,\n> = {\n contentWidth: number;\n renderedLines: readonly string[];\n sections: ReadonlyOverlayViewportSections<Row>;\n viewportState: ReadonlyViewportState;\n};\n\nexport function createReadonlyOverlayChrome(\n surfaceVariant: SpacePanelSurfaceVariant = \"light\"\n): ReadonlyOverlayChrome {\n const surfaceBox = new Box(\n PANEL_HORIZONTAL_PADDING,\n PANEL_VERTICAL_PADDING,\n (width) => spacePiTuiTheme.resolvePanelSurfaceBg(surfaceVariant)(width)\n );\n const text = new Text(\"\", 0, 0);\n surfaceBox.addChild(text);\n return {\n borderBgFn: spacePiTuiTheme.resolvePanelBorderBg(surfaceVariant),\n surfaceBox,\n text,\n };\n}\n\nexport function syncReadonlyOverlayChrome(\n chrome: ReadonlyOverlayChrome,\n surfaceVariant: SpacePanelSurfaceVariant\n): void {\n chrome.borderBgFn = spacePiTuiTheme.resolvePanelBorderBg(surfaceVariant);\n chrome.surfaceBox.setBgFn(\n spacePiTuiTheme.resolvePanelSurfaceBg(surfaceVariant)\n );\n}\n\nexport function renderReadonlyOverlayChrome(\n chrome: ReadonlyOverlayChrome,\n width: number\n): string[] {\n const surfaceWidth = Math.max(\n 1,\n width - PANEL_BORDER_LEFT - PANEL_BORDER_RIGHT\n );\n const surfaceLines = chrome.surfaceBox.render(surfaceWidth);\n const leftBorder = chrome.borderBgFn(\" \".repeat(PANEL_BORDER_LEFT));\n const rightBorder = chrome.borderBgFn(\" \".repeat(PANEL_BORDER_RIGHT));\n const renderedLines: string[] = [];\n\n for (let index = 0; index < PANEL_BORDER_TOP; index += 1) {\n renderedLines.push(chrome.borderBgFn(\" \".repeat(width)));\n }\n\n for (const line of surfaceLines) {\n renderedLines.push(`${leftBorder}${line}${rightBorder}`);\n }\n\n for (let index = 0; index < PANEL_BORDER_BOTTOM; index += 1) {\n renderedLines.push(chrome.borderBgFn(\" \".repeat(width)));\n }\n\n return renderedLines;\n}\n\nexport function buildReadonlyOverlayText(input: {\n sections: ReadonlyOverlaySections;\n surfaceVariant: SpacePanelSurfaceVariant;\n title: string;\n}): string[] {\n const renderedLines: string[] = [];\n const { bodyLines, controlLines, footerLines, headerLines } = input.sections;\n\n appendRenderedSection({\n lines: headerLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n title: input.title,\n tone: \"primary\",\n useAccentTitle: true,\n });\n appendSectionGap({\n nextLines: controlLines,\n previousLines: headerLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n });\n appendRenderedSection({\n lines: controlLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n title: input.title,\n tone: \"primary\",\n useAccentTitle: false,\n });\n appendSectionGap({\n nextLines: bodyLines,\n previousLines: controlLines.length > 0 ? controlLines : headerLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n });\n appendRenderedSection({\n lines: bodyLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n title: input.title,\n tone: \"primary\",\n useAccentTitle: false,\n });\n\n let footerPreviousLines = headerLines;\n if (controlLines.length > 0) {\n footerPreviousLines = controlLines;\n }\n if (bodyLines.length > 0) {\n footerPreviousLines = bodyLines;\n }\n appendSectionGap({\n nextLines: footerLines,\n previousLines: footerPreviousLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n });\n appendRenderedSection({\n lines: footerLines,\n renderedLines,\n surfaceVariant: input.surfaceVariant,\n title: input.title,\n tone: \"instruction\",\n useAccentTitle: false,\n });\n\n return renderedLines;\n}\n\nexport function resolveReadonlyOverlayContentWidth(width: number): number {\n const availableWidth = Math.max(\n 1,\n width - PANEL_BORDER_LEFT - PANEL_BORDER_RIGHT\n );\n return Math.max(1, availableWidth - PANEL_HORIZONTAL_PADDING * 2);\n}\n\nexport function resolveReadonlyOverlayMaxDisplayRows(\n maxPanelRows: number\n): number {\n return Math.max(\n 1,\n maxPanelRows -\n PANEL_VERTICAL_PADDING * 2 -\n PANEL_BORDER_TOP -\n PANEL_BORDER_BOTTOM\n );\n}\n\nexport function wrapReadonlyViewportRows<\n Row extends ReadonlyViewportRow = ReadonlyViewportRow,\n>(input: {\n contentWidth: number;\n lines: readonly string[];\n mapRow: (text: string, sourceLineIndex: number) => Row;\n}): Row[] {\n const width = Math.max(1, input.contentWidth);\n\n return input.lines.flatMap((line, sourceLineIndex) => {\n const wrapped = wrapAnsi(line, width, {\n hard: true,\n trim: false,\n wordWrap: true,\n });\n const wrappedLines = wrapped.length > 0 ? wrapped.split(\"\\n\") : [\"\"];\n\n return wrappedLines.map((text) => input.mapRow(text, sourceLineIndex));\n });\n}\n\nexport function buildReadonlyOverlayRenderResult<\n Row extends ReadonlyViewportRow = ReadonlyViewportRow,\n>(input: {\n maxPanelRows: number;\n resolveSections: (\n contentWidth: number\n ) => ReadonlyOverlayViewportSections<Row>;\n runtimeFooter?: {\n alwaysShowScrollHint?: boolean;\n scrollHintLine?: string;\n wrapLines?: (\n lines: readonly string[],\n contentWidth: number\n ) => readonly ReadonlyViewportRow[];\n };\n scrollMode: ReadonlyViewportScrollMode;\n surfaceVariant: SpacePanelSurfaceVariant;\n title: string;\n width: number;\n}): ReadonlyOverlayRenderResult<Row> {\n const contentWidth = resolveReadonlyOverlayContentWidth(input.width);\n const sections = input.resolveSections(contentWidth);\n const viewportState = resolveReadonlyViewportState({\n bodyAnchorRowIndex: sections.bodyAnchorRowIndex,\n bodyAnchorRowRange: sections.bodyAnchorRowRange,\n bodyRows: sections.bodyRows,\n controlRows: sections.controlRows,\n footerRows: sections.footerRows,\n headerRows: sections.headerRows,\n maxDisplayRows: resolveReadonlyOverlayMaxDisplayRows(input.maxPanelRows),\n runtimeFooter: input.runtimeFooter\n ? {\n ...input.runtimeFooter,\n wrapLines: input.runtimeFooter.wrapLines\n ? (lines) =>\n input.runtimeFooter?.wrapLines?.(lines, contentWidth) ?? []\n : undefined,\n }\n : undefined,\n scrollMode: input.scrollMode,\n });\n const renderedLines = buildReadonlyOverlayText({\n sections: {\n bodyLines: viewportState.visibleBodyLines,\n controlLines: sections.controlRows.map((row) => row.text),\n footerLines: viewportState.footerLines,\n headerLines: sections.headerRows.map((row) => row.text),\n },\n surfaceVariant: input.surfaceVariant,\n title: input.title,\n });\n\n return {\n contentWidth,\n renderedLines,\n sections,\n viewportState,\n };\n}\n\nfunction appendSectionGap(input: {\n nextLines: readonly string[];\n previousLines: readonly string[];\n renderedLines: string[];\n surfaceVariant: SpacePanelSurfaceVariant;\n}): void {\n if (input.previousLines.length === 0 || input.nextLines.length === 0) {\n return;\n }\n\n input.renderedLines.push(\n renderOverlayTextLine({\n line: \"\",\n surfaceVariant: input.surfaceVariant,\n tone: \"primary\",\n })\n );\n}\n\nfunction appendRenderedSection(input: {\n lines: readonly string[];\n renderedLines: string[];\n surfaceVariant: SpacePanelSurfaceVariant;\n title: string;\n tone: \"accent\" | \"instruction\" | \"primary\" | \"secondary\";\n useAccentTitle: boolean;\n}): void {\n for (const line of input.lines) {\n const plainLine = stripVTControlCharacters(line).trim();\n const tone =\n input.useAccentTitle &&\n input.title.trim() &&\n plainLine.startsWith(input.title.trim())\n ? \"accent\"\n : input.tone;\n input.renderedLines.push(\n renderOverlayTextLine({\n line,\n surfaceVariant: input.surfaceVariant,\n tone,\n })\n );\n }\n}\n\nfunction renderOverlayTextLine(input: {\n line: string;\n surfaceVariant: SpacePanelSurfaceVariant;\n tone: \"accent\" | \"instruction\" | \"primary\" | \"secondary\";\n}): string {\n return spacePiTuiTheme.renderPanelTextLine({\n surfaceVariant: input.surfaceVariant,\n text: input.line,\n tone: input.tone,\n });\n}\n","import { type Component, Key, matchesKey } from \"@mariozechner/pi-tui\";\nimport { clampNumber } from \"../../../../ui/visible-window\";\nimport {\n buildPanelDisplaySections,\n type PanelDisplayBodyItemAnchor,\n} from \"../../../panel/space-panel-display\";\nimport type { PanelViewState } from \"../../../view/space-session-view-state\";\nimport {\n buildReadonlyOverlayRenderResult,\n createReadonlyOverlayChrome,\n renderReadonlyOverlayChrome,\n resolveReadonlyOverlayContentWidth,\n resolveReadonlyOverlayMaxDisplayRows,\n syncReadonlyOverlayChrome,\n wrapReadonlyViewportRows,\n} from \"./readonly-overlay-surface\";\nimport {\n type ReadonlyViewportRow,\n resolveNextReadonlyViewportOffset,\n resolveReadonlyViewportState,\n} from \"./readonly-viewport\";\n\ntype WrappedPanelRow = ReadonlyViewportRow & {\n sourceLineIndex: number;\n};\n\ntype WrappedPanelItemAnchor = {\n endRowIndex: number;\n id: string;\n startRowIndex: number;\n};\n\ntype WrappedPanelSections = {\n bodyAnchorRowIndex: number | null;\n bodyAnchorRowRange: { end: number; start: number } | null;\n bodyItemAnchors: readonly WrappedPanelItemAnchor[];\n bodyRows: readonly WrappedPanelRow[];\n controlRows: readonly WrappedPanelRow[];\n footerRows: readonly WrappedPanelRow[];\n headerRows: readonly WrappedPanelRow[];\n};\n\nexport class ReadonlyOverlayPanel implements Component {\n readonly #chrome = createReadonlyOverlayChrome();\n readonly #getMaxPanelRows: () => number;\n readonly #onClose: () => void;\n #panel: PanelViewState;\n #lastRenderWidth = 80;\n #scrollOffset = 0;\n\n constructor(input: {\n getMaxPanelRows: () => number;\n onClose: () => void;\n panel: PanelViewState;\n }) {\n this.#getMaxPanelRows = input.getMaxPanelRows;\n this.#onClose = input.onClose;\n this.#panel = input.panel;\n this.#syncText(80);\n }\n\n setPanel(panel: PanelViewState): void {\n this.#panel = panel;\n this.#syncText(this.#lastRenderWidth);\n }\n\n handleInput(data: string): void {\n const nextScrollOffset = resolveNextReadonlyScrollOffset({\n currentScrollOffset: this.#scrollOffset,\n data,\n getMaxPanelRows: this.#getMaxPanelRows,\n panel: this.#panel,\n width: this.#lastRenderWidth,\n });\n if (nextScrollOffset !== this.#scrollOffset) {\n this.#scrollOffset = nextScrollOffset;\n this.#syncText(this.#lastRenderWidth);\n this.invalidate();\n return;\n }\n\n if (matchesKey(data, Key.escape)) {\n this.#onClose();\n }\n }\n\n invalidate(): void {\n this.#chrome.surfaceBox.invalidate();\n }\n\n render(width: number): string[] {\n this.#lastRenderWidth = width;\n this.#syncText(width);\n return renderReadonlyOverlayChrome(this.#chrome, width);\n }\n\n #syncText(width: number): void {\n syncReadonlyOverlayChrome(this.#chrome, this.#panel.surfaceVariant);\n const renderResult = buildReadonlyOffsetRenderResult({\n getMaxPanelRows: this.#getMaxPanelRows,\n panel: this.#panel,\n scrollOffset: this.#scrollOffset,\n width,\n });\n this.#scrollOffset = renderResult.viewportState.offset;\n this.#chrome.text.setText(renderResult.renderedLines.join(\"\\n\"));\n }\n}\n\nexport class SearchableOverlayPanel implements Component {\n readonly #chrome = createReadonlyOverlayChrome();\n readonly #getMaxPanelRows: () => number;\n readonly #onActiveItemChange: (activeItemId: string | null) => void;\n readonly #onClose: () => void;\n readonly #onQueryChange: (query: string) => void;\n #panel: PanelViewState;\n #lastRenderWidth = 80;\n\n constructor(input: {\n getMaxPanelRows: () => number;\n onActiveItemChange: (activeItemId: string | null) => void;\n onClose: () => void;\n onQueryChange: (query: string) => void;\n panel: PanelViewState;\n }) {\n this.#getMaxPanelRows = input.getMaxPanelRows;\n this.#onActiveItemChange = input.onActiveItemChange;\n this.#onClose = input.onClose;\n this.#onQueryChange = input.onQueryChange;\n this.#panel = input.panel;\n this.#syncText(80);\n }\n\n setPanel(panel: PanelViewState): void {\n this.#panel = panel;\n this.#syncText(this.#lastRenderWidth);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, Key.escape)) {\n this.#onClose();\n return;\n }\n\n if (matchesKey(data, Key.backspace)) {\n const currentQuery = this.#panel.searchableList?.control.query ?? \"\";\n if (currentQuery.length > 0) {\n this.#onQueryChange(currentQuery.slice(0, -1));\n }\n return;\n }\n\n const nextActiveItemId = resolveNextSearchableActiveItemId({\n data,\n getMaxPanelRows: this.#getMaxPanelRows,\n panel: this.#panel,\n width: this.#lastRenderWidth,\n });\n if (nextActiveItemId !== this.#panel.searchableList?.activeItemId) {\n this.#onActiveItemChange(nextActiveItemId);\n return;\n }\n\n if (isPrintablePanelQueryInput(data)) {\n const currentQuery = this.#panel.searchableList?.control.query ?? \"\";\n this.#onQueryChange(`${currentQuery}${data}`);\n }\n }\n\n invalidate(): void {\n this.#chrome.surfaceBox.invalidate();\n }\n\n render(width: number): string[] {\n this.#lastRenderWidth = width;\n this.#syncText(width);\n return renderReadonlyOverlayChrome(this.#chrome, width);\n }\n\n #syncText(width: number): void {\n syncReadonlyOverlayChrome(this.#chrome, this.#panel.surfaceVariant);\n const renderResult = buildReadonlyOverlayRenderResult({\n maxPanelRows: this.#getMaxPanelRows(),\n resolveSections: (contentWidth) => {\n const wrappedSections = buildWrappedPanelSections({\n contentWidth,\n panel: this.#panel,\n });\n const activeItemAnchor = resolveWrappedActiveItemAnchor(\n wrappedSections.bodyItemAnchors,\n this.#panel.searchableList?.activeItemId ?? null\n );\n return {\n ...wrappedSections,\n bodyAnchorRowIndex: activeItemAnchor?.startRowIndex ?? null,\n bodyAnchorRowRange: activeItemAnchor\n ? {\n end: activeItemAnchor.endRowIndex,\n start: activeItemAnchor.startRowIndex,\n }\n : null,\n };\n },\n runtimeFooter: {\n wrapLines: (lines, contentWidth) =>\n wrapPanelSectionRows(lines, contentWidth),\n },\n scrollMode: {\n kind: \"anchor\",\n },\n surfaceVariant: this.#panel.surfaceVariant,\n title: this.#panel.title,\n width,\n });\n this.#chrome.text.setText(renderResult.renderedLines.join(\"\\n\"));\n }\n}\n\nfunction resolveNextReadonlyScrollOffset(input: {\n currentScrollOffset: number;\n data: string;\n getMaxPanelRows: () => number;\n panel: PanelViewState;\n width: number;\n}): number {\n const viewportState = buildReadonlyViewportState({\n getMaxPanelRows: input.getMaxPanelRows,\n panel: input.panel,\n scrollOffset: input.currentScrollOffset,\n width: input.width,\n });\n return resolveNextReadonlyViewportOffset({\n canScroll: viewportState.canScroll,\n currentOffset: viewportState.offset,\n data: input.data,\n maxOffset: viewportState.maxOffset,\n visibleBodyRowCount: viewportState.visibleBodyRowCount,\n });\n}\n\nfunction buildReadonlyViewportState(input: {\n getMaxPanelRows: () => number;\n panel: PanelViewState;\n scrollOffset: number;\n width: number;\n}) {\n return buildReadonlyOffsetRenderResult(input).viewportState;\n}\n\nfunction resolveNextSearchableActiveItemId(input: {\n data: string;\n getMaxPanelRows: () => number;\n panel: PanelViewState;\n width: number;\n}): string | null {\n const searchableList = input.panel.searchableList;\n if (!searchableList) {\n return null;\n }\n\n const panelContentWidth = resolveReadonlyOverlayContentWidth(input.width);\n const wrappedSections = buildWrappedPanelSections({\n contentWidth: panelContentWidth,\n panel: input.panel,\n });\n const itemAnchors = wrappedSections.bodyItemAnchors;\n if (itemAnchors.length === 0) {\n return null;\n }\n\n const currentIndex = clampNumber(\n itemAnchors.findIndex(\n (anchor) => anchor.id === searchableList.activeItemId\n ),\n 0,\n itemAnchors.length - 1\n );\n const currentAnchor = itemAnchors[currentIndex];\n if (!currentAnchor) {\n return itemAnchors[0]?.id ?? null;\n }\n const viewportState = resolveReadonlyViewportState({\n bodyAnchorRowIndex: currentAnchor.startRowIndex,\n bodyAnchorRowRange: {\n end: currentAnchor.endRowIndex,\n start: currentAnchor.startRowIndex,\n },\n bodyRows: wrappedSections.bodyRows,\n controlRows: wrappedSections.controlRows,\n footerRows: wrappedSections.footerRows,\n headerRows: wrappedSections.headerRows,\n maxDisplayRows: resolveReadonlyOverlayMaxDisplayRows(\n input.getMaxPanelRows()\n ),\n runtimeFooter: {\n wrapLines: (lines) => wrapPanelSectionRows(lines, panelContentWidth),\n },\n scrollMode: {\n kind: \"anchor\",\n },\n });\n\n if (matchesKey(input.data, Key.up)) {\n return itemAnchors[Math.max(0, currentIndex - 1)]?.id ?? currentAnchor.id;\n }\n if (matchesKey(input.data, Key.down)) {\n return (\n itemAnchors[Math.min(itemAnchors.length - 1, currentIndex + 1)]?.id ??\n currentAnchor.id\n );\n }\n if (matchesKey(input.data, Key.home)) {\n return itemAnchors[0]?.id ?? currentAnchor.id;\n }\n if (matchesKey(input.data, Key.end)) {\n return itemAnchors.at(-1)?.id ?? currentAnchor.id;\n }\n if (matchesKey(input.data, Key.pageUp)) {\n return resolvePageMoveItemId({\n currentAnchor,\n deltaRows: -viewportState.visibleBodyRowCount,\n fallbackIndex: 0,\n itemAnchors,\n });\n }\n if (matchesKey(input.data, Key.pageDown)) {\n return resolvePageMoveItemId({\n currentAnchor,\n deltaRows: viewportState.visibleBodyRowCount,\n fallbackIndex: itemAnchors.length - 1,\n itemAnchors,\n });\n }\n\n return searchableList.activeItemId;\n}\n\nfunction resolvePageMoveItemId(input: {\n currentAnchor: WrappedPanelItemAnchor;\n deltaRows: number;\n fallbackIndex: number;\n itemAnchors: readonly WrappedPanelItemAnchor[];\n}): string | null {\n const targetRowIndex = input.currentAnchor.startRowIndex + input.deltaRows;\n if (input.deltaRows < 0) {\n for (let index = input.itemAnchors.length - 1; index >= 0; index -= 1) {\n const anchor = input.itemAnchors[index];\n if (anchor && anchor.startRowIndex <= targetRowIndex) {\n return anchor.id;\n }\n }\n } else {\n for (const anchor of input.itemAnchors) {\n if (anchor.startRowIndex >= targetRowIndex) {\n return anchor.id;\n }\n }\n }\n return input.itemAnchors[input.fallbackIndex]?.id ?? null;\n}\n\nfunction buildWrappedPanelSections(input: {\n contentWidth: number;\n panel: PanelViewState;\n}): WrappedPanelSections {\n const sections = buildPanelDisplaySections({\n contentWidth: input.contentWidth,\n panel: input.panel,\n });\n const bodyRows = wrapPanelSectionRows(sections.bodyLines, input.contentWidth);\n const controlRows = wrapPanelSectionRows(\n sections.controlLines,\n input.contentWidth\n );\n const footerRows = wrapPanelSectionRows(\n sections.footerLines,\n input.contentWidth\n );\n const headerRows = wrapPanelSectionRows(\n sections.headerLines,\n input.contentWidth\n );\n return {\n bodyAnchorRowIndex: resolveWrappedAnchorRowIndex(\n bodyRows,\n sections.bodyAnchorLineIndex\n ),\n bodyAnchorRowRange: null,\n bodyItemAnchors: resolveWrappedItemAnchors(\n bodyRows,\n sections.bodyItemAnchors\n ),\n bodyRows,\n controlRows,\n footerRows,\n headerRows,\n };\n}\n\nfunction wrapPanelSectionRows(\n lines: readonly string[],\n contentWidth: number\n): WrappedPanelRow[] {\n return wrapReadonlyViewportRows({\n contentWidth,\n lines,\n mapRow: (text, sourceLineIndex) => ({\n sourceLineIndex,\n text,\n }),\n });\n}\n\nfunction buildReadonlyOffsetRenderResult(input: {\n getMaxPanelRows: () => number;\n panel: PanelViewState;\n scrollOffset: number;\n width: number;\n}) {\n return buildReadonlyOverlayRenderResult({\n maxPanelRows: input.getMaxPanelRows(),\n resolveSections: (contentWidth) =>\n buildWrappedPanelSections({\n contentWidth,\n panel: input.panel,\n }),\n runtimeFooter: {\n wrapLines: (lines, contentWidth) =>\n wrapPanelSectionRows(lines, contentWidth),\n },\n scrollMode: {\n kind: \"offset\",\n offset: input.scrollOffset,\n },\n surfaceVariant: input.panel.surfaceVariant,\n title: input.panel.title,\n width: input.width,\n });\n}\n\nfunction resolveWrappedAnchorRowIndex(\n rows: readonly WrappedPanelRow[],\n anchorLineIndex: number | null\n): number | null {\n if (anchorLineIndex === null) {\n return null;\n }\n\n const rowIndex = rows.findIndex(\n (row) => row.sourceLineIndex === anchorLineIndex\n );\n return rowIndex >= 0 ? rowIndex : null;\n}\n\nfunction resolveWrappedItemAnchors(\n rows: readonly WrappedPanelRow[],\n anchors: readonly PanelDisplayBodyItemAnchor[]\n): WrappedPanelItemAnchor[] {\n return anchors\n .map((anchor, index) => {\n const startRowIndex = rows.findIndex(\n (row) => row.sourceLineIndex === anchor.lineIndex\n );\n if (startRowIndex < 0) {\n return null;\n }\n const nextAnchorLineIndex =\n anchors[index + 1]?.lineIndex ?? Number.POSITIVE_INFINITY;\n let endRowIndex = startRowIndex;\n for (\n let rowIndex = startRowIndex;\n rowIndex < rows.length;\n rowIndex += 1\n ) {\n const row = rows[rowIndex];\n if (!row || row.sourceLineIndex >= nextAnchorLineIndex) {\n break;\n }\n endRowIndex = rowIndex;\n }\n return {\n endRowIndex,\n id: anchor.id,\n startRowIndex,\n };\n })\n .filter((anchor): anchor is WrappedPanelItemAnchor => anchor !== null);\n}\n\nfunction resolveWrappedActiveItemAnchor(\n itemAnchors: readonly WrappedPanelItemAnchor[],\n activeItemId: string | null\n): WrappedPanelItemAnchor | null {\n if (!activeItemId) {\n return null;\n }\n return itemAnchors.find((anchor) => anchor.id === activeItemId) ?? null;\n}\n\nfunction isPrintablePanelQueryInput(data: string): boolean {\n if (!containsOnlyPrintablePanelQueryCharacters(data)) {\n return false;\n }\n if (\n matchesKey(data, Key.up) ||\n matchesKey(data, Key.down) ||\n matchesKey(data, Key.pageUp) ||\n matchesKey(data, Key.pageDown) ||\n matchesKey(data, Key.home) ||\n matchesKey(data, Key.end) ||\n matchesKey(data, Key.escape) ||\n matchesKey(data, Key.enter) ||\n matchesKey(data, Key.ctrl(\"d\"))\n ) {\n return false;\n }\n return true;\n}\n\nfunction containsOnlyPrintablePanelQueryCharacters(value: string): boolean {\n if (value.length === 0) {\n return false;\n }\n\n for (const character of value) {\n const codePoint = character.codePointAt(0);\n if (codePoint === undefined) {\n return false;\n }\n if (codePoint < 0x20 || codePoint === 0x7f) {\n return false;\n }\n }\n\n return true;\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport pc from \"picocolors\";\nimport stringWidth from \"string-width\";\nimport wrapAnsi from \"wrap-ansi\";\nimport { renderOpenMeldBrandAccent } from \"../../../../ui/brand\";\nimport { renderPositiveAccentText } from \"../../../../ui/positive-accent\";\nimport { buildPublicSpaceWarningLines } from \"../../../../ui/public-space-warning\";\nimport type {\n SessionHeaderDocumentBlockViewState,\n SpaceSummaryFactsViewState,\n} from \"../../../view/space-session-view-state\";\n\nconst HEADER_TOP_COPY_GAP = 2;\nconst LOGO_VERSION_GAP = \" \";\nconst LOGO_VERSION_MIN_GAP = \"\";\nconst SUMMARY_ROW_GAP = 2;\nconst SEPARATOR_CHAR = \"─\";\nconst DEFAULT_SPACE_NAME = \"Untitled Space\";\nconst CURRENT_SPACE_PREFIX = \"Current Space › \";\nconst PUBLIC_SPACE_HINT = buildPublicSpaceWarningLines(\"anyone_can_join\")[0];\nconst MEMBERS_ONLY_SPACE_HINT = \"Only current members can open this Space.\";\nconst PASSWORD_SPACE_HINT = \"A password is required for access.\";\n\nexport function renderSessionHeaderLines(input: {\n block: SessionHeaderDocumentBlockViewState;\n width: number;\n}): string[] {\n const width = Math.max(1, input.width);\n\n const lines = [\n ...renderTopCopyLine({\n leftText: input.block.productLabel,\n rightText: input.block.tagline,\n width,\n }),\n \"\",\n ...renderCenteredLogoLines({\n logoLines: input.block.logoLines,\n versionLabel: input.block.versionLabel,\n width,\n }),\n \"\",\n ...renderSummaryHeaderLines({\n facts: input.block.summaryFacts,\n summaryHintText: input.block.summaryHintText ?? null,\n width,\n }),\n ];\n\n return lines;\n}\n\nfunction renderTopCopyLine(input: {\n leftText: string;\n rightText: string;\n width: number;\n}): string[] {\n const leftText = renderOpenMeldBrandAccent(input.leftText);\n const rightText = renderOpenMeldBrandAccent(input.rightText);\n const leftWidth = measureVisibleWidth(leftText);\n const rightWidth = measureVisibleWidth(rightText);\n const availableGapWidth = input.width - leftWidth - rightWidth;\n\n if (availableGapWidth >= HEADER_TOP_COPY_GAP) {\n return [`${leftText}${\" \".repeat(availableGapWidth)}${rightText}`];\n }\n\n return [leftText, alignRight(rightText, input.width)];\n}\n\nfunction renderCenteredLogoLines(input: {\n logoLines: readonly string[];\n versionLabel: string | null;\n width: number;\n}): string[] {\n const renderedLines: string[] = [];\n const lastLineIndex = input.logoLines.length - 1;\n\n for (const [index, line] of input.logoLines.entries()) {\n const isLastLine = index === lastLineIndex;\n const versionLabel = isLastLine ? input.versionLabel : null;\n renderedLines.push(\n ...renderCenteredLogoLine(line, versionLabel, input.width)\n );\n }\n\n return renderedLines;\n}\n\nfunction renderCenteredLogoLine(\n logoLine: string,\n versionLabel: string | null,\n width: number\n): string[] {\n const logoWidth = measureVisibleWidth(logoLine);\n const baseLeftPadding = Math.max(0, Math.floor((width - logoWidth) / 2));\n const leftPadding = baseLeftPadding;\n const centeredLogoLine = `${\" \".repeat(leftPadding)}${logoLine}`;\n\n if (!versionLabel) {\n return [centeredLogoLine];\n }\n\n const styledVersionLabel = pc.dim(versionLabel);\n const versionWidth = measureVisibleWidth(styledVersionLabel);\n const inlinePlacement = resolveInlineVersionPlacement({\n logoWidth,\n versionWidth,\n width,\n baseLeftPadding,\n });\n\n if (inlinePlacement) {\n const alignedLogoLine = `${\" \".repeat(inlinePlacement.leftPadding)}${logoLine}`;\n return [\n `${alignedLogoLine}${inlinePlacement.gapText}${styledVersionLabel}`,\n ];\n }\n\n const versionIndent = Math.max(\n 0,\n Math.min(\n width - versionWidth,\n leftPadding + Math.max(0, logoWidth - versionWidth)\n )\n );\n\n return [\n centeredLogoLine,\n `${\" \".repeat(versionIndent)}${styledVersionLabel}`,\n ];\n}\n\nfunction resolveInlineVersionPlacement(input: {\n logoWidth: number;\n versionWidth: number;\n width: number;\n baseLeftPadding: number;\n}): { leftPadding: number; gapText: string } | null {\n for (const gapText of [LOGO_VERSION_GAP, LOGO_VERSION_MIN_GAP]) {\n const maxLeftPadding =\n input.width - input.logoWidth - gapText.length - input.versionWidth;\n if (maxLeftPadding < 0) {\n continue;\n }\n\n return {\n leftPadding: Math.min(input.baseLeftPadding, maxLeftPadding),\n gapText,\n };\n }\n\n return null;\n}\n\nfunction renderSummaryHeaderLines(input: {\n facts: SpaceSummaryFactsViewState;\n summaryHintText: string | null;\n width: number;\n}): string[] {\n const accessSummary = buildAccessSummary(input.facts);\n const lines = [\n ...renderSplitLine({\n leftText: resolveSpaceNameText(input.facts),\n rightText: pc.dim(input.facts.spaceId),\n width: input.width,\n minGapWidth: SUMMARY_ROW_GAP,\n }),\n pc.dim(SEPARATOR_CHAR.repeat(input.width)),\n ];\n\n const detailLines = renderSummaryDetailLines({\n leftText: buildPresenceSummaryText(input.facts, input.summaryHintText),\n rightText: buildAccessSummaryInlineText(accessSummary),\n width: input.width,\n });\n\n if (detailLines.length > 0) {\n lines.push(...detailLines);\n }\n\n lines.push(\"\");\n return lines;\n}\n\nfunction renderSplitLine(input: {\n leftText: string;\n rightText: string;\n width: number;\n minGapWidth: number;\n}): string[] {\n const leftText = input.leftText.trim();\n const rightText = input.rightText.trim();\n\n if (!(leftText || rightText)) {\n return [];\n }\n if (!rightText) {\n return wrapText(leftText, input.width);\n }\n if (!leftText) {\n return renderRightAlignedWrappedText(rightText, input.width);\n }\n\n const leftWidth = measureVisibleWidth(leftText);\n const rightWidth = measureVisibleWidth(rightText);\n const availableGapWidth = input.width - leftWidth - rightWidth;\n\n if (availableGapWidth >= input.minGapWidth) {\n return [`${leftText}${\" \".repeat(availableGapWidth)}${rightText}`];\n }\n\n return [\n ...wrapText(leftText, input.width),\n ...renderRightAlignedWrappedText(rightText, input.width),\n ];\n}\n\nfunction renderSummaryDetailLines(input: {\n leftText: string;\n rightText: string;\n width: number;\n}): string[] {\n const leftText = input.leftText.trim();\n const rightText = input.rightText.trim();\n\n if (!(leftText || rightText)) {\n return [];\n }\n if (!rightText) {\n return wrapText(leftText, input.width);\n }\n if (!leftText) {\n return renderRightAlignedWrappedText(rightText, input.width);\n }\n\n return renderSplitLine({\n leftText,\n rightText,\n width: input.width,\n minGapWidth: SUMMARY_ROW_GAP,\n });\n}\n\nfunction resolveSpaceNameText(facts: SpaceSummaryFactsViewState): string {\n return `${pc.dim(CURRENT_SPACE_PREFIX)}${facts.spaceName ?? DEFAULT_SPACE_NAME}`;\n}\n\nfunction buildAccessSummary(facts: SpaceSummaryFactsViewState): {\n labelText: string;\n detailText: string;\n} {\n switch (facts.accessLabel) {\n case \"members only\":\n return {\n labelText: renderPositiveAccentText(\"🔒 Members only\"),\n detailText: MEMBERS_ONLY_SPACE_HINT,\n };\n case \"anyone with the link\":\n return {\n labelText: pc.yellow(\"⚠️ Anyone with the link\"),\n detailText: PUBLIC_SPACE_HINT,\n };\n case \"password required\":\n case \"password required to view and join\":\n return {\n labelText: renderPositiveAccentText(\"🔒 Password required\"),\n detailText: PASSWORD_SPACE_HINT,\n };\n case \"anyone can view; password required to join\":\n return {\n labelText: pc.yellow(\"⚠️ Anyone can view\"),\n detailText: \"A password is required to join.\",\n };\n case \"private\":\n return {\n labelText: renderPositiveAccentText(\"🔒 Private\"),\n detailText: \"Only invited people can find this Space.\",\n };\n default:\n return {\n labelText: pc.dim(\"Access unavailable\"),\n detailText: \"\",\n };\n }\n}\n\nfunction buildAccessSummaryInlineText(input: {\n labelText: string;\n detailText: string;\n}): string {\n if (!input.detailText) {\n return input.labelText;\n }\n return `${input.labelText}${pc.dim(` · ${input.detailText}`)}`;\n}\n\nfunction buildPresenceSummaryText(\n facts: SpaceSummaryFactsViewState,\n summaryHintText: string | null\n): string {\n const parts: string[] = [];\n\n if (\n typeof facts.membersCount === \"number\" &&\n Number.isFinite(facts.membersCount)\n ) {\n parts.push(`👥 ${facts.membersCount}`);\n }\n\n if (\n typeof facts.liveHumanCount === \"number\" &&\n Number.isFinite(facts.liveHumanCount)\n ) {\n parts.push(\n `${facts.liveHumanCount} live ${facts.liveHumanCount === 1 ? \"human\" : \"humans\"}`\n );\n }\n\n if (parts.length === 0) {\n return \"\";\n }\n\n if (!summaryHintText) {\n return parts.join(\" · \");\n }\n\n return `${parts.join(\" · \")}${pc.dim(` · ${summaryHintText}`)}`;\n}\n\nfunction wrapText(text: string, width: number): string[] {\n const normalizedText = text.trim();\n if (!normalizedText) {\n return [];\n }\n\n return wrapAnsi(normalizedText, Math.max(1, width), {\n hard: true,\n trim: false,\n wordWrap: true,\n }).split(\"\\n\");\n}\n\nfunction renderRightAlignedWrappedText(text: string, width: number): string[] {\n return wrapText(text, width).map((line) => alignRight(line, width));\n}\n\nfunction alignRight(text: string, width: number): string {\n const visibleWidth = measureVisibleWidth(text);\n return `${\" \".repeat(Math.max(0, width - visibleWidth))}${text}`;\n}\n\nfunction measureVisibleWidth(text: string): number {\n return stringWidth(stripVTControlCharacters(text));\n}\n","import { type Component, Text } from \"@mariozechner/pi-tui\";\nimport {\n renderTranscriptBlocks,\n type TranscriptBlockViewState,\n} from \"../../../transcript/transcript-render\";\n\nexport class TranscriptBlockPanel implements Component {\n readonly #text = new Text(\"\", 0, 0);\n #blocks: readonly TranscriptBlockViewState[] = [];\n\n setBlocks(blocks: readonly TranscriptBlockViewState[]): void {\n this.#blocks = blocks;\n this.#text.invalidate();\n }\n\n invalidate(): void {\n this.#text.invalidate();\n }\n\n render(width: number): string[] {\n this.#text.setText(renderTranscriptBlocks(this.#blocks, width).join(\"\\n\"));\n return this.#text.render(width);\n }\n}\n","import type { Component } from \"@mariozechner/pi-tui\";\nimport type { SessionDocumentBlockViewState } from \"../../../view/space-session-view-state\";\nimport { renderSessionHeaderLines } from \"./render-session-header-lines\";\nimport { renderSpaceSummaryLines } from \"./render-space-summary-lines\";\nimport { TranscriptBlockPanel } from \"./transcript-block-panel\";\n\nexport class SessionDocumentPanel implements Component {\n readonly #transcriptBlockPanel = new TranscriptBlockPanel();\n #blocks: readonly SessionDocumentBlockViewState[] = [];\n\n setBlocks(blocks: readonly SessionDocumentBlockViewState[]): void {\n this.#blocks = blocks;\n this.#transcriptBlockPanel.invalidate();\n }\n\n invalidate(): void {\n this.#transcriptBlockPanel.invalidate();\n }\n\n render(width: number): string[] {\n return buildDocumentLines(this.#blocks, this.#transcriptBlockPanel, width);\n }\n}\n\nfunction buildDocumentLines(\n blocks: readonly SessionDocumentBlockViewState[],\n transcriptBlockPanel: TranscriptBlockPanel,\n width: number\n): string[] {\n const lines: string[] = [];\n let previousBlock: SessionDocumentBlockViewState | null = null;\n\n for (const block of blocks) {\n let blockLines: string[];\n if (block.kind === \"session_header\") {\n blockLines = renderSessionHeaderLines({\n block,\n width,\n });\n } else if (block.kind === \"transcript\") {\n blockLines = renderTranscriptBlock(block, transcriptBlockPanel, width);\n } else if (block.kind === \"space_summary\") {\n blockLines = renderSpaceSummaryLines({\n segments: block.segments,\n tone: \"default\",\n width,\n });\n } else {\n blockLines = [...block.lines];\n }\n\n if (blockLines.length === 0) {\n continue;\n }\n if (previousBlock && shouldInsertBlockGap(previousBlock, block)) {\n lines.push(\"\");\n }\n lines.push(...blockLines);\n previousBlock = block;\n }\n\n return lines;\n}\n\nfunction shouldInsertBlockGap(\n _previousBlock: SessionDocumentBlockViewState,\n _nextBlock: SessionDocumentBlockViewState\n): boolean {\n return true;\n}\n\nfunction renderTranscriptBlock(\n block: Extract<SessionDocumentBlockViewState, { kind: \"transcript\" }>,\n transcriptBlockPanel: TranscriptBlockPanel,\n width: number\n): string[] {\n transcriptBlockPanel.setBlocks(block.blocks);\n return transcriptBlockPanel.render(width);\n}\n","import { type Component, Text } from \"@mariozechner/pi-tui\";\n\nexport class StatusBar implements Component {\n readonly #text = new Text(\"\", 0, 0);\n #visible = false;\n\n setText(value: string): void {\n const normalizedValue = value.trim();\n this.#visible = normalizedValue.length > 0;\n this.#text.setText(normalizedValue);\n }\n\n invalidate(): void {\n this.#text.invalidate();\n }\n\n render(width: number): string[] {\n if (!this.#visible) {\n return [];\n }\n return this.#text.render(width);\n }\n}\n","import { stripVTControlCharacters } from \"node:util\";\nimport { type Component, Key, matchesKey } from \"@mariozechner/pi-tui\";\nimport { formatPanelInstructionsLine } from \"../../../panel/space-panel-definition\";\nimport {\n renderTranscriptBlocks,\n type TranscriptBlockViewState,\n} from \"../../../transcript/transcript-render\";\nimport {\n buildReadonlyOverlayRenderResult,\n createReadonlyOverlayChrome,\n renderReadonlyOverlayChrome,\n resolveReadonlyOverlayContentWidth,\n resolveReadonlyOverlayMaxDisplayRows,\n syncReadonlyOverlayChrome,\n wrapReadonlyViewportRows,\n} from \"./readonly-overlay-surface\";\nimport {\n type ReadonlyViewportRow,\n resolveNextReadonlyViewportOffset,\n resolveReadonlyViewportState,\n} from \"./readonly-viewport\";\n\nconst TRANSCRIPT_READER_TITLE = \"📜 Transcript History\";\nconst TRANSCRIPT_READER_HEADER_LINE =\n \"Read older messages without leaving the live session.\";\nconst TRANSCRIPT_READER_EMPTY_LINE = \"No messages yet.\";\nconst TRANSCRIPT_READER_UPDATES_BELOW_LINE = \"New updates below · End to jump\";\nconst TRANSCRIPT_READER_CLOSE_LINE = formatPanelInstructionsLine([\n {\n id: \"close\",\n keys: [\"Esc\"],\n label: \"close\",\n },\n]);\n\ntype TranscriptReaderRenderState = {\n hasNewUpdatesBelow: boolean;\n isFollowingLatest: boolean;\n scrollOffset: number;\n};\n\nexport class TranscriptReaderOverlay implements Component {\n readonly #chrome = createReadonlyOverlayChrome(\"dark\");\n readonly #getMaxPanelRows: () => number;\n readonly #onClose: () => void;\n\n #blocks: readonly TranscriptBlockViewState[];\n #hasNewUpdatesBelow = false;\n #isFollowingLatest = true;\n #lastRenderWidth = 80;\n #lastRenderedRowCount = 0;\n #pendingBlockUpdate = true;\n #scrollOffset = 0;\n\n constructor(input: {\n blocks: readonly TranscriptBlockViewState[];\n getMaxPanelRows: () => number;\n onClose: () => void;\n }) {\n this.#blocks = input.blocks;\n this.#getMaxPanelRows = input.getMaxPanelRows;\n this.#onClose = input.onClose;\n this.#syncText(80);\n }\n\n setBlocks(blocks: readonly TranscriptBlockViewState[]): void {\n this.#blocks = blocks;\n this.#pendingBlockUpdate = true;\n this.#syncText(this.#lastRenderWidth);\n }\n\n handleInput(data: string): void {\n if (matchesKey(data, Key.escape)) {\n this.#onClose();\n return;\n }\n\n const viewportState = this.#buildViewportState(this.#lastRenderWidth);\n const nextScrollOffset = resolveNextReadonlyViewportOffset({\n canScroll: viewportState.canScroll,\n currentOffset: viewportState.offset,\n data,\n maxOffset: viewportState.maxOffset,\n visibleBodyRowCount: viewportState.visibleBodyRowCount,\n });\n if (nextScrollOffset === viewportState.offset) {\n return;\n }\n\n this.#scrollOffset = nextScrollOffset;\n this.#isFollowingLatest = nextScrollOffset >= viewportState.maxOffset;\n if (this.#isFollowingLatest) {\n this.#hasNewUpdatesBelow = false;\n }\n this.#syncText(this.#lastRenderWidth);\n this.invalidate();\n }\n\n invalidate(): void {\n this.#chrome.surfaceBox.invalidate();\n }\n\n render(width: number): string[] {\n this.#lastRenderWidth = width;\n this.#syncText(width);\n return renderReadonlyOverlayChrome(this.#chrome, width);\n }\n\n #syncText(width: number): void {\n syncReadonlyOverlayChrome(this.#chrome, \"dark\");\n const currentRenderState = this.#normalizeRenderState(\n this.#readRenderState()\n );\n let renderResult = this.#buildOverlayRenderResult(\n width,\n currentRenderState\n );\n const previousVisibleBodyEnd =\n renderResult.viewportState.offset +\n renderResult.viewportState.visibleBodyRowCount;\n const nextHasNewUpdatesBelow = this.#resolveNextHasNewUpdatesBelow({\n bodyRowCount: renderResult.sections.bodyRows.length,\n renderState: currentRenderState,\n });\n let nextRenderState =\n nextHasNewUpdatesBelow === currentRenderState.hasNewUpdatesBelow\n ? currentRenderState\n : {\n ...currentRenderState,\n hasNewUpdatesBelow: nextHasNewUpdatesBelow,\n };\n\n if (this.#pendingBlockUpdate && !currentRenderState.isFollowingLatest) {\n const previewViewportState =\n nextRenderState === currentRenderState\n ? renderResult.viewportState\n : this.#buildViewportState(width, nextRenderState);\n const preservedOffset = Math.max(\n 0,\n Math.min(\n previewViewportState.maxOffset,\n previousVisibleBodyEnd - previewViewportState.visibleBodyRowCount\n )\n );\n if (preservedOffset !== nextRenderState.scrollOffset) {\n nextRenderState = {\n ...nextRenderState,\n scrollOffset: preservedOffset,\n };\n }\n if (preservedOffset >= previewViewportState.maxOffset) {\n nextRenderState = {\n ...nextRenderState,\n hasNewUpdatesBelow: false,\n isFollowingLatest: true,\n };\n }\n }\n\n if (!this.#isSameRenderState(currentRenderState, nextRenderState)) {\n renderResult = this.#buildOverlayRenderResult(width, nextRenderState);\n }\n const nextIsFollowingLatest =\n renderResult.viewportState.offset >= renderResult.viewportState.maxOffset;\n this.#scrollOffset = renderResult.viewportState.offset;\n this.#isFollowingLatest = nextIsFollowingLatest;\n this.#hasNewUpdatesBelow = nextIsFollowingLatest\n ? false\n : nextRenderState.hasNewUpdatesBelow;\n this.#lastRenderedRowCount = renderResult.sections.bodyRows.length;\n this.#pendingBlockUpdate = false;\n this.#chrome.text.setText(renderResult.renderedLines.join(\"\\n\"));\n }\n\n #buildViewportState(\n width: number,\n renderState: TranscriptReaderRenderState = this.#readRenderState()\n ) {\n const contentWidth = resolveReadonlyOverlayContentWidth(width);\n return resolveReadonlyViewportState({\n ...this.#buildOverlaySections(contentWidth, renderState),\n maxDisplayRows: resolveReadonlyOverlayMaxDisplayRows(\n this.#getMaxPanelRows()\n ),\n runtimeFooter: this.#buildViewportRuntimeFooter(contentWidth),\n scrollMode: renderState.isFollowingLatest\n ? {\n kind: \"anchor\",\n }\n : {\n kind: \"offset\",\n offset: renderState.scrollOffset,\n },\n });\n }\n\n #buildOverlayRenderResult(\n width: number,\n renderState: TranscriptReaderRenderState = this.#readRenderState()\n ) {\n return buildReadonlyOverlayRenderResult({\n maxPanelRows: this.#getMaxPanelRows(),\n resolveSections: (contentWidth) =>\n this.#buildOverlaySections(contentWidth, renderState),\n runtimeFooter: this.#buildOverlayRuntimeFooter(),\n scrollMode: renderState.isFollowingLatest\n ? {\n kind: \"anchor\",\n }\n : {\n kind: \"offset\",\n offset: renderState.scrollOffset,\n },\n surfaceVariant: \"dark\",\n title: TRANSCRIPT_READER_TITLE,\n width,\n });\n }\n\n #readRenderState(): TranscriptReaderRenderState {\n return {\n hasNewUpdatesBelow: this.#hasNewUpdatesBelow,\n isFollowingLatest: this.#isFollowingLatest,\n scrollOffset: this.#scrollOffset,\n };\n }\n\n #normalizeRenderState(\n renderState: TranscriptReaderRenderState\n ): TranscriptReaderRenderState {\n if (!renderState.isFollowingLatest) {\n return renderState;\n }\n if (!renderState.hasNewUpdatesBelow) {\n return renderState;\n }\n return {\n ...renderState,\n hasNewUpdatesBelow: false,\n };\n }\n\n #isSameRenderState(\n left: TranscriptReaderRenderState,\n right: TranscriptReaderRenderState\n ): boolean {\n return (\n left.hasNewUpdatesBelow === right.hasNewUpdatesBelow &&\n left.isFollowingLatest === right.isFollowingLatest &&\n left.scrollOffset === right.scrollOffset\n );\n }\n\n #buildOverlaySections(\n contentWidth: number,\n renderState: TranscriptReaderRenderState\n ) {\n const latestBlockRowRange = renderState.isFollowingLatest\n ? this.#buildLatestBlockRowRange(contentWidth)\n : null;\n return {\n bodyAnchorRowIndex: latestBlockRowRange?.start ?? null,\n bodyAnchorRowRange: latestBlockRowRange,\n bodyRows: this.#buildBodyRows(contentWidth),\n controlRows: [],\n footerRows: wrapPlainTextRows(\n this.#buildFooterLines(renderState),\n contentWidth\n ),\n headerRows: wrapPlainTextRows(\n [TRANSCRIPT_READER_TITLE, TRANSCRIPT_READER_HEADER_LINE],\n contentWidth\n ),\n };\n }\n\n #buildOverlayRuntimeFooter() {\n return {\n alwaysShowScrollHint: true,\n wrapLines: (lines: readonly string[], contentWidth: number) =>\n wrapPlainTextRows(lines, contentWidth),\n };\n }\n\n #buildViewportRuntimeFooter(contentWidth: number) {\n return {\n alwaysShowScrollHint: true,\n wrapLines: (lines: readonly string[]) =>\n wrapPlainTextRows(lines, contentWidth),\n };\n }\n\n #buildBodyRows(contentWidth: number): ReadonlyViewportRow[] {\n const lines = renderTranscriptBlocks(this.#blocks, contentWidth);\n if (lines.length === 0) {\n return [\n {\n text: TRANSCRIPT_READER_EMPTY_LINE,\n },\n ];\n }\n return lines.map((text) => ({ text }));\n }\n\n #buildLatestBlockRowRange(contentWidth: number): {\n end: number;\n start: number;\n } | null {\n const lastBlock = this.#blocks.at(-1);\n if (!lastBlock) {\n return null;\n }\n\n const lastBlockLines = renderTranscriptBlocks([lastBlock], contentWidth);\n if (lastBlockLines.length === 0) {\n return null;\n }\n const visibleLastBlockRowRange =\n resolveVisibleTranscriptRowRange(lastBlockLines);\n if (this.#blocks.length === 1) {\n return {\n end: visibleLastBlockRowRange.end,\n start: visibleLastBlockRowRange.start,\n };\n }\n\n const prefixLines = renderTranscriptBlocks(\n this.#blocks.slice(0, -1),\n contentWidth\n );\n const previousBlock = this.#blocks.at(-2);\n if (!previousBlock) {\n return {\n end: lastBlockLines.length - 1,\n start: 0,\n };\n }\n\n const previousAndLastLines = renderTranscriptBlocks(\n [previousBlock, lastBlock],\n contentWidth\n );\n const previousBlockLines = renderTranscriptBlocks(\n [previousBlock],\n contentWidth\n );\n const gapLineCount = Math.max(\n 0,\n previousAndLastLines.length -\n previousBlockLines.length -\n lastBlockLines.length\n );\n const start = prefixLines.length + gapLineCount;\n\n return {\n end: start + visibleLastBlockRowRange.end,\n start: start + visibleLastBlockRowRange.start,\n };\n }\n\n #buildFooterLines(renderState: TranscriptReaderRenderState): string[] {\n const lines: string[] = [];\n if (renderState.hasNewUpdatesBelow && !renderState.isFollowingLatest) {\n lines.push(TRANSCRIPT_READER_UPDATES_BELOW_LINE);\n }\n lines.push(TRANSCRIPT_READER_CLOSE_LINE);\n return lines;\n }\n\n #resolveNextHasNewUpdatesBelow(input: {\n bodyRowCount: number;\n renderState: TranscriptReaderRenderState;\n }): boolean {\n if (!this.#pendingBlockUpdate) {\n return input.renderState.hasNewUpdatesBelow;\n }\n if (input.renderState.isFollowingLatest) {\n return false;\n }\n if (input.bodyRowCount > this.#lastRenderedRowCount) {\n return true;\n }\n return input.renderState.hasNewUpdatesBelow;\n }\n}\n\nfunction wrapPlainTextRows(\n lines: readonly string[],\n contentWidth: number\n): ReadonlyViewportRow[] {\n return wrapReadonlyViewportRows({\n contentWidth,\n lines,\n mapRow: (text) => ({\n text,\n }),\n });\n}\n\nfunction resolveVisibleTranscriptRowRange(lines: readonly string[]): {\n end: number;\n start: number;\n} {\n let start = 0;\n while (\n start < lines.length &&\n stripVTControlCharacters(lines[start] ?? \"\").trim().length === 0\n ) {\n start += 1;\n }\n\n let end = lines.length - 1;\n while (\n end >= start &&\n stripVTControlCharacters(lines[end] ?? \"\").trim().length === 0\n ) {\n end -= 1;\n }\n\n if (end < start) {\n return {\n end: Math.max(0, lines.length - 1),\n start: 0,\n };\n }\n\n return {\n end,\n start,\n };\n}\n","import {\n Container,\n Key,\n matchesKey,\n type OverlayOptions,\n ProcessTerminal,\n type Terminal,\n TUI,\n} from \"@mariozechner/pi-tui\";\nimport pc from \"picocolors\";\nimport { renderOpenMeldBrandAccent } from \"../../../ui/brand\";\nimport type { SpacePanelKind } from \"../../panel/space-panel-definition\";\nimport {\n resolveReadonlyOverlayShortcut,\n resolveReadonlySessionFooterText,\n} from \"../../readonly-session-shortcuts\";\nimport type {\n PanelViewState,\n SpaceSessionViewState,\n} from \"../../view/space-session-view-state\";\nimport type { InteractiveSpaceShell } from \"../interactive-space-shell\";\nimport { ComposerActivityStrip } from \"./components/composer-activity-strip\";\nimport { ComposerPanel } from \"./components/composer-panel\";\nimport {\n ReadonlyOverlayPanel,\n SearchableOverlayPanel,\n} from \"./components/overlay-host\";\nimport { SessionDocumentPanel } from \"./components/session-document-panel\";\nimport { StatusBar } from \"./components/status-bar\";\nimport { TranscriptReaderOverlay } from \"./components/transcript-reader-overlay\";\nimport { PiTuiComposerAutocompleteProvider } from \"./pi-tui-composer-autocomplete-provider\";\nimport { spacePiTuiEditorTheme } from \"./theme\";\n\nconst OVERLAY_MODAL_WIDTH = \"78%\" as const;\nconst OVERLAY_MODAL_MAX_HEIGHT_PERCENT = 70;\nconst OVERLAY_MODAL_MAX_HEIGHT = \"70%\" as const;\nconst CTRL_C_EXIT_CONFIRMATION_WINDOW_MS = 1500;\nconst CTRL_C_EXIT_CONFIRMATION_TEXT = renderOpenMeldBrandAccent(\n \"Press Ctrl+C again to leave this Space.\"\n);\n\nimport {\n type SpaceComposerAuthoredMentionInTextOrder,\n updateAuthoredMentionRanges,\n} from \"@openmeld/space\";\n\ntype PiTuiInteractiveSpaceShellInput = {\n getRecentMentionProfileIds?: () => readonly string[];\n onBufferChange: (bufferText: string) => void;\n onClose: () => void;\n onOverlayClose: () => void;\n onOverlayActiveItemChange: (activeItemId: string | null) => void;\n onOverlayQueryChange: (query: string) => void;\n onOpenOverlay?: (kind: SpacePanelKind) => void;\n onSubmit: (text: string) => void;\n terminal?: Terminal;\n};\n\nexport class PiTuiInteractiveSpaceShell implements InteractiveSpaceShell {\n #authoredText = \"\";\n #authoredMentions: SpaceComposerAuthoredMentionInTextOrder[] = [];\n #submittedMentions: {\n text: string;\n mentions: readonly SpaceComposerAuthoredMentionInTextOrder[];\n } | null = null;\n\n getAuthoredMentions(\n text: string\n ): readonly SpaceComposerAuthoredMentionInTextOrder[] {\n if (this.#submittedMentions?.text === text) {\n return this.#submittedMentions.mentions;\n }\n return this.#authoredText === text ? this.#authoredMentions : [];\n }\n\n #updateAuthoredText(text: string): void {\n this.#authoredMentions = updateAuthoredMentionRanges({\n previousText: this.#authoredText,\n text,\n mentions: this.#authoredMentions,\n });\n this.#authoredText = text;\n }\n readonly #input: PiTuiInteractiveSpaceShellInput;\n readonly #terminal: Terminal;\n readonly #tui: TUI;\n readonly #root = new Container();\n readonly #sessionDocumentPanel = new SessionDocumentPanel();\n readonly #composerActivityStrip: ComposerActivityStrip;\n readonly #composerPanel: ComposerPanel;\n readonly #statusBar = new StatusBar();\n\n #latestViewState: SpaceSessionViewState | null = null;\n #started = false;\n #syncingEditorText = false;\n #overlayHandle: ReturnType<TUI[\"showOverlay\"]> | null = null;\n #overlayPanel:\n | ReadonlyOverlayPanel\n | SearchableOverlayPanel\n | TranscriptReaderOverlay\n | null = null;\n #overlayKind: SpaceSessionViewState[\"overlay\"][\"kind\"] | \"transcript-reader\" =\n \"none\";\n #removeInputListener: (() => void) | null = null;\n #composerVisible = false;\n #ctrlCExitTimeout: ReturnType<typeof setTimeout> | null = null;\n #ctrlCExitDeadlineMs: number | null = null;\n\n constructor(input: PiTuiInteractiveSpaceShellInput) {\n this.#input = input;\n this.#terminal = input.terminal ?? new ProcessTerminal();\n this.#tui = new TUI(this.#terminal, true);\n this.#composerActivityStrip = new ComposerActivityStrip(this.#tui);\n this.#composerPanel = new ComposerPanel(this.#tui, spacePiTuiEditorTheme);\n this.#composerPanel.editor.setAutocompleteProvider(\n new PiTuiComposerAutocompleteProvider({\n onMentionSelected: (selection) => {\n this.#updateAuthoredText(selection.text);\n this.#authoredMentions.push({\n profileId: selection.profileId,\n relation: selection.relation,\n start: selection.start,\n text: selection.mentionText,\n });\n this.#authoredMentions.sort(\n (a, b) => (a.start ?? 0) - (b.start ?? 0)\n );\n },\n getMembersSnapshot: () =>\n this.#latestViewState?.resources.membersSnapshot ?? null,\n getRecentMentionProfileIds: () =>\n this.#input.getRecentMentionProfileIds?.() ?? [],\n })\n );\n this.#composerPanel.editor.onChange = (text) => {\n this.#updateAuthoredText(text);\n if (this.#syncingEditorText) {\n return;\n }\n this.#input.onBufferChange(text);\n };\n this.#composerPanel.editor.onSubmit = (text) => {\n this.#submittedMentions = { text, mentions: [...this.#authoredMentions] };\n this.#input.onSubmit(text);\n };\n\n this.#root.addChild(this.#sessionDocumentPanel);\n this.#root.addChild(this.#composerActivityStrip);\n this.#root.addChild(this.#composerPanel);\n this.#root.addChild(this.#statusBar);\n this.#tui.addChild(this.#root);\n this.#composerPanel.setVisible(false);\n this.#tui.setFocus(this.#composerPanel.editor);\n }\n\n start(): void {\n if (this.#started) {\n return;\n }\n this.#started = true;\n if (this.#latestViewState) {\n this.#applyViewState(this.#latestViewState);\n }\n this.#removeInputListener = this.#tui.addInputListener((data) =>\n this.#handleInput(data)\n );\n this.#tui.start();\n }\n\n render(viewState: SpaceSessionViewState): void {\n this.#latestViewState = viewState;\n if (!this.#started) {\n return;\n }\n this.#applyViewState(viewState);\n this.#requestUiRender();\n }\n\n #applyViewState(viewState: SpaceSessionViewState): void {\n this.#sessionDocumentPanel.setBlocks(viewState.sessionDocument.blocks);\n this.#composerActivityStrip.setActivity(viewState.composerActivity);\n this.#composerVisible = viewState.composer.visible;\n this.#composerPanel.setVisible(viewState.composer.visible);\n this.#composerPanel.setLeadingBlankLines(\n viewState.composerActivity.visible ? 0 : 1\n );\n this.#composerPanel.setHelperText(viewState.composer.helperText);\n this.#composerPanel.setSummarySegments(\n viewState.spaceSummary.composerFooterSegments\n );\n this.#composerPanel.setPlaceholderText(viewState.composer.placeholderText);\n this.#composerPanel.setShowPlaceholder(viewState.composer.showPlaceholder);\n this.#syncStatusBar();\n this.#syncEditorText(viewState.composer.bufferText);\n this.#syncOverlay(viewState);\n if (this.#composerVisible && !this.#overlayHandle) {\n this.#tui.setFocus(this.#composerPanel.editor);\n }\n }\n\n clearSubmittedInputLine(_line: string): void {\n // The editor clears its own submitted buffer during submit handling.\n this.#submittedMentions = null;\n }\n\n prepareExternalWrite(): void {\n if (!this.#started) {\n return;\n }\n this.#tui.invalidate();\n setImmediate(() => {\n this.#requestHardResetRender();\n });\n }\n\n stop(): void {\n if (!this.#started) {\n return;\n }\n this.#started = false;\n this.#overlayHandle?.hide();\n this.#overlayHandle = null;\n this.#overlayPanel = null;\n this.#overlayKind = \"none\";\n this.#clearCtrlCExitConfirmation();\n this.#removeInputListener?.();\n this.#removeInputListener = null;\n this.#composerActivityStrip.stop();\n this.#tui.stop();\n }\n\n #syncStatusBar(): void {\n this.#statusBar.setText(this.#resolveStatusBarText());\n }\n\n #resolveStatusBarText(): string {\n if (this.#ctrlCExitDeadlineMs !== null) {\n return CTRL_C_EXIT_CONFIRMATION_TEXT;\n }\n if (!this.#latestViewState) {\n return \"\";\n }\n return resolveReadonlyFooterText(this.#latestViewState);\n }\n\n #shouldConfirmCtrlCExitNow(): boolean {\n return (\n this.#ctrlCExitDeadlineMs !== null &&\n Date.now() <= this.#ctrlCExitDeadlineMs\n );\n }\n\n #handleInput(data: string): { consume: true } | undefined {\n const isCtrlC = matchesKey(data, Key.ctrl(\"c\")) || data === \"\\u0003\";\n if (this.#ctrlCExitDeadlineMs !== null && !isCtrlC) {\n this.#clearCtrlCExitConfirmation();\n }\n if (isCtrlC) {\n return this.#handleCtrlCInput();\n }\n if (matchesKey(data, Key.ctrl(\"d\"))) {\n return this.#handleCtrlDInput();\n }\n if (this.#isTranscriptReaderOpen() && !this.#composerVisible) {\n const overlayKind = resolveReadonlyOverlayShortcut(data);\n if (overlayKind) {\n this.#closeTranscriptReader({\n restoreComposerFocus: false,\n });\n this.#input.onOpenOverlay?.(overlayKind);\n return { consume: true };\n }\n }\n if (isTranscriptNavigationInput(data)) {\n if (this.#overlayHandle) {\n return undefined;\n }\n if (this.#openTranscriptReader(data)) {\n return { consume: true };\n }\n }\n if (this.#composerVisible || this.#overlayHandle) {\n return undefined;\n }\n return this.#handleReadonlyInput(data);\n }\n\n #handleCtrlCInput(): { consume: true } {\n if (!this.#composerVisible) {\n this.#input.onClose();\n return { consume: true };\n }\n if (this.#shouldConfirmCtrlCExitNow()) {\n this.#clearCtrlCExitConfirmation();\n this.#input.onClose();\n return { consume: true };\n }\n this.#armCtrlCExitConfirmation();\n return { consume: true };\n }\n\n #handleCtrlDInput(): { consume: true } | undefined {\n if (this.#overlayHandle) {\n return undefined;\n }\n this.#input.onClose();\n return { consume: true };\n }\n\n #handleReadonlyInput(data: string): { consume: true } {\n const overlayKind = resolveReadonlyOverlayShortcut(data);\n if (overlayKind) {\n this.#input.onOpenOverlay?.(overlayKind);\n return { consume: true };\n }\n if (data === \"q\") {\n this.#input.onClose();\n return { consume: true };\n }\n return { consume: true };\n }\n\n #armCtrlCExitConfirmation(): void {\n this.#clearCtrlCExitConfirmationTimer();\n this.#ctrlCExitDeadlineMs = Date.now() + CTRL_C_EXIT_CONFIRMATION_WINDOW_MS;\n this.#syncStatusBar();\n this.#requestUiRender();\n this.#ctrlCExitTimeout = setTimeout(() => {\n this.#ctrlCExitTimeout = null;\n this.#ctrlCExitDeadlineMs = null;\n this.#syncStatusBar();\n this.#requestUiRender();\n }, CTRL_C_EXIT_CONFIRMATION_WINDOW_MS);\n }\n\n #clearCtrlCExitConfirmation(): void {\n if (this.#ctrlCExitDeadlineMs === null && this.#ctrlCExitTimeout === null) {\n return;\n }\n this.#clearCtrlCExitConfirmationTimer();\n this.#ctrlCExitDeadlineMs = null;\n this.#syncStatusBar();\n this.#requestUiRender();\n }\n\n #clearCtrlCExitConfirmationTimer(): void {\n if (this.#ctrlCExitTimeout === null) {\n return;\n }\n clearTimeout(this.#ctrlCExitTimeout);\n this.#ctrlCExitTimeout = null;\n }\n\n #syncEditorText(nextBufferText: string): void {\n if (this.#composerPanel.editor.getText() === nextBufferText) {\n return;\n }\n this.#syncingEditorText = true;\n try {\n if (this.#submittedMentions?.text === nextBufferText) {\n this.#authoredText = nextBufferText;\n this.#authoredMentions = [...this.#submittedMentions.mentions];\n }\n this.#composerPanel.editor.setText(nextBufferText);\n } finally {\n this.#syncingEditorText = false;\n }\n }\n\n #syncOverlay(viewState: SpaceSessionViewState): void {\n const panel = viewState.overlay.panel;\n if (!panel) {\n if (this.#isTranscriptReaderOpen()) {\n this.#syncTranscriptReader(viewState);\n return;\n }\n if (this.#overlayHandle) {\n this.#overlayHandle.hide();\n this.#overlayHandle = null;\n this.#overlayPanel = null;\n this.#overlayKind = \"none\";\n if (this.#composerVisible) {\n this.#tui.setFocus(this.#composerPanel.editor);\n }\n }\n return;\n }\n\n if (this.#isTranscriptReaderOpen()) {\n this.#closeTranscriptReader({\n restoreComposerFocus: false,\n });\n }\n\n if (!(this.#overlayHandle && this.#overlayKind === panel.kind)) {\n this.#overlayHandle?.hide();\n const overlayPanel = this.#createOverlayPanel(panel);\n this.#overlayPanel = overlayPanel;\n this.#overlayHandle = this.#tui.showOverlay(\n overlayPanel,\n this.#resolveOverlayLayout(panel)\n );\n this.#overlayKind = panel.kind;\n return;\n }\n\n if (\n this.#overlayPanel instanceof ReadonlyOverlayPanel ||\n this.#overlayPanel instanceof SearchableOverlayPanel\n ) {\n this.#overlayPanel.setPanel(panel);\n }\n this.#overlayHandle.focus();\n this.#requestUiRender();\n }\n\n #createOverlayPanel(\n panel: PanelViewState\n ): ReadonlyOverlayPanel | SearchableOverlayPanel {\n switch (panel.mode) {\n case \"readonly\":\n return new ReadonlyOverlayPanel({\n getMaxPanelRows: () =>\n resolveOverlayMaxPanelRows(this.#terminal.rows),\n panel,\n onClose: this.#input.onOverlayClose,\n });\n case \"searchable_list\":\n return new SearchableOverlayPanel({\n getMaxPanelRows: () =>\n resolveOverlayMaxPanelRows(this.#terminal.rows),\n onActiveItemChange: this.#input.onOverlayActiveItemChange,\n onClose: this.#input.onOverlayClose,\n onQueryChange: this.#input.onOverlayQueryChange,\n panel,\n });\n default:\n return assertUnreachable(panel.mode);\n }\n }\n\n #openTranscriptReader(initialInput?: string): boolean {\n if (this.#overlayHandle || !this.#latestViewState) {\n return false;\n }\n\n const overlayPanel = new TranscriptReaderOverlay({\n blocks: this.#latestViewState.transcript.blocks,\n getMaxPanelRows: () => resolveOverlayMaxPanelRows(this.#terminal.rows),\n onClose: () => {\n this.#closeTranscriptReader();\n },\n });\n this.#overlayPanel = overlayPanel;\n this.#overlayHandle = this.#tui.showOverlay(\n overlayPanel,\n this.#resolveCenteredOverlayLayout()\n );\n this.#overlayKind = \"transcript-reader\";\n if (initialInput) {\n overlayPanel.handleInput(initialInput);\n }\n this.#requestUiRender();\n return true;\n }\n\n #closeTranscriptReader(input?: { restoreComposerFocus?: boolean }): void {\n if (!this.#isTranscriptReaderOpen()) {\n return;\n }\n\n this.#overlayHandle?.hide();\n this.#overlayHandle = null;\n this.#overlayPanel = null;\n this.#overlayKind = \"none\";\n if ((input?.restoreComposerFocus ?? true) && this.#composerVisible) {\n this.#tui.setFocus(this.#composerPanel.editor);\n }\n this.#requestUiRender();\n }\n\n #syncTranscriptReader(viewState: SpaceSessionViewState): void {\n if (!(this.#overlayPanel instanceof TranscriptReaderOverlay)) {\n return;\n }\n\n this.#overlayPanel.setBlocks(viewState.transcript.blocks);\n this.#overlayHandle?.focus();\n this.#requestUiRender();\n }\n\n #isTranscriptReaderOpen(): boolean {\n return this.#overlayKind === \"transcript-reader\";\n }\n\n #resolveCenteredOverlayLayout(): OverlayOptions {\n return {\n anchor: \"center\",\n width: OVERLAY_MODAL_WIDTH,\n maxHeight: OVERLAY_MODAL_MAX_HEIGHT,\n };\n }\n\n #resolveOverlayLayout(panel: PanelViewState): OverlayOptions {\n switch (panel.layout) {\n case \"centered_modal\":\n return this.#resolveCenteredOverlayLayout();\n default:\n return assertUnreachable(panel.layout);\n }\n }\n\n #requestUiRender(): void {\n if (!this.#started) {\n return;\n }\n this.#tui.requestRender();\n }\n\n #requestHardResetRender(): void {\n if (!this.#started) {\n return;\n }\n this.#tui.requestRender(true);\n }\n}\n\nfunction resolveReadonlyFooterText(viewState: SpaceSessionViewState): string {\n if (viewState.surface !== \"active-session\" || viewState.composer.visible) {\n return \"\";\n }\n if (viewState.context.connectionMode === \"watch\") {\n return pc.dim(resolveReadonlySessionFooterText(\"watch\"));\n }\n if (viewState.context.connectionMode === \"history\") {\n return pc.dim(resolveReadonlySessionFooterText(\"history\"));\n }\n return \"\";\n}\n\nfunction resolveOverlayMaxPanelRows(rows: number): number {\n if (!(Number.isFinite(rows) && rows > 0)) {\n return 1;\n }\n return Math.max(\n 1,\n Math.floor((rows * OVERLAY_MODAL_MAX_HEIGHT_PERCENT) / 100)\n );\n}\n\nfunction isTranscriptNavigationInput(data: string): boolean {\n return (\n matchesKey(data, Key.pageUp) ||\n matchesKey(data, Key.pageDown) ||\n matchesKey(data, Key.home) ||\n matchesKey(data, Key.end)\n );\n}\n\nfunction assertUnreachable(value: never): never {\n throw new Error(`Unsupported PI-TUI overlay state: ${String(value)}`);\n}\n","import type { SpaceMeta } from \"@openmeld/protocol\";\n\nexport type SpaceMetaUpsertInput = {\n creator?: SpaceMeta[\"creator\"] | null;\n spaceCreatedAt?: string | null;\n spaceUpdatedAt?: string | null;\n name?: string | null;\n guide?: string | null;\n passwordProtected?: boolean;\n spacePurpose?: string | null;\n};\n\nexport function toSpaceMetaUpsertInput(meta: SpaceMeta): SpaceMetaUpsertInput {\n const next: SpaceMetaUpsertInput = {};\n\n if (Object.hasOwn(meta, \"creator\")) {\n next.creator = meta.creator ?? null;\n }\n if (Object.hasOwn(meta, \"name\")) {\n next.name = meta.name ?? null;\n }\n if (Object.hasOwn(meta, \"createdAt\")) {\n next.spaceCreatedAt = meta.createdAt ?? null;\n }\n if (Object.hasOwn(meta, \"updatedAt\")) {\n next.spaceUpdatedAt = meta.updatedAt ?? null;\n }\n if (Object.hasOwn(meta, \"guide\")) {\n next.guide = meta.guide ?? null;\n }\n if (typeof meta.passwordProtected === \"boolean\") {\n next.passwordProtected = meta.passwordProtected;\n }\n if (Object.hasOwn(meta, \"purpose\")) {\n next.spacePurpose = meta.purpose ?? null;\n }\n\n return next;\n}\n","import type { SignalTextReplyTo } from \"@openmeld/protocol\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport type {\n SpaceMessageReadProjection,\n SpaceReplyWorkflowProjection,\n} from \"@openmeld/space\";\nimport type { SpacePanelKind } from \"../panel/space-panel-definition\";\n\nexport type SpaceTranscriptFormattedMessage = {\n bodyLines: readonly string[];\n relationLines: readonly string[];\n metaLines: readonly string[];\n threadIndicatorLine?: string | null;\n headerBadge?: string | null;\n};\n\nexport type SpaceTranscriptProfileSnapshot = {\n kind: \"human\" | \"agent\" | \"system\" | \"unknown\";\n profileId: string | null;\n profileName: string;\n ownerUserId?: string | null;\n ownerName?: string | null;\n agentControllerRef?: string | null;\n};\n\nexport type SpaceTranscriptReplyRef = SignalTextReplyTo;\n\nexport type SpaceTranscriptItem = {\n line: string;\n groupKey: string;\n refreshPrompt?: boolean;\n kind?: \"message\" | \"system_notice\" | \"presence\" | \"membership_notice\";\n formattedMessage?: SpaceTranscriptFormattedMessage;\n messageReadProjection?: SpaceMessageReadProjection;\n replyWorkflowProjection?: SpaceReplyWorkflowProjection;\n profile?: SpaceTranscriptProfileSnapshot;\n systemPurpose?: string | null;\n ts?: number;\n presenceAction?: \"join\" | \"left\";\n actorProfileId?: string;\n actorKind?: \"human\" | \"agent\" | \"unknown\";\n actorLabel?: string;\n actorAvatar?: string;\n membershipNotice?: SpaceMembershipNotice;\n replyRef?: SpaceTranscriptReplyRef;\n};\n\nexport type SpaceMembershipNotice = {\n action: \"member_added\" | \"member_removed\";\n actorProfileId: string | null;\n actorKind: \"human\" | \"agent\" | \"unknown\";\n actorLabel: string;\n targetProfileId: string | null;\n targetProfileKind: \"human\" | \"agent\";\n targetProfileLabel: string;\n mentionLabel: string | null;\n ts: number;\n};\n\nexport type SpaceOverlayKind = \"none\" | SpacePanelKind;\n\nexport type SpaceScreenState = {\n connection: {\n status: \"connecting\" | \"connected\" | \"closing\" | \"closed\";\n closeReason: string | null;\n closeCode: number | null;\n closeSource: \"close\" | \"error\" | null;\n };\n composer: {\n bufferText: string;\n };\n transcript: {\n items: SpaceTranscriptItem[];\n };\n status: {\n overlayLine: string;\n };\n overlay: {\n kind: SpaceOverlayKind;\n openedAtMs: number | null;\n interaction: {\n activeItemId: string | null;\n query: string;\n };\n };\n members: {\n refreshError: string | null;\n snapshot: SpaceMembersSnapshot | null;\n updatedAtMs: number | null;\n };\n};\n\nexport function createInitialSpaceScreenState(): SpaceScreenState {\n return {\n connection: {\n status: \"connecting\",\n closeReason: null,\n closeCode: null,\n closeSource: null,\n },\n composer: {\n bufferText: \"\",\n },\n transcript: {\n items: [],\n },\n status: {\n overlayLine: \"\",\n },\n overlay: {\n kind: \"none\",\n openedAtMs: null,\n interaction: {\n activeItemId: null,\n query: \"\",\n },\n },\n members: {\n refreshError: null,\n snapshot: null,\n updatedAtMs: null,\n },\n };\n}\n","import type { SpaceScreenAction } from \"./space-screen-actions\";\nimport {\n createInitialSpaceScreenState,\n type SpaceScreenState,\n} from \"./space-screen-state\";\n\ntype SpaceScreenListener = (state: SpaceScreenState) => void;\n\nexport type SpaceScreenStore = {\n getState(): SpaceScreenState;\n dispatch(action: SpaceScreenAction): void;\n subscribe(listener: SpaceScreenListener): () => void;\n};\n\nexport function createSpaceScreenStore(\n initialState: SpaceScreenState = createInitialSpaceScreenState()\n): SpaceScreenStore {\n let state = initialState;\n const listeners = new Set<SpaceScreenListener>();\n\n const notify = (): void => {\n for (const listener of listeners) {\n listener(state);\n }\n };\n\n return {\n getState() {\n return state;\n },\n dispatch(action) {\n const nextState = reduceSpaceScreenState(state, action);\n if (nextState === state) {\n return;\n }\n state = nextState;\n notify();\n },\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\nfunction reduceSpaceScreenState(\n state: SpaceScreenState,\n action: SpaceScreenAction\n): SpaceScreenState {\n switch (action.type) {\n case \"connection.connected\":\n if (state.connection.status === \"connected\") {\n return state;\n }\n return {\n ...state,\n connection: {\n ...state.connection,\n status: \"connected\",\n },\n };\n\n case \"connection.closing\":\n return {\n ...state,\n connection: {\n ...state.connection,\n status: \"closing\",\n closeReason: action.reason,\n },\n };\n\n case \"connection.closed\":\n return {\n ...state,\n connection: {\n ...state.connection,\n status: \"closed\",\n closeReason: action.reason,\n closeCode: action.code ?? null,\n closeSource: action.source,\n },\n };\n\n case \"composer.buffer.updated\":\n return {\n ...state,\n composer: {\n ...state.composer,\n bufferText: action.bufferText,\n },\n };\n\n case \"transcript.item.appended\":\n return {\n ...state,\n transcript: {\n ...state.transcript,\n items: [...state.transcript.items, action.item],\n },\n };\n\n case \"status.overlay.updated\":\n if (state.status.overlayLine === action.line) {\n return state;\n }\n return {\n ...state,\n status: {\n ...state.status,\n overlayLine: action.line,\n },\n };\n\n case \"overlay.opened\":\n if (\n state.overlay.kind === action.kind &&\n state.overlay.openedAtMs === action.openedAtMs\n ) {\n return state;\n }\n return {\n ...state,\n overlay: {\n kind: action.kind,\n openedAtMs: action.openedAtMs,\n interaction: state.overlay.interaction,\n },\n };\n\n case \"overlay.closed\":\n if (state.overlay.kind === \"none\") {\n return state;\n }\n return {\n ...state,\n overlay: {\n kind: \"none\",\n openedAtMs: null,\n interaction: {\n activeItemId: null,\n query: \"\",\n },\n },\n };\n\n case \"overlay.interaction.reset\":\n if (\n state.overlay.interaction.activeItemId === null &&\n state.overlay.interaction.query === \"\"\n ) {\n return state;\n }\n return {\n ...state,\n overlay: {\n ...state.overlay,\n interaction: {\n activeItemId: null,\n query: \"\",\n },\n },\n };\n\n case \"overlay.query.updated\":\n if (state.overlay.interaction.query === action.query) {\n return state;\n }\n return {\n ...state,\n overlay: {\n ...state.overlay,\n interaction: {\n ...state.overlay.interaction,\n query: action.query,\n },\n },\n };\n\n case \"overlay.active-item.updated\":\n if (state.overlay.interaction.activeItemId === action.activeItemId) {\n return state;\n }\n return {\n ...state,\n overlay: {\n ...state.overlay,\n interaction: {\n ...state.overlay.interaction,\n activeItemId: action.activeItemId,\n },\n },\n };\n\n case \"members.updated\":\n return {\n ...state,\n members: {\n refreshError: null,\n snapshot: action.snapshot,\n updatedAtMs: action.updatedAtMs,\n },\n };\n\n case \"members.refresh.failed\":\n if (state.members.refreshError === action.error) {\n return state;\n }\n return {\n ...state,\n members: {\n ...state.members,\n refreshError: action.error,\n },\n };\n\n default:\n return state;\n }\n}\n","import {\n clearLine,\n createInterface,\n cursorTo,\n moveCursor,\n} from \"node:readline\";\nimport type {\n HelloAck,\n SignalEnvelope,\n SpaceCursor,\n SpaceMeta,\n} from \"@openmeld/protocol\";\nimport {\n normalizeSpaceCursorPatch,\n SPACE_MEMBER_JOIN_NOTICE_PURPOSE,\n SPACE_MEMBER_REMOVE_NOTICE_PURPOSE,\n toCompatibleSpaceAddressingRequestWireValue,\n} from \"@openmeld/schemas\";\nimport type {\n AgentProfileBindingModelSelection,\n OpenMeldRequestContext,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport { resolveNextRecentMentionProfileIdsForQueuedText } from \"@openmeld/space\";\nimport pc from \"picocolors\";\nimport stringWidth from \"string-width\";\nimport { resolveAuthenticationGuidance } from \"../auth/auth-guidance\";\nimport { resolveBaseUrl } from \"../config/base-url\";\nimport { acquireLock, runWithHeldLock } from \"../config/lock\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { buildOpenMeldRequestContextFromProfileIdentity } from \"../config/openmeld-request-context\";\nimport {\n resolveGatewayHost,\n updateProfileSpaceHistoryStatus,\n upsertProfileSpaceHistory,\n} from \"../config/profile-space-history-api\";\nimport {\n buildOpenMeldProfileIdentityRequestHeadersWithAuth,\n buildOpenMeldRequestContextHeadersWithAuth,\n} from \"../config/request-headers\";\nimport { requireOpenMeldProfile } from \"../config/resolve-openmeld-profile\";\nimport { toSpaceCursorUrl, toSpaceWsUrl } from \"../protocol/urls\";\nimport {\n makeHello,\n makeTextSignal,\n parseIncoming,\n parseServerErrorFrame,\n sanitizeText,\n} from \"../protocol/wire\";\nimport { formatOpenMeldCliCommand } from \"../runtime/cli-entry-command\";\nimport { resolveRuntimeContext } from \"../runtime/context\";\nimport { formatMessage } from \"../runtime/messages\";\nimport { createPresenter } from \"../runtime/presenter/index\";\nimport type { ResolvedCliView } from \"../runtime/types\";\nimport { connectWebSocket } from \"../transport/ws\";\nimport { errLine, outJsonLine } from \"../ui/io\";\nimport {\n formatConnectIntro,\n formatInputPrompt,\n type OutputMode,\n} from \"../ui/output\";\nimport { sanitizeTerminalDisplayText } from \"../ui/terminal-safe-text\";\nimport { rethrowSpaceAddressingSnapshotLoadFailure } from \"./addressing-preflight\";\nimport {\n buildAgentSessionMetaPayload,\n normalizeAgentOutputEvent,\n normalizeAgentOutputMembersSnapshot,\n} from \"./agent-output-contract\";\nimport {\n type ComposeDraftState,\n consumeComposeInputLine,\n emptyComposeDraft,\n} from \"./compose-input\";\nimport { ComposerController } from \"./composer/composer-controller\";\nimport { prepareCliSpaceComposerSubmission } from \"./composer-submission-adapter\";\nimport {\n normalizeRecentHistoryLimit,\n processIgnoredOlderThanLiveFloorSignal,\n rememberSeenSignalId,\n resolveInitialLiveFloorTs,\n shouldIgnoreIncomingSignal,\n} from \"./connect-catchup\";\nimport {\n applyDispatchActivityEventToStatusMap,\n clearDispatchActivitiesForSignal,\n clearUnconfirmedPendingOutboundRows,\n countRenderedTerminalRows,\n pruneExpiredDispatchRows,\n resolveDispatchRowStatusTexts,\n resolveNearestDispatchRowExpiryMs,\n resolveNonTransientSignalText,\n resolveReplyingStatusColumns,\n resolveSignalClientMessageId,\n resolveSignalTextMetaFromEnvelope,\n toComposerDispatchRows,\n} from \"./connect-dispatch-activity\";\nimport {\n emitHumanConnectTranscriptEvent,\n replayConnectInitialHistoryBootstrap,\n} from \"./connect-history-transcript-bootstrap\";\nimport {\n buildSpaceCursorPatch,\n normalizeCursorLastSeenTs,\n normalizeOptionalIsoDateTime,\n normalizeOptionalTrimmedText,\n normalizeRoleValue,\n normalizeStoredMentionAliasValue,\n resolveCreatorKind,\n resolveCreatorProfileId,\n resolveMaxLastSeenTs,\n resolveSessionMentionAlias,\n resolveSessionMeta,\n resolveSessionRoleContext,\n} from \"./connect-session-meta\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { parseHttpFailure } from \"./http-failure\";\nimport {\n clearPendingHumanSendRowsByClientMessageId,\n upsertPendingHumanSendRow,\n} from \"./human-send-state\";\nimport {\n type InteractiveTextSubmitResult,\n performInteractiveTextSubmit,\n} from \"./interactive-text-submit\";\nimport {\n resolveSpaceJoinReadModelSeed,\n type SpaceJoinReadModelSeed,\n} from \"./join-read-model-seed\";\nimport {\n isLocalSpaceStateCorruptResult,\n readSpaceConfig,\n readSpaceLastSeenTs,\n readSpaceRecentMentionProfileIds,\n toLocalSpaceStateIntegrityError,\n updateSpaceLastSeenTs,\n upsertSpaceConfig,\n writeSpaceRecentMentionProfileIds,\n} from \"./local-state\";\nimport { projectSpaceProfileCache } from \"./local-state-projection\";\nimport { fetchSpaceMeta } from \"./meta-api\";\nimport { resolveMembersSearchableActiveItemId } from \"./panel/space-panel-content\";\nimport type { SpacePanelKind } from \"./panel/space-panel-definition\";\nimport { buildPanelDisplayLines } from \"./panel/space-panel-display\";\nimport {\n confirmPendingOutboundRows,\n confirmPendingOutboundRowsForSignal,\n} from \"./pending-outbound-confirmation\";\nimport { resolveSpaceSessionDiagnostics } from \"./preflight\";\nimport { buildFormalSignalReadPayload } from \"./read-projection/formal-message-read-output\";\nimport type { SpaceRuntimeEvent } from \"./runtime/space-runtime-events\";\nimport { SpaceSessionRuntime } from \"./runtime/space-session-runtime\";\nimport {\n buildActiveSpaceSessionContext,\n buildSpaceSessionProfileContextFromIdentity,\n buildSpaceSessionProfileIdentity,\n rememberSessionOwnerDisplayName,\n type SpaceSessionProfileIdentity,\n toProtocolProfile,\n} from \"./session-profile\";\nimport {\n type InteractiveHumanShellKind,\n resolveInteractiveHumanShellKind,\n} from \"./shell/interactive-shell-kind\";\nimport type { InteractiveSpaceShell } from \"./shell/interactive-space-shell\";\nimport { LegacyInteractiveSpaceShell } from \"./shell/legacy-interactive-space-shell\";\nimport { mountPiTuiSessionShell } from \"./shell/pi-tui/mount-pi-tui-session-shell\";\nimport { PiTuiInteractiveSpaceShell } from \"./shell/pi-tui/pi-tui-interactive-space-shell\";\nimport { toSpaceMetaUpsertInput } from \"./space-meta-upsert-input\";\nimport { createSpaceScreenStore } from \"./state/space-screen-store\";\nimport { buildSpaceSessionViewState } from \"./view/build-space-session-view-state\";\nimport type { ComposerDispatchRowState } from \"./view/space-session-view-state\";\n\nconst PENDING_OUTBOUND_CONFIRMATION_MAX = 200;\nconst CATCHUP_LIVE_BUFFER_MAX = 2000;\nconst WS_UNEXPECTED_SERVER_RESPONSE_REGEX =\n /unexpected server response:\\s*(\\d{3})/i;\nconst REPLYING_STATUS_SYSTEM_LABEL = \"📣 system\";\nconst REPLYING_STATUS_AGENT_LABEL = \"🤖\";\nconst REPLYING_STATUS_PROMPT_GAP_LINES = 1;\nconst CHAT_GROUP_DIVIDER_MARGIN = 2;\nconst CHAT_GROUP_DIVIDER_MIN_WIDTH = 24;\nconst CHAT_GROUP_DIVIDER_MAX_WIDTH = 120;\nconst CHAT_GROUP_DIVIDER_CHAR = \"╌\";\nconst CHAT_GROUP_DIVIDER_SIDE_GAP_LINES = 1;\nconst LEAVE_CARD_FALLBACK_CONTENT_WIDTH = 68;\nconst LEAVE_CARD_MAX_CONTENT_WIDTH = 72;\nconst LEAVE_CARD_MIN_CONTENT_WIDTH = 8;\nconst LEAVE_CARD_LEADING_BLANK_LINES = 2;\nconst MEMBERS_PANEL_REFRESH_DEBOUNCE_MS = 250;\nconst SPACE_META_REFRESH_DEBOUNCE_MS = 1000;\n\ntype DispatchActivityRowState = ComposerDispatchRowState;\ntype ConnectProfileIdentity = SpaceSessionProfileIdentity;\ntype ComposerIntentResolution =\n | ReturnType<ComposerController[\"consumeLegacyLine\"]>\n | ReturnType<ComposerController[\"consumeEditorSubmit\"]>;\n\nfunction resolveOptionalReadableLocalSpaceConfig(\n result: Awaited<ReturnType<typeof readSpaceConfig>>,\n operation: string\n) {\n if (result.kind === \"missing\") {\n return null;\n }\n if (isLocalSpaceStateCorruptResult(result)) {\n throw toLocalSpaceStateIntegrityError({\n operation,\n result,\n });\n }\n return result.value;\n}\n\nfunction handleInteractiveComposerIntent(input: {\n resolution: ComposerIntentResolution;\n submittedText: string;\n applyComposerBuffer: (bufferText: string) => void;\n closeOverlay: () => void;\n prepareExternalWrite: () => void;\n presenter: ReturnType<typeof createPresenter>;\n handleSendTextError: (error: unknown) => void;\n sendText: (input: {\n nextBufferText: string;\n submittedText: string;\n text: string;\n }) => Promise<void>;\n showOverlay: (kind: SpacePanelKind) => Promise<void>;\n cleanup: (reason: string) => void;\n clearSubmittedInputLine: (text: string) => void;\n}): void {\n const { resolution, submittedText } = input;\n\n switch (resolution.kind) {\n case \"quit\":\n input.cleanup(\"quit\");\n return;\n\n case \"buffer.updated\":\n input.applyComposerBuffer(resolution.nextBufferText);\n input.closeOverlay();\n return;\n\n case \"submit.rejected\":\n input.applyComposerBuffer(resolution.nextBufferText);\n input.closeOverlay();\n input.prepareExternalWrite();\n input.presenter.event(\"info\", \"connect.reject\", {\n reason: resolution.reason,\n });\n return;\n\n case \"submit\":\n input.applyComposerBuffer(resolution.nextBufferText);\n input.closeOverlay();\n setImmediate(() => {\n input\n .sendText({\n nextBufferText: resolution.nextBufferText,\n submittedText,\n text: resolution.text,\n })\n .catch((error) => {\n input.handleSendTextError(error);\n });\n });\n return;\n\n case \"command.panel.open\":\n input.applyComposerBuffer(resolution.nextBufferText);\n input.closeOverlay();\n ignoreAsyncResult(input.showOverlay(resolution.panelKind));\n return;\n\n default:\n assertUnreachableComposerIntent(resolution);\n return;\n }\n}\n\nfunction handleInteractiveRuntimeEvent(input: {\n event: SpaceRuntimeEvent;\n store: ReturnType<typeof createSpaceScreenStore>;\n rowsById: Map<string, DispatchActivityRowState>;\n enableLocalEcho: boolean;\n selfProfileId: string;\n syncActivityPresentation: () => void;\n reportOutboundSendFailure: (failure: {\n error: string;\n hint?: string;\n }) => void;\n handleIncomingEvent: (\n event: SignalEnvelope | HelloAck,\n source: \"history\" | \"live\"\n ) => void;\n handleHistoryLoadedEvent: (\n event: Extract<SpaceRuntimeEvent, { type: \"history.loaded\" }>\n ) => void;\n handleMembersUpdatedEvent: (\n event: Extract<SpaceRuntimeEvent, { type: \"members.updated\" }>\n ) => void;\n handleConnectionClosedEvent: (\n event: Extract<SpaceRuntimeEvent, { type: \"connection.closed\" }>\n ) => void;\n}): void {\n switch (input.event.type) {\n case \"connected\":\n input.store.dispatch({\n type: \"connection.connected\",\n });\n return;\n\n case \"history.loaded\":\n input.handleHistoryLoadedEvent(input.event);\n return;\n\n case \"members.updated\":\n input.handleMembersUpdatedEvent(input.event);\n return;\n\n case \"send.queued\":\n return;\n\n case \"send.confirmed\":\n confirmPendingOutboundRows({\n rowsById: input.rowsById,\n clientMessageId: input.event.clientMessageId,\n });\n input.syncActivityPresentation();\n return;\n\n case \"send.failed\":\n clearPendingHumanSendRowsByClientMessageId({\n rowsById: input.rowsById,\n clientMessageId: input.event.clientMessageId,\n });\n input.syncActivityPresentation();\n input.reportOutboundSendFailure({\n error: `couldn't send the message: ${input.event.error}`,\n hint: \"rejoin the space and try sending it again\",\n });\n return;\n\n case \"signal.received\":\n if (\n input.event.source === \"live\" &&\n isSignalEnvelope(input.event.event) &&\n confirmPendingOutboundRowsForSignal({\n rowsById: input.rowsById,\n event: input.event.event,\n selfProfileId: input.selfProfileId,\n })\n ) {\n input.syncActivityPresentation();\n }\n input.handleIncomingEvent(input.event.event, input.event.source);\n return;\n\n case \"connection.closed\":\n input.handleConnectionClosedEvent(input.event);\n return;\n\n default:\n assertUnreachableRuntimeEvent(input.event);\n return;\n }\n}\n\nfunction handleInteractiveIncomingEvent(input: {\n event: SignalEnvelope | HelloAck;\n source: \"history\" | \"live\";\n liveFloorTs: number;\n seenSignalIds: Set<string>;\n selfProfileId: string;\n appendTranscriptEvent: (\n event: SignalEnvelope | HelloAck,\n source: \"history\" | \"live\"\n ) => void;\n onIgnoredOlderThanLiveFloor: (event: SignalEnvelope | HelloAck) => void;\n scheduleMembersSnapshotRefresh: () => void;\n scheduleSpaceMetaRefresh: () => void;\n}): void {\n if (input.source === \"history\") {\n input.appendTranscriptEvent(input.event, \"history\");\n return;\n }\n\n const ignoreResult = shouldIgnoreIncomingSignal({\n event: input.event,\n liveFloorTs: input.liveFloorTs,\n seenSignalIds: input.seenSignalIds,\n selfProfileId: input.selfProfileId,\n });\n if (ignoreResult.ignore) {\n if (ignoreResult.reason === \"seen_replay_duplicate\") {\n return;\n }\n if (ignoreResult.reason === \"older_than_live_floor\") {\n input.onIgnoredOlderThanLiveFloor(input.event);\n }\n return;\n }\n\n input.appendTranscriptEvent(input.event, \"live\");\n if (\n input.source === \"live\" &&\n shouldRefreshMembersSnapshotForEvent(input.event)\n ) {\n input.scheduleMembersSnapshotRefresh();\n }\n if (input.source === \"live\" && shouldRefreshSpaceMetaForEvent(input.event)) {\n input.scheduleSpaceMetaRefresh();\n }\n}\n\n// eslint-disable-next-line complexity -- keep this orchestration function intentionally sequential.\n// CLI shell orchestration only: connect/join state, transport, and local UX\n// coordination live here; shared space semantics must stay behind package APIs.\nexport async function runConnect(input: {\n profile?: string;\n openMeldProfile?: OpenMeldProfile;\n baseUrl?: string;\n space: string;\n password?: string;\n // Join-only bridge: the join handoff seam owns when this side effect is enabled.\n trackProfileSpaceHistory?: boolean;\n connectionMode: \"join\" | \"watch\";\n sendCommand?: string;\n stdio: boolean;\n output?: string;\n localEcho?: boolean;\n historyLimit?: number;\n rawStream?: boolean;\n role?: string;\n mentionAlias?: string;\n view?: string;\n}) {\n const runtime = await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n });\n const presenter = createPresenter(runtime);\n\n const openMeldProfile =\n input.openMeldProfile ??\n (await requireOpenMeldProfile({\n openMeldProfileId: input.profile,\n persistSelection: false,\n authAction:\n input.connectionMode === \"watch\"\n ? \"watching a space\"\n : \"joining a space\",\n }));\n const openMeldProfileId = openMeldProfile.openMeldProfileId;\n const baseUrl = await resolveBaseUrl(input.baseUrl);\n const space = input.space.trim();\n const shouldTrackProfileSpaceHistory =\n input.trackProfileSpaceHistory === true;\n const gatewayHost = shouldTrackProfileSpaceHistory\n ? resolveGatewayHost(baseUrl)\n : null;\n const requestedOutput: OutputMode =\n input.output === \"text\" ? \"text\" : \"ndjson\";\n const output: OutputMode =\n runtime.resolvedView === \"agent\" ? \"ndjson\" : requestedOutput;\n const agentRawStreamEnabled =\n runtime.resolvedView === \"agent\" && input.rawStream === true;\n const connectionMode = resolveConnectionModeOrThrow(input.connectionMode);\n const recentHistoryLimit = normalizeRecentHistoryLimit(input.historyLimit);\n const enableLocalEcho =\n runtime.resolvedView === \"human\" &&\n input.stdio &&\n output === \"text\" &&\n input.localEcho === true;\n\n const agentControllerConversationId =\n openMeldProfile.profileKind === \"agent\"\n ? String(\n (\n openMeldProfile as OpenMeldProfile & {\n agentControllerConversationId?: string;\n }\n ).agentControllerConversationId ?? \"\"\n ).trim()\n : \"\";\n const profileIdentity: ConnectProfileIdentity =\n buildSpaceSessionProfileIdentity({\n openMeldProfile,\n agentControllerConversationId,\n });\n const buildProfileRequestContext = () =>\n buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity,\n });\n const ownerDisplayNameByUserId = new Map<string, string>();\n rememberSessionOwnerDisplayName(ownerDisplayNameByUserId, openMeldProfile);\n\n const heldLock = await acquireConnectLock({\n openMeldProfileId,\n baseUrl,\n space,\n profileId: profileIdentity.openMeldProfileId,\n connectionMode,\n });\n\n const wsUrl = toSpaceWsUrl(baseUrl, space);\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Session flow is intentionally linear to preserve cleanup ordering and observability.\n const runSession = async (): Promise<void> => {\n const spaceMeta = await fetchSpaceMeta({\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n password: input.password,\n }).catch(async (err) => {\n if (gatewayHost) {\n await syncProfileSpaceHistoryStatusForJoinFailure({\n openMeldProfileId,\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n gatewayHost,\n error: err,\n }).catch((syncError) => {\n presenter.event(\n \"info\",\n \"connect.warn.profile_space_history_sync_failed\",\n {\n error: toErrorMessage(syncError),\n }\n );\n });\n }\n if (isSpaceNotFoundHttpError(err)) {\n throw new Error(\n formatMessage(runtime.resolvedView, \"connect.error.space_not_found\", {\n space,\n })\n );\n }\n throw err;\n });\n\n await applyFetchedSpaceMeta({\n openMeldProfileId,\n baseUrl,\n space,\n profileHandle: profileIdentity.profileHandle,\n profileName: profileIdentity.profileName,\n spaceMeta,\n output,\n rawStream: agentRawStreamEnabled,\n resolvedView: runtime.resolvedView,\n });\n\n let localSpaceConfig = resolveOptionalReadableLocalSpaceConfig(\n await readSpaceConfig({ openMeldProfileId, space }),\n \"reading local space config before connect\"\n );\n let localProfileCache = localSpaceConfig\n ? projectSpaceProfileCache(localSpaceConfig)\n : null;\n const localLastSeenTs = await readSpaceLastSeenTs({\n openMeldProfileId,\n space,\n });\n let cloudCursor = await fetchSpaceCursor({\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n password: input.password,\n }).catch((err) => {\n presenter.event(\"info\", \"connect.warn.cursor_fetch_failed\", {\n error: toErrorMessage(err),\n });\n return null;\n });\n\n const localRole = normalizeRoleValue(localProfileCache?.role);\n const localMentionAlias = normalizeStoredMentionAliasValue({\n mentionAlias: localProfileCache?.mentionAlias,\n profileId: profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n profileKind: openMeldProfile.profileKind,\n });\n const roleContext = resolveSessionRoleContext({\n inputRole: input.role,\n localRole,\n cloudRole: normalizeRoleValue(cloudCursor?.role),\n });\n const mentionAlias = resolveSessionMentionAlias({\n inputMentionAlias: input.mentionAlias,\n localMentionAlias,\n cloudMentionAlias: normalizeStoredMentionAliasValue({\n mentionAlias: cloudCursor?.mentionAlias,\n profileId: profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n profileKind: openMeldProfile.profileKind,\n }),\n profileId: profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n profileKind: openMeldProfile.profileKind,\n });\n if (roleContext.role !== localRole || mentionAlias !== localMentionAlias) {\n await upsertSpaceConfig({\n openMeldProfileId,\n baseUrl,\n space,\n profileHandle: profileIdentity.profileHandle,\n profileName: profileIdentity.profileName,\n role: roleContext.role ?? null,\n mentionAlias: mentionAlias ?? null,\n });\n localSpaceConfig = resolveOptionalReadableLocalSpaceConfig(\n await readSpaceConfig({ openMeldProfileId, space }),\n \"refreshing local space config after connect cache update\"\n );\n localProfileCache = localSpaceConfig\n ? projectSpaceProfileCache(localSpaceConfig)\n : null;\n }\n\n const cloudLastSeenTs = normalizeCursorLastSeenTs(cloudCursor);\n const lastSeenTs = resolveMaxLastSeenTs(localLastSeenTs, cloudLastSeenTs);\n\n if (\n typeof lastSeenTs === \"number\" &&\n (localLastSeenTs === null || lastSeenTs > localLastSeenTs)\n ) {\n await updateSpaceLastSeenTs({\n openMeldProfileId,\n space,\n lastSeenTs,\n });\n }\n const cloudRole = normalizeRoleValue(cloudCursor?.role);\n const cloudMentionAlias = normalizeStoredMentionAliasValue({\n mentionAlias: cloudCursor?.mentionAlias,\n profileId: profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n profileKind: openMeldProfile.profileKind,\n });\n const shouldSyncLastSeen =\n typeof lastSeenTs === \"number\" &&\n (cloudLastSeenTs === null || lastSeenTs > cloudLastSeenTs);\n const shouldSyncRole = roleContext.role !== cloudRole;\n const shouldSyncMentionAlias = mentionAlias !== cloudMentionAlias;\n const cursorPatch = buildSpaceCursorPatch({\n lastSeenTs,\n shouldSyncRole,\n shouldSyncMentionAlias,\n role: roleContext.role,\n mentionAlias,\n });\n if (\n cursorPatch &&\n (shouldSyncLastSeen || shouldSyncRole || shouldSyncMentionAlias)\n ) {\n const updatedCursor = await updateSpaceCursor({\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n password: input.password,\n ...cursorPatch,\n }).catch((err) => {\n presenter.event(\"info\", \"connect.warn.cursor_patch_failed\", {\n error: toErrorMessage(err),\n });\n return null;\n });\n if (updatedCursor) {\n cloudCursor = updatedCursor;\n }\n }\n\n const initialLiveFloorTs = resolveInitialLiveFloorTs({\n lastSeenTs,\n nowMs: Date.now(),\n });\n const sessionMeta = resolveSessionMeta(\n space,\n spaceMeta,\n localSpaceConfig?.name,\n localSpaceConfig?.spaceCreatedAt\n );\n const readModelSeed = resolveSpaceJoinReadModelSeed({\n baseUrl,\n ownerDisplayNameByUserId,\n password: input.password,\n profileIdentity,\n space,\n });\n\n if (runtime.resolvedView === \"human\" && input.stdio && output === \"text\") {\n if (gatewayHost) {\n await syncProfileSpaceHistoryActive({\n openMeldProfileId,\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n gatewayHost,\n spaceMeta,\n lastSeenTs,\n }).catch((error) => {\n presenter.event(\n \"info\",\n \"connect.warn.profile_space_history_sync_failed\",\n {\n error: toErrorMessage(error),\n }\n );\n });\n }\n\n const sessionDiagnosticsPromise = resolveSpaceSessionDiagnostics({\n baseUrl,\n profile: openMeldProfile,\n });\n\n await runInteractiveHumanTextSession({\n openMeldProfileId,\n baseUrl,\n space,\n password: input.password,\n presenter,\n profileIdentity,\n connectionMode,\n sessionMeta,\n wsUrl,\n recentHistoryLimit,\n initialLiveFloorTs,\n lastSeenTs,\n enableLocalEcho,\n ownerDisplayNameByUserId,\n readModelSeed,\n sessionDiagnosticsPromise,\n });\n return;\n }\n\n let liveFloorTs = initialLiveFloorTs;\n\n let pendingLastSeen: number | null = null;\n let pendingTimer: NodeJS.Timeout | null = null;\n const activityRowsById = new Map<string, DispatchActivityRowState>();\n let rl: ReturnType<typeof createInterface> | null = null;\n let hasPrintedTextLine = false;\n let lastPrintedTextLineGroupKey: string | null = null;\n let nextDividerGapPlacement: \"top\" | \"bottom\" = \"top\";\n let allowLiveCursorPersistence = true;\n let persistedLastSeenFloorTs = initialLiveFloorTs;\n const pauseLiveCursorPersistence = (): void => {\n if (!allowLiveCursorPersistence) {\n return;\n }\n allowLiveCursorPersistence = false;\n presenter.event(\"info\", \"connect.warn.cursor_sync_paused\");\n };\n const shouldHideSubmittedInputLine =\n runtime.resolvedView === \"human\" && input.stdio && output === \"text\";\n const enableReplyingPromptStatus = shouldHideSubmittedInputLine;\n const includeReplyingStatusInPrompt = false;\n const composePromptPrefix = pc.dim(\"[draft] \");\n let composeDraftState: ComposeDraftState = emptyComposeDraft();\n let replyingStatusSweepTimer: NodeJS.Timeout | null = null;\n const pruneExpiredReplyingStatuses = (): void => {\n if (!enableReplyingPromptStatus || activityRowsById.size === 0) {\n return;\n }\n pruneExpiredDispatchRows(activityRowsById, Date.now());\n };\n const resolveReplyingStatusTexts = (): string[] => {\n pruneExpiredReplyingStatuses();\n return resolveDispatchRowStatusTexts({\n rowsById: activityRowsById,\n terminalColumns: resolveReplyingStatusColumns(),\n });\n };\n const resolveInputPrompt = (): string => {\n const baseInputPrompt = formatInputPrompt(profileIdentity, {\n spaceMembersSnapshot: readModelSeed.getMembersSnapshot(),\n });\n if (composeDraftState.lines.length > 0) {\n return `${composePromptPrefix}${baseInputPrompt}`;\n }\n if (!enableReplyingPromptStatus) {\n return baseInputPrompt;\n }\n if (!includeReplyingStatusInPrompt) {\n return baseInputPrompt;\n }\n const replyingStatuses = resolveReplyingStatusTexts();\n if (replyingStatuses.length === 0) {\n return baseInputPrompt;\n }\n return `${baseInputPrompt}[${replyingStatuses[0]}] `;\n };\n const refreshInputPrompt = (): void => {\n if (!(rl && runtime.resolvedView === \"human\")) {\n return;\n }\n rl.setPrompt(resolveInputPrompt());\n rl.prompt(true);\n };\n const resolvePromptCursorRows = (): number => {\n if (!(rl && runtime.resolvedView === \"human\" && process.stdout.isTTY)) {\n return 0;\n }\n try {\n const rows = rl.getCursorPos().rows;\n return Number.isInteger(rows) && rows > 0 ? rows : 0;\n } catch {\n return 0;\n }\n };\n const countPromptDisplayRows = (inputText: string): number => {\n const columns = resolveReplyingStatusColumns();\n if (columns === null) {\n return 1;\n }\n const promptWidth = stringWidth(resolveInputPrompt());\n const inputWidth = stringWidth(inputText);\n const totalWidth = Math.max(1, promptWidth + inputWidth);\n return Math.max(1, Math.ceil(totalWidth / columns));\n };\n let visibleReplyingStatusLine = \"\";\n let visibleReplyingStatusLineRows = 0;\n const canRenderReplyingStatusLine = (): boolean => {\n return (\n enableReplyingPromptStatus &&\n process.stdout.isTTY &&\n rl !== null &&\n runtime.resolvedView === \"human\"\n );\n };\n const clearInteractiveOverlay = (input?: {\n submittedInputText?: string;\n includeVisibleReplyingStatus?: boolean;\n }): void => {\n if (!(runtime.resolvedView === \"human\" && rl && process.stdout.isTTY)) {\n return;\n }\n const promptRowsAboveCurrent =\n typeof input?.submittedInputText === \"string\"\n ? countPromptDisplayRows(input.submittedInputText)\n : resolvePromptCursorRows();\n const visibleReplyingRowsAbovePrompt =\n input?.includeVisibleReplyingStatus === true &&\n visibleReplyingStatusLine.length > 0\n ? REPLYING_STATUS_PROMPT_GAP_LINES + visibleReplyingStatusLineRows\n : 0;\n const rowsAboveCurrent =\n promptRowsAboveCurrent + visibleReplyingRowsAbovePrompt;\n clearLine(process.stdout, 0);\n cursorTo(process.stdout, 0);\n for (let rowOffset = 0; rowOffset < rowsAboveCurrent; rowOffset += 1) {\n moveCursor(process.stdout, 0, -1);\n clearLine(process.stdout, 0);\n cursorTo(process.stdout, 0);\n }\n if (input?.includeVisibleReplyingStatus === true) {\n visibleReplyingStatusLine = \"\";\n visibleReplyingStatusLineRows = 0;\n }\n };\n const clearVisibleReplyingStatusLine = (): void => {\n if (\n !canRenderReplyingStatusLine() ||\n visibleReplyingStatusLine.length === 0\n ) {\n return;\n }\n clearInteractiveOverlay({\n includeVisibleReplyingStatus: true,\n });\n };\n const renderVisibleReplyingStatusLine = (text: string): void => {\n if (!canRenderReplyingStatusLine()) {\n return;\n }\n const normalizedText = text.trim();\n if (!normalizedText) {\n clearVisibleReplyingStatusLine();\n return;\n }\n if (visibleReplyingStatusLine === normalizedText) {\n return;\n }\n if (visibleReplyingStatusLine.length > 0) {\n clearVisibleReplyingStatusLine();\n } else {\n clearPromptLineBeforeExternalWrite();\n }\n process.stdout.write(\n `${normalizedText}${\"\\n\".repeat(REPLYING_STATUS_PROMPT_GAP_LINES + 1)}`\n );\n visibleReplyingStatusLine = normalizedText;\n visibleReplyingStatusLineRows = countRenderedTerminalRows(normalizedText);\n };\n const syncReplyingStatusPresentation = (): void => {\n const promptStatuses = resolveReplyingStatusTexts();\n if (promptStatuses.length > 0) {\n const decoratedReplyingStatus = promptStatuses\n .map((statusText) => {\n return `* ${REPLYING_STATUS_SYSTEM_LABEL} · ${REPLYING_STATUS_AGENT_LABEL} ${statusText}`;\n })\n .join(\"\\n\");\n renderVisibleReplyingStatusLine(pc.dim(decoratedReplyingStatus));\n } else {\n clearVisibleReplyingStatusLine();\n }\n refreshInputPrompt();\n };\n const scheduleReplyingStatusSweep = (): void => {\n if (replyingStatusSweepTimer) {\n clearTimeout(replyingStatusSweepTimer);\n replyingStatusSweepTimer = null;\n }\n if (!enableReplyingPromptStatus || activityRowsById.size === 0) {\n return;\n }\n const nearestExpiryMs =\n resolveNearestDispatchRowExpiryMs(activityRowsById);\n if (nearestExpiryMs === null) {\n return;\n }\n const delayMs = Math.max(250, nearestExpiryMs - Date.now());\n replyingStatusSweepTimer = setTimeout(() => {\n pruneExpiredReplyingStatuses();\n syncReplyingStatusPresentation();\n scheduleReplyingStatusSweep();\n }, delayMs);\n };\n const handleReplyingHintStatusEvent = (event: SignalEnvelope): void => {\n if (!enableReplyingPromptStatus || event.type !== \"signal.text\") {\n return;\n }\n const statusChanged =\n applyDispatchActivityEventToStatusMap({\n rowsById: activityRowsById,\n event,\n nowMs: Date.now(),\n }) ||\n clearDispatchActivitiesForSignal({\n rowsById: activityRowsById,\n event,\n });\n if (!statusChanged) {\n return;\n }\n scheduleReplyingStatusSweep();\n syncReplyingStatusPresentation();\n };\n const flushLastSeen = async () => {\n if (!pendingLastSeen) {\n return;\n }\n if (!allowLiveCursorPersistence) {\n pendingLastSeen = null;\n return;\n }\n const ts = pendingLastSeen;\n pendingLastSeen = null;\n await updateSpaceLastSeenTs({\n openMeldProfileId,\n space,\n lastSeenTs: ts,\n });\n await updateSpaceCursor({\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n password: input.password,\n lastSeenTs: ts,\n }).catch((err) => {\n presenter.event(\"info\", \"connect.warn.persist_last_seen\", {\n error: toErrorMessage(err),\n });\n });\n };\n const scheduleLastSeen = (ts: number) => {\n pendingLastSeen = Math.max(pendingLastSeen ?? 0, ts);\n if (pendingTimer) {\n return;\n }\n pendingTimer = setTimeout(async () => {\n pendingTimer = null;\n try {\n await flushLastSeen();\n } catch (err) {\n presenter.event(\"info\", \"connect.warn.persist_last_seen\", {\n error: toErrorMessage(err),\n });\n }\n }, 1000);\n };\n const cancelLastSeenTimer = () => {\n if (!pendingTimer) {\n return;\n }\n clearTimeout(pendingTimer);\n pendingTimer = null;\n };\n const scheduleEventLastSeen = (event: SignalEnvelope | HelloAck): void => {\n if (!isSignalEnvelope(event)) {\n return;\n }\n if (!allowLiveCursorPersistence) {\n return;\n }\n if (event.ts <= persistedLastSeenFloorTs) {\n return;\n }\n persistedLastSeenFloorTs = event.ts;\n scheduleLastSeen(event.ts);\n };\n const consumePendingOutboundConfirmation = (\n event: SignalEnvelope | HelloAck\n ): void => {\n if (\n event.type !== \"signal.text\" ||\n event.profile?.profileId !== profileIdentity.openMeldProfileId\n ) {\n return;\n }\n if (\n !confirmPendingOutboundRows({\n rowsById: activityRowsById,\n clientMessageId: resolveSignalClientMessageId(event),\n })\n ) {\n return;\n }\n syncReplyingStatusPresentation();\n };\n const emitTextGroupDivider = (): void => {\n const dividerLine = buildChatGroupDividerLine();\n if (!dividerLine) {\n process.stdout.write(\"\\n\");\n return;\n }\n const useTopGap = nextDividerGapPlacement === \"top\";\n const topGapLines = useTopGap ? CHAT_GROUP_DIVIDER_SIDE_GAP_LINES : 0;\n const bottomGapLines = useTopGap ? 0 : CHAT_GROUP_DIVIDER_SIDE_GAP_LINES;\n process.stdout.write(\n `${\"\\n\".repeat(topGapLines)}${dividerLine}\\n${\"\\n\".repeat(bottomGapLines)}`\n );\n nextDividerGapPlacement = useTopGap ? \"bottom\" : \"top\";\n };\n const emitTextLine = (inputLine: {\n line: string;\n groupKey: string;\n refreshPrompt?: boolean;\n }): void => {\n if (runtime.resolvedView !== \"human\") {\n process.stdout.write(`${inputLine.line}\\n`);\n return;\n }\n clearPromptLineBeforeExternalWrite();\n const isGroupBoundary =\n hasPrintedTextLine &&\n lastPrintedTextLineGroupKey !== inputLine.groupKey;\n if (isGroupBoundary) {\n emitTextGroupDivider();\n }\n process.stdout.write(`${inputLine.line}\\n`);\n hasPrintedTextLine = true;\n lastPrintedTextLineGroupKey = inputLine.groupKey;\n if (inputLine.refreshPrompt !== false && rl) {\n process.stdout.write(\"\\n\");\n refreshInputPrompt();\n }\n };\n const clearSubmittedInputLine = (line: string): void => {\n if (!(shouldHideSubmittedInputLine && process.stdout.isTTY)) {\n return;\n }\n // Keep chat output clean: remove the full submitted prompt/input block,\n // even when it wrapped across multiple terminal rows.\n clearInteractiveOverlay({\n submittedInputText: line,\n });\n };\n const clearPromptLineBeforeExternalWrite = (): void => {\n if (!(runtime.resolvedView === \"human\" && rl && process.stdout.isTTY)) {\n return;\n }\n clearInteractiveOverlay();\n };\n const catchupSeenSignalIds = new Set<string>();\n const recordConnectEvent = (\n event: SignalEnvelope | HelloAck,\n source: \"history\" | \"live\"\n ): void => {\n scheduleEventLastSeen(event);\n if (isSignalEnvelope(event)) {\n liveFloorTs = Math.max(liveFloorTs, event.ts);\n if (source === \"live\") {\n rememberSeenSignalId(catchupSeenSignalIds, event.id);\n readModelSeed.rememberSignal(event);\n }\n handleReplyingHintStatusEvent(event);\n }\n\n consumePendingOutboundConfirmation(event);\n };\n const emitNdjsonEvent = (event: SignalEnvelope | HelloAck): void => {\n if (isSignalEnvelope(event)) {\n const signal =\n runtime.resolvedView === \"agent\"\n ? (normalizeAgentOutputEvent(event) as SignalEnvelope)\n : event;\n outJsonLine(\n buildFormalSignalReadPayload({\n signal,\n membersSnapshot: readModelSeed.getMembersSnapshot(),\n signalIndex: readModelSeed.getSignalIndex(),\n })\n );\n return;\n }\n\n outJsonLine(\n runtime.resolvedView === \"agent\"\n ? normalizeAgentOutputEvent(event)\n : event\n );\n };\n const emitHumanTextEvent = (event: SignalEnvelope | HelloAck): void => {\n emitHumanConnectTranscriptEvent({\n event,\n ownerDisplayNameByUserId,\n readModelSeed,\n sessionProfileIdentity: profileIdentity,\n onTranscriptItem: (transcriptItem) => {\n emitTextLine({\n line: transcriptItem.line,\n groupKey: transcriptItem.groupKey,\n });\n },\n });\n };\n const emitReplayHistoryTranscript = (inputLines: {\n lines: readonly string[];\n lastTranscriptGroupKey: string | null;\n }): void => {\n for (const line of inputLines.lines) {\n process.stdout.write(`${line}\\n`);\n }\n if (inputLines.lastTranscriptGroupKey) {\n hasPrintedTextLine = true;\n lastPrintedTextLineGroupKey = inputLines.lastTranscriptGroupKey;\n }\n };\n const emitEvent = (\n event: SignalEnvelope | HelloAck,\n source: \"history\" | \"live\"\n ): void => {\n recordConnectEvent(event, source);\n if (output === \"ndjson\") {\n emitNdjsonEvent(event);\n return;\n }\n emitHumanTextEvent(event);\n };\n const ws = await connectWebSocket(wsUrl, {\n headers: await buildOpenMeldProfileIdentityRequestHeadersWithAuth({\n requestUrl: wsUrl,\n profileIdentity,\n spacePassword: input.password,\n }),\n }).catch((err) => {\n throw new Error(toErrorMessage(err));\n });\n const initialMembersSnapshot = await readModelSeed\n .ensureMembersSnapshotLoaded()\n .catch((error: unknown) => {\n presenter.event(\"info\", \"connect.warn.members_fetch_failed\", {\n error: toErrorMessage(error),\n });\n return readModelSeed.getMembersSnapshot();\n });\n\n if (gatewayHost) {\n await syncProfileSpaceHistoryActive({\n openMeldProfileId,\n requestContext: buildProfileRequestContext(),\n baseUrl,\n space,\n gatewayHost,\n spaceMeta,\n lastSeenTs,\n }).catch((error) => {\n presenter.event(\n \"info\",\n \"connect.warn.profile_space_history_sync_failed\",\n {\n error: toErrorMessage(error),\n }\n );\n });\n }\n\n emitSessionMeta({\n accessMode: sessionMeta.accessMode,\n output,\n spaceId: sessionMeta.spaceId,\n spaceName: sessionMeta.spaceName,\n spaceCreatedAt: sessionMeta.spaceCreatedAt,\n spaceCreatorName: sessionMeta.spaceCreatorName,\n spaceCreatorId: sessionMeta.spaceCreatorId,\n passwordProtected: sessionMeta.passwordProtected,\n profileId: profileIdentity.openMeldProfileId,\n profileName: profileIdentity.profileName,\n profileKind: profileIdentity.kind,\n ownerUserId: profileIdentity.ownerUserId,\n ownerName: profileIdentity.ownerName,\n agentControllerRef: profileIdentity.agentControllerRef,\n agentControllerConversationId:\n profileIdentity.agentControllerConversationId,\n modelSelection: resolveSessionProfileModelSelection({\n profileId: profileIdentity.openMeldProfileId,\n spaceMembersSnapshot: readModelSeed.getMembersSnapshot() ?? undefined,\n }),\n spaceMembersSnapshot: readModelSeed.getMembersSnapshot() ?? undefined,\n gatewayUrl: baseUrl,\n stdio: input.stdio,\n visibility: sessionMeta.visibility,\n });\n if (output === \"ndjson\" && initialMembersSnapshot) {\n emitSpaceMembers(\n runtime.resolvedView === \"agent\"\n ? normalizeAgentOutputMembersSnapshot(initialMembersSnapshot)\n : initialMembersSnapshot\n );\n }\n\n let isReplayingHistory = true;\n const bufferedLiveEvents: Array<SignalEnvelope | HelloAck> = [];\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Event handling keeps the replay/live merge rules in one place.\n const handleIncomingEvent = (event: SignalEnvelope | HelloAck): void => {\n const ignoreResult = shouldIgnoreIncomingSignal({\n event,\n liveFloorTs,\n seenSignalIds: catchupSeenSignalIds,\n selfProfileId: profileIdentity.openMeldProfileId,\n });\n if (ignoreResult.ignore) {\n if (ignoreResult.reason === \"seen_replay_duplicate\") {\n return;\n }\n if (ignoreResult.reason === \"older_than_live_floor\") {\n processIgnoredOlderThanLiveFloorSignal({\n event,\n seenSignalIds: catchupSeenSignalIds,\n onDispatchActivityEvent: handleReplyingHintStatusEvent,\n });\n return;\n }\n return;\n }\n if (isReplayingHistory) {\n if (bufferedLiveEvents.length < CATCHUP_LIVE_BUFFER_MAX) {\n bufferedLiveEvents.push(event);\n return;\n }\n isReplayingHistory = false;\n presenter.event(\"info\", \"connect.warn.catchup_live_buffer_overflow\", {\n limit: CATCHUP_LIVE_BUFFER_MAX,\n });\n pauseLiveCursorPersistence();\n for (const bufferedEvent of bufferedLiveEvents) {\n handleIncomingEvent(bufferedEvent);\n }\n bufferedLiveEvents.length = 0;\n }\n emitEvent(event, \"live\");\n };\n\n ws.onMessage((raw) => {\n const parsed = safeJsonParse(raw);\n const serverError = parseServerErrorFrame(parsed);\n if (serverError) {\n if (output === \"ndjson\") {\n outJsonLine(serverError);\n return;\n }\n errLine(\n `space stream error: ${formatServerErrorFrameMessage(serverError)}`\n );\n return;\n }\n const event = parseIncoming(parsed);\n if (!event) {\n if (output === \"ndjson\") {\n outJsonLine({ type: \"raw\", data: raw });\n }\n return;\n }\n handleIncomingEvent(event);\n });\n\n let isClosing = false;\n let localCloseReason: string | null = null;\n let wsEnded = false;\n ws.onClose((code, reason) => {\n wsEnded = true;\n const closeDetails = resolveWebSocketCloseDetails({ code, reason });\n reportPendingOutboundUnconfirmed({\n context: \"closed\",\n reason: closeDetails.reason,\n });\n if (\n shouldRenderHumanNormalLeaveCard({\n resolvedView: runtime.resolvedView,\n closeCode: closeDetails.code,\n localCloseReason,\n exitCode: process.exitCode,\n })\n ) {\n clearPromptLineBeforeExternalWrite();\n emitHumanNormalLeaveCard({\n spaceId: sessionMeta.spaceId,\n writeLine: (codeLabel, text) => {\n presenter.line({\n code: codeLabel,\n text,\n });\n },\n });\n process.exitCode = process.exitCode ?? 0;\n return;\n }\n if (isClosing && closeDetails.code === 1006) {\n presenter.event(\"info\", \"connect.closed\");\n process.exitCode = process.exitCode ?? 0;\n return;\n }\n presenter.event(\"info\", \"connect.closed_with_code_reason\", closeDetails);\n process.exitCode = process.exitCode ?? 0;\n });\n\n ws.onError((err) => {\n wsEnded = true;\n reportPendingOutboundUnconfirmed({\n context: \"error\",\n reason: toErrorMessage(err),\n });\n presenter.event(\n \"error\",\n \"connect.error\",\n resolveWebSocketError(err, runtime.resolvedView)\n );\n process.exitCode = 1;\n });\n\n ws.send(JSON.stringify(makeHello(toProtocolProfile(profileIdentity))));\n\n const replayState = await replayConnectInitialHistoryBootstrap({\n profileIdentity,\n baseUrl,\n space,\n password: input.password,\n recentHistoryLimit,\n readModelSeed,\n ownerDisplayNameByUserId,\n seenSignalIds: catchupSeenSignalIds,\n onReplayEvent: (event) => {\n if (output === \"ndjson\") {\n emitEvent(event, \"history\");\n return;\n }\n recordConnectEvent(event, \"history\");\n },\n onReplayTranscriptRendered:\n output === \"text\" && runtime.resolvedView === \"human\"\n ? emitReplayHistoryTranscript\n : undefined,\n onError: (err) => {\n presenter.event(\"info\", \"connect.warn.catchup_failed\", {\n error: toErrorMessage(err),\n });\n },\n });\n liveFloorTs = Math.max(\n liveFloorTs,\n replayState.latestReplayedSignalTs ?? liveFloorTs\n );\n if (!replayState.synced) {\n pauseLiveCursorPersistence();\n }\n isReplayingHistory = false;\n for (const event of bufferedLiveEvents) {\n handleIncomingEvent(event);\n }\n bufferedLiveEvents.length = 0;\n let forceTerminateTimer: NodeJS.Timeout | null = null;\n const clearForceTerminate = () => {\n if (!forceTerminateTimer) {\n return;\n }\n clearTimeout(forceTerminateTimer);\n forceTerminateTimer = null;\n };\n const cleanup = (why: string) => {\n if (isClosing) {\n return;\n }\n isClosing = true;\n localCloseReason = why;\n\n // Remove signal handlers immediately to avoid duplicate cleanup logs.\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGTERM\", onSigterm);\n\n if (runtime.resolvedView !== \"human\") {\n presenter.event(\"info\", \"connect.closing\", { why });\n }\n try {\n rl?.close();\n } catch {\n // ignore\n }\n\n try {\n ws.close(1000, why);\n } catch {\n // ignore\n }\n\n // Give the close handshake a brief window before forcing termination.\n forceTerminateTimer = setTimeout(() => {\n try {\n ws.terminate();\n } catch {\n // ignore\n }\n }, 800);\n ws.waitUntilClosed().then(clearForceTerminate).catch(clearForceTerminate);\n };\n const onSigint = () => cleanup(\"SIGINT\");\n const onSigterm = () => cleanup(\"SIGTERM\");\n process.once(\"SIGINT\", onSigint);\n process.once(\"SIGTERM\", onSigterm);\n\n if (wsEnded) {\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGTERM\", onSigterm);\n if (replyingStatusSweepTimer) {\n clearTimeout(replyingStatusSweepTimer);\n replyingStatusSweepTimer = null;\n }\n cancelLastSeenTimer();\n await flushLastSeen();\n return;\n }\n\n if (!input.stdio) {\n const noStdioEventData = buildNoStdioEventData({\n connectionMode,\n profileId: profileIdentity.openMeldProfileId,\n spaceId: space,\n sendCommand: input.sendCommand,\n });\n if (output === \"text\") {\n if (connectionMode === \"watch\") {\n presenter.event(\"info\", \"connect.watch_ready\");\n } else {\n presenter.event(\n \"info\",\n \"connect.connected_no_stdio\",\n noStdioEventData\n );\n }\n } else if (!agentRawStreamEnabled) {\n presenter.event(\"info\", \"connect.connected_no_stdio\", noStdioEventData);\n }\n await ws.waitUntilClosed();\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGTERM\", onSigterm);\n if (replyingStatusSweepTimer) {\n clearTimeout(replyingStatusSweepTimer);\n replyingStatusSweepTimer = null;\n }\n cancelLastSeenTimer();\n await flushLastSeen();\n return;\n }\n\n if (output === \"text\") {\n if (runtime.resolvedView === \"human\") {\n process.stdout.write(\"\\n\");\n }\n const chatWakeupHintText = formatMessage(\n runtime.resolvedView,\n \"connect.chat_mention_hint\"\n );\n const chatReadyText = formatMessage(\n runtime.resolvedView,\n \"connect.chat_ready\"\n );\n const chatExitHintText = formatMessage(\n runtime.resolvedView,\n \"connect.chat_exit_hint\"\n );\n const chatPromptQuestionText = formatMessage(\n runtime.resolvedView,\n \"connect.chat_prompt_question\"\n );\n if (runtime.resolvedView === \"human\") {\n process.stdout.write(`${pc.dim(chatWakeupHintText)}\\n`);\n }\n process.stdout.write(`${pc.dim(chatReadyText)}\\n`);\n process.stdout.write(`${pc.dim(chatExitHintText)}\\n`);\n if (runtime.resolvedView === \"human\") {\n process.stdout.write(`\\n${pc.dim(chatPromptQuestionText)}\\n`);\n }\n } else {\n presenter.event(\"info\", \"connect.connected_stdio\");\n }\n rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal:\n runtime.resolvedView === \"human\" && process.stdout.isTTY === true,\n crlfDelay: Number.POSITIVE_INFINITY,\n });\n if (runtime.resolvedView === \"human\") {\n rl.setPrompt(resolveInputPrompt());\n rl.prompt();\n }\n const resolveOutboundTextFromLine = (\n line: string\n ): { kind: \"quit\" } | { kind: \"none\" } | { kind: \"send\"; text: string } => {\n const action = consumeComposeInputLine({\n line,\n draft: composeDraftState,\n });\n if (action.kind === \"quit\") {\n return { kind: \"quit\" };\n }\n if (action.kind === \"continue\") {\n composeDraftState = action.nextDraft;\n if (runtime.resolvedView === \"human\") {\n refreshInputPrompt();\n }\n return { kind: \"none\" };\n }\n\n composeDraftState = action.nextDraft;\n const sanitized = sanitizeText(action.text);\n if (!sanitized.ok) {\n presenter.event(\"info\", \"connect.reject\", { reason: sanitized.reason });\n if (runtime.resolvedView === \"human\") {\n refreshInputPrompt();\n }\n return { kind: \"none\" };\n }\n\n return {\n kind: \"send\",\n text: sanitized.value,\n };\n };\n function reportOutboundSendFailure(inputFailure: {\n error: string;\n hint?: string;\n }): void {\n syncReplyingStatusPresentation();\n presenter.event(\"error\", \"connect.error\", inputFailure);\n process.exitCode = 1;\n if (runtime.resolvedView === \"human\") {\n refreshInputPrompt();\n }\n }\n function reportPendingOutboundUnconfirmed(inputPending: {\n context: \"closed\" | \"error\";\n reason?: string;\n }): void {\n if (!clearUnconfirmedPendingOutboundRows(activityRowsById)) {\n return;\n }\n syncReplyingStatusPresentation();\n const reasonSuffix = inputPending.reason\n ? ` (${inputPending.reason})`\n : \"\";\n presenter.event(\"error\", \"connect.error\", {\n error: `last message may not have been confirmed before the connection ${inputPending.context === \"closed\" ? \"closed\" : \"failed\"}${reasonSuffix}`,\n hint: \"rejoin the space and send it again if you still do not see it\",\n });\n process.exitCode = 1;\n }\n const prepareRawStdioOutboundText = async (text: string) => {\n const preparedSubmission = await prepareCliSpaceComposerSubmission({\n missingSnapshotMessage:\n \"Cannot validate recipients because current Space members could not be loaded.\",\n onMembersSnapshotLoaded: (membersSnapshot) => {\n readModelSeed.applyMembersSnapshot(membersSnapshot);\n },\n onSnapshotLoadFailure: (error) => {\n presenter.event(\"info\", \"connect.warn.members_fetch_failed\", {\n error: toErrorMessage(error),\n });\n rethrowSpaceAddressingSnapshotLoadFailure(error);\n },\n loadMembersSnapshot: async () => {\n const currentMembersSnapshot = readModelSeed.getMembersSnapshot();\n if (currentMembersSnapshot) {\n return currentMembersSnapshot;\n }\n return await readModelSeed.ensureMembersSnapshotLoaded();\n },\n text,\n });\n\n return {\n messageEnvelope: preparedSubmission.outboundMessageEnvelope ?? null,\n text: preparedSubmission.outboundText,\n };\n };\n const sendOutboundText = async (inputText: string): Promise<void> => {\n if (isClosing || wsEnded) {\n reportOutboundSendFailure({\n error:\n \"couldn't send the message because the space connection is already closed\",\n hint: \"rejoin the space and try sending it again\",\n });\n return;\n }\n const preparedOutboundText = await prepareRawStdioOutboundText(\n inputText\n ).catch((error) => {\n presenter.event(\"info\", \"connect.reject\", {\n reason: toErrorMessage(error),\n });\n if (runtime.resolvedView === \"human\") {\n refreshInputPrompt();\n }\n return null;\n });\n if (!preparedOutboundText) {\n return;\n }\n const outboundText = preparedOutboundText.text;\n const clientMessageId = crypto.randomUUID();\n try {\n ws.send(\n JSON.stringify(\n toCompatibleSpaceAddressingRequestWireValue(\n makeTextSignal(outboundText, {\n ...(preparedOutboundText.messageEnvelope\n ? { messageEnvelope: preparedOutboundText.messageEnvelope }\n : {}),\n meta: {\n clientMessageId,\n },\n })\n )\n )\n );\n } catch (error) {\n reportOutboundSendFailure({\n error: `couldn't send the message: ${toErrorMessage(error)}`,\n hint: \"rejoin the space and try sending it again\",\n });\n return;\n }\n upsertPendingHumanSendRow({\n enableLocalEcho,\n rowsById: activityRowsById,\n text: outboundText,\n clientMessageId,\n terminalColumns: resolveReplyingStatusColumns(),\n nowMs: Date.now(),\n maxPendingRows: PENDING_OUTBOUND_CONFIRMATION_MAX,\n });\n syncReplyingStatusPresentation();\n if (runtime.resolvedView === \"human\") {\n refreshInputPrompt();\n }\n };\n rl.on(\"line\", (line) => {\n const resolution = resolveOutboundTextFromLine(line);\n if (resolution.kind === \"quit\") {\n cleanup(\"quit\");\n return;\n }\n if (resolution.kind === \"none\") {\n return;\n }\n setImmediate(() => {\n clearSubmittedInputLine(line);\n sendOutboundText(resolution.text).catch((error) => {\n reportOutboundSendFailure({\n error: `couldn't send the message: ${toErrorMessage(error)}`,\n hint: \"rejoin the space and try sending it again\",\n });\n });\n });\n });\n rl.on(\"close\", () => {\n cleanup(\"stdin closed\");\n });\n\n await ws.waitUntilClosed();\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGTERM\", onSigterm);\n clearForceTerminate();\n if (replyingStatusSweepTimer) {\n clearTimeout(replyingStatusSweepTimer);\n replyingStatusSweepTimer = null;\n }\n cancelLastSeenTimer();\n await flushLastSeen();\n };\n\n if (!heldLock) {\n return await runSession();\n }\n\n return await runWithHeldLock({\n lock: heldLock.lock,\n run: runSession,\n releaseContext: {\n component: \"space.connect\",\n lockKey: heldLock.lockKey,\n mode: connectionMode,\n profileId: profileIdentity.openMeldProfileId,\n space,\n },\n });\n}\n\n// eslint-disable-next-line complexity -- keep the interactive shell/runtime orchestration linear to preserve event ordering and cleanup safety.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: This function coordinates shell, runtime, store, and shutdown sequencing in one place.\nasync function runInteractiveHumanTextSession(input: {\n openMeldProfileId: string;\n baseUrl: string;\n space: string;\n password?: string;\n presenter: ReturnType<typeof createPresenter>;\n profileIdentity: ConnectProfileIdentity;\n connectionMode: \"join\" | \"watch\";\n sessionMeta: ReturnType<typeof resolveSessionMeta>;\n wsUrl: string;\n recentHistoryLimit: number;\n initialLiveFloorTs: number;\n lastSeenTs: number | null;\n enableLocalEcho: boolean;\n ownerDisplayNameByUserId: Map<string, string>;\n readModelSeed: SpaceJoinReadModelSeed;\n sessionDiagnosticsPromise: ReturnType<typeof resolveSpaceSessionDiagnostics>;\n}): Promise<void> {\n const store = createSpaceScreenStore();\n const composerController = new ComposerController();\n let openOverlayFromShell: ((kind: SpacePanelKind) => void) | null = null;\n const sessionContext = buildActiveSpaceSessionContext({\n profile: buildSpaceSessionProfileContextFromIdentity({\n kind: input.profileIdentity.kind,\n ownerName: input.profileIdentity.ownerName,\n ownerUserId: input.profileIdentity.ownerUserId,\n openMeldProfileId: input.profileIdentity.openMeldProfileId,\n profileName: input.profileIdentity.profileName,\n }),\n baseUrl: input.baseUrl,\n connectionMode: input.connectionMode,\n session: {\n accessMode: input.sessionMeta.accessMode ?? null,\n spaceCreatedAt: input.sessionMeta.spaceCreatedAt ?? null,\n spaceCreatorId: input.sessionMeta.spaceCreatorId ?? null,\n spaceCreatorName: input.sessionMeta.spaceCreatorName ?? null,\n spaceId: input.sessionMeta.spaceId,\n spaceName: input.sessionMeta.spaceName ?? null,\n passwordProtected: input.sessionMeta.passwordProtected ?? null,\n storageSoftLimitBytes: input.sessionMeta.storageSoftLimitBytes ?? null,\n storageUsagePercent: input.sessionMeta.storageUsagePercent ?? null,\n storageUsedBytes: input.sessionMeta.storageUsedBytes ?? null,\n visibility: input.sessionMeta.visibility ?? null,\n },\n });\n const preferredShellKind = resolveInteractiveHumanShellKind();\n let activeShellKind = preferredShellKind;\n let shell!: InteractiveSpaceShell;\n let removeStoreListener: () => void = () => undefined;\n let piTuiSessionMount: ReturnType<typeof mountPiTuiSessionShell> | null =\n null;\n let localCloseReason: string | null = null;\n let sessionDiagnostics: Awaited<\n ReturnType<typeof resolveSpaceSessionDiagnostics>\n > = {\n openMeldServiceLabel: \"unknown\",\n canWakeLocalAgentsLabel: \"unknown\",\n };\n let recentMentionProfileIds = await readSpaceRecentMentionProfileIds({\n openMeldProfileId: input.openMeldProfileId,\n space: input.space,\n });\n const buildCurrentViewState = () =>\n buildSpaceSessionViewState({\n context: sessionContext,\n resources: {\n composerActivity: {\n nowMs: Date.now(),\n rows: toComposerDispatchRows(activityRowsById),\n },\n sessionDiagnostics,\n },\n screenState: store.getState(),\n });\n const refreshCurrentViewState = (): void => {\n if (piTuiSessionMount) {\n piTuiSessionMount.refreshViewState();\n return;\n }\n shell.render(buildCurrentViewState());\n };\n const syncShellRenderSubscription = (): void => {\n removeStoreListener();\n if (shell instanceof PiTuiInteractiveSpaceShell) {\n piTuiSessionMount = mountPiTuiSessionShell({\n context: sessionContext,\n getResources: () => ({\n composerActivity: {\n nowMs: Date.now(),\n rows: toComposerDispatchRows(activityRowsById),\n },\n sessionDiagnostics,\n }),\n shell,\n store,\n });\n removeStoreListener = piTuiSessionMount.removeStoreListener;\n return;\n }\n piTuiSessionMount = null;\n removeStoreListener = store.subscribe(() => {\n shell.render(buildCurrentViewState());\n });\n };\n\n const activityRowsById = new Map<string, DispatchActivityRowState>();\n const catchupSeenSignalIds = new Set<string>();\n let liveFloorTs = input.initialLiveFloorTs;\n let allowLiveCursorPersistence = true;\n let persistedLastSeenFloorTs = input.initialLiveFloorTs;\n let pendingLastSeen: number | null = null;\n let pendingTimer: NodeJS.Timeout | null = null;\n let replyingStatusSweepTimer: NodeJS.Timeout | null = null;\n let membersSnapshotRefreshTimer: NodeJS.Timeout | null = null;\n let spaceMetaRefreshTimer: NodeJS.Timeout | null = null;\n let isClosing = false;\n let wsEnded = false;\n let interactiveIntroEmitted = false;\n\n ignoreAsyncResult(\n input.sessionDiagnosticsPromise\n .then((resolvedDiagnostics) => {\n sessionDiagnostics = resolvedDiagnostics;\n if (!(isClosing || wsEnded)) {\n refreshCurrentViewState();\n }\n })\n .catch(() => undefined)\n );\n\n const applyMembersSnapshot = (\n membersSnapshot: SpaceMembersSnapshot | null\n ): void => {\n input.readModelSeed.applyMembersSnapshot(membersSnapshot);\n store.dispatch({\n type: \"members.updated\",\n snapshot: input.readModelSeed.getMembersSnapshot(),\n updatedAtMs: Date.now(),\n });\n syncMembersOverlayInteraction();\n };\n const applySessionStorageUsage = (spaceMeta: SpaceMeta): void => {\n const storageUsage = spaceMeta.storageUsage;\n sessionContext.session.storageUsedBytes =\n typeof storageUsage?.usedBytes === \"number\"\n ? storageUsage.usedBytes\n : null;\n sessionContext.session.storageSoftLimitBytes =\n typeof storageUsage?.softLimitBytes === \"number\"\n ? storageUsage.softLimitBytes\n : null;\n sessionContext.session.storageUsagePercent =\n typeof storageUsage?.usagePercent === \"number\"\n ? storageUsage.usagePercent\n : null;\n };\n const refreshSpaceMeta = async (): Promise<void> => {\n try {\n const spaceMeta = await fetchSpaceMeta({\n requestContext: buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: input.profileIdentity,\n }),\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n });\n applySessionStorageUsage(spaceMeta);\n if (!(isClosing || wsEnded)) {\n refreshCurrentViewState();\n }\n } catch (error) {\n input.presenter.event(\"info\", \"connect.warn.meta_fetch_failed\", {\n error: toErrorMessage(error),\n });\n }\n };\n const reportMembersRefreshFailure = (error: unknown): void => {\n const errorMessage = toErrorMessage(error);\n input.presenter.event(\"info\", \"connect.warn.members_fetch_failed\", {\n error: errorMessage,\n });\n store.dispatch({\n type: \"members.refresh.failed\",\n error: errorMessage,\n });\n };\n const refreshMembersSnapshot = async (): Promise<void> => {\n try {\n await input.readModelSeed.refreshMembersSnapshot();\n applyMembersSnapshot(input.readModelSeed.getMembersSnapshot());\n } catch (error) {\n reportMembersRefreshFailure(error);\n }\n };\n const syncMembersOverlayInteraction = (): void => {\n const screenState = store.getState();\n if (screenState.overlay.kind !== \"members\") {\n return;\n }\n const nextActiveItemId = resolveMembersSearchableActiveItemId({\n preferredActiveItemId: screenState.overlay.interaction.activeItemId,\n query: screenState.overlay.interaction.query,\n snapshot: screenState.members.snapshot,\n });\n store.dispatch({\n type: \"overlay.active-item.updated\",\n activeItemId: nextActiveItemId,\n });\n };\n const updateOverlayQuery = (query: string): void => {\n store.dispatch({\n type: \"overlay.query.updated\",\n query,\n });\n syncMembersOverlayInteraction();\n };\n const updateOverlayActiveItem = (activeItemId: string | null): void => {\n store.dispatch({\n type: \"overlay.active-item.updated\",\n activeItemId,\n });\n };\n const clearMembersSnapshotRefreshTimer = (): void => {\n if (!membersSnapshotRefreshTimer) {\n return;\n }\n clearTimeout(membersSnapshotRefreshTimer);\n membersSnapshotRefreshTimer = null;\n };\n const clearSpaceMetaRefreshTimer = (): void => {\n if (!spaceMetaRefreshTimer) {\n return;\n }\n clearTimeout(spaceMetaRefreshTimer);\n spaceMetaRefreshTimer = null;\n };\n const scheduleMembersSnapshotRefresh = (): void => {\n if (activeShellKind === \"legacy\") {\n return;\n }\n clearMembersSnapshotRefreshTimer();\n membersSnapshotRefreshTimer = setTimeout(() => {\n membersSnapshotRefreshTimer = null;\n ignoreAsyncResult(refreshMembersSnapshot());\n }, MEMBERS_PANEL_REFRESH_DEBOUNCE_MS);\n };\n const scheduleSpaceMetaRefresh = (): void => {\n if (activeShellKind === \"legacy\") {\n return;\n }\n clearSpaceMetaRefreshTimer();\n spaceMetaRefreshTimer = setTimeout(() => {\n spaceMetaRefreshTimer = null;\n ignoreAsyncResult(refreshSpaceMeta());\n }, SPACE_META_REFRESH_DEBOUNCE_MS);\n };\n\n let resolveHistoryReady: (() => void) | null = null;\n const historyReadyPromise = new Promise<void>((resolve) => {\n resolveHistoryReady = resolve;\n });\n const finishHistoryReady = (): void => {\n if (!resolveHistoryReady) {\n return;\n }\n resolveHistoryReady();\n resolveHistoryReady = null;\n };\n\n const runtime = new SpaceSessionRuntime({\n wsUrl: input.wsUrl,\n wsHeaders: await buildOpenMeldProfileIdentityRequestHeadersWithAuth({\n requestUrl: input.wsUrl,\n profileIdentity: input.profileIdentity,\n spacePassword: input.password,\n }),\n helloProfile: toProtocolProfile(input.profileIdentity),\n selfProfileId: input.profileIdentity.openMeldProfileId,\n loadMembers: async () => {\n return await input.readModelSeed\n .ensureMembersSnapshotLoaded()\n .catch((error) => {\n input.presenter.event(\"info\", \"connect.warn.members_fetch_failed\", {\n error: toErrorMessage(error),\n });\n return input.readModelSeed.getMembersSnapshot();\n });\n },\n replayHistory: async (onEvent) => {\n const replayState = await replayConnectInitialHistoryBootstrap({\n profileIdentity: input.profileIdentity,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n recentHistoryLimit: input.recentHistoryLimit,\n readModelSeed: input.readModelSeed,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n seenSignalIds: catchupSeenSignalIds,\n onReplayEvent: onEvent,\n onError: (error) => {\n input.presenter.event(\"info\", \"connect.warn.catchup_failed\", {\n error: toErrorMessage(error),\n });\n },\n });\n return { synced: replayState.synced };\n },\n formatError: toErrorMessage,\n });\n\n function createInteractiveHumanShell(\n kind: InteractiveHumanShellKind\n ): InteractiveSpaceShell {\n if (kind === \"legacy\") {\n return new LegacyInteractiveSpaceShell({\n onLine: handleLegacyLine,\n onClose: () => {\n cleanup(\"stdin closed\");\n },\n });\n }\n return new PiTuiInteractiveSpaceShell({\n getRecentMentionProfileIds: () => recentMentionProfileIds,\n onBufferChange: (bufferText) => {\n applyComposerBuffer(bufferText);\n },\n onClose: () => {\n cleanup(\"stdin closed\");\n },\n onOpenOverlay: (kind) => {\n openOverlayFromShell?.(kind);\n },\n onOverlayActiveItemChange: (activeItemId) => {\n updateOverlayActiveItem(activeItemId);\n },\n onOverlayClose: () => {\n closeOverlay();\n },\n onOverlayQueryChange: (query) => {\n updateOverlayQuery(query);\n },\n onSubmit: (text) => {\n handleEditorSubmit(text);\n },\n });\n }\n shell = createInteractiveHumanShell(preferredShellKind);\n syncShellRenderSubscription();\n\n const pauseLiveCursorPersistence = (): void => {\n if (!allowLiveCursorPersistence) {\n return;\n }\n allowLiveCursorPersistence = false;\n input.presenter.event(\"info\", \"connect.warn.cursor_sync_paused\");\n };\n const pruneExpiredReplyingStatuses = (): void => {\n if (activityRowsById.size === 0) {\n return;\n }\n pruneExpiredDispatchRows(activityRowsById, Date.now());\n };\n const resolveReplyingStatusTexts = (): string[] => {\n pruneExpiredReplyingStatuses();\n return resolveDispatchRowStatusTexts({\n rowsById: activityRowsById,\n terminalColumns: resolveReplyingStatusColumns(),\n });\n };\n const syncOverlayLine = (): void => {\n const replyingStatuses = resolveReplyingStatusTexts();\n if (replyingStatuses.length === 0) {\n store.dispatch({\n type: \"status.overlay.updated\",\n line: \"\",\n });\n return;\n }\n const decoratedReplyingStatus = replyingStatuses\n .map((statusText) => {\n return `* ${REPLYING_STATUS_SYSTEM_LABEL} · ${REPLYING_STATUS_AGENT_LABEL} ${statusText}`;\n })\n .join(\"\\n\");\n store.dispatch({\n type: \"status.overlay.updated\",\n line: decoratedReplyingStatus,\n });\n };\n const syncComposerActivityPresentation = (): void => {\n syncOverlayLine();\n if (piTuiSessionMount) {\n piTuiSessionMount.refreshViewState();\n }\n };\n const scheduleReplyingStatusSweep = (): void => {\n if (replyingStatusSweepTimer) {\n clearTimeout(replyingStatusSweepTimer);\n replyingStatusSweepTimer = null;\n }\n if (activityRowsById.size === 0) {\n return;\n }\n const nearestExpiryMs = resolveNearestDispatchRowExpiryMs(activityRowsById);\n if (nearestExpiryMs === null) {\n return;\n }\n const delayMs = Math.max(250, nearestExpiryMs - Date.now());\n replyingStatusSweepTimer = setTimeout(() => {\n pruneExpiredReplyingStatuses();\n syncComposerActivityPresentation();\n scheduleReplyingStatusSweep();\n }, delayMs);\n };\n const handleReplyingHintStatusEvent = (event: SignalEnvelope): void => {\n const statusChanged =\n applyDispatchActivityEventToStatusMap({\n rowsById: activityRowsById,\n event,\n nowMs: Date.now(),\n }) ||\n clearDispatchActivitiesForSignal({\n rowsById: activityRowsById,\n event,\n });\n if (!statusChanged) {\n return;\n }\n scheduleReplyingStatusSweep();\n syncComposerActivityPresentation();\n };\n const flushLastSeen = async (): Promise<void> => {\n if (!pendingLastSeen) {\n return;\n }\n if (!allowLiveCursorPersistence) {\n pendingLastSeen = null;\n return;\n }\n const ts = pendingLastSeen;\n pendingLastSeen = null;\n await updateSpaceLastSeenTs({\n openMeldProfileId: input.openMeldProfileId,\n space: input.space,\n lastSeenTs: ts,\n });\n await updateSpaceCursor({\n requestContext: buildOpenMeldRequestContextFromProfileIdentity({\n profileIdentity: input.profileIdentity,\n }),\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n lastSeenTs: ts,\n }).catch((error) => {\n shell.prepareExternalWrite();\n input.presenter.event(\"info\", \"connect.warn.persist_last_seen\", {\n error: toErrorMessage(error),\n });\n });\n };\n const scheduleLastSeen = (ts: number): void => {\n pendingLastSeen = Math.max(pendingLastSeen ?? 0, ts);\n if (pendingTimer) {\n return;\n }\n pendingTimer = setTimeout(async () => {\n pendingTimer = null;\n try {\n await flushLastSeen();\n } catch (error) {\n shell.prepareExternalWrite();\n input.presenter.event(\"info\", \"connect.warn.persist_last_seen\", {\n error: toErrorMessage(error),\n });\n }\n }, 1000);\n };\n const cancelLastSeenTimer = (): void => {\n if (!pendingTimer) {\n return;\n }\n clearTimeout(pendingTimer);\n pendingTimer = null;\n };\n const scheduleEventLastSeen = (event: SignalEnvelope | HelloAck): void => {\n if (!isSignalEnvelope(event)) {\n return;\n }\n if (!allowLiveCursorPersistence) {\n return;\n }\n if (event.ts <= persistedLastSeenFloorTs) {\n return;\n }\n persistedLastSeenFloorTs = event.ts;\n scheduleLastSeen(event.ts);\n };\n const reportOutboundSendFailure = (failure: {\n error: string;\n hint?: string;\n }): void => {\n syncComposerActivityPresentation();\n shell.prepareExternalWrite();\n input.presenter.event(\"error\", \"connect.error\", failure);\n process.exitCode = 1;\n };\n const prepareInteractiveOutboundText = async (text: string) => {\n const preparedSubmission = await prepareCliSpaceComposerSubmission({\n authoredMentionsInTextOrder: shell.getAuthoredMentions?.(text) ?? [],\n missingSnapshotMessage:\n \"Cannot validate recipients because current Space members could not be loaded.\",\n onMembersSnapshotLoaded: (membersSnapshot) => {\n applyMembersSnapshot(membersSnapshot);\n },\n onSnapshotLoadFailure: (error) => {\n reportMembersRefreshFailure(error);\n rethrowSpaceAddressingSnapshotLoadFailure(error);\n },\n loadMembersSnapshot: async () => {\n const currentMembersSnapshot = store.getState().members.snapshot;\n if (currentMembersSnapshot) {\n return currentMembersSnapshot;\n }\n return await input.readModelSeed.ensureMembersSnapshotLoaded();\n },\n text,\n });\n\n return {\n mentionsInTextOrder:\n preparedSubmission.preparedSubmission.mentionsInTextOrder,\n messageEnvelope: preparedSubmission.outboundMessageEnvelope ?? null,\n resolvedStructuredTargets:\n preparedSubmission.preparedSubmission.resolvedStructuredTargets,\n text: preparedSubmission.outboundText,\n };\n };\n const reportPendingOutboundUnconfirmed = (pending: {\n context: \"closed\" | \"error\";\n reason?: string;\n }): void => {\n if (!clearUnconfirmedPendingOutboundRows(activityRowsById)) {\n return;\n }\n syncComposerActivityPresentation();\n const reasonSuffix = pending.reason ? ` (${pending.reason})` : \"\";\n shell.prepareExternalWrite();\n input.presenter.event(\"error\", \"connect.error\", {\n error: `last message may not have been confirmed before the connection ${pending.context === \"closed\" ? \"closed\" : \"failed\"}${reasonSuffix}`,\n hint: \"rejoin the space and send it again if you still do not see it\",\n });\n process.exitCode = 1;\n };\n const appendTranscriptEvent = (\n event: SignalEnvelope | HelloAck,\n source: \"history\" | \"live\"\n ): void => {\n scheduleEventLastSeen(event);\n if (isSignalEnvelope(event)) {\n liveFloorTs = Math.max(liveFloorTs, event.ts);\n if (source === \"live\") {\n rememberSeenSignalId(catchupSeenSignalIds, event.id);\n input.readModelSeed.rememberSignal(event);\n }\n handleReplyingHintStatusEvent(event);\n }\n\n emitHumanConnectTranscriptEvent({\n event,\n ownerDisplayNameByUserId: input.ownerDisplayNameByUserId,\n readModelSeed: input.readModelSeed,\n sessionProfileIdentity: input.profileIdentity,\n onTranscriptItem: (transcriptItem) => {\n store.dispatch({\n type: \"transcript.item.appended\",\n item: transcriptItem,\n });\n },\n });\n };\n const handleIncomingEvent = (\n event: SignalEnvelope | HelloAck,\n source: \"history\" | \"live\"\n ): void => {\n handleInteractiveIncomingEvent({\n appendTranscriptEvent,\n event,\n liveFloorTs,\n onIgnoredOlderThanLiveFloor: (ignoredEvent) => {\n processIgnoredOlderThanLiveFloorSignal({\n event: ignoredEvent,\n seenSignalIds: catchupSeenSignalIds,\n onDispatchActivityEvent: handleReplyingHintStatusEvent,\n });\n },\n scheduleMembersSnapshotRefresh,\n scheduleSpaceMetaRefresh,\n seenSignalIds: catchupSeenSignalIds,\n selfProfileId: input.profileIdentity.openMeldProfileId,\n source,\n });\n };\n const applyComposerBuffer = (bufferText: string): void => {\n store.dispatch({\n type: \"composer.buffer.updated\",\n bufferText,\n });\n };\n const closeOverlay = (): void => {\n clearMembersSnapshotRefreshTimer();\n store.dispatch({\n type: \"overlay.closed\",\n });\n };\n const showOverlay = async (kind: SpacePanelKind): Promise<void> => {\n const openedAtMs = Date.now();\n store.dispatch({\n type: \"overlay.interaction.reset\",\n });\n if (activeShellKind === \"legacy\") {\n await showLegacyOverlayFallback(kind, openedAtMs);\n return;\n }\n store.dispatch({\n type: \"overlay.opened\",\n kind,\n openedAtMs,\n });\n if (kind === \"members\") {\n syncMembersOverlayInteraction();\n }\n if (kind === \"members\") {\n ignoreAsyncResult(refreshMembersSnapshot());\n }\n };\n openOverlayFromShell = (kind) => {\n ignoreAsyncResult(showOverlay(kind));\n };\n const showLegacyOverlayFallback = async (\n kind: SpacePanelKind,\n openedAtMs: number\n ): Promise<void> => {\n if (kind === \"members\") {\n await refreshMembersSnapshot();\n }\n store.dispatch({\n type: \"overlay.opened\",\n kind,\n openedAtMs,\n });\n shell.prepareExternalWrite();\n const panel = buildCurrentViewState().overlay.panel;\n if (!(panel && panel.kind === kind)) {\n store.dispatch({\n type: \"overlay.closed\",\n });\n refreshCurrentViewState();\n return;\n }\n for (const line of buildPanelDisplayLines({\n contentWidth: resolveLegacyPanelContentWidth(process.stdout.columns),\n includeControls: panel.mode !== \"searchable_list\",\n panel,\n })) {\n process.stdout.write(`${line}\\n`);\n }\n process.stdout.write(\"\\n\");\n store.dispatch({\n type: \"overlay.closed\",\n });\n refreshCurrentViewState();\n };\n const handleHistoryLoadedEvent = (\n event: Extract<SpaceRuntimeEvent, { type: \"history.loaded\" }>\n ): void => {\n if (!event.synced) {\n if (event.reason === \"live_buffer_overflow\") {\n input.presenter.event(\n \"info\",\n \"connect.warn.catchup_live_buffer_overflow\",\n {\n limit: CATCHUP_LIVE_BUFFER_MAX,\n }\n );\n }\n pauseLiveCursorPersistence();\n }\n finishHistoryReady();\n };\n const handleMembersUpdatedEvent = (\n event: Extract<SpaceRuntimeEvent, { type: \"members.updated\" }>\n ): void => {\n const membersSnapshot = event.snapshot ?? null;\n applyMembersSnapshot(membersSnapshot);\n };\n const handleConnectionClosedEvent = (\n event: Extract<SpaceRuntimeEvent, { type: \"connection.closed\" }>\n ): void => {\n wsEnded = true;\n finishHistoryReady();\n store.dispatch({\n type: \"connection.closed\",\n reason: event.reason,\n ...(typeof event.code === \"number\" ? { code: event.code } : {}),\n source: event.source,\n });\n if (event.source === \"error\") {\n reportPendingOutboundUnconfirmed({\n context: \"error\",\n reason: event.reason,\n });\n if (activityRowsById.size > 0) {\n activityRowsById.clear();\n syncComposerActivityPresentation();\n }\n shell.prepareExternalWrite();\n input.presenter.event(\n \"error\",\n \"connect.error\",\n resolveWebSocketError(event.error ?? event.reason, \"human\")\n );\n process.exitCode = 1;\n return;\n }\n\n const closeDetails = resolveWebSocketCloseDetails({\n code: event.code ?? 1006,\n reason: event.reason,\n });\n reportPendingOutboundUnconfirmed({\n context: \"closed\",\n reason: closeDetails.reason,\n });\n if (activityRowsById.size > 0) {\n activityRowsById.clear();\n syncComposerActivityPresentation();\n }\n if (\n shouldRenderHumanNormalLeaveCard({\n resolvedView: \"human\",\n closeCode: closeDetails.code,\n localCloseReason,\n exitCode: process.exitCode,\n })\n ) {\n shell.prepareExternalWrite();\n emitHumanNormalLeaveCard({\n spaceId: input.sessionMeta.spaceId,\n writeLine: (codeLabel, text) => {\n input.presenter.line({\n code: codeLabel,\n text,\n });\n },\n });\n process.exitCode = process.exitCode ?? 0;\n return;\n }\n if (isClosing && closeDetails.code === 1006) {\n shell.prepareExternalWrite();\n input.presenter.event(\"info\", \"connect.closed\");\n process.exitCode = process.exitCode ?? 0;\n return;\n }\n shell.prepareExternalWrite();\n input.presenter.event(\n \"info\",\n \"connect.closed_with_code_reason\",\n closeDetails\n );\n process.exitCode = process.exitCode ?? 0;\n };\n const removeRuntimeListener = runtime.subscribe((event) => {\n handleInteractiveRuntimeEvent({\n event,\n handleConnectionClosedEvent,\n handleHistoryLoadedEvent,\n handleIncomingEvent,\n handleMembersUpdatedEvent,\n rowsById: activityRowsById,\n enableLocalEcho: input.enableLocalEcho,\n selfProfileId: input.profileIdentity.openMeldProfileId,\n reportOutboundSendFailure,\n store,\n syncActivityPresentation: syncComposerActivityPresentation,\n });\n });\n function cleanup(why: string): void {\n if (isClosing) {\n return;\n }\n isClosing = true;\n localCloseReason = why;\n store.dispatch({\n type: \"connection.closing\",\n reason: why,\n });\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGTERM\", onSigterm);\n shell.stop();\n runtime.stop(why);\n }\n function onSigint(): void {\n cleanup(\"SIGINT\");\n }\n function onSigterm(): void {\n cleanup(\"SIGTERM\");\n }\n function handleComposerIntent(payload: {\n resolution: ComposerIntentResolution;\n submittedText: string;\n }): void {\n handleInteractiveComposerIntent({\n resolution: payload.resolution,\n submittedText: payload.submittedText,\n applyComposerBuffer,\n cleanup,\n clearSubmittedInputLine: (submittedText) => {\n shell.clearSubmittedInputLine(submittedText);\n },\n closeOverlay,\n prepareExternalWrite: () => {\n shell.prepareExternalWrite();\n },\n handleSendTextError: (error) => {\n reportOutboundSendFailure({\n error: toErrorMessage(error),\n });\n },\n presenter: input.presenter,\n sendText: async (sendInput) => {\n let submitResult: InteractiveTextSubmitResult;\n try {\n submitResult = await performInteractiveTextSubmit({\n nextBufferText: sendInput.nextBufferText,\n submittedText: sendInput.submittedText,\n text: sendInput.text,\n prepareOutboundText: prepareInteractiveOutboundText,\n queueText: (outboundText) => runtime.sendText(outboundText),\n applyComposerBuffer,\n clearSubmittedInputLine: (submittedText) => {\n shell.clearSubmittedInputLine(submittedText);\n },\n });\n } catch (error) {\n shell.prepareExternalWrite();\n input.presenter.event(\"info\", \"connect.reject\", {\n reason: toErrorMessage(error),\n });\n applyComposerBuffer(sendInput.submittedText);\n return;\n }\n if (submitResult.status !== \"queued\") {\n return;\n }\n\n if (\n upsertPendingHumanSendRow({\n enableLocalEcho: input.enableLocalEcho,\n rowsById: activityRowsById,\n text: submitResult.text,\n clientMessageId: submitResult.clientMessageId,\n terminalColumns: resolveReplyingStatusColumns(),\n nowMs: Date.now(),\n maxPendingRows: PENDING_OUTBOUND_CONFIRMATION_MAX,\n })\n ) {\n syncComposerActivityPresentation();\n }\n\n const membersSnapshot = store.getState().members.snapshot;\n const nextRecentMentionProfileIds =\n resolveNextRecentMentionProfileIdsForQueuedText({\n currentRecentProfileIds: recentMentionProfileIds,\n submittedText: submitResult.text,\n structuredMentionProfileIdsInTextOrder:\n submitResult.resolvedStructuredTargets.profileIdsInTextOrder,\n mentionsInTextOrder: submitResult.mentionsInTextOrder,\n mentionProfileIndex: input.readModelSeed.getMentionHighlightIndex(),\n allowedProfileIds: membersSnapshot\n ? listSpaceMemberProfileIds(membersSnapshot)\n : null,\n });\n if (!nextRecentMentionProfileIds) {\n return;\n }\n\n recentMentionProfileIds = nextRecentMentionProfileIds;\n ignoreAsyncResult(\n writeSpaceRecentMentionProfileIds({\n openMeldProfileId: input.openMeldProfileId,\n space: input.space,\n recentMentionProfileIds: nextRecentMentionProfileIds,\n allowedProfileIds: membersSnapshot\n ? listSpaceMemberProfileIds(membersSnapshot)\n : null,\n }).catch((error) => {\n input.presenter.event(\n \"info\",\n \"connect.warn.persist_recent_mentions\",\n {\n error: toErrorMessage(error),\n }\n );\n })\n );\n },\n showOverlay,\n });\n }\n function handleLegacyLine(line: string): void {\n const resolution = composerController.consumeLegacyLine({\n line,\n bufferText: store.getState().composer.bufferText,\n });\n handleComposerIntent({\n resolution,\n submittedText: line,\n });\n }\n function handleEditorSubmit(text: string): void {\n const resolution = composerController.consumeEditorSubmit({\n text,\n nextBufferText: \"\",\n });\n handleComposerIntent({\n resolution,\n submittedText: text,\n });\n }\n const emitInteractiveSessionMeta = (): void => {\n emitSessionMeta({\n accessMode: input.sessionMeta.accessMode,\n output: \"text\",\n spaceId: input.sessionMeta.spaceId,\n spaceName: input.sessionMeta.spaceName,\n spaceCreatedAt: input.sessionMeta.spaceCreatedAt,\n spaceCreatorName: input.sessionMeta.spaceCreatorName,\n spaceCreatorId: input.sessionMeta.spaceCreatorId,\n passwordProtected: input.sessionMeta.passwordProtected,\n profileId: input.profileIdentity.openMeldProfileId,\n profileName: input.profileIdentity.profileName,\n profileKind: input.profileIdentity.kind,\n ownerUserId: input.profileIdentity.ownerUserId,\n ownerName: input.profileIdentity.ownerName,\n agentControllerRef: input.profileIdentity.agentControllerRef,\n agentControllerConversationId:\n input.profileIdentity.agentControllerConversationId,\n modelSelection: resolveSessionProfileModelSelection({\n profileId: input.profileIdentity.openMeldProfileId,\n spaceMembersSnapshot: store.getState().members.snapshot ?? undefined,\n }),\n spaceMembersSnapshot: store.getState().members.snapshot ?? undefined,\n gatewayUrl: input.baseUrl,\n stdio: true,\n visibility: input.sessionMeta.visibility,\n });\n interactiveIntroEmitted = true;\n };\n const shouldEmitInteractiveSessionMeta = (\n shellKind: InteractiveHumanShellKind\n ): boolean => {\n return shellKind === \"legacy\";\n };\n let watchReadyEmitted = false;\n const emitInteractiveWatchReady = (): void => {\n if (watchReadyEmitted) {\n return;\n }\n process.stdout.write(\n `${pc.dim(formatMessage(\"human\", \"connect.watch_ready\"))}\\n`\n );\n watchReadyEmitted = true;\n };\n\n try {\n const runtimeProcess = await runtime.start();\n\n if (shouldEmitInteractiveSessionMeta(preferredShellKind)) {\n emitInteractiveSessionMeta();\n }\n\n process.once(\"SIGINT\", onSigint);\n process.once(\"SIGTERM\", onSigterm);\n\n await historyReadyPromise;\n if (wsEnded) {\n await runtimeProcess.closed;\n return;\n }\n\n if (input.connectionMode === \"join\") {\n process.stdout.write(\"\\n\");\n process.stdout.write(\n `${pc.dim(formatMessage(\"human\", \"connect.chat_mention_hint\"))}\\n`\n );\n process.stdout.write(\n `${pc.dim(formatMessage(\"human\", \"connect.chat_ready\"))}\\n`\n );\n process.stdout.write(\n `${pc.dim(formatMessage(\"human\", \"connect.chat_exit_hint\"))}\\n`\n );\n process.stdout.write(\n `\\n${pc.dim(formatMessage(\"human\", \"connect.chat_prompt_question\"))}\\n`\n );\n } else if (preferredShellKind === \"legacy\") {\n process.stdout.write(\"\\n\");\n emitInteractiveWatchReady();\n }\n\n try {\n shell.start();\n if (!(shell instanceof PiTuiInteractiveSpaceShell)) {\n refreshCurrentViewState();\n }\n } catch (error) {\n if (activeShellKind !== \"pi-tui\") {\n throw error;\n }\n shell.stop();\n removeStoreListener();\n piTuiSessionMount = null;\n activeShellKind = \"legacy\";\n shell = createInteractiveHumanShell(\"legacy\");\n syncShellRenderSubscription();\n if (\n shouldEmitInteractiveSessionMeta(activeShellKind) &&\n !interactiveIntroEmitted\n ) {\n emitInteractiveSessionMeta();\n }\n if (input.connectionMode === \"watch\") {\n emitInteractiveWatchReady();\n }\n shell.prepareExternalWrite();\n input.presenter.line({\n code: \"connect.warn.interactive_shell_fallback\",\n text: pc.dim(\n `pi-tui composer fallback to legacy shell: ${toErrorMessage(error)}`\n ),\n });\n shell.start();\n refreshCurrentViewState();\n }\n\n await runtimeProcess.closed;\n } finally {\n process.off(\"SIGINT\", onSigint);\n process.off(\"SIGTERM\", onSigterm);\n if (replyingStatusSweepTimer) {\n clearTimeout(replyingStatusSweepTimer);\n replyingStatusSweepTimer = null;\n }\n clearMembersSnapshotRefreshTimer();\n clearSpaceMetaRefreshTimer();\n cancelLastSeenTimer();\n await flushLastSeen();\n shell.stop();\n removeRuntimeListener();\n removeStoreListener();\n }\n}\n\nfunction assertUnreachableComposerIntent(value: never): never {\n throw new Error(`Unhandled composer intent: ${JSON.stringify(value)}`);\n}\n\nfunction assertUnreachableRuntimeEvent(value: never): never {\n throw new Error(`Unhandled runtime event: ${JSON.stringify(value)}`);\n}\n\nfunction resolveLegacyPanelContentWidth(\n terminalWidth: number | undefined\n): number {\n const safeTerminalWidth = Math.max(40, terminalWidth ?? 100);\n const modalWidth = Math.max(1, Math.floor(safeTerminalWidth * 0.78));\n return Math.max(1, modalWidth - 4);\n}\n\nconst UNKNOWN_ERROR_MESSAGE = \"unknown error\";\n\ntype WebSocketCloseDetails = {\n code: number;\n codeLabel: string;\n reason: string;\n hint?: string;\n};\n\nconst WEBSOCKET_CLOSE_CODE_LABELS: Record<number, string> = {\n 1000: \"normal_closure\",\n 1001: \"going_away\",\n 1002: \"protocol_error\",\n 1003: \"unsupported_data\",\n 1005: \"no_status_received\",\n 1006: \"abnormal_closure\",\n 1007: \"invalid_frame_payload_data\",\n 1008: \"policy_violation\",\n 1009: \"message_too_big\",\n 1010: \"mandatory_extension\",\n 1011: \"internal_error\",\n 1012: \"service_restart\",\n 1013: \"try_again_later\",\n 1014: \"bad_gateway\",\n 1015: \"tls_handshake\",\n};\n\ntype WebSocketErrorDetails = {\n error: string;\n category?: string;\n hint?: string;\n};\n\nfunction toErrorMessage(err: unknown): string {\n if (typeof err === \"string\") {\n return normalizeErrorText(err) ?? UNKNOWN_ERROR_MESSAGE;\n }\n\n if (err instanceof AggregateError) {\n const aggregateMessage = toAggregateErrorMessage(err);\n if (aggregateMessage) {\n return aggregateMessage;\n }\n }\n\n if (err instanceof Error) {\n return toRegularErrorMessage(err) ?? UNKNOWN_ERROR_MESSAGE;\n }\n\n const codeMessage = toErrorCodeMessage(err);\n if (codeMessage) {\n return codeMessage;\n }\n\n return normalizeErrorText(String(err ?? \"\")) ?? UNKNOWN_ERROR_MESSAGE;\n}\n\nfunction resolveWebSocketCloseDetails(input: {\n code: number;\n reason: string;\n}): WebSocketCloseDetails {\n const codeLabel = WEBSOCKET_CLOSE_CODE_LABELS[input.code] ?? \"unknown_code\";\n const reason =\n normalizeErrorText(input.reason) ?? resolveDefaultCloseReason(input.code);\n const hint = resolveCloseHint(input.code);\n\n return {\n code: input.code,\n codeLabel,\n reason,\n ...(hint ? { hint } : {}),\n };\n}\n\nfunction resolveDefaultCloseReason(code: number): string {\n switch (code) {\n case 1000:\n return \"normal closure\";\n case 1001:\n return \"endpoint is going away\";\n case 1002:\n return \"protocol error\";\n case 1003:\n return \"unsupported data\";\n case 1005:\n return \"closed without a full close handshake\";\n case 1006:\n return \"connection dropped unexpectedly\";\n case 1007:\n return \"received invalid data\";\n case 1008:\n return \"policy violation\";\n case 1009:\n return \"message too big\";\n case 1010:\n return \"required connection feature missing\";\n case 1011:\n return \"server had an internal error\";\n case 1012:\n return \"service restart\";\n case 1013:\n return \"service is busy, try again in a moment\";\n case 1014:\n return \"bad gateway\";\n case 1015:\n return \"TLS handshake failure\";\n default:\n return \"no close reason provided\";\n }\n}\n\nfunction resolveCloseHint(code: number): string | undefined {\n switch (code) {\n case 1006:\n return \"this is usually a network issue or a temporary server restart\";\n case 1008:\n return \"the server rejected the request; check your login, profile, and space access\";\n case 1011:\n return \"the server hit an internal error; try again\";\n case 1012:\n return \"the service is restarting; wait a moment and try again\";\n case 1013:\n return \"the service is busy right now; wait a moment and try again\";\n default:\n return undefined;\n }\n}\n\nfunction buildHumanNormalLeaveCardLines(input: { spaceId: string }): string[] {\n const horizontalPadding = 0;\n const contentWidth = resolveLeaveCardContentWidth(horizontalPadding);\n const normalizedSpaceId = input.spaceId.trim();\n const rejoinCommand =\n normalizedSpaceId.length > 0\n ? formatOpenMeldCliCommand(`openmeld space join ${normalizedSpaceId}`)\n : formatOpenMeldCliCommand(\"openmeld space join <space-id>\");\n\n const rows = [\n {\n plainText: \"👋 Space Left\",\n displayText: \"👋 Space Left\",\n },\n ...createLeaveCardWrappedRows({\n text: \"You have left the space. (closed code=1000)\",\n contentWidth,\n }),\n ...createLeaveCardWrappedRows({\n text: \"If you are an agent, you might still be mentioned and spawned even if you have left the space.\",\n contentWidth,\n }),\n {\n plainText: \"\",\n displayText: \"\",\n },\n ...createLeaveCardWrappedRows({\n text: \"To re-join this space, run:\",\n contentWidth,\n }),\n {\n plainText: rejoinCommand,\n displayText: pc.cyan(rejoinCommand),\n },\n ];\n const renderedRows = rows.map((row) => row.displayText);\n return Array.from(\n { length: LEAVE_CARD_LEADING_BLANK_LINES },\n () => \"\"\n ).concat(renderedRows);\n}\n\nfunction emitHumanNormalLeaveCard(input: {\n spaceId: string;\n writeLine: (code: string, text: string) => void;\n}): void {\n const leaveCardLines = buildHumanNormalLeaveCardLines({\n spaceId: input.spaceId,\n });\n for (const [lineIndex, lineText] of leaveCardLines.entries()) {\n input.writeLine(`connect.closed_normal_leave.${lineIndex}`, lineText);\n }\n}\n\nfunction shouldRenderHumanNormalLeaveCard(input: {\n resolvedView: ResolvedCliView;\n closeCode: number;\n localCloseReason: string | null;\n exitCode: string | number | null | undefined;\n}): boolean {\n if (input.resolvedView !== \"human\") {\n return false;\n }\n if (input.exitCode === 1) {\n return false;\n }\n if (input.localCloseReason !== null) {\n return true;\n }\n return input.closeCode === 1000;\n}\n\nfunction resolveLeaveCardContentWidth(horizontalPadding: number): number {\n const terminalColumns =\n process.stdout.isTTY === true && typeof process.stdout.columns === \"number\"\n ? process.stdout.columns\n : null;\n if (terminalColumns === null || terminalColumns <= 0) {\n return LEAVE_CARD_FALLBACK_CONTENT_WIDTH;\n }\n const availableWidth = Math.max(\n LEAVE_CARD_MIN_CONTENT_WIDTH,\n terminalColumns - (horizontalPadding * 2 + 2)\n );\n return Math.min(LEAVE_CARD_MAX_CONTENT_WIDTH, availableWidth);\n}\n\nfunction createLeaveCardWrappedRows(input: {\n text: string;\n contentWidth: number;\n colorize?: (text: string) => string;\n}): Array<{ plainText: string; displayText: string }> {\n const wrappedLines = wrapTextForCard({\n text: input.text,\n width: input.contentWidth,\n });\n return wrappedLines.map((line) => ({\n plainText: line,\n displayText: input.colorize ? input.colorize(line) : line,\n }));\n}\n\nfunction wrapTextForCard(input: { text: string; width: number }): string[] {\n const normalized = input.text.replaceAll(/\\s+/g, \" \").trim();\n if (normalized.length === 0) {\n return [\"\"];\n }\n\n const words = normalized.split(\" \");\n const lines: string[] = [];\n let currentLine = \"\";\n\n for (const word of words) {\n if (word.length > input.width) {\n if (currentLine.length > 0) {\n lines.push(currentLine);\n currentLine = \"\";\n }\n for (let cursor = 0; cursor < word.length; cursor += input.width) {\n lines.push(word.slice(cursor, cursor + input.width));\n }\n continue;\n }\n\n const nextLine = currentLine ? `${currentLine} ${word}` : word;\n if (nextLine.length <= input.width) {\n currentLine = nextLine;\n continue;\n }\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n currentLine = word;\n }\n\n if (currentLine.length > 0) {\n lines.push(currentLine);\n }\n\n return lines.length > 0 ? lines : [\"\"];\n}\n\nfunction resolveWebSocketError(\n error: unknown,\n resolvedView: \"human\" | \"agent\"\n): WebSocketErrorDetails {\n const message = toErrorMessage(error);\n const hint = resolveWebSocketErrorHint(message, resolvedView);\n\n return {\n error: message,\n ...(hint ? { category: hint.category, hint: hint.message } : {}),\n };\n}\n\nfunction resolveWebSocketErrorHint(\n message: string,\n resolvedView: \"human\" | \"agent\"\n): { category: string; message: string } | null {\n const normalized = message.toLowerCase();\n const handshakeStatus = parseUnexpectedWebSocketResponseStatus(normalized);\n if (handshakeStatus !== null) {\n return resolveWebSocketHandshakeErrorHint(handshakeStatus, resolvedView);\n }\n\n if (normalized.includes(\"econnrefused\")) {\n return {\n category: \"connection_refused\",\n message:\n \"can't reach the gateway; make sure OpenMeld is running and the gateway URL is correct\",\n };\n }\n\n if (normalized.includes(\"enotfound\") || normalized.includes(\"eai_again\")) {\n return {\n category: \"dns_resolution_failed\",\n message:\n \"can't find the gateway host; check the URL and your DNS or network\",\n };\n }\n\n if (normalized.includes(\"etimedout\") || normalized.includes(\"timeout\")) {\n return {\n category: \"network_timeout\",\n message:\n \"opening the connection timed out; check your network or proxy and try again\",\n };\n }\n\n if (\n normalized.includes(\"econnreset\") ||\n normalized.includes(\"socket hang up\")\n ) {\n return {\n category: \"connection_reset\",\n message:\n \"the connection was reset while opening; this is usually a network issue or a server restart\",\n };\n }\n\n if (\n normalized.includes(\"self signed certificate\") ||\n normalized.includes(\"unable to verify the first certificate\")\n ) {\n return {\n category: \"tls_verification_failed\",\n message:\n \"couldn't verify the server certificate; use a trusted certificate or trusted endpoint\",\n };\n }\n\n return null;\n}\n\nfunction resolveWebSocketHandshakeErrorHint(\n handshakeStatus: number,\n resolvedView: \"human\" | \"agent\"\n): { category: string; message: string } | null {\n if (handshakeStatus === 401) {\n const guidance = resolveAuthenticationGuidance({\n reason: \"required\",\n action: \"joining a space\",\n });\n return {\n category: \"auth_required\",\n message:\n resolvedView === \"agent\"\n ? guidance.agentErrorMessage\n : guidance.errorNextStep,\n };\n }\n if (handshakeStatus === 403) {\n return {\n category: \"access_denied\",\n message: \"this profile may not have access to this space\",\n };\n }\n if (handshakeStatus === 404) {\n return {\n category: \"ws_route_not_found\",\n message:\n \"couldn't find the space stream endpoint; check the gateway URL and space ID\",\n };\n }\n if (handshakeStatus >= 500) {\n return {\n category: \"gateway_upstream_failure\",\n message:\n \"the server returned an error while opening the connection; try again\",\n };\n }\n return null;\n}\n\nfunction parseUnexpectedWebSocketResponseStatus(\n message: string\n): number | null {\n const match = WS_UNEXPECTED_SERVER_RESPONSE_REGEX.exec(message);\n if (!match) {\n return null;\n }\n const status = Number.parseInt(match[1] ?? \"\", 10);\n return Number.isFinite(status) ? status : null;\n}\n\nfunction toAggregateErrorMessage(error: AggregateError): string | null {\n const nestedMessages = error.errors\n .map((item) => toErrorMessage(item))\n .filter((message) => message !== UNKNOWN_ERROR_MESSAGE);\n if (nestedMessages.length === 0) {\n return null;\n }\n return [...new Set(nestedMessages)].join(\"; \");\n}\n\nfunction toRegularErrorMessage(error: Error): string | null {\n const message = normalizeErrorText(error.message);\n if (message) {\n return message;\n }\n\n const causeMessage = toErrorMessage(error.cause);\n if (causeMessage !== UNKNOWN_ERROR_MESSAGE) {\n return causeMessage;\n }\n\n const name = normalizeErrorText(error.name);\n if (name && name !== \"Error\") {\n return name;\n }\n\n return null;\n}\n\nfunction toErrorCodeMessage(error: unknown): string | null {\n if (!error || typeof error !== \"object\" || !(\"code\" in error)) {\n return null;\n }\n return normalizeErrorText(String((error as { code?: unknown }).code ?? \"\"));\n}\n\nfunction normalizeErrorText(value: string): string | null {\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return null;\n }\n}\n\nfunction parseJsonResponse<T>(raw: string, endpointName: string): T {\n try {\n return JSON.parse(raw) as T;\n } catch {\n throw new Error(`Invalid JSON response from ${endpointName} endpoint`);\n }\n}\n\nfunction isSpaceNotFoundHttpError(err: unknown): boolean {\n const parsed = parseHttpErrorMessage(err);\n if (!(parsed && parsed.status === 404)) {\n return false;\n }\n\n const bodyText = parsed.body.toLowerCase();\n if (bodyText.includes(\"space not found\")) {\n return true;\n }\n\n const body = safeJsonParse(parsed.body);\n if (!body || typeof body !== \"object\") {\n return false;\n }\n\n const payload = body as {\n code?: unknown;\n message?: unknown;\n error?: { code?: unknown; message?: unknown } | null;\n };\n const code = readHttpErrorField(payload, \"code\");\n const message = readHttpErrorField(payload, \"message\");\n\n return (\n code === \"space.not_found\" ||\n (code === \"upstream_error\" && message.toLowerCase() === \"space not found\")\n );\n}\n\nfunction parseHttpErrorMessage(\n error: unknown\n): { status: number; body: string } | null {\n const parsed = parseHttpFailure(error);\n if (!parsed) {\n return null;\n }\n return {\n status: parsed.status,\n body: parsed.body,\n };\n}\n\nfunction readHttpErrorField(\n payload: { code?: unknown; message?: unknown; error?: unknown },\n field: \"code\" | \"message\"\n): string {\n if (typeof payload[field] === \"string\") {\n return payload[field];\n }\n if (\n payload.error &&\n typeof payload.error === \"object\" &&\n typeof (payload.error as Record<string, unknown>)[field] === \"string\"\n ) {\n return String((payload.error as Record<string, unknown>)[field]);\n }\n return \"\";\n}\n\ntype ProfileSpaceHistorySyncInput = {\n openMeldProfileId: string;\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n gatewayHost: string;\n};\n\nasync function syncProfileSpaceHistoryActive(\n input: ProfileSpaceHistorySyncInput & {\n spaceMeta: SpaceMeta;\n lastSeenTs: number | null;\n }\n): Promise<void> {\n const creatorProfileId = resolveCreatorProfileId(input.spaceMeta.creator);\n const creatorKind = resolveCreatorKind(input.spaceMeta.creator?.kind);\n const spaceName = normalizeOptionalTrimmedText(input.spaceMeta.name);\n const spaceCreatedAt = normalizeOptionalIsoDateTime(\n input.spaceMeta.createdAt\n );\n const spaceUpdatedAt = normalizeOptionalIsoDateTime(\n input.spaceMeta.updatedAt\n );\n\n await upsertProfileSpaceHistory({\n baseUrl: input.baseUrl,\n requestContext: input.requestContext,\n openMeldProfileId: input.openMeldProfileId,\n spaceId: input.space,\n body: {\n gatewayHost: input.gatewayHost,\n ...(spaceName === undefined ? {} : { spaceName }),\n ...(creatorProfileId === undefined ? {} : { creatorProfileId }),\n ...(creatorKind === undefined ? {} : { creatorKind }),\n ...(spaceCreatedAt === undefined ? {} : { spaceCreatedAt }),\n ...(spaceUpdatedAt === undefined ? {} : { spaceUpdatedAt }),\n ...(typeof input.lastSeenTs === \"number\"\n ? { lastSeenTs: input.lastSeenTs }\n : {}),\n lastJoinedAt: new Date().toISOString(),\n status: \"active\",\n },\n });\n}\n\nasync function syncProfileSpaceHistoryStatusForJoinFailure(\n input: ProfileSpaceHistorySyncInput & {\n error: unknown;\n }\n): Promise<void> {\n const statusUpdate = resolveSpaceHistoryStatusFromJoinError(input.error);\n if (!statusUpdate) {\n return;\n }\n\n await updateProfileSpaceHistoryStatus({\n baseUrl: input.baseUrl,\n requestContext: input.requestContext,\n openMeldProfileId: input.openMeldProfileId,\n spaceId: input.space,\n body: {\n gatewayHost: input.gatewayHost,\n status: statusUpdate.status,\n ...(statusUpdate.reason ? { reason: statusUpdate.reason } : {}),\n },\n });\n}\n\nfunction resolveSpaceHistoryStatusFromJoinError(error: unknown): {\n status: \"removed\" | \"inaccessible\";\n reason?: string;\n} | null {\n const details = parseHttpErrorDetails(error);\n if (!details) {\n return null;\n }\n\n if (details.status === 404 && isSpaceNotFoundHttpError(error)) {\n return {\n status: \"removed\",\n ...(details.reason ? { reason: details.reason } : {}),\n };\n }\n\n const statusCode = details.status;\n if (statusCode === 401 || statusCode === 403) {\n return {\n status: \"inaccessible\",\n ...(details.reason ? { reason: details.reason } : {}),\n };\n }\n\n const errorCode = details.code.toLowerCase();\n if (errorCode === \"auth.unauthenticated\" || errorCode.includes(\"forbidden\")) {\n return {\n status: \"inaccessible\",\n ...(details.reason ? { reason: details.reason } : {}),\n };\n }\n\n return null;\n}\n\nfunction parseHttpErrorDetails(error: unknown): {\n status: number;\n code: string;\n reason: string | null;\n} | null {\n const parsed = parseHttpFailure(error);\n if (!parsed) {\n return null;\n }\n\n const code = parsed.code.trim();\n const message =\n normalizeErrorText(parsed.message) ?? normalizeErrorText(parsed.body);\n const reason = buildStatusReason(parsed.status, code, message);\n\n return {\n status: parsed.status,\n code,\n reason,\n };\n}\n\nfunction buildStatusReason(\n status: number,\n code: string,\n message: string | null\n): string | null {\n const summaryParts = [`http ${status}`];\n if (code) {\n summaryParts.push(code);\n }\n if (message) {\n summaryParts.push(message);\n }\n const summary = normalizeErrorText(summaryParts.join(\": \"));\n if (!summary) {\n return null;\n }\n if (summary.length <= 500) {\n return summary;\n }\n return summary.slice(0, 500);\n}\n\nfunction formatServerErrorFrameMessage(input: {\n error: string;\n requestId?: string;\n}): string {\n const error = String(input.error ?? \"\").trim() || \"unknown_error\";\n const requestId =\n typeof input.requestId === \"string\" ? input.requestId.trim() : \"\";\n if (!requestId) {\n return error;\n }\n return `${error} (requestId: ${requestId})`;\n}\n\nfunction acquireConnectLock(input: {\n openMeldProfileId: string;\n baseUrl: string;\n space: string;\n profileId: string;\n connectionMode: \"join\" | \"watch\";\n}) {\n const lockKey = resolveConnectLockKey(input);\n if (!lockKey) {\n return null;\n }\n return acquireLock({\n openMeldProfileId: input.openMeldProfileId,\n key: lockKey,\n meta: {\n mode: input.connectionMode,\n space: input.space,\n profileId: input.profileId,\n },\n }).then((lock) => ({\n lock,\n lockKey,\n }));\n}\n\nfunction resolveConnectLockKey(input: {\n baseUrl: string;\n space: string;\n profileId: string;\n connectionMode: \"join\" | \"watch\";\n}): string | null {\n if (input.connectionMode !== \"join\") {\n return null;\n }\n const gatewayHost = new URL(input.baseUrl).host;\n return `${gatewayHost}__${input.space}__${input.profileId}__join`;\n}\n\nfunction resolveConnectionModeOrThrow(\n connectionMode: \"join\" | \"watch\" | undefined\n): \"join\" | \"watch\" {\n if (connectionMode === \"join\" || connectionMode === \"watch\") {\n return connectionMode;\n }\n throw new Error(\"runConnect requires explicit connectionMode\");\n}\n\nfunction buildNoStdioEventData(input: {\n connectionMode: \"join\" | \"watch\";\n profileId: string;\n spaceId: string;\n sendCommand?: string;\n}): Record<string, unknown> {\n const payload: Record<string, unknown> = {\n connectionMode: input.connectionMode,\n profileId: input.profileId,\n spaceId: input.spaceId,\n };\n const sendCommand = String(input.sendCommand ?? \"\").trim();\n if (input.connectionMode === \"join\" && sendCommand.length > 0) {\n payload.sendCommand = sendCommand;\n }\n return payload;\n}\n\nfunction isSignalEnvelope(\n event: SignalEnvelope | HelloAck\n): event is SignalEnvelope {\n return \"id\" in event && typeof event.id === \"string\";\n}\n\nasync function applyFetchedSpaceMeta(input: {\n openMeldProfileId: string;\n baseUrl: string;\n space: string;\n profileHandle?: string;\n profileName: string;\n spaceMeta: SpaceMeta;\n output: OutputMode;\n rawStream: boolean;\n resolvedView: \"human\" | \"agent\";\n}): Promise<void> {\n await upsertSpaceConfig({\n openMeldProfileId: input.openMeldProfileId,\n baseUrl: input.baseUrl,\n space: input.space,\n profileHandle: input.profileHandle,\n profileName: input.profileName,\n ...toSpaceMetaUpsertInput(input.spaceMeta),\n });\n\n if (!(input.rawStream && input.output === \"ndjson\")) {\n emitSpaceGuide(input.spaceMeta, input.output, input.resolvedView);\n }\n}\n\ntype SessionMetaOutputInput = {\n accessMode?: SpaceMeta[\"accessMode\"];\n output: OutputMode;\n spaceId: string;\n spaceName?: string;\n spaceCreatedAt?: string;\n spaceCreatorName?: string;\n spaceCreatorId?: string;\n passwordProtected?: boolean;\n profileId: string;\n profileName: string;\n profileKind?: \"human\" | \"agent\" | \"system\";\n ownerUserId?: string;\n ownerName?: string;\n agentControllerRef?: string;\n agentControllerConversationId?: string;\n modelSelection?: AgentProfileBindingModelSelection | null;\n spaceMembersSnapshot?: SpaceMembersSnapshot;\n gatewayUrl: string;\n stdio: boolean;\n visibility?: SpaceMeta[\"visibility\"];\n};\n\nfunction emitSessionMeta(input: SessionMetaOutputInput): void {\n if (input.output === \"ndjson\") {\n outJsonLine(buildSessionMetaEventPayload(input));\n return;\n }\n\n if (input.output !== \"text\") {\n return;\n }\n\n emitSessionMetaText(input);\n}\n\nfunction emitSessionMetaText(input: SessionMetaOutputInput): void {\n for (const line of formatConnectIntro({\n accessMode: input.accessMode,\n spaceId: input.spaceId,\n spaceName: input.spaceName,\n spaceCreatedAt: input.spaceCreatedAt,\n spaceCreatorName: input.spaceCreatorName,\n spaceCreatorId: input.spaceCreatorId,\n passwordProtected: input.passwordProtected,\n profileId: input.profileId,\n profileName: input.profileName,\n profileKind: input.profileKind,\n ownerUserId: input.ownerUserId,\n ownerName: input.ownerName,\n agentControllerRef: input.agentControllerRef,\n agentControllerConversationId: input.agentControllerConversationId,\n modelSelection: input.modelSelection,\n spaceMembersSnapshot: input.spaceMembersSnapshot,\n gatewayUrl: input.gatewayUrl,\n stdio: input.stdio,\n visibility: input.visibility,\n })) {\n errLine(line);\n }\n}\n\nfunction buildSessionMetaEventPayload(\n input: SessionMetaOutputInput\n): Record<string, unknown> {\n return buildAgentSessionMetaPayload({\n accessMode: input.accessMode,\n gatewayUrl: input.gatewayUrl,\n mode: input.stdio ? \"interactive chat\" : \"watch-only stream\",\n passwordProtected: input.passwordProtected,\n agentControllerConversationId: input.agentControllerConversationId,\n agentControllerRef: input.agentControllerRef,\n modelSelection: input.modelSelection,\n profileId: input.profileId,\n profileKind: input.profileKind,\n profileName: input.profileName,\n ownerName: input.ownerName,\n ownerUserId: input.ownerUserId,\n spaceCreatedAt: input.spaceCreatedAt,\n spaceCreatorId: input.spaceCreatorId,\n spaceCreatorName: input.spaceCreatorName,\n spaceId: input.spaceId,\n spaceName: input.spaceName,\n visibility: input.visibility,\n });\n}\n\nfunction resolveSessionProfileModelSelection(input: {\n profileId: string;\n spaceMembersSnapshot?: SpaceMembersSnapshot;\n}): AgentProfileBindingModelSelection | null {\n return (\n input.spaceMembersSnapshot?.agents.find(\n (agent) => agent.profileId === input.profileId\n )?.modelSelection ?? null\n );\n}\n\nfunction emitSpaceMembers(snapshot: SpaceMembersSnapshot): void {\n outJsonLine({\n type: \"system.space.members\",\n payload: snapshot,\n });\n}\nfunction errBlock(text: string): void {\n process.stderr.write(`${text}\\n`);\n}\n\nfunction emitSpaceGuide(\n meta: SpaceMeta,\n output: OutputMode,\n resolvedView: \"human\" | \"agent\"\n): void {\n const rawGuide = String(meta.guide ?? \"\").trim();\n if (!rawGuide) {\n return;\n }\n\n if (output === \"ndjson\") {\n outJsonLine({\n type: \"system.space.guide\",\n spaceId: meta.spaceId,\n guide: rawGuide,\n ...(meta.creator ? { creator: meta.creator } : {}),\n });\n return;\n }\n\n const guide = sanitizeTerminalDisplayText(rawGuide, \"multi-line\");\n\n errLine(\n formatMessage(resolvedView, \"connect.space_guide\", {\n spaceId: meta.spaceId,\n })\n );\n errBlock(guide);\n}\n\nasync function fetchSpaceCursor(input: {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n}): Promise<SpaceCursor> {\n const endpoint = toSpaceCursorUrl(\n input.baseUrl,\n input.space,\n input.requestContext.actorContext.openMeldProfileId\n );\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.connect_fetch_cursor\",\n init: {\n method: \"GET\",\n headers: await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n }),\n },\n });\n\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n return parseJsonResponse<SpaceCursor>(raw, \"space cursor\");\n}\n\nasync function updateSpaceCursor(input: {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n lastSeenTs?: number;\n role?: string;\n mentionAlias?: string;\n}): Promise<SpaceCursor> {\n const endpoint = toSpaceCursorUrl(\n input.baseUrl,\n input.space,\n input.requestContext.actorContext.openMeldProfileId\n );\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n const cursorPatch = normalizeSpaceCursorPatch({\n ...(typeof input.lastSeenTs === \"number\"\n ? { lastSeenTs: input.lastSeenTs }\n : {}),\n ...(typeof input.role === \"string\" ? { role: input.role } : {}),\n ...(typeof input.mentionAlias === \"string\"\n ? { mentionAlias: input.mentionAlias }\n : {}),\n });\n if (!cursorPatch.ok) {\n throw new Error(cursorPatch.message);\n }\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.connect_update_cursor\",\n init: {\n method: \"PATCH\",\n headers,\n body: JSON.stringify(cursorPatch.value),\n },\n });\n\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n return parseJsonResponse<SpaceCursor>(raw, \"space cursor\");\n}\n\nfunction buildChatGroupDividerLine(): string {\n if (process.stdout.isTTY !== true) {\n return \"\";\n }\n const columns = resolveTerminalColumns();\n const width = clampNumber(\n columns - CHAT_GROUP_DIVIDER_MARGIN * 2,\n CHAT_GROUP_DIVIDER_MIN_WIDTH,\n CHAT_GROUP_DIVIDER_MAX_WIDTH\n );\n const margin = \" \".repeat(CHAT_GROUP_DIVIDER_MARGIN);\n return pc.dim(pc.gray(`${margin}${CHAT_GROUP_DIVIDER_CHAR.repeat(width)}`));\n}\n\nfunction resolveTerminalColumns(): number {\n const rawColumns = process.stdout.columns;\n if (!Number.isInteger(rawColumns) || rawColumns < 1) {\n return 80;\n }\n return rawColumns;\n}\n\nfunction clampNumber(value: number, min: number, max: number): number {\n if (value < min) {\n return min;\n }\n if (value > max) {\n return max;\n }\n return value;\n}\n\nfunction shouldRefreshMembersSnapshotForEvent(\n event: SignalEnvelope | HelloAck\n): boolean {\n if (!isSignalEnvelope(event)) {\n return false;\n }\n\n if (event.type === \"presence.join\" || event.type === \"presence.quit\") {\n return true;\n }\n\n if (event.type !== \"signal.text\") {\n return false;\n }\n\n const meta = resolveSignalTextMetaFromEnvelope(event);\n const purpose = String(meta?.purpose ?? \"\").trim();\n if (\n purpose === SPACE_MEMBER_JOIN_NOTICE_PURPOSE ||\n purpose === SPACE_MEMBER_REMOVE_NOTICE_PURPOSE\n ) {\n return true;\n }\n\n return false;\n}\n\nfunction shouldRefreshSpaceMetaForEvent(\n event: SignalEnvelope | HelloAck\n): boolean {\n if (!isSignalEnvelope(event)) {\n return false;\n }\n\n if (event.type === \"presence.join\" || event.type === \"presence.quit\") {\n return true;\n }\n\n return resolveNonTransientSignalText(event) !== null;\n}\n\nfunction ignoreAsyncResult(promise: Promise<void>): void {\n promise.catch(() => undefined);\n}\n\nfunction listSpaceMemberProfileIds(snapshot: SpaceMembersSnapshot): string[] {\n return [...snapshot.agents, ...snapshot.humans].map(\n (member) => member.profileId\n );\n}\n","import type {\n OpenMeldRequestContext,\n SpaceIdentityDirectory,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport { buildSignalIndex, type SpaceSignalIndex } from \"@openmeld/space\";\nimport type { SpaceApi } from \"../cli-space-api\";\n\nexport function withResolvedSpacePassword(spacePassword: string | undefined) {\n return spacePassword === undefined ? {} : { spacePassword };\n}\n\nexport function buildIdentityOnlyMembersSnapshotForReadProjection(\n identityDirectory: SpaceIdentityDirectory | null\n): SpaceMembersSnapshot | null {\n if (!identityDirectory) {\n return null;\n }\n\n const humans = identityDirectory.entries\n .filter((entry) => entry.profileKind === \"human\")\n .map((entry) => ({\n profileId: entry.profileId,\n profileName: entry.profileName,\n profileKind: \"human\" as const,\n status: \"active\" as const,\n memberSource: \"backfilled\" as const,\n memberSourceLabel: \"Member\",\n addedAt: identityDirectory.generatedAt,\n removedAt: null,\n createdAt: identityDirectory.generatedAt,\n updatedAt: identityDirectory.generatedAt,\n addedByProfileId: null,\n addedByOwnerUserId: null,\n addedByDisplayName: null,\n removedByProfileId: null,\n removedByOwnerUserId: null,\n removalReason: null,\n firstEnteredAt: null,\n lastEnteredAt: null,\n lastSeenAt: null,\n lastSeenLabel: null,\n liveNow: false,\n mentionAlias: entry.mentionAlias,\n ownerUserId: entry.ownerUserId,\n ownerName: entry.ownerName,\n }));\n const agents = identityDirectory.entries\n .filter((entry) => entry.profileKind === \"agent\")\n .map((entry) => ({\n profileId: entry.profileId,\n profileName: entry.profileName,\n profileKind: \"agent\" as const,\n status: \"active\" as const,\n memberSource: \"backfilled\" as const,\n memberSourceLabel: \"Member\",\n addedAt: identityDirectory.generatedAt,\n removedAt: null,\n createdAt: identityDirectory.generatedAt,\n updatedAt: identityDirectory.generatedAt,\n addedByProfileId: null,\n addedByOwnerUserId: null,\n addedByDisplayName: null,\n removedByProfileId: null,\n removedByOwnerUserId: null,\n removalReason: null,\n firstEnteredAt: null,\n lastEnteredAt: null,\n lastSeenAt: null,\n lastSeenLabel: null,\n liveNow: false,\n mentionAlias: entry.mentionAlias,\n ownerUserId: entry.ownerUserId,\n ownerName: entry.ownerName,\n agentControllerRef: entry.agentControllerRef,\n agentControllerConversationId: null,\n }));\n\n return {\n spaceId: identityDirectory.spaceId,\n generatedAt: identityDirectory.generatedAt,\n summary: {\n totalCount: humans.length + agents.length,\n humanCount: humans.length,\n agentCount: agents.length,\n liveNowCount: 0,\n },\n humans,\n agents,\n };\n}\n\nexport async function loadSpaceMembersSnapshotOrNull(input: {\n spaceApi: SpaceApi;\n spaceId: string;\n requestContext: OpenMeldRequestContext;\n resolvedPassword: string | undefined;\n required?: boolean;\n skip?: boolean;\n}): Promise<SpaceMembersSnapshot | null> {\n if (input.skip === true) {\n return null;\n }\n\n try {\n return await input.spaceApi.getMembersSnapshot({\n spaceId: input.spaceId,\n requestContext: input.requestContext,\n ...withResolvedSpacePassword(input.resolvedPassword),\n });\n } catch (error) {\n if (input.required) {\n throw error;\n }\n return null;\n }\n}\n\nexport async function loadSpaceIdentityDirectoryOrNull(input: {\n spaceApi: SpaceApi;\n spaceId: string;\n requestContext: OpenMeldRequestContext;\n resolvedPassword: string | undefined;\n required?: boolean;\n skip?: boolean;\n}): Promise<SpaceIdentityDirectory | null> {\n if (input.skip === true) {\n return null;\n }\n\n try {\n return await input.spaceApi.getIdentityDirectory({\n spaceId: input.spaceId,\n requestContext: input.requestContext,\n ...withResolvedSpacePassword(input.resolvedPassword),\n });\n } catch (error) {\n if (input.required) {\n throw error;\n }\n return null;\n }\n}\n\nexport async function loadSpaceSignalIndexOrNull(input: {\n spaceApi: SpaceApi;\n spaceId: string;\n requestContext: OpenMeldRequestContext;\n resolvedPassword: string | undefined;\n required?: boolean;\n skip?: boolean;\n}): Promise<SpaceSignalIndex | null> {\n if (input.skip === true) {\n return null;\n }\n\n try {\n const signalEnvelopeResponse = await input.spaceApi.listSignalEnvelopes({\n spaceId: input.spaceId,\n requestContext: input.requestContext,\n ...withResolvedSpacePassword(input.resolvedPassword),\n });\n return buildSignalIndex(signalEnvelopeResponse.envelopes);\n } catch (error) {\n if (input.required) {\n throw error;\n }\n return null;\n }\n}\n","import type { SignalEnvelope } from \"@openmeld/protocol\";\nimport type { SpaceMembersSnapshot } from \"@openmeld/schemas/types\";\nimport { buildSignalIndex, type SpaceSignalIndex } from \"@openmeld/space\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { formatMessage, type MessageKey } from \"../runtime/messages\";\nimport type { Presenter } from \"../runtime/presenter\";\nimport type { SpaceSignalThreadSummary } from \"./read-projection/formal-message-read-output\";\nimport {\n buildSpaceSessionProfileContext,\n buildSpaceSessionProfileIdentity,\n rememberMembersSnapshotOwnerDisplayNames,\n rememberSessionOwnerDisplayName,\n} from \"./session-profile\";\nimport { buildHumanTranscriptItemFromEvent } from \"./transcript/transcript-item-builder\";\nimport {\n buildHumanTranscriptProjection,\n renderTranscriptBlocks,\n} from \"./transcript/transcript-render\";\n\nexport function buildHumanReadSignalsTranscriptItems(input: {\n openMeldProfile: OpenMeldProfile;\n events: readonly SignalEnvelope[];\n membersSnapshot: SpaceMembersSnapshot | null;\n signalIndex?: SpaceSignalIndex | null;\n spaceId?: string;\n threadByRootSignalId?: ReadonlyMap<string, SpaceSignalThreadSummary> | null;\n}) {\n const ownerDisplayNameByUserId = new Map<string, string>();\n rememberSessionOwnerDisplayName(\n ownerDisplayNameByUserId,\n input.openMeldProfile\n );\n rememberMembersSnapshotOwnerDisplayNames(\n ownerDisplayNameByUserId,\n input.membersSnapshot\n );\n const sessionProfileIdentity = buildSpaceSessionProfileIdentity({\n openMeldProfile: input.openMeldProfile,\n });\n const signalIndex = input.signalIndex ?? buildSignalIndex(input.events);\n\n return input.events.flatMap((event) => {\n const transcriptItem = buildHumanTranscriptItemFromEvent({\n event,\n selfProfileId: input.openMeldProfile.openMeldProfileId,\n sessionProfileIdentity,\n signalIndex,\n ownerDisplayNameByUserId,\n spaceId: input.spaceId,\n spaceMembersSnapshot: input.membersSnapshot,\n threadSummary: input.threadByRootSignalId?.get(event.id) ?? null,\n });\n return transcriptItem ? [transcriptItem] : [];\n });\n}\n\nexport function emitHumanReadSignalsTextProjection(input: {\n openMeldProfile: OpenMeldProfile;\n presenter: Presenter;\n transcriptItems: ReturnType<typeof buildHumanReadSignalsTranscriptItems>;\n membersSnapshot: SpaceMembersSnapshot | null;\n emptyCode?: MessageKey;\n focusedSummary?: string | null;\n}): void {\n const projection = buildHumanTranscriptProjection({\n items: input.transcriptItems,\n membersSnapshot: input.membersSnapshot,\n sessionProfile: buildSpaceSessionProfileContext(input.openMeldProfile),\n });\n const renderWidth = Math.max(process.stdout.columns ?? 100, 40);\n const transcriptLines = renderTranscriptBlocks(\n projection.transcriptBlocks,\n renderWidth\n );\n\n for (const line of transcriptLines) {\n input.presenter.line({\n code: \"tail.signal.text\",\n text: line,\n });\n }\n\n const focusedSummary = String(input.focusedSummary ?? \"\").trim();\n if (focusedSummary) {\n input.presenter.line({\n code: \"tail.history.focused_summary\",\n text: focusedSummary,\n });\n }\n\n if (transcriptLines.length > 0 || focusedSummary) {\n return;\n }\n\n const emptyCode = input.emptyCode ?? \"tail.empty\";\n input.presenter.line({\n code: emptyCode,\n text: formatMessage(\"human\", emptyCode),\n });\n}\n","import type { SpacePanelKind } from \"../../panel/space-panel-definition\";\nimport type { SpaceScreenStore } from \"../../state/space-screen-store\";\nimport type {\n SpaceSessionContext,\n SpaceSessionDiagnosticsViewState,\n} from \"../../view/space-session-view-state\";\nimport { mountPiTuiSessionShell } from \"./mount-pi-tui-session-shell\";\nimport { PiTuiInteractiveSpaceShell } from \"./pi-tui-interactive-space-shell\";\n\ntype ReadonlyPiTuiSessionResources = {\n sessionDiagnostics?: SpaceSessionDiagnosticsViewState;\n};\n\nexport async function runReadonlyPiTuiSession(input: {\n context: SpaceSessionContext;\n getResources?: () => ReadonlyPiTuiSessionResources;\n store: SpaceScreenStore;\n syncOverlayInteraction?: (kind: SpacePanelKind) => void;\n}): Promise<void> {\n let resolveClosed: (() => void) | null = null;\n const closedPromise = new Promise<void>((resolve) => {\n resolveClosed = resolve;\n });\n const shell = new PiTuiInteractiveSpaceShell({\n onBufferChange: () => undefined,\n onClose: () => {\n resolveClosed?.();\n },\n onOpenOverlay: (kind) => {\n input.store.dispatch({\n type: \"overlay.interaction.reset\",\n });\n input.store.dispatch({\n type: \"overlay.opened\",\n kind,\n openedAtMs: Date.now(),\n });\n input.syncOverlayInteraction?.(kind);\n },\n onOverlayActiveItemChange: (activeItemId) => {\n input.store.dispatch({\n type: \"overlay.active-item.updated\",\n activeItemId,\n });\n },\n onOverlayClose: () => {\n input.store.dispatch({\n type: \"overlay.closed\",\n });\n },\n onOverlayQueryChange: (query) => {\n input.store.dispatch({\n type: \"overlay.query.updated\",\n query,\n });\n input.syncOverlayInteraction?.(\"members\");\n },\n onSubmit: () => undefined,\n });\n const { removeStoreListener } = mountPiTuiSessionShell({\n context: input.context,\n getResources: input.getResources,\n shell,\n store: input.store,\n });\n\n try {\n shell.start();\n await closedPromise;\n } finally {\n removeStoreListener();\n shell.stop();\n }\n}\n","import type { SignalEnvelope, SpaceMeta } from \"@openmeld/protocol\";\nimport type {\n SpaceIdentityDirectory,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport {\n buildSignalIndex,\n buildSignalMessageReadProjection,\n type SpaceSignalIndex,\n} from \"@openmeld/space\";\nimport { resolveBaseUrl } from \"../config/base-url\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { buildOpenMeldRequestContextFromProfile } from \"../config/openmeld-request-context\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport { requireOpenMeldProfile } from \"../config/resolve-openmeld-profile\";\nimport { toSpaceMetaUrl } from \"../protocol/urls\";\nimport { parseEnvelope } from \"../protocol/wire\";\nimport { formatOpenMeldCliCommand } from \"../runtime/cli-entry-command\";\nimport { resolveRuntimeContext } from \"../runtime/context\";\nimport { formatMessage } from \"../runtime/messages\";\nimport { createPresenter } from \"../runtime/presenter/index\";\nimport { outJsonLine } from \"../ui/io\";\nimport { formatTextEvent } from \"../ui/output\";\nimport {\n buildAgentSessionMetaPayload,\n normalizeAgentOutputEvent,\n} from \"./agent-output-contract\";\nimport { createCliSpaceApi, type SpaceSignalsReadQuery } from \"./cli-space-api\";\nimport { assertFullSignalIdArgument } from \"./command-context\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { resolveMembersSearchableActiveItemId } from \"./panel/space-panel-content\";\nimport {\n buildFormalSignalReadPayload,\n type SpaceSignalThreadReplyPreview,\n type SpaceSignalThreadSummary,\n} from \"./read-projection/formal-message-read-output\";\nimport {\n buildIdentityOnlyMembersSnapshotForReadProjection,\n loadSpaceIdentityDirectoryOrNull,\n loadSpaceSignalIndexOrNull,\n} from \"./read-projection/space-read-projection-context\";\nimport {\n buildHumanReadSignalsTranscriptItems,\n emitHumanReadSignalsTextProjection,\n} from \"./read-signals-output\";\nimport {\n buildActiveSpaceSessionContext,\n buildSpaceSessionProfileContext,\n} from \"./session-profile\";\nimport { runReadonlyPiTuiSession } from \"./shell/pi-tui/run-readonly-pi-tui-session\";\nimport { parseSpaceMetaResponse } from \"./space-meta-response\";\nimport { createSpaceScreenStore } from \"./state/space-screen-store\";\nimport { buildHumanTranscriptProjection } from \"./transcript/transcript-render\";\n\nexport type SpaceHistorySignalKind = NonNullable<\n SpaceSignalsReadQuery[\"kinds\"]\n>[number];\n\nexport const SPACE_HISTORY_BRIEF_TEXT_MAX_CHARACTERS = 1200;\nconst SPACE_HISTORY_BRIEF_TRUNCATION_MARKER = \"…\";\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: Tail keeps protocol parsing and dual-view emission in one flow.\nexport async function runTail(input: {\n profile?: string;\n openMeldProfile?: OpenMeldProfile;\n baseUrl?: string;\n space: string;\n password?: string;\n limit: number;\n brief?: boolean;\n json: boolean;\n rawStream?: boolean;\n view?: string;\n afterSignalId?: string;\n aroundSignalId?: string;\n beforeCount?: number;\n afterCount?: number;\n fromProfileIds?: readonly string[];\n kinds?: readonly SpaceHistorySignalKind[];\n}) {\n if (!Number.isInteger(input.limit) || input.limit < 0) {\n throw new Error(\"limit must be a non-negative integer\");\n }\n\n const runtime = await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n });\n const presenter = createPresenter(runtime);\n\n assertFullSignalIdArgument({\n value: input.afterSignalId,\n flag: \"--after-signal\",\n resolvedView: runtime.resolvedView,\n });\n assertFullSignalIdArgument({\n value: input.aroundSignalId,\n flag: \"--around-signal\",\n resolvedView: runtime.resolvedView,\n });\n\n const openMeldProfile =\n input.openMeldProfile ??\n (await requireOpenMeldProfile({\n openMeldProfileId: input.profile,\n persistSelection: false,\n authAction: \"viewing space history\",\n }));\n const baseUrl = await resolveBaseUrl(input.baseUrl);\n const spaceApi = createCliSpaceApi(baseUrl);\n const space = input.space.trim();\n const historyQuery = buildHistoryReadQuery(input);\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile,\n });\n const parsedResponse = await spaceApi.listSignals({\n spaceId: space,\n requestContext,\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n query: historyQuery,\n });\n const parsedEnvelopes = parsedResponse.signals.flatMap((item: unknown) => {\n const env = parseEnvelope(item);\n return env ? [env] : [];\n });\n let signalIndex = buildSignalIndex(parsedEnvelopes);\n const agentRawContract = runtime.resolvedView === \"agent\";\n const spaceMeta = await fetchHistorySpaceMeta({\n requestContext,\n baseUrl,\n password: input.password,\n space,\n }).catch(() => null);\n const identityDirectory = await loadSpaceIdentityDirectoryOrNull({\n spaceApi,\n spaceId: space,\n requestContext,\n resolvedPassword: input.password,\n });\n const identityOnlyMembersSnapshot =\n buildIdentityOnlyMembersSnapshotForReadProjection(identityDirectory);\n if (\n shouldPromoteHistorySignalIndex({\n identityDirectory,\n signals: parsedEnvelopes,\n signalIndex,\n })\n ) {\n signalIndex =\n (await loadSpaceSignalIndexOrNull({\n spaceApi,\n spaceId: space,\n requestContext,\n resolvedPassword: input.password,\n required: true,\n })) ?? signalIndex;\n }\n if (input.brief === true) {\n const threadByRootSignalId = await loadThreadSummaryByRootSignalId({\n spaceApi,\n spaceId: space,\n requestContext,\n password: input.password,\n });\n outJsonLine(\n buildSpaceHistoryBriefPayload({\n openMeldProfile,\n events: parsedEnvelopes,\n identityDirectory,\n signalIndex,\n spaceId: space,\n threadByRootSignalId,\n })\n );\n return;\n }\n const canUseHumanHistoryPiTui =\n runtime.resolvedView === \"human\" &&\n !input.json &&\n process.stdin.isTTY === true &&\n process.stdout.isTTY === true;\n if (runtime.resolvedView === \"human\" && !input.json) {\n const threadByRootSignalId = await loadThreadSummaryByRootSignalId({\n spaceApi,\n spaceId: space,\n requestContext,\n password: input.password,\n });\n const transcriptItems = buildHumanReadSignalsTranscriptItems({\n openMeldProfile,\n events: parsedEnvelopes,\n membersSnapshot: identityOnlyMembersSnapshot,\n signalIndex,\n spaceId: space,\n threadByRootSignalId,\n });\n const transcriptProjection = buildHumanTranscriptProjection({\n items: transcriptItems,\n membersSnapshot: identityOnlyMembersSnapshot,\n sessionProfile: buildSpaceSessionProfileContext(openMeldProfile),\n });\n if (canUseHumanHistoryPiTui) {\n await runHumanHistoryPiTuiViewer({\n openMeldProfile,\n baseUrl,\n membersSnapshot: identityOnlyMembersSnapshot,\n password: input.password,\n space,\n spaceMeta,\n transcriptItems,\n });\n return;\n }\n emitHumanReadSignalsTextProjection({\n openMeldProfile,\n presenter,\n transcriptItems,\n membersSnapshot: identityOnlyMembersSnapshot,\n focusedSummary: buildFocusedHistorySummary({\n systemNoticeCount:\n transcriptProjection.hiddenSummary.hiddenSystemNoticeCount,\n }),\n });\n return;\n }\n const shouldEmitFullEnvelope = input.json || agentRawContract;\n const spaceMembersSnapshot = shouldEmitFullEnvelope\n ? null\n : identityOnlyMembersSnapshot;\n if (agentRawContract && spaceMeta) {\n outJsonLine(\n buildAgentSessionMetaPayload({\n accessMode: spaceMeta.accessMode,\n gatewayUrl: baseUrl,\n mode: \"history viewer\",\n passwordProtected: spaceMeta.passwordProtected,\n agentControllerConversationId: undefined,\n agentControllerRef: undefined,\n profileId: openMeldProfile.openMeldProfileId,\n profileKind: openMeldProfile.profileKind,\n profileName: openMeldProfile.profileName,\n ownerName: openMeldProfile.ownerName,\n ownerUserId: openMeldProfile.ownerUserId,\n spaceCreatedAt: spaceMeta.createdAt,\n spaceCreatorId: spaceMeta.creator?.profileId,\n spaceCreatorName: spaceMeta.creator?.profileName,\n spaceId: space,\n spaceName: spaceMeta.name,\n visibility: spaceMeta.visibility,\n })\n );\n }\n const threadByRootSignalId = await loadThreadSummaryByRootSignalId({\n spaceApi,\n spaceId: space,\n requestContext,\n password: input.password,\n });\n let emitted = 0;\n for (const env of parsedEnvelopes) {\n emitted += 1;\n\n if (agentRawContract) {\n outJsonLine(\n buildFormalSignalReadPayload({\n signal: normalizeAgentOutputEvent(env) as SignalEnvelope,\n identityDirectory,\n signalIndex,\n thread: threadByRootSignalId.get(env.id) ?? null,\n })\n );\n continue;\n }\n\n if (shouldEmitFullEnvelope) {\n presenter.data({\n code: \"tail.signal\",\n payload: buildFormalSignalReadPayload({\n signal: env,\n identityDirectory,\n signalIndex,\n thread: threadByRootSignalId.get(env.id) ?? null,\n }),\n });\n continue;\n }\n\n const textLine = formatTextEvent(env, {\n view: runtime.resolvedView,\n selfProfileId: openMeldProfile.openMeldProfileId,\n spaceMembersSnapshot,\n });\n if (textLine) {\n presenter.line({\n code:\n env.type === \"signal.text\" ? \"tail.signal.text\" : \"tail.signal.other\",\n text: textLine,\n data: env,\n });\n continue;\n }\n\n presenter.line({\n code: \"tail.signal.other\",\n text: `${env.type} (${env.profile?.profileId ?? \"unknown\"})`,\n data: env,\n });\n }\n\n if (emitted !== 0) {\n return;\n }\n\n if (agentRawContract) {\n return;\n }\n\n const emptyText = formatMessage(runtime.resolvedView, \"tail.empty\");\n if (shouldEmitFullEnvelope) {\n presenter.data({\n code: \"tail.empty\",\n payload: { text: emptyText },\n });\n return;\n }\n\n presenter.line({\n code: \"tail.empty\",\n text: emptyText,\n });\n}\n\nasync function loadThreadSummaryByRootSignalId(input: {\n spaceApi: ReturnType<typeof createCliSpaceApi>;\n spaceId: string;\n requestContext: import(\"@openmeld/schemas/types\").OpenMeldRequestContext;\n password?: string;\n}): Promise<Map<string, SpaceSignalThreadSummary>> {\n const map = new Map<string, SpaceSignalThreadSummary>();\n try {\n const response = await input.spaceApi.listThreads({\n spaceId: input.spaceId,\n requestContext: input.requestContext,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n const previewByThreadId = new Map(\n response.previews.map((preview) => [preview.threadId, preview] as const)\n );\n for (const thread of response.threads) {\n const preview = previewByThreadId.get(thread.threadId);\n map.set(thread.rootSignalId, {\n threadId: thread.threadId,\n replyCount: preview?.replyCount ?? 0,\n replyPreviews: buildThreadReplyPreviews(preview?.signals ?? []),\n });\n }\n } catch {\n // fail-soft: thread metadata is decorative; history must still render\n // even when the thread listing call fails.\n return map;\n }\n return map;\n}\n\n// Backend thread previews return the earliest signals (ORDER BY created_at ASC,\n// capped server-side). We surface the first N as a lightweight preview, so this\n// is \"earliest N\", not \"latest N\" — slice direction and naming stay aligned with\n// the server contract to avoid a hidden dependency on the server-side cap value.\nconst THREAD_REPLY_PREVIEW_LIMIT = 2;\n\nfunction buildThreadReplyPreviews(\n rawSignals: readonly unknown[]\n): SpaceSignalThreadReplyPreview[] {\n const parsed = rawSignals\n .slice(0, THREAD_REPLY_PREVIEW_LIMIT)\n .flatMap((item) => {\n const env = parseEnvelope(item);\n return env ? [env] : [];\n });\n const localIndex = buildSignalIndex(parsed);\n return parsed.map((signal) => {\n const projection = isMessageSemanticSignal(signal)\n ? buildSignalMessageReadProjection({\n signal,\n identityDirectory: null,\n signalIndex: localIndex,\n })\n : null;\n return {\n actorProfileId: signal.profile?.profileId ?? null,\n actorProfileName: signal.profile?.profileName ?? null,\n text: projection?.text ?? null,\n };\n });\n}\n\nfunction buildHistoryReadQuery(input: {\n limit: number;\n afterSignalId?: string;\n aroundSignalId?: string;\n beforeCount?: number;\n afterCount?: number;\n fromProfileIds?: readonly string[];\n kinds?: readonly SpaceHistorySignalKind[];\n}): {\n recent?: boolean;\n limit?: number;\n afterSignalId?: string;\n aroundSignalId?: string;\n beforeCount?: number;\n afterCount?: number;\n fromProfileIds?: readonly string[];\n kinds?: readonly SpaceHistorySignalKind[];\n} {\n const hasAfterSignal = Boolean(String(input.afterSignalId ?? \"\").trim());\n const hasAroundSignal = Boolean(String(input.aroundSignalId ?? \"\").trim());\n return {\n ...(hasAfterSignal\n ? {\n afterSignalId: input.afterSignalId,\n limit: input.limit,\n }\n : {}),\n ...(hasAroundSignal\n ? {\n aroundSignalId: input.aroundSignalId,\n beforeCount: input.beforeCount,\n afterCount: input.afterCount,\n }\n : {}),\n ...(hasAfterSignal || hasAroundSignal\n ? {}\n : {\n recent: true,\n limit: input.limit,\n }),\n fromProfileIds: input.fromProfileIds,\n kinds: input.kinds,\n };\n}\n\nfunction shouldPromoteHistorySignalIndex(input: {\n identityDirectory: SpaceIdentityDirectory | null;\n signals: readonly SignalEnvelope[];\n signalIndex: SpaceSignalIndex;\n}): boolean {\n for (const signal of input.signals) {\n if (!isMessageSemanticSignal(signal)) {\n continue;\n }\n\n const projection = buildSignalMessageReadProjection({\n signal,\n identityDirectory: input.identityDirectory,\n signalIndex: input.signalIndex,\n });\n if (\n projection.replyToSignalId &&\n projection.replyToContext?.resolved !== true\n ) {\n return true;\n }\n }\n\n return false;\n}\n\nfunction buildSpaceHistoryBriefPayload(input: {\n openMeldProfile: OpenMeldProfile;\n events: readonly SignalEnvelope[];\n identityDirectory: SpaceIdentityDirectory | null;\n signalIndex: SpaceSignalIndex;\n spaceId: string;\n threadByRootSignalId: Map<string, SpaceSignalThreadSummary>;\n}) {\n return {\n type: \"space.history.brief\",\n spaceId: input.spaceId,\n actingProfile: {\n profileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n profileKind: input.openMeldProfile.profileKind,\n ownerUserId: input.openMeldProfile.ownerUserId,\n ownerName: input.openMeldProfile.ownerName ?? null,\n },\n proof: {\n conversationReadable: true,\n checkedBy: \"space.history\",\n note: \"This command proves readable conversation access for the acting profile. It does not prove Wake execution success.\",\n },\n briefTextMaxCharacters: SPACE_HISTORY_BRIEF_TEXT_MAX_CHARACTERS,\n messages: input.events.map((event) =>\n buildSpaceHistoryBriefMessage({\n event,\n identityDirectory: input.identityDirectory,\n profileId: input.openMeldProfile.openMeldProfileId,\n signalIndex: input.signalIndex,\n spaceId: input.spaceId,\n thread: input.threadByRootSignalId.get(event.id) ?? null,\n })\n ),\n ...buildThreadNextCommandsField({\n spaceId: input.spaceId,\n profileId: input.openMeldProfile.openMeldProfileId,\n threadByRootSignalId: input.threadByRootSignalId,\n }),\n };\n}\n\nfunction buildThreadNextCommandsField(input: {\n spaceId: string;\n profileId: string;\n threadByRootSignalId: Map<string, SpaceSignalThreadSummary>;\n}): { nextCommands?: string[] } {\n if (input.threadByRootSignalId.size === 0) {\n return {};\n }\n const threadIds = [\n ...new Set(\n [...input.threadByRootSignalId.values()].map(\n (summary) => summary.threadId\n )\n ),\n ];\n return {\n nextCommands: threadIds.map((threadId) =>\n formatOpenMeldCliCommand(\n `openmeld space thread ${input.spaceId} ${threadId} --profile ${input.profileId} --view agent`\n )\n ),\n };\n}\n\nfunction buildSpaceHistoryBriefMessage(input: {\n event: SignalEnvelope;\n identityDirectory: SpaceIdentityDirectory | null;\n profileId: string;\n signalIndex: SpaceSignalIndex;\n spaceId: string;\n thread?: SpaceSignalThreadSummary | null;\n}) {\n const messageReadProjection = isMessageSemanticSignal(input.event)\n ? buildSignalMessageReadProjection({\n signal: input.event,\n identityDirectory: input.identityDirectory,\n signalIndex: input.signalIndex,\n })\n : null;\n const briefText = buildBriefMessageText(messageReadProjection?.text ?? null);\n\n return {\n signalId: input.event.id,\n timestamp: input.event.ts,\n kind: input.event.type,\n actor: {\n profileId: input.event.profile?.profileId ?? null,\n profileName: input.event.profile?.profileName ?? null,\n profileKind: input.event.profile?.kind ?? null,\n },\n text: briefText.text,\n ...(messageReadProjection?.reactions\n ? { reactions: messageReadProjection.reactions }\n : {}),\n textOriginalCharacters: briefText.originalCharacters,\n textTruncated: briefText.truncated,\n ...(input.event.type === \"signal.text\" && input.event.data.files?.length\n ? { files: input.event.data.files }\n : {}),\n ...(briefText.truncated\n ? {\n fullTextCommand: formatOpenMeldCliCommand(\n `openmeld space history ${input.spaceId} --around-signal ${input.event.id} --before 0 --after 0 --kind ${toHistoryKindOption(input.event.type)} --profile ${input.profileId} --view agent`\n ),\n }\n : {}),\n ...(messageReadProjection?.replyToSignalId\n ? { replyTo: messageReadProjection.replyToSignalId }\n : {}),\n ...(messageReadProjection?.wakeTargets.length\n ? { wakeTargets: messageReadProjection.wakeTargets }\n : {}),\n ...(messageReadProjection?.referenceTargets.length\n ? { referenceTargets: messageReadProjection.referenceTargets }\n : {}),\n ...(messageReadProjection?.mentionTargets.length\n ? { mentionTargets: messageReadProjection.mentionTargets }\n : {}),\n ...(input.thread ? { thread: input.thread } : {}),\n };\n}\n\nfunction buildBriefMessageText(text: string | null): {\n originalCharacters: number | null;\n text: string | null;\n truncated: boolean;\n} {\n if (text === null) {\n return { originalCharacters: null, text: null, truncated: false };\n }\n const characters = [...text];\n if (characters.length <= SPACE_HISTORY_BRIEF_TEXT_MAX_CHARACTERS) {\n return {\n originalCharacters: characters.length,\n text,\n truncated: false,\n };\n }\n return {\n originalCharacters: characters.length,\n text: `${characters\n .slice(0, SPACE_HISTORY_BRIEF_TEXT_MAX_CHARACTERS - 1)\n .join(\"\")\n .trimEnd()}${SPACE_HISTORY_BRIEF_TRUNCATION_MARKER}`,\n truncated: true,\n };\n}\n\nfunction toHistoryKindOption(\n signalType: SignalEnvelope[\"type\"]\n): \"status\" | \"system_notice\" | \"text\" {\n if (signalType === \"signal.status\") {\n return \"status\";\n }\n if (signalType === \"signal.system_notice\") {\n return \"system_notice\";\n }\n return \"text\";\n}\n\nfunction isMessageSemanticSignal(\n signal: SignalEnvelope\n): signal is\n | Extract<SignalEnvelope, { type: \"signal.text\" }>\n | Extract<SignalEnvelope, { type: \"signal.status\" }>\n | Extract<SignalEnvelope, { type: \"signal.system_notice\" }> {\n return (\n signal.type === \"signal.text\" ||\n signal.type === \"signal.status\" ||\n signal.type === \"signal.system_notice\"\n );\n}\n\nasync function fetchHistorySpaceMeta(input: {\n requestContext: import(\"@openmeld/schemas/types\").OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n}) {\n const endpoint = toSpaceMetaUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n const res = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.history.meta\",\n init: { headers },\n });\n const raw = await res.text();\n if (!res.ok) {\n throw new Error(`HTTP ${res.status}: ${raw}`);\n }\n return parseSpaceMetaResponse({\n raw,\n endpoint,\n operation: \"fetchSpaceMeta\",\n });\n}\n\nasync function runHumanHistoryPiTuiViewer(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n membersSnapshot: SpaceMembersSnapshot | null;\n password?: string;\n space: string;\n spaceMeta: SpaceMeta | null;\n transcriptItems: ReturnType<typeof buildHumanReadSignalsTranscriptItems>;\n}): Promise<void> {\n const store = createSpaceScreenStore();\n\n store.dispatch({\n type: \"connection.connected\",\n });\n store.dispatch({\n type: \"members.updated\",\n snapshot: input.membersSnapshot,\n updatedAtMs: Date.now(),\n });\n\n for (const transcriptItem of input.transcriptItems) {\n store.dispatch({\n type: \"transcript.item.appended\",\n item: transcriptItem,\n });\n }\n\n const context = buildHumanHistorySessionContext({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n spaceMeta: input.spaceMeta,\n });\n await runReadonlyPiTuiSession({\n context,\n getResources: () => ({\n sessionDiagnostics: {\n openMeldServiceLabel: \"unknown\",\n canWakeLocalAgentsLabel: \"unknown\",\n },\n }),\n store,\n syncOverlayInteraction: (kind) => {\n if (kind === \"members\") {\n syncMembersHistoryOverlayInteraction(store);\n }\n },\n });\n}\n\nfunction buildHumanHistorySessionContext(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n spaceMeta: SpaceMeta | null;\n}) {\n return buildActiveSpaceSessionContext({\n profile: buildSpaceSessionProfileContext(input.openMeldProfile),\n baseUrl: input.baseUrl,\n connectionMode: \"history\",\n session: {\n accessMode: input.spaceMeta?.accessMode ?? null,\n passwordProtected: input.spaceMeta?.passwordProtected ?? null,\n spaceCreatedAt: input.spaceMeta?.createdAt ?? null,\n spaceCreatorId: input.spaceMeta?.creator?.profileId ?? null,\n spaceCreatorName: input.spaceMeta?.creator?.profileName ?? null,\n spaceId: input.space,\n spaceName: input.spaceMeta?.name ?? null,\n storageSoftLimitBytes:\n input.spaceMeta?.storageUsage?.softLimitBytes ?? null,\n storageUsagePercent: input.spaceMeta?.storageUsage?.usagePercent ?? null,\n storageUsedBytes: input.spaceMeta?.storageUsage?.usedBytes ?? null,\n visibility: input.spaceMeta?.visibility ?? null,\n },\n });\n}\n\nfunction syncMembersHistoryOverlayInteraction(\n store: ReturnType<typeof createSpaceScreenStore>\n): void {\n const screenState = store.getState();\n if (screenState.overlay.kind !== \"members\") {\n return;\n }\n const activeItemId = resolveMembersSearchableActiveItemId({\n preferredActiveItemId: screenState.overlay.interaction.activeItemId,\n query: screenState.overlay.interaction.query,\n snapshot: screenState.members.snapshot,\n });\n store.dispatch({\n type: \"overlay.active-item.updated\",\n activeItemId,\n });\n}\n\nfunction buildFocusedHistorySummary(input: {\n systemNoticeCount: number;\n}): string {\n const parts: string[] = [];\n if (input.systemNoticeCount > 0) {\n parts.push(\n `${String(input.systemNoticeCount)} ${input.systemNoticeCount === 1 ? \"system notice\" : \"system notices\"}`\n );\n }\n if (parts.length === 0) {\n return \"\";\n }\n return `History is showing chat first. Hidden ${parts.join(\" and \")}.`;\n}\n","import { cancel, isCancel, password as passwordPrompt } from \"@clack/prompts\";\nimport {\n normalizeSpacePasswordText,\n SPACE_PASSWORD_MIN_LENGTH,\n} from \"@openmeld/schemas\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport { parseHttpFailure } from \"./http-failure\";\n\nconst HTTP_ERROR_MESSAGE_REGEX = /^HTTP\\s+(\\d{3})\\s*:\\s*([\\s\\S]*)$/i;\nconst SPACE_PASSWORD_REQUIRED_HINT_REGEX =\n /\\bspace[.\\s]+password[.\\s]+required\\b/i;\nconst SPACE_PASSWORD_INVALID_HINT_REGEX =\n /\\bspace[.\\s]+password[.\\s]+invalid\\b/i;\n\nexport type SpacePasswordPromptReason = \"required\" | \"invalid\";\n\ntype PasswordPromptPresenter = Pick<ReturnType<typeof createPresenter>, \"line\">;\n\nexport function validateSpacePasswordInput(\n value: string | undefined\n): string | undefined {\n const normalized = normalizeSpacePasswordInput(value);\n if (normalized.length === 0) {\n return \"Enter a password.\";\n }\n if (normalized.length < SPACE_PASSWORD_MIN_LENGTH) {\n return `Use at least ${SPACE_PASSWORD_MIN_LENGTH} characters.`;\n }\n return undefined;\n}\n\nexport function buildSpacePasswordRequirementsText(): string {\n return `at least ${SPACE_PASSWORD_MIN_LENGTH} characters; numbers, letters, and symbols are allowed.`;\n}\n\nexport function resolveSpacePasswordPromptReason(\n error: unknown\n): SpacePasswordPromptReason | null {\n const parsed = parseHttpErrorMessage(error);\n const rawMessage = toErrorMessage(error);\n if (!parsed) {\n if (isLegacyPlainPasswordError(rawMessage, \"required\")) {\n return \"required\";\n }\n if (isLegacyPlainPasswordError(rawMessage, \"invalid\")) {\n return \"invalid\";\n }\n return null;\n }\n\n const code = parsed.code.toLowerCase();\n\n if (\n code === \"space.password_required\" ||\n isWrappedHttpPasswordError(parsed, \"required\")\n ) {\n return \"required\";\n }\n if (\n code === \"space.password_invalid\" ||\n isWrappedHttpPasswordError(parsed, \"invalid\")\n ) {\n return \"invalid\";\n }\n return null;\n}\n\nfunction isLegacyPlainPasswordError(\n message: string,\n reason: SpacePasswordPromptReason\n): boolean {\n const normalized = message.trim().toLowerCase();\n if (reason === \"required\") {\n return normalized === \"space password required\";\n }\n return normalized === \"space password invalid\";\n}\n\nfunction isWrappedHttpPasswordError(\n parsed: {\n body: string;\n code: string;\n message: string;\n status: number;\n },\n reason: SpacePasswordPromptReason\n): boolean {\n const expectedStatus = reason === \"required\" ? 401 : 403;\n const hintRegex =\n reason === \"required\"\n ? SPACE_PASSWORD_REQUIRED_HINT_REGEX\n : SPACE_PASSWORD_INVALID_HINT_REGEX;\n if (parsed.status === expectedStatus && hintRegex.test(parsed.message)) {\n return true;\n }\n return (\n new RegExp(`\\\\bHTTP\\\\s+${expectedStatus}\\\\b`, \"i\").test(parsed.message) &&\n hintRegex.test(parsed.message)\n );\n}\n\nexport async function promptSpacePassword(): Promise<string | null> {\n const password = await passwordPrompt({\n message: \"Space password\",\n mask: \"•\",\n clearOnError: true,\n validate: validateSpacePasswordInput,\n });\n if (isCancel(password) || typeof password !== \"string\") {\n cancel(\"Cancelled.\");\n return null;\n }\n return normalizeSpacePasswordText(password);\n}\n\nexport function emitSpacePasswordPromptNotice(input: {\n presenter: PasswordPromptPresenter;\n reason: SpacePasswordPromptReason;\n codePrefix: string;\n requiredText?: string;\n invalidText?: string;\n}): void {\n input.presenter.line({\n code: `${input.codePrefix}.${input.reason}`,\n text:\n input.reason === \"required\"\n ? (input.requiredText ??\n \"This space is protected. Enter password to continue.\")\n : (input.invalidText ?? \"Password did not match. Try again.\"),\n });\n}\n\nfunction normalizeSpacePasswordInput(value: unknown): string {\n return typeof value === \"string\" ? normalizeSpacePasswordText(value) : \"\";\n}\n\nexport async function runSpaceReadWithPasswordRetry<T>(input: {\n initialPassword?: string;\n interactive: boolean;\n presenter: PasswordPromptPresenter;\n execute: (password?: string) => Promise<T>;\n}): Promise<\n | {\n status: \"completed\";\n result: T;\n password?: string;\n }\n | { status: \"cancelled\" }\n> {\n return await runSpacePasswordRetry({\n initialPassword: input.initialPassword,\n interactive: input.interactive,\n presenter: input.presenter,\n codePrefix: \"space.read.password\",\n execute: input.execute,\n });\n}\n\nexport async function runSpaceWriteWithPasswordRetry<T>(input: {\n initialPassword?: string;\n interactive: boolean;\n presenter: PasswordPromptPresenter;\n requiredText?: string;\n invalidText?: string;\n execute: (password?: string) => Promise<T>;\n}): Promise<\n | {\n status: \"completed\";\n result: T;\n password?: string;\n }\n | { status: \"cancelled\" }\n> {\n return await runSpacePasswordRetry({\n initialPassword: input.initialPassword,\n interactive: input.interactive,\n presenter: input.presenter,\n codePrefix: \"space.write.password\",\n requiredText: input.requiredText,\n invalidText: input.invalidText,\n execute: input.execute,\n });\n}\n\nexport async function runSpacePasswordRetry<T>(input: {\n initialPassword?: string;\n interactive: boolean;\n presenter: PasswordPromptPresenter;\n codePrefix: string;\n requiredText?: string;\n invalidText?: string;\n execute: (password?: string) => Promise<T>;\n}): Promise<\n | {\n status: \"completed\";\n result: T;\n password?: string;\n }\n | { status: \"cancelled\" }\n> {\n let nextPassword = input.initialPassword;\n\n for (;;) {\n try {\n const result = await input.execute(nextPassword);\n return {\n status: \"completed\",\n result,\n ...(nextPassword === undefined ? {} : { password: nextPassword }),\n };\n } catch (error) {\n const passwordPromptReason = input.interactive\n ? resolveSpacePasswordPromptReason(error)\n : null;\n if (!passwordPromptReason) {\n throw error;\n }\n emitSpacePasswordPromptNotice({\n presenter: input.presenter,\n reason: passwordPromptReason,\n codePrefix: input.codePrefix,\n requiredText: input.requiredText,\n invalidText: input.invalidText,\n });\n const promptedPassword = await promptSpacePassword();\n if (promptedPassword === null) {\n return { status: \"cancelled\" };\n }\n nextPassword = promptedPassword;\n }\n }\n}\n\nfunction parseHttpErrorMessage(error: unknown): {\n body: string;\n code: string;\n message: string;\n status: number;\n} | null {\n const parsedFailure = parseHttpFailure(error);\n if (parsedFailure) {\n return {\n body: parsedFailure.body,\n code: parsedFailure.code,\n message: parsedFailure.message,\n status: parsedFailure.status,\n };\n }\n\n const message = toErrorMessage(error);\n const match = HTTP_ERROR_MESSAGE_REGEX.exec(message.trim());\n if (!match) {\n return null;\n }\n\n const status = Number.parseInt(match[1] ?? \"\", 10);\n if (!Number.isFinite(status)) {\n return null;\n }\n const body = match[2] ?? \"\";\n const payload = safeJsonParse(body);\n const code = readHttpErrorField(payload, \"code\");\n const errorMessage = readHttpErrorField(payload, \"message\");\n return {\n body,\n code,\n message: errorMessage,\n status,\n };\n}\n\nfunction readHttpErrorField(\n payload: unknown,\n field: \"code\" | \"message\"\n): string {\n if (!payload || typeof payload !== \"object\") {\n return \"\";\n }\n const record = payload as {\n code?: unknown;\n message?: unknown;\n error?: { code?: unknown; message?: unknown } | null;\n };\n if (typeof record[field] === \"string\") {\n return record[field];\n }\n if (record.error && typeof record.error[field] === \"string\") {\n return record.error[field] ?? \"\";\n }\n return \"\";\n}\n\nfunction safeJsonParse(raw: string): unknown {\n try {\n return JSON.parse(raw);\n } catch {\n return null;\n }\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error) {\n return error.message;\n }\n return String(error);\n}\n","import { cancel, confirm, isCancel } from \"@clack/prompts\";\nimport type { SpaceMeta } from \"@openmeld/protocol\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { buildOpenMeldRequestContextFromProfile } from \"../config/openmeld-request-context\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport {\n buildPublicSpaceJoinConfirmPromptConfig,\n type PublicSpaceExposure,\n resolvePublicSpaceExposure,\n} from \"../ui/public-space-warning\";\nimport { fetchSpaceMeta } from \"./meta-api\";\nimport { runSpacePasswordRetry } from \"./password-flow\";\n\nexport type SpaceJoinAccessBootstrapResult =\n | {\n status: \"ready\";\n password?: string;\n spaceMeta: SpaceMeta;\n publicExposure: PublicSpaceExposure | null;\n }\n | {\n status: \"cancelled\";\n };\n\ntype JoinAccessBootstrapPresenter = Pick<\n ReturnType<typeof createPresenter>,\n \"line\"\n>;\n\n// Join access bootstrap owns password/meta/public-space truth only.\n// Membership flow and connect handoff start after this returns ready.\nexport async function resolveSpaceJoinAccessBootstrap(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n initialPassword?: string;\n resolvedView: \"human\" | \"agent\";\n presenter: JoinAccessBootstrapPresenter;\n canPromptJoinPassword: boolean;\n canConfirmPublicSpaceJoin: boolean;\n}): Promise<SpaceJoinAccessBootstrapResult> {\n const accessState = await resolveJoinAccessState({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n initialPassword: input.initialPassword,\n presenter: input.presenter,\n canPromptJoinPassword: input.canPromptJoinPassword,\n });\n if (accessState.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n\n const publicExposure = resolvePublicSpaceExposure(accessState.spaceMeta);\n const confirmedPublicSpace = await confirmPublicSpaceJoinAccess({\n publicExposure,\n resolvedView: input.resolvedView,\n canConfirmPublicSpaceJoin: input.canConfirmPublicSpaceJoin,\n });\n if (!confirmedPublicSpace) {\n return {\n status: \"cancelled\",\n };\n }\n\n return {\n status: \"ready\",\n password: accessState.password,\n spaceMeta: accessState.spaceMeta,\n publicExposure,\n };\n}\n\nasync function resolveJoinAccessState(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n initialPassword?: string;\n presenter: JoinAccessBootstrapPresenter;\n canPromptJoinPassword: boolean;\n}): Promise<\n | {\n status: \"ready\";\n password?: string;\n spaceMeta: SpaceMeta;\n }\n | {\n status: \"cancelled\";\n }\n> {\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n });\n const accessResult = await runSpacePasswordRetry({\n initialPassword: input.initialPassword,\n interactive: input.canPromptJoinPassword,\n presenter: input.presenter,\n codePrefix: \"space.join.password\",\n execute: async (password) =>\n await fetchSpaceMeta({\n requestContext,\n baseUrl: input.baseUrl,\n space: input.space,\n password,\n }),\n });\n if (accessResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n\n return {\n status: \"ready\",\n password: accessResult.password,\n spaceMeta: accessResult.result,\n };\n}\n\nasync function confirmPublicSpaceJoinAccess(input: {\n publicExposure: PublicSpaceExposure | null;\n resolvedView: \"human\" | \"agent\";\n canConfirmPublicSpaceJoin: boolean;\n}): Promise<boolean> {\n if (!input.publicExposure) {\n return true;\n }\n if (input.resolvedView !== \"human\") {\n return true;\n }\n if (!input.canConfirmPublicSpaceJoin) {\n throw new Error(\n \"This Space can be read by anyone with the link. Re-run this command in an interactive terminal so you can confirm before joining.\"\n );\n }\n\n const confirmed = await confirm({\n ...buildPublicSpaceJoinConfirmPromptConfig({\n exposure: input.publicExposure,\n }),\n initialValue: true,\n });\n if (isCancel(confirmed)) {\n cancel(\"Cancelled.\");\n return false;\n }\n return confirmed;\n}\n","import {\n isOpenMeldLockError,\n type OpenMeldLockError,\n resolveOpenMeldOrphanedLockIssue,\n} from \"../config/lock\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport {\n formatOpenMeldCliTextBlock,\n resolveUserFacingCliEntryCommand,\n} from \"../runtime/cli-entry-command\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport { SpaceCommandOutputHandledError } from \"./command-output-handled\";\nimport { runConnect } from \"./connect\";\nimport { runSpacePasswordRetry } from \"./password-flow\";\n\ntype JoinConnectHandoffPresenter = Pick<\n ReturnType<typeof createPresenter>,\n \"data\" | \"event\" | \"line\"\n>;\n\nexport type SpaceJoinConnectHandoffInput = {\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n initialPassword?: string;\n output?: string;\n localEcho: boolean;\n historyLimit?: number;\n role?: string;\n mentionAlias?: string;\n presenter: JoinConnectHandoffPresenter;\n resolvedView: \"human\" | \"agent\";\n canPromptJoinPassword: boolean;\n rawStream: boolean;\n};\n\n// Join connect handoff owns join-side stream-only fallback, connect retry,\n// lock presentation, and join-only runtime side effects only.\nexport async function runSpaceJoinConnectHandoff(\n input: SpaceJoinConnectHandoffInput\n): Promise<\"connected\" | \"cancelled\"> {\n const useStdio = shouldUseJoinStdio(input.resolvedView);\n const sendCommand = resolveStreamOnlyJoinSendCommand({\n useStdio,\n profileId: input.openMeldProfileId,\n spaceId: input.space,\n baseUrl: input.baseUrl,\n });\n if (!useStdio) {\n input.presenter.event(\"info\", \"space.join.stdin_fallback_watch\", {\n connectionMode: \"join\",\n profileId: input.openMeldProfileId,\n spaceId: input.space,\n ...(sendCommand ? { sendCommand } : {}),\n });\n }\n\n try {\n return await connectSpaceJoinWithPasswordRetry({\n openMeldProfileId: input.openMeldProfileId,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n initialPassword: input.initialPassword,\n stdio: useStdio,\n output: input.output,\n localEcho: input.localEcho,\n historyLimit: input.historyLimit,\n role: input.role,\n mentionAlias: input.mentionAlias,\n sendCommand,\n presenter: input.presenter,\n canPromptJoinPassword: input.canPromptJoinPassword,\n rawStream: input.rawStream,\n resolvedView: input.resolvedView,\n });\n } catch (error) {\n if (input.resolvedView === \"human\" && isOpenMeldLockError(error)) {\n const lockMessage = buildHumanReadableSpaceJoinLockMessage(error);\n emitSpaceJoinLockBlocked({\n presenter: input.presenter,\n output: input.output,\n message: lockMessage,\n });\n throw new SpaceCommandOutputHandledError(lockMessage);\n }\n throw error;\n }\n}\n\nfunction shouldUseJoinStdio(resolvedView: \"human\" | \"agent\"): boolean {\n if (resolvedView !== \"agent\") {\n return true;\n }\n return process.stdin.isTTY === true;\n}\n\nfunction buildStreamOnlyJoinSendCommand(input: {\n profileId: string;\n spaceId: string;\n baseUrl: string;\n}): string {\n const cliEntry = resolveUserFacingCliEntryCommand();\n return `${cliEntry} space --gateway-url ${input.baseUrl} send --profile ${input.profileId} ${input.spaceId} <text...>`;\n}\n\nfunction resolveStreamOnlyJoinSendCommand(input: {\n useStdio: boolean;\n profileId: string;\n spaceId: string;\n baseUrl: string;\n}): string | undefined {\n if (input.useStdio) {\n return undefined;\n }\n return buildStreamOnlyJoinSendCommand({\n profileId: input.profileId,\n spaceId: input.spaceId,\n baseUrl: input.baseUrl,\n });\n}\n\nasync function connectSpaceJoinWithPasswordRetry(input: {\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n initialPassword?: string;\n stdio: boolean;\n output?: string;\n localEcho: boolean;\n historyLimit?: number;\n role?: string;\n mentionAlias?: string;\n sendCommand?: string;\n presenter: JoinConnectHandoffPresenter;\n canPromptJoinPassword: boolean;\n rawStream: boolean;\n resolvedView: \"human\" | \"agent\";\n}): Promise<\"connected\" | \"cancelled\"> {\n const handoffResult = await runSpacePasswordRetry({\n initialPassword: input.initialPassword,\n interactive: input.canPromptJoinPassword,\n presenter: input.presenter,\n codePrefix: \"space.join.password\",\n execute: async (password) => {\n await runConnect({\n profile: input.openMeldProfileId,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n password,\n trackProfileSpaceHistory: true,\n stdio: input.stdio,\n output: input.output,\n localEcho: input.localEcho,\n historyLimit: input.historyLimit,\n role: input.role,\n mentionAlias: input.mentionAlias,\n connectionMode: \"join\",\n sendCommand: input.sendCommand,\n rawStream: input.rawStream,\n view: input.resolvedView,\n });\n return \"connected\" as const;\n },\n });\n if (handoffResult.status === \"cancelled\") {\n return \"cancelled\";\n }\n\n return handoffResult.result;\n}\n\nfunction buildHumanReadableSpaceJoinLockMessage(\n error: OpenMeldLockError\n): string {\n const orphanedIssue = resolveOpenMeldOrphanedLockIssue(error);\n if (orphanedIssue) {\n return formatOpenMeldCliTextBlock(\n [\n \"🔒 Join blocked\",\n `Reason: ${orphanedIssue.summary}`,\n \"\",\n \"✅ What to do now\",\n `1) ${orphanedIssue.primaryAction}`,\n \"\",\n \"🤖 Agent View\",\n \"Run with `--view agent` to get full lock path and metadata.\",\n ].join(\"\\n\")\n );\n }\n\n const lines = [\n \"🔒 Join blocked\",\n \"Reason: This profile has already joined this space.\",\n \"\",\n \"✅ What to do now\",\n \"1) Use the terminal where this profile is already joined.\",\n \"2) Or stop that session (Ctrl+C), then run `openmeld space join <space-id>` here.\",\n \"3) To join now as another participant, create a new profile or switch to a different profile, then join.\",\n \"\",\n \"🤖 Agent View\",\n \"Run with `--view agent` to get full lock path and metadata.\",\n ];\n return formatOpenMeldCliTextBlock(lines.join(\"\\n\"));\n}\n\nfunction emitSpaceJoinLockBlocked(input: {\n presenter: JoinConnectHandoffPresenter;\n output?: string;\n message: string;\n}): void {\n if (input.output === \"ndjson\") {\n input.presenter.data({\n code: \"space.join.lock_blocked\",\n payload: {\n text: input.message,\n },\n });\n return;\n }\n input.presenter.line({\n code: \"space.join.lock_blocked\",\n text: input.message,\n });\n}\n","import { createDelayedSpinner } from \"../ui/delayed-spinner\";\n\nexport const SPACE_JOIN_LOCAL_READINESS_SPINNER_MESSAGE =\n \"Checking local agent readiness before joining...\";\nexport const SPACE_JOIN_SPACE_READINESS_SPINNER_MESSAGE =\n \"Checking space readiness before joining...\";\n\nexport function shouldShowSpaceJoinProgress(input: {\n resolvedView: \"human\" | \"agent\";\n interactive: boolean;\n output?: string;\n rawStream?: boolean;\n}): boolean {\n return (\n input.resolvedView === \"human\" &&\n input.interactive &&\n input.rawStream !== true &&\n input.output !== \"ndjson\"\n );\n}\n\nexport async function withSpaceJoinProgress<T>(input: {\n enabled: boolean;\n message: string;\n run: () => Promise<T>;\n}): Promise<T> {\n const spinner = createDelayedSpinner({\n enabled: input.enabled,\n message: input.message,\n });\n spinner.start();\n\n try {\n const result = await input.run();\n spinner.complete();\n return result;\n } catch (error) {\n spinner.fail();\n throw error;\n }\n}\n","import {\n buildCommandAuthenticationPromptMessage,\n ensureCommandAuthenticationOrCancel,\n} from \"../auth/command-auth\";\nimport { resolveBaseUrl } from \"../config/base-url\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { resolveLocalServiceDemand } from \"../local-service/lifecycle/local-service-demand\";\nimport {\n formatInlineOpenMeldCliCommands,\n formatOpenMeldCliCommand,\n} from \"../runtime/cli-entry-command\";\nimport { resolveRuntimeContext } from \"../runtime/context\";\nimport { createSpaceTargetGuideError } from \"../runtime/dual-view-guide-catalog\";\nimport { canUseInteractivePrompts } from \"../runtime/interaction\";\nimport { formatMessage } from \"../runtime/messages\";\nimport { createPresenter } from \"../runtime/presenter/index\";\nimport { assessActionParticipationCandidate } from \"../system/action-participation-planner\";\nimport { runLocalParticipationOrchestrator } from \"../system/local-participation-orchestrator\";\nimport { resolveServiceParticipationReadiness } from \"../system/service-participation-readiness\";\nimport { emitSpaceAgentOverview } from \"./agent-overview\";\nimport {\n assertValidSpaceIdTarget,\n resolveOpenMeldProfileForSpaceCommand,\n} from \"./command-context\";\nimport {\n SPACE_JOIN_LOCAL_READINESS_SPINNER_MESSAGE,\n SPACE_JOIN_SPACE_READINESS_SPINNER_MESSAGE,\n shouldShowSpaceJoinProgress,\n withSpaceJoinProgress,\n} from \"./join-progress\";\nimport type { SpaceCommandNavigationStatus } from \"./navigation-status\";\nimport {\n emitResolvedSpaceCommandPreflight,\n emitSpaceCommandPreflight,\n} from \"./preflight\";\n\nexport type SpaceJoinEntryTarget = {\n space: string;\n baseUrl?: string;\n};\n\nexport type SpaceJoinTargetResolution =\n | {\n status: \"submitted\";\n value: SpaceJoinEntryTarget;\n }\n | {\n status: \"cancelled\" | \"back\" | \"create\";\n value: null;\n };\n\nexport type SpaceJoinEntryTargetOutcome =\n | {\n status: \"submitted\";\n target: SpaceJoinEntryTarget;\n }\n | {\n status: \"completed\" | \"cancelled\" | \"back\";\n };\n\nexport type PreparedSpaceJoinEntryContext = {\n status: \"ready\";\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n localDemand: Awaited<ReturnType<typeof resolveLocalServiceDemand>> | null;\n authenticatedGatewayUrl: string | null;\n allowPromptForSpaceTarget: boolean;\n allowPromptForRoleContext: boolean;\n canPromptPreJoinActions: boolean;\n allowBackToTargetSelection: boolean;\n hasExplicitBaseUrlInput: boolean;\n};\n\nconst LOCAL_SERVICE_ONLY_JOIN_BLOCK_REASON_CODES: ReadonlySet<string> = new Set(\n [\"service.drifted\", \"service.not_installed\", \"service.not_running\"] as const\n);\n\nconst LOCAL_PARTICIPATION_ONLY_JOIN_BLOCK_REASON_CODES: ReadonlySet<string> =\n new Set([\n \"service.not_installed\",\n \"service.drifted\",\n \"service.not_running\",\n \"dispatch.storage_not_ready\",\n \"service.gateway_chain_unhealthy\",\n \"profile.unbound\",\n \"controller.binding.disabled\",\n \"projection.missing\",\n \"controller.registry.disabled\",\n \"controller.launch.choice_required\",\n \"controller.launch.needs_repair\",\n \"workspace.missing\",\n \"workspace.invalid\",\n \"runtime.adapter.unsupported\",\n \"controller.bootstrap.failed\",\n \"controller.gateway.unhealthy\",\n \"route.offline\",\n \"route.not_registered\",\n ] as const);\n\n// Join entry owns the front door only: runtime/auth/preflight/target routing.\n// It must stop before bootstrap, password retry, and connect handoff begin.\nexport async function prepareSpaceJoinEntryContext(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n view?: string;\n allowPrompt?: boolean;\n output?: string;\n rawStream?: boolean;\n entryChecksHandled?: boolean;\n}): Promise<PreparedSpaceJoinEntryContext | { status: \"cancelled\" }> {\n const runtime = await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n });\n const presenter = createPresenter(runtime);\n if (\n runtime.resolvedView === \"agent\" &&\n String(input.space ?? \"\").trim().length === 0\n ) {\n emitJoinEntryOverview({\n presenter,\n resolvedView: runtime.resolvedView,\n rawStream: input.rawStream,\n });\n }\n assertJoinEntryTargetGuard({\n space: input.space,\n resolvedView: runtime.resolvedView,\n });\n\n const resolvedBaseUrl = await resolveBaseUrl(input.baseUrl);\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const allowPrompt = input.allowPrompt ?? canUseInteractivePrompts(runtime);\n if (!input.entryChecksHandled) {\n const authReady = await ensureCommandAuthenticationOrCancel({\n runtime,\n ...(hasExplicitBaseUrlInput ? { gatewayUrl: resolvedBaseUrl } : {}),\n promptMessage: buildCommandAuthenticationPromptMessage(\"joining a space\"),\n allowPrompt,\n });\n if (!authReady) {\n return {\n status: \"cancelled\",\n };\n }\n }\n\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive: canUseInteractivePrompts(runtime),\n });\n\n const serviceState = await withSpaceJoinProgress({\n enabled: shouldShowSpaceJoinProgress({\n resolvedView: runtime.resolvedView,\n interactive: allowPrompt && canUseInteractivePrompts(runtime),\n output: input.output,\n rawStream: input.rawStream,\n }),\n message: SPACE_JOIN_LOCAL_READINESS_SPINNER_MESSAGE,\n run: async () =>\n await prepareSpaceJoinServiceState({\n openMeldProfile,\n interactiveHuman: isHumanInteractiveJoinRuntime(runtime),\n input: {\n baseUrl: input.baseUrl,\n resolvedBaseUrl,\n view: input.view,\n },\n }),\n });\n\n const allowPromptForSpaceTarget =\n input.allowPrompt ?? canUseInteractivePrompts(runtime);\n const allowPromptForRoleContext =\n input.allowPrompt ?? canUseInteractivePrompts(runtime);\n const canPromptPreJoinActions =\n allowPromptForSpaceTarget && runtime.resolvedView === \"human\";\n const allowBackToTargetSelection =\n canPromptPreJoinActions && String(input.space ?? \"\").trim().length === 0;\n\n return {\n status: \"ready\",\n runtime,\n presenter,\n openMeldProfile,\n baseUrl: serviceState.baseUrl,\n localDemand: serviceState.localDemand,\n authenticatedGatewayUrl: hasExplicitBaseUrlInput ? resolvedBaseUrl : null,\n allowPromptForSpaceTarget,\n allowPromptForRoleContext,\n canPromptPreJoinActions,\n allowBackToTargetSelection,\n hasExplicitBaseUrlInput: serviceState.hasExplicitBaseUrlInput,\n };\n}\n\nfunction emitJoinEntryOverview(input: {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n rawStream?: boolean;\n}): void {\n if (input.rawStream === true) {\n return;\n }\n emitSpaceAgentOverview({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n command: \"join\",\n });\n}\n\nfunction assertJoinEntryTargetGuard(input: {\n space?: string;\n resolvedView: \"human\" | \"agent\";\n}): void {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (input.resolvedView === \"agent\" && explicitSpace.length === 0) {\n throw createSpaceTargetGuideError(\"join\");\n }\n if (!explicitSpace) {\n return;\n }\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n}\n\nfunction isHumanInteractiveJoinRuntime(\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>\n): boolean {\n return runtime.resolvedView === \"human\" && canUseInteractivePrompts(runtime);\n}\n\nexport async function resolveSpaceJoinEntryTargetOutcome(input: {\n resolveTarget: () => Promise<SpaceJoinTargetResolution>;\n runCreate: () => Promise<SpaceCommandNavigationStatus>;\n}): Promise<SpaceJoinEntryTargetOutcome> {\n const targetResult = await input.resolveTarget();\n if (targetResult.status === \"submitted\") {\n return {\n status: \"submitted\",\n target: targetResult.value,\n };\n }\n if (targetResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (targetResult.status === \"back\") {\n return {\n status: \"back\",\n };\n }\n\n const createResult = await input.runCreate();\n if (createResult === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (createResult === \"back\") {\n return {\n status: \"back\",\n };\n }\n return {\n status: \"completed\",\n };\n}\n\nasync function prepareSpaceJoinServiceState(input: {\n openMeldProfile: OpenMeldProfile;\n interactiveHuman: boolean;\n input: {\n baseUrl?: string;\n resolvedBaseUrl?: string;\n view?: string;\n };\n}): Promise<{\n localDemand: Awaited<ReturnType<typeof resolveLocalServiceDemand>> | null;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n}> {\n const localDemand = input.interactiveHuman\n ? await resolveLocalServiceDemand({\n ownerUserId: input.openMeldProfile.ownerUserId,\n }).catch(() => null)\n : null;\n const hasExplicitBaseUrlInput =\n String(input.input.baseUrl ?? \"\").trim().length > 0;\n const baseUrl =\n input.input.resolvedBaseUrl ?? (await resolveBaseUrl(input.input.baseUrl));\n return {\n baseUrl,\n hasExplicitBaseUrlInput,\n localDemand,\n };\n}\n\nexport async function assertSpaceJoinTargetPreflightReady(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n allowPrompt?: boolean;\n localDemand?: Awaited<ReturnType<typeof resolveLocalServiceDemand>> | null;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n serviceIntent?: \"space_join\" | \"space_create_join\";\n showProgress?: boolean;\n view?: string;\n}): Promise<\"continue\" | \"cancelled\"> {\n const explicitLocalAgentProfile =\n input.openMeldProfile.profileKind === \"agent\";\n const serviceIntent = input.serviceIntent ?? \"space_join\";\n let preflight = await runSpaceJoinPreflightWithProgress({\n ...input,\n emitOutput: false,\n runtimeProjection: input.localDemand?.projection ?? undefined,\n });\n let assessment = resolveSpaceJoinParticipationAssessment({\n openMeldProfile: input.openMeldProfile,\n preflight,\n });\n\n const orchestratorResult = await runLocalParticipationOrchestrator({\n intent: serviceIntent,\n plan: {\n intent: serviceIntent,\n assessments: [assessment],\n shouldOfferServiceGate:\n assessment.localParticipationState === \"needs_openmeld_service\",\n hasAgentPreparationWork:\n assessment.localParticipationState === \"needs_agent_prepare\",\n hasReadyLocalAgentParticipation:\n assessment.localParticipationState === \"ready\",\n explicitLocalAgentCount: explicitLocalAgentProfile ? 1 : 0,\n },\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n allowPrompt: input.allowPrompt ?? true,\n gatewayUrl: input.baseUrl,\n localDemand: input.localDemand,\n forceServicePrompt: explicitLocalAgentProfile,\n profilesToPrepare: explicitLocalAgentProfile ? [input.openMeldProfile] : [],\n view: input.view,\n });\n if (orchestratorResult.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (orchestratorResult.status === \"recheck_required\") {\n preflight = await runSpaceJoinPreflightWithProgress({\n ...input,\n emitOutput: false,\n });\n assessment = resolveSpaceJoinParticipationAssessment({\n openMeldProfile: input.openMeldProfile,\n preflight,\n });\n }\n emitResolvedSpaceCommandPreflight({\n presenter: input.presenter,\n command: \"join\",\n resolvedView: input.resolvedView,\n humanServiceGuidanceMode: \"suppress\",\n preflight,\n });\n assessment = resolveSpaceJoinParticipationAssessment({\n openMeldProfile: input.openMeldProfile,\n preflight,\n });\n\n const blockedJoinResult = handleBlockedSpaceJoinLocalParticipation({\n openMeldProfile: input.openMeldProfile,\n explicitLocalAgentProfile,\n preflight,\n presenter: input.presenter,\n assessmentState: assessment.localParticipationState,\n });\n if (blockedJoinResult) {\n return blockedJoinResult;\n }\n if (preflight.deviceReplyReadiness.replyReadiness === \"blocked\") {\n throw new Error(preflight.deviceReplyReadiness.reasonText);\n }\n return \"continue\";\n}\n\nasync function runSpaceJoinPreflight(input: {\n openMeldProfile: OpenMeldProfile;\n allowPrompt?: boolean;\n baseUrl: string;\n emitOutput: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n runtimeProjection?: Awaited<\n ReturnType<typeof resolveLocalServiceDemand>\n >[\"projection\"];\n}) {\n return await emitSpaceCommandPreflight({\n presenter: input.presenter,\n command: \"join\",\n profile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n resolvedView: input.resolvedView,\n humanServiceGuidanceMode: \"suppress\",\n emitOutput: input.emitOutput,\n runtimeProjection: input.runtimeProjection,\n });\n}\n\nasync function runSpaceJoinPreflightWithProgress(input: {\n openMeldProfile: OpenMeldProfile;\n allowPrompt?: boolean;\n baseUrl: string;\n emitOutput: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n runtimeProjection?: Awaited<\n ReturnType<typeof resolveLocalServiceDemand>\n >[\"projection\"];\n showProgress?: boolean;\n}) {\n return await withSpaceJoinProgress({\n enabled: input.showProgress === true,\n message: SPACE_JOIN_SPACE_READINESS_SPINNER_MESSAGE,\n run: async () => await runSpaceJoinPreflight(input),\n });\n}\n\nfunction resolveSpaceJoinParticipationAssessment(input: {\n openMeldProfile: OpenMeldProfile;\n preflight: Awaited<ReturnType<typeof emitSpaceCommandPreflight>>;\n}) {\n const serviceParticipationReadiness =\n input.preflight.serviceParticipationReadiness ??\n resolveServiceParticipationReadiness({\n deviceReplyReadiness: input.preflight.deviceReplyReadiness,\n });\n return assessActionParticipationCandidate({\n profileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n profileKind:\n input.openMeldProfile.profileKind === \"agent\" ? \"agent\" : \"human\",\n localParticipationReadiness: serviceParticipationReadiness.serviceReadiness,\n localParticipationReasonCodes: [\n ...input.preflight.deviceReplyReadiness.reasonCodes,\n ],\n });\n}\n\nfunction handleBlockedSpaceJoinLocalParticipation(input: {\n openMeldProfile: OpenMeldProfile;\n explicitLocalAgentProfile: boolean;\n preflight: Awaited<ReturnType<typeof emitSpaceCommandPreflight>>;\n presenter: ReturnType<typeof createPresenter>;\n assessmentState: ReturnType<\n typeof resolveSpaceJoinParticipationAssessment\n >[\"localParticipationState\"];\n}): \"continue\" | null {\n if (\n input.preflight.deviceReplyReadiness.replyReadiness !== \"blocked\" ||\n !isBlockingLocalParticipationJoinAttention(input.preflight)\n ) {\n return null;\n }\n if (input.explicitLocalAgentProfile) {\n input.presenter.line({\n code: \"space.join.local_participation.pending\",\n text: buildSpaceJoinMembershipOnlyMessage({\n openMeldProfile: input.openMeldProfile,\n reasonCodes: input.preflight.deviceReplyReadiness.reasonCodes,\n }),\n });\n return \"continue\";\n }\n if (input.assessmentState === \"not_needed\") {\n input.presenter.line({\n code: \"space.join.service.not_needed\",\n text: formatInlineOpenMeldCliCommands(\n \"OpenMeld will join this space. Local agent participation on this device can be checked later with `openmeld service status`.\"\n ),\n });\n return \"continue\";\n }\n input.presenter.line({\n code: \"space.join.service.pending\",\n text: formatInlineOpenMeldCliCommands(\n \"OpenMeld will join this space. Local agent participation on this device can be checked separately with `openmeld service status`.\"\n ),\n });\n return \"continue\";\n}\n\nfunction isBlockingLocalParticipationJoinAttention(\n preflight: Awaited<ReturnType<typeof emitSpaceCommandPreflight>>\n): boolean {\n const { deviceReplyReadiness } = preflight;\n return (\n deviceReplyReadiness.replyReadiness === \"blocked\" &&\n deviceReplyReadiness.reasonCodes.length > 0 &&\n deviceReplyReadiness.reasonCodes.every((reasonCode) =>\n LOCAL_PARTICIPATION_ONLY_JOIN_BLOCK_REASON_CODES.has(reasonCode)\n )\n );\n}\n\nfunction buildSpaceJoinMembershipOnlyMessage(input: {\n openMeldProfile: OpenMeldProfile;\n reasonCodes: readonly string[];\n}): string {\n const profileName = input.openMeldProfile.profileName;\n const profileId = input.openMeldProfile.openMeldProfileId;\n const reasonCodes = input.reasonCodes;\n const statusCommand = formatOpenMeldCliCommand(\n `openmeld service status --profile ${profileId}`\n );\n\n if (reasonCodes.includes(\"profile.unbound\")) {\n return `${profileName} will join this space. Choose its local agent in OpenMeld Web when you want it to handle work from this device.`;\n }\n\n if (\n reasonCodes.some((reasonCode) =>\n LOCAL_SERVICE_ONLY_JOIN_BLOCK_REASON_CODES.has(reasonCode)\n ) ||\n reasonCodes.includes(\"dispatch.storage_not_ready\") ||\n reasonCodes.includes(\"service.gateway_chain_unhealthy\") ||\n reasonCodes.includes(\"route.offline\") ||\n reasonCodes.includes(\"route.not_registered\")\n ) {\n return formatInlineOpenMeldCliCommands(\n `${profileName} will join this space. OpenMeld has not confirmed its local reply path on this device yet. Use \\`${statusCommand}\\` to check this device.`\n );\n }\n\n if (\n reasonCodes.includes(\"controller.launch.needs_repair\") ||\n reasonCodes.includes(\"controller.launch.choice_required\") ||\n reasonCodes.includes(\"workspace.missing\") ||\n reasonCodes.includes(\"workspace.invalid\")\n ) {\n return formatInlineOpenMeldCliCommands(\n `${profileName} will join this space, but its local agent setup on this device needs attention. Use \\`openmeld agents list\\` to find the local agent, then run \\`openmeld agents repair --agent <agent-id>\\`.`\n );\n }\n\n return `${profileName} will join this space. Check Local Agents in OpenMeld Web when you want it to handle work from this device.`;\n}\n\nexport function buildJoinTargetMissingMessage(input: {\n resolvedView: \"human\" | \"agent\";\n}): string {\n return formatMessage(input.resolvedView, \"space.target.missing\", {\n command: \"join\",\n });\n}\n","import type { InfoCardRow } from \"../ui/info-card\";\n\nconst BRING_PROFILES_PROMPT_MESSAGE =\n \"Bring your agents or other profiles with you?\";\nconst CHOOSE_PROFILES_TO_BRING_MESSAGE =\n \"Choose at least one agent or profile to bring into this space\";\nconst JOIN_PROFILE_WORKBENCH_MESSAGE =\n \"Review the profiles to bring into this space\";\nconst CHOOSE_MEMBERS_TO_REMOVE_MESSAGE =\n \"Choose at least one member to remove from this space\";\n\nexport function buildBringProfilesWithYouPromptConfig() {\n return {\n message: BRING_PROFILES_PROMPT_MESSAGE,\n noOption: {\n value: \"no\",\n label: \"No\",\n hint: \"Join this space on my own\",\n },\n yesOption: {\n value: \"yes\",\n label: \"Yes\",\n hint: \"Choose at least one human or agent profile to bring in\",\n },\n backOption: {\n value: \"back\",\n label: \"Back\",\n hint: \"Return to the previous step\",\n },\n } as const;\n}\n\nexport function getChooseProfilesToBringMessage(): string {\n return CHOOSE_PROFILES_TO_BRING_MESSAGE;\n}\n\nexport function getJoinProfileWorkbenchMessage(): string {\n return JOIN_PROFILE_WORKBENCH_MESSAGE;\n}\n\nexport function getChooseMembersToRemoveMessage(): string {\n return CHOOSE_MEMBERS_TO_REMOVE_MESSAGE;\n}\n\nexport function buildSpaceAddMembersHumanResultCard(input: {\n added: ReadonlyArray<{\n profileName: string;\n profileKind: string;\n }>;\n alreadyJoined: ReadonlyArray<{\n profileName: string;\n profileKind: string;\n }>;\n broadcastJoinNoticeCount: number;\n}): {\n title: string;\n rows: InfoCardRow[];\n} {\n const rows: InfoCardRow[] = [];\n\n if (input.added.length > 0) {\n for (const member of input.added) {\n rows.push({\n label: \"\",\n value: formatAddedMemberLabel(member),\n });\n }\n } else {\n rows.push({\n label: \"\",\n value: \"No new profiles were added.\",\n });\n }\n\n if (input.alreadyJoined.length > 0) {\n rows.push({\n label: \"\",\n value: `Already here: ${input.alreadyJoined.map((member) => formatAddedMemberLabel(member)).join(\", \")}`,\n });\n }\n\n if (input.broadcastJoinNoticeCount > 0) {\n rows.push({\n label: \"\",\n value: `Broadcast ${String(input.broadcastJoinNoticeCount)} join ${pluralize(input.broadcastJoinNoticeCount, \"notice\", \"notices\")}`,\n });\n }\n\n return {\n title:\n input.added.length > 0 ? \"Added to This Space\" : \"Space Members Updated\",\n rows,\n };\n}\n\nexport function buildSpaceRemoveMembersHumanResultCard(input: {\n removed: ReadonlyArray<{\n profileName: string;\n profileKind: string;\n }>;\n alreadyAbsent: ReadonlyArray<{\n profileName: string;\n profileKind: string;\n }>;\n broadcastRemoveNoticeCount: number;\n}): {\n title: string;\n rows: InfoCardRow[];\n} {\n const rows: InfoCardRow[] = [];\n\n if (input.removed.length > 0) {\n for (const member of input.removed) {\n rows.push({\n label: \"\",\n value: formatAddedMemberLabel(member),\n });\n }\n } else {\n rows.push({\n label: \"\",\n value: \"No active members were removed.\",\n });\n }\n\n if (input.alreadyAbsent.length > 0) {\n rows.push({\n label: \"\",\n value: `Already absent: ${input.alreadyAbsent.map((member) => formatAddedMemberLabel(member)).join(\", \")}`,\n });\n }\n\n if (input.broadcastRemoveNoticeCount > 0) {\n rows.push({\n label: \"\",\n value: `Broadcast ${String(input.broadcastRemoveNoticeCount)} removal ${pluralize(input.broadcastRemoveNoticeCount, \"notice\", \"notices\")}`,\n });\n }\n\n return {\n title:\n input.removed.length > 0\n ? \"Removed from This Space\"\n : \"Space Members Updated\",\n rows,\n };\n}\n\nfunction formatAddedMemberLabel(input: {\n profileName: string;\n profileKind: string;\n}): string {\n return `${input.profileName} (${input.profileKind})`;\n}\n\nfunction pluralize(count: number, singular: string, plural: string): string {\n return count === 1 ? singular : plural;\n}\n","import { cancel, confirm, isCancel, select } from \"@clack/prompts\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport type {\n AgentProfileSetupResult,\n persistAgentTransportSelection,\n resolveAgentProfileSetup,\n} from \"../profile/agent-setup-flow\";\nimport type {\n CreateProfileKind,\n createProfileByKind,\n resolveCreateProfileKind,\n resolveCreateProfileName,\n} from \"../profile/create-flow\";\nimport { resolveOpenClawLocalDiagnosticsValue } from \"../provider-hosts/openclaw/diagnostics\";\nimport { formatInlineOpenMeldCliCommands } from \"../runtime/cli-entry-command\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport { resolveCurrentReplyReadinessSnapshot } from \"../system/current-reply-readiness-snapshot\";\nimport { buildReplyReadinessGuidance } from \"../system/reply-readiness-guidance\";\nimport { renderInfoCard } from \"../ui/info-card\";\nimport {\n buildPublicSpaceBringAgentsConfirmPromptConfig,\n type PublicSpaceExposure,\n} from \"../ui/public-space-warning\";\nimport {\n promptSearchMultiselectWorkbench,\n type SearchPromptFooterAction,\n type SearchPromptFooterActionResolver,\n} from \"../ui/search-select\";\nimport { formatTransportModeDisplay } from \"../ui/transport-mode-display\";\nimport type { StructuredGatewayFailure } from \"./gateway-response\";\nimport {\n buildBringProfilesWithYouPromptConfig,\n getJoinProfileWorkbenchMessage,\n} from \"./space-add-members-ui\";\n\nexport type SpaceJoinMembershipBootstrapResult =\n | { status: \"ready\" }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\nexport type SpaceJoinProfileWorkbenchState = {\n pendingSelectedProfileIds: string[];\n locallyCreatedPendingProfiles: SpaceJoinMembershipCandidate[];\n};\n\nexport type SpaceJoinMembershipCandidate = {\n openMeldProfile?: OpenMeldProfile;\n profileId: string;\n profileHandle?: string;\n profileName: string;\n profileKind: \"human\" | \"agent\";\n ownerProfileName?: string;\n ownerUserId?: string;\n ownerName?: string;\n agentControllerRef?: string;\n controllerEnabled?: boolean;\n localTargetAgentId?: string | null;\n localTargetDisplayName?: string | null;\n localTargetLaunchStatus?:\n | \"ready\"\n | \"needs_choice\"\n | \"needs_repair\"\n | \"not_available\"\n | null;\n localTargetSelectable?: boolean;\n localParticipationReadiness?:\n | \"ready\"\n | \"needs_repair\"\n | \"not_running\"\n | \"not_installed\"\n | \"unknown\"\n | null;\n localParticipationReasonCodes?: string[];\n localParticipationReasonText?: string | null;\n alreadyJoined: boolean;\n needsActivation: boolean;\n};\n\ntype SpaceJoinAddMembersFlowResult = {\n status: \"ready\" | \"cancelled\" | \"back\";\n workbenchState: SpaceJoinProfileWorkbenchState;\n};\n\ntype SpaceJoinWorkbenchSelectionResult =\n | { status: \"ready\" }\n | { status: \"cancelled\" }\n | {\n status: \"retry\";\n workbenchState: SpaceJoinProfileWorkbenchState;\n };\n\ntype SpaceJoinProfileWorkbenchAction = \"create_new\" | \"join_now\";\n\ntype SpaceJoinMembershipSearchItem = {\n value: string;\n label: string;\n detail: string;\n searchText: string;\n disabled: boolean;\n};\n\ntype SpaceJoinMembershipApplyResult = {\n added: SpaceJoinMembershipCandidate[];\n alreadyJoined: SpaceJoinMembershipCandidate[];\n failed: Array<{\n candidate: SpaceJoinMembershipCandidate;\n error: unknown;\n }>;\n warnings: Array<{\n candidate: SpaceJoinMembershipCandidate;\n error: unknown;\n }>;\n};\n\ntype SpaceJoinAddMembersNoticeSummary = {\n recordedCount: number;\n failedCount: number;\n firstFailure?: StructuredGatewayFailure;\n};\n\ntype JoinMembershipBootstrapPresenter = ReturnType<typeof createPresenter>;\n\n// Arrow-property signatures keep these dependencies contravariant: a new\n// required parameter on an implementation must fail typecheck here instead of\n// being silently accepted the way method-shorthand (bivariant) members allow.\nexport type SpaceJoinMembershipBootstrapDependencies = {\n resolveSpaceMemberCandidatesForAdd: (input: {\n currentProfile: OpenMeldProfile;\n currentOwnerUserId?: string;\n mode: \"profiles\";\n space: string;\n baseUrl: string;\n password?: string;\n }) => Promise<SpaceJoinMembershipCandidate[]>;\n resolveSelectedSpaceMemberCandidates: (input: {\n candidates: SpaceJoinMembershipCandidate[];\n selectedProfileIds: string[];\n }) => SpaceJoinMembershipCandidate[];\n normalizeRequestedMemberIds: (value: unknown) => string[];\n sortSpaceMemberCandidatesForPrompt: (input: {\n candidates: SpaceJoinMembershipCandidate[];\n initialSelectedProfileIds: string[];\n }) => SpaceJoinMembershipCandidate[];\n buildHumanSpaceMemberCandidateSearchItem: (\n candidate: SpaceJoinMembershipCandidate\n ) => SpaceJoinMembershipSearchItem;\n createProfileByKind: typeof createProfileByKind;\n resolveCreateProfileKind: typeof resolveCreateProfileKind;\n resolveCreateProfileName: typeof resolveCreateProfileName;\n resolveAgentProfileSetup: typeof resolveAgentProfileSetup;\n persistAgentTransportSelection: typeof persistAgentTransportSelection;\n prepareSpaceMemberCandidatesLocalParticipation: (input: {\n actorProfile: OpenMeldProfile;\n candidates: SpaceJoinMembershipCandidate[];\n presenter: JoinMembershipBootstrapPresenter;\n resolvedView: \"human\" | \"agent\";\n }) => Promise<\n | {\n status: \"continue\";\n candidates: SpaceJoinMembershipCandidate[];\n }\n | {\n status: \"cancelled\";\n }\n >;\n applySpaceAddMembers: (input: {\n actorProfile: OpenMeldProfile;\n candidates: SpaceJoinMembershipCandidate[];\n space: string;\n baseUrl: string;\n password?: string;\n }) => Promise<SpaceJoinMembershipApplyResult>;\n persistSpaceAddMembersJoinNotices: (input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n addedMembers: SpaceJoinMembershipCandidate[];\n }) => Promise<SpaceJoinAddMembersNoticeSummary>;\n emitSpaceAddMembersResult: (input: {\n mode: \"profiles\";\n presenter: JoinMembershipBootstrapPresenter;\n resolvedView: \"human\" | \"agent\";\n space: string;\n selectedCount: number;\n result: SpaceJoinMembershipApplyResult;\n joinNoticeSummary: SpaceJoinAddMembersNoticeSummary;\n }) => void;\n};\n\n// Join membership bootstrap owns bring-profiles, workbench, create-profile,\n// and apply-before-join flow only. Access truth and connect handoff stay out.\nexport async function resolveSpaceJoinMembershipBootstrap(\n input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n publicExposure: PublicSpaceExposure | null;\n canPromptPreJoinActions: boolean;\n skipBringProfilesPrompt: boolean;\n allowBackToTargetSelection: boolean;\n resolvedView: \"human\" | \"agent\";\n presenter: JoinMembershipBootstrapPresenter;\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<SpaceJoinMembershipBootstrapResult> {\n if (!input.canPromptPreJoinActions) {\n return { status: \"ready\" };\n }\n if (input.skipBringProfilesPrompt) {\n return { status: \"ready\" };\n }\n\n let workbenchState = createSpaceJoinProfileWorkbenchState(\n undefined,\n dependencies\n );\n for (;;) {\n const addMembersDecision = await confirmJoinAddMembersBeforeConnect({\n allowBack: input.allowBackToTargetSelection,\n });\n if (addMembersDecision === null) {\n return { status: \"cancelled\" };\n }\n if (addMembersDecision === \"back\") {\n return { status: \"back\" };\n }\n if (addMembersDecision === \"no\") {\n return { status: \"ready\" };\n }\n\n const addMembersFlowResult = await runJoinAddMembersFlowBeforeConnect(\n {\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n publicExposure: input.publicExposure,\n resolvedView: input.resolvedView,\n presenter: input.presenter,\n workbenchState,\n },\n dependencies\n );\n workbenchState = addMembersFlowResult.workbenchState;\n if (addMembersFlowResult.status === \"back\") {\n continue;\n }\n if (addMembersFlowResult.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n return { status: \"ready\" };\n }\n}\n\nasync function runJoinAddMembersFlowBeforeConnect(\n input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n publicExposure: PublicSpaceExposure | null;\n resolvedView: \"human\" | \"agent\";\n presenter: JoinMembershipBootstrapPresenter;\n workbenchState: SpaceJoinProfileWorkbenchState;\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<SpaceJoinAddMembersFlowResult> {\n let workbenchState = createSpaceJoinProfileWorkbenchState(\n {\n pendingSelectedProfileIds: input.workbenchState.pendingSelectedProfileIds,\n locallyCreatedPendingProfiles:\n input.workbenchState.locallyCreatedPendingProfiles,\n },\n dependencies\n );\n\n for (;;) {\n const fetchedCandidates =\n await dependencies.resolveSpaceMemberCandidatesForAdd({\n currentProfile: input.openMeldProfile,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n mode: \"profiles\",\n space: input.space,\n baseUrl: input.baseUrl,\n password: input.password,\n });\n workbenchState = reconcileSpaceJoinProfileWorkbenchState(\n {\n workbenchState,\n candidates: fetchedCandidates,\n },\n dependencies\n );\n const visibleCandidates = mergeSpaceJoinMembershipCandidates(\n fetchedCandidates,\n workbenchState.locallyCreatedPendingProfiles\n );\n\n const workbenchResult = await promptJoinProfileWorkbenchBeforeConnect(\n {\n candidates: visibleCandidates,\n workbenchState,\n },\n dependencies\n );\n workbenchState = createSpaceJoinProfileWorkbenchState(\n {\n pendingSelectedProfileIds: workbenchResult.selectedProfileIds,\n locallyCreatedPendingProfiles:\n workbenchState.locallyCreatedPendingProfiles,\n },\n dependencies\n );\n if (workbenchResult.status === \"back\") {\n return {\n status: \"back\",\n workbenchState,\n };\n }\n if (workbenchResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n workbenchState,\n };\n }\n\n if (workbenchResult.action === \"create_new\") {\n const createdProfile = await runJoinCreateProfileBeforeConnect(\n {\n resolvedView: input.resolvedView,\n presenter: input.presenter,\n },\n dependencies\n );\n if (createdProfile === \"cancelled\") {\n return {\n status: \"cancelled\",\n workbenchState,\n };\n }\n if (!createdProfile) {\n continue;\n }\n workbenchState = createSpaceJoinProfileWorkbenchState(\n {\n pendingSelectedProfileIds: [\n ...workbenchState.pendingSelectedProfileIds,\n createdProfile.openMeldProfileId,\n ],\n locallyCreatedPendingProfiles: [\n ...workbenchState.locallyCreatedPendingProfiles,\n buildLocallyCreatedPendingSpaceJoinMembershipCandidate(\n createdProfile\n ),\n ],\n },\n dependencies\n );\n continue;\n }\n\n const submitResult = await runJoinWorkbenchSelectionBeforeConnect(\n {\n profile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n ownerUserId: input.openMeldProfile.ownerUserId,\n password: input.password,\n publicExposure: input.publicExposure,\n resolvedView: input.resolvedView,\n presenter: input.presenter,\n workbenchState,\n },\n dependencies\n );\n if (submitResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n workbenchState,\n };\n }\n if (submitResult.status === \"retry\") {\n workbenchState = submitResult.workbenchState;\n continue;\n }\n return {\n status: \"ready\",\n workbenchState,\n };\n }\n}\n\nfunction createSpaceJoinProfileWorkbenchState(\n input:\n | {\n pendingSelectedProfileIds?: string[];\n locallyCreatedPendingProfiles?: SpaceJoinMembershipCandidate[];\n }\n | undefined,\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): SpaceJoinProfileWorkbenchState {\n return {\n pendingSelectedProfileIds: dependencies.normalizeRequestedMemberIds(\n input?.pendingSelectedProfileIds\n ),\n locallyCreatedPendingProfiles: normalizeSpaceJoinMembershipCandidates(\n input?.locallyCreatedPendingProfiles\n ),\n };\n}\n\nfunction reconcileSpaceJoinProfileWorkbenchState(\n input: {\n workbenchState: SpaceJoinProfileWorkbenchState;\n candidates: SpaceJoinMembershipCandidate[];\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): SpaceJoinProfileWorkbenchState {\n const visibleLocalPendingProfiles =\n input.workbenchState.locallyCreatedPendingProfiles.filter(\n (candidate) =>\n !input.candidates.some(\n (fetchedCandidate) =>\n fetchedCandidate.profileId === candidate.profileId\n )\n );\n const visibleCandidates = mergeSpaceJoinMembershipCandidates(\n input.candidates,\n visibleLocalPendingProfiles\n );\n const selectableIds = new Set(\n visibleCandidates\n .filter((candidate) => !candidate.alreadyJoined)\n .map((candidate) => candidate.profileId)\n );\n return createSpaceJoinProfileWorkbenchState(\n {\n pendingSelectedProfileIds:\n input.workbenchState.pendingSelectedProfileIds.filter((profileId) =>\n selectableIds.has(profileId)\n ),\n locallyCreatedPendingProfiles: visibleLocalPendingProfiles,\n },\n dependencies\n );\n}\n\nasync function promptJoinProfileWorkbenchBeforeConnect(\n input: {\n candidates: SpaceJoinMembershipCandidate[];\n workbenchState: SpaceJoinProfileWorkbenchState;\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<\n | {\n status: \"action\";\n action: SpaceJoinProfileWorkbenchAction;\n selectedProfileIds: string[];\n }\n | {\n status: \"back\";\n selectedProfileIds: string[];\n }\n | {\n status: \"cancelled\";\n selectedProfileIds: string[];\n }\n> {\n const sortedCandidates = dependencies.sortSpaceMemberCandidatesForPrompt({\n candidates: input.candidates,\n initialSelectedProfileIds: input.workbenchState.pendingSelectedProfileIds,\n });\n const hasVisibleProfiles = sortedCandidates.some(\n (candidate) => !candidate.alreadyJoined\n );\n const footerActionsResolver: SearchPromptFooterActionResolver<string> = ({\n selectedValues,\n }) =>\n buildJoinProfileWorkbenchFooterActions({\n hasVisibleProfiles,\n selectedCount: selectedValues.length,\n });\n\n const selected = await promptSearchMultiselectWorkbench({\n message: getJoinProfileWorkbenchMessage(),\n items: sortedCandidates.map((candidate) =>\n dependencies.buildHumanSpaceMemberCandidateSearchItem(candidate)\n ),\n maxVisible: 8,\n allowBack: true,\n backLabel: \"Back\",\n emptyLabel: \"No other profiles are available yet.\",\n footerActions: footerActionsResolver({\n selectedValues: input.workbenchState.pendingSelectedProfileIds,\n }),\n footerActionsResolver,\n initialSelectedValues: input.workbenchState.pendingSelectedProfileIds,\n });\n if (selected.status === \"action\") {\n if (selected.action !== \"create_new\" && selected.action !== \"join_now\") {\n throw new Error(\n `unexpected join workbench action: ${String(selected.action)}`\n );\n }\n return {\n status: \"action\",\n action: selected.action,\n selectedProfileIds: dependencies.normalizeRequestedMemberIds(\n selected.selectedValues\n ),\n };\n }\n\n if (selected.status === \"back\") {\n return {\n status: \"back\",\n selectedProfileIds: dependencies.normalizeRequestedMemberIds(\n selected.selectedValues\n ),\n };\n }\n\n return {\n status: \"cancelled\",\n selectedProfileIds: dependencies.normalizeRequestedMemberIds(\n selected.selectedValues\n ),\n };\n}\n\nfunction buildJoinProfileWorkbenchFooterActions(input: {\n hasVisibleProfiles: boolean;\n selectedCount: number;\n}): SearchPromptFooterAction[] {\n const createAction: SearchPromptFooterAction = {\n value: \"create_new\",\n icon: \"🆕\",\n label: \"Create new profile\",\n hint: \"Create it, then return here.\",\n };\n const joinAction: SearchPromptFooterAction = {\n value: \"join_now\",\n icon: \"➡️\",\n label: buildJoinProfileWorkbenchJoinActionLabel(input.selectedCount),\n separatorBefore: true,\n ...(input.selectedCount > 0 ? { accent: true } : {}),\n ...(input.selectedCount === 0\n ? {\n hint: \"Select at least one profile first.\",\n disabled: true,\n }\n : {}),\n };\n return [createAction, joinAction];\n}\n\nfunction buildJoinProfileWorkbenchJoinActionLabel(\n selectedCount: number\n): string {\n const profileLabel = selectedCount === 1 ? \"profile\" : \"profiles\";\n return `Join this space with ${String(selectedCount)} selected ${profileLabel}`;\n}\n\nasync function runJoinWorkbenchSelectionBeforeConnect(\n input: {\n profile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n ownerUserId?: string;\n password?: string;\n publicExposure: PublicSpaceExposure | null;\n resolvedView: \"human\" | \"agent\";\n presenter: JoinMembershipBootstrapPresenter;\n workbenchState: SpaceJoinProfileWorkbenchState;\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<SpaceJoinWorkbenchSelectionResult> {\n const fetchedCandidates =\n await dependencies.resolveSpaceMemberCandidatesForAdd({\n currentProfile: input.profile,\n currentOwnerUserId: input.ownerUserId,\n mode: \"profiles\",\n space: input.space,\n baseUrl: input.baseUrl,\n password: input.password,\n });\n const candidates = mergeSpaceJoinMembershipCandidates(\n fetchedCandidates,\n input.workbenchState.locallyCreatedPendingProfiles\n );\n const selectedProfileIds = dependencies.normalizeRequestedMemberIds(\n input.workbenchState.pendingSelectedProfileIds\n );\n if (selectedProfileIds.length === 0) {\n return { status: \"ready\" };\n }\n const selectedCandidates = dependencies.resolveSelectedSpaceMemberCandidates({\n candidates,\n selectedProfileIds,\n });\n if (selectedCandidates.length !== selectedProfileIds.length) {\n const resolvedSelectedIds = new Set(\n selectedCandidates.map((candidate) => candidate.profileId)\n );\n const unresolvedSelectedProfileIds = selectedProfileIds.filter(\n (profileId) => !resolvedSelectedIds.has(profileId)\n );\n input.presenter.line({\n code: \"space.join.membership_selection.sync_pending\",\n text: \"One or more selected profiles are still syncing. Review the list again, then retry when the missing profiles appear.\",\n data: {\n unresolvedSelectedProfileIds,\n },\n });\n return {\n status: \"retry\",\n workbenchState: createSpaceJoinProfileWorkbenchState(\n {\n pendingSelectedProfileIds: selectedProfileIds,\n locallyCreatedPendingProfiles:\n input.workbenchState.locallyCreatedPendingProfiles,\n },\n dependencies\n ),\n };\n }\n const applyResult = await applySelectedSpaceAddMembersBeforeJoin(\n {\n actorProfile: input.profile,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n publicExposure: input.publicExposure,\n resolvedView: input.resolvedView,\n presenter: input.presenter,\n selectedCandidates,\n cancelResult: \"cancelled\",\n },\n dependencies\n );\n return applyResult === \"cancelled\"\n ? { status: \"cancelled\" }\n : { status: \"ready\" };\n}\n\nfunction mergeSpaceJoinMembershipCandidates(\n fetchedCandidates: SpaceJoinMembershipCandidate[],\n locallyCreatedPendingProfiles: SpaceJoinMembershipCandidate[]\n): SpaceJoinMembershipCandidate[] {\n if (locallyCreatedPendingProfiles.length === 0) {\n return fetchedCandidates;\n }\n\n const mergedCandidates = [...fetchedCandidates];\n const seenProfileIds = new Set(\n fetchedCandidates.map((candidate) => candidate.profileId)\n );\n for (const candidate of locallyCreatedPendingProfiles) {\n if (seenProfileIds.has(candidate.profileId)) {\n continue;\n }\n seenProfileIds.add(candidate.profileId);\n mergedCandidates.push(candidate);\n }\n return mergedCandidates;\n}\n\nfunction normalizeSpaceJoinMembershipCandidates(\n value: unknown\n): SpaceJoinMembershipCandidate[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const normalizedCandidates: SpaceJoinMembershipCandidate[] = [];\n const seenProfileIds = new Set<string>();\n for (const item of value) {\n const candidate = normalizeSpaceJoinMembershipCandidate(item);\n if (!candidate || seenProfileIds.has(candidate.profileId)) {\n continue;\n }\n seenProfileIds.add(candidate.profileId);\n normalizedCandidates.push(candidate);\n }\n return normalizedCandidates;\n}\n\nfunction normalizeSpaceJoinMembershipCandidate(\n value: unknown\n): SpaceJoinMembershipCandidate | null {\n if (!value || typeof value !== \"object\") {\n return null;\n }\n\n const candidate = value as Partial<SpaceJoinMembershipCandidate>;\n const profileId = String(candidate.profileId ?? \"\").trim();\n const profileName = String(candidate.profileName ?? \"\").trim();\n const profileKind = resolveSpaceJoinMembershipProfileKind(\n candidate.profileKind\n );\n if (!(profileId && profileName && profileKind)) {\n return null;\n }\n\n return {\n profileId,\n profileName,\n profileKind,\n alreadyJoined: candidate.alreadyJoined === true,\n needsActivation: candidate.needsActivation === true,\n profileHandle: normalizeOptionalString(candidate.profileHandle),\n ownerProfileName: normalizeOptionalString(candidate.ownerProfileName),\n ownerUserId: normalizeOptionalString(candidate.ownerUserId),\n ownerName: normalizeOptionalString(candidate.ownerName),\n agentControllerRef: normalizeOptionalString(candidate.agentControllerRef),\n controllerEnabled: candidate.controllerEnabled === true,\n };\n}\n\nfunction resolveSpaceJoinMembershipProfileKind(\n value: unknown\n): SpaceJoinMembershipCandidate[\"profileKind\"] | null {\n return value === \"human\" || value === \"agent\" ? value : null;\n}\n\nfunction normalizeOptionalString(value: unknown): string | undefined {\n return typeof value === \"string\" ? value : undefined;\n}\n\nfunction buildLocallyCreatedPendingSpaceJoinMembershipCandidate(\n profile: OpenMeldProfile\n): SpaceJoinMembershipCandidate {\n return {\n profileId: profile.openMeldProfileId,\n profileHandle: profile.profileHandle,\n profileName: profile.profileName,\n profileKind: profile.profileKind === \"agent\" ? \"agent\" : \"human\",\n ownerUserId: profile.ownerUserId,\n ownerName:\n typeof profile.ownerName === \"string\" ? profile.ownerName : undefined,\n agentControllerRef: undefined,\n controllerEnabled: false,\n alreadyJoined: false,\n needsActivation: false,\n };\n}\n\nasync function confirmJoinAddMembersBeforeConnect(input: {\n allowBack: boolean;\n}): Promise<\"yes\" | \"no\" | \"back\" | null> {\n const prompt = buildBringProfilesWithYouPromptConfig();\n const next = await select({\n message: prompt.message,\n initialValue: \"no\",\n options: [\n prompt.noOption,\n prompt.yesOption,\n ...(input.allowBack ? [prompt.backOption] : []),\n ],\n });\n if (isCancel(next)) {\n cancel(\"Cancelled.\");\n return null;\n }\n if (next === \"yes\" || next === \"no\" || next === \"back\") {\n return next;\n }\n throw new Error(`unexpected join add-members decision: ${String(next)}`);\n}\n\nasync function runJoinCreateProfileBeforeConnect(\n input: {\n resolvedView: \"human\" | \"agent\";\n presenter: JoinMembershipBootstrapPresenter;\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<OpenMeldProfile | \"cancelled\" | null> {\n const draft = await resolveJoinCreatedProfileDraft(\n {\n resolvedView: input.resolvedView,\n },\n dependencies\n );\n if (draft === \"cancelled\") {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n if (!draft) {\n return null;\n }\n\n const created = await dependencies.createProfileByKind({\n profileName: draft.profileName,\n profileKind: draft.profileKind,\n ...(draft.localAgentSelection\n ? { localAgentSelection: draft.localAgentSelection }\n : {}),\n });\n if (draft.setupResult?.status === \"configured\") {\n await dependencies.persistAgentTransportSelection({\n agentControllerRef: draft.setupResult.agentControllerRef,\n transportMode: draft.setupResult.transportMode,\n });\n }\n emitJoinCreatedProfileCard({\n presenter: input.presenter,\n profile: created,\n setupResult: draft.setupResult,\n });\n await emitJoinCreatedProfileReadinessNotice({\n presenter: input.presenter,\n profile: created,\n setupResult: draft.setupResult,\n });\n return created;\n}\n\nasync function resolveJoinCreatedProfileDraft(\n input: {\n resolvedView: \"human\" | \"agent\";\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<\n | {\n profileKind: CreateProfileKind;\n profileName: string;\n localAgentSelection?: {\n agentControllerRef: string;\n controllerEnabled: boolean;\n };\n setupResult: AgentProfileSetupResult | null;\n }\n | \"cancelled\"\n | null\n> {\n while (true) {\n const profileKind = await dependencies.resolveCreateProfileKind({\n explicitKind: undefined,\n allowPrompt: true,\n resolvedView: input.resolvedView,\n allowBack: true,\n backLabel: \"Back\",\n });\n if (profileKind.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (profileKind.status === \"back\") {\n return null;\n }\n\n while (true) {\n const profileName = await dependencies.resolveCreateProfileName({\n explicitProfileName: undefined,\n allowPrompt: true,\n resolvedView: input.resolvedView,\n profileKind: profileKind.value,\n allowBack: true,\n backLabel: \"Back\",\n });\n if (profileName.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (profileName.status === \"back\") {\n break;\n }\n\n const localAgentSelectionResolution =\n await resolveJoinCreatedProfileLocalAgentSelection(\n profileKind.value,\n dependencies\n );\n if (localAgentSelectionResolution.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (localAgentSelectionResolution.status === \"back\") {\n continue;\n }\n\n return {\n profileKind: profileKind.value,\n profileName: profileName.value,\n localAgentSelection: localAgentSelectionResolution.localAgentSelection,\n setupResult: localAgentSelectionResolution.setupResult,\n };\n }\n }\n}\n\nasync function resolveJoinCreatedProfileLocalAgentSelection(\n profileKind: CreateProfileKind,\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<\n | {\n status: \"submitted\";\n localAgentSelection?: {\n agentControllerRef: string;\n controllerEnabled: boolean;\n };\n setupResult: AgentProfileSetupResult | null;\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n }\n> {\n if (profileKind !== \"agent\") {\n return {\n status: \"submitted\",\n setupResult: null,\n };\n }\n\n const setupResult = await dependencies.resolveAgentProfileSetup({\n interactive: true,\n useAutoSelectionWhenNonInteractive: false,\n selectControllerMessage:\n \"Choose which agent controller this profile should use.\",\n selectTransportModeMessage:\n \"How should this profile connect to its agent controller?\",\n selectResponsePolicyMessage: \"When should this profile auto-reply?\",\n skipControllerOptionLabel: \"Skip for now\",\n allowBackToCaller: true,\n });\n if (setupResult.status === \"cancelled\") {\n return {\n status: \"cancelled\",\n };\n }\n if (setupResult.status === \"back\") {\n return {\n status: \"back\",\n };\n }\n return {\n status: \"submitted\",\n ...(setupResult.status === \"configured\"\n ? {\n localAgentSelection: {\n agentControllerRef: setupResult.agentControllerRef,\n controllerEnabled: true,\n },\n }\n : {}),\n setupResult,\n };\n}\n\nfunction emitJoinCreatedProfileCard(input: {\n presenter: JoinMembershipBootstrapPresenter;\n profile: OpenMeldProfile;\n setupResult: AgentProfileSetupResult | null;\n}): void {\n const controllerSummary =\n input.setupResult?.status === \"configured\"\n ? `${input.setupResult.controllerDisplayName} (${input.setupResult.agentControllerRef})`\n : \"Not set up\";\n const transportSummary =\n input.setupResult?.status === \"configured\"\n ? formatTransportModeDisplay(input.setupResult.transportMode)\n : \"Not set up\";\n\n renderInfoCard({\n presenter: input.presenter,\n title: \"Profile Created\",\n codePrefix: \"space.join.profile_created.card\",\n rows: [\n {\n label: \"Profile Name\",\n value: input.profile.profileName,\n },\n {\n label: \"Type\",\n value: input.profile.profileKind,\n },\n {\n label: \"Profile ID\",\n value: input.profile.openMeldProfileId,\n },\n {\n label: \"Agent\",\n value: controllerSummary,\n },\n {\n label: \"Connection Type\",\n value: transportSummary,\n },\n ],\n sanitize: true,\n });\n\n if (!input.setupResult || input.setupResult.status === \"configured\") {\n return;\n }\n\n const assignControllerCommand = `openmeld setup --profile ${input.profile.openMeldProfileId} --local-agent <agent-id>`;\n const summary =\n input.setupResult.status === \"skipped_no_enabled_controllers\"\n ? \"OpenMeld created this profile without an agent because none is turned on right now.\"\n : \"OpenMeld created this profile without an agent.\";\n input.presenter.line({\n code: \"space.join.profile_setup.skipped\",\n text: formatInlineOpenMeldCliCommands(\n `${summary} You can set one later with \\`${assignControllerCommand}\\`.`\n ),\n });\n}\n\nasync function emitJoinCreatedProfileReadinessNotice(input: {\n presenter: JoinMembershipBootstrapPresenter;\n profile: OpenMeldProfile;\n setupResult: AgentProfileSetupResult | null;\n}): Promise<void> {\n if (\n input.profile.profileKind !== \"agent\" ||\n input.setupResult?.status !== \"configured\"\n ) {\n return;\n }\n\n const replyReadinessSnapshot = await resolveCurrentReplyReadinessSnapshot({\n checkGatewayChain: false,\n openClawDiagnosticsMode: \"repair\",\n ownerUserId: input.profile.ownerUserId,\n profile: input.profile,\n }).catch(() => null);\n const agentReplyReadiness = replyReadinessSnapshot?.agentReplyReadiness;\n if (\n !replyReadinessSnapshot ||\n agentReplyReadiness?.replyReadiness !== \"blocked\"\n ) {\n return;\n }\n\n const guidance = buildReplyReadinessGuidance({\n openClawLocalDiagnostics: resolveOpenClawLocalDiagnosticsValue(\n replyReadinessSnapshot.openClawLocalDiagnostics\n ),\n profile: input.profile,\n replyReadiness: agentReplyReadiness,\n });\n\n renderInfoCard({\n presenter: input.presenter,\n title: \"Can't Reply Yet\",\n codePrefix: \"space.join.profile_ready_attention.card\",\n sanitize: true,\n rows: [\n {\n label: \"Profile Name\",\n value: input.profile.profileName,\n },\n {\n label: \"Can Reply in Space\",\n value: \"Unavailable\",\n },\n {\n label: \"Why\",\n value: guidance.summary,\n },\n {\n label: \"Do This\",\n value:\n guidance.nextSteps[0] ??\n formatInlineOpenMeldCliCommands(\n \"retry after OpenMeld local setup is fixed\"\n ),\n },\n ...(guidance.nextSteps[1]\n ? [\n {\n label: \"Then\",\n value: guidance.nextSteps[1],\n },\n ]\n : []),\n ],\n });\n}\n\nasync function applySelectedSpaceAddMembersBeforeJoin(\n input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n publicExposure: PublicSpaceExposure | null;\n resolvedView: \"human\" | \"agent\";\n presenter: JoinMembershipBootstrapPresenter;\n selectedCandidates: SpaceJoinMembershipCandidate[];\n cancelResult: \"cancelled\" | \"back\";\n },\n dependencies: SpaceJoinMembershipBootstrapDependencies\n): Promise<\"completed\" | \"cancelled\" | \"back\"> {\n const confirmedCandidates =\n await filterAgentCandidatesForPublicSpaceBeforeJoin({\n candidates: input.selectedCandidates,\n publicExposure: input.publicExposure,\n });\n if (confirmedCandidates.status === \"cancelled\") {\n return input.cancelResult;\n }\n if (confirmedCandidates.skippedAgentCount > 0) {\n const profileLabel =\n confirmedCandidates.skippedAgentCount === 1 ? \"profile\" : \"profiles\";\n input.presenter.line({\n code: \"space.add_members.public_agent_skipped\",\n text: `Skipped ${String(confirmedCandidates.skippedAgentCount)} agent ${profileLabel} because anyone with the link can read this Space.`,\n data: {\n spaceId: input.space,\n skippedAgentCount: confirmedCandidates.skippedAgentCount,\n },\n });\n }\n if (confirmedCandidates.candidates.length === 0) {\n return \"completed\";\n }\n\n const servicePreparationResult =\n await dependencies.prepareSpaceMemberCandidatesLocalParticipation({\n actorProfile: input.actorProfile,\n candidates: confirmedCandidates.candidates,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n });\n if (servicePreparationResult.status === \"cancelled\") {\n return input.cancelResult;\n }\n\n const result = await dependencies.applySpaceAddMembers({\n actorProfile: input.actorProfile,\n candidates: servicePreparationResult.candidates,\n space: input.space,\n baseUrl: input.baseUrl,\n password: input.password,\n });\n const joinNoticeSummary =\n await dependencies.persistSpaceAddMembersJoinNotices({\n actorProfile: input.actorProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n addedMembers: result.added,\n });\n dependencies.emitSpaceAddMembersResult({\n mode: \"profiles\",\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n space: input.space,\n selectedCount: servicePreparationResult.candidates.length,\n result,\n joinNoticeSummary,\n });\n if (result.failed.length > 0 && result.added.length === 0) {\n throw new Error(\n `failed to add members for space ${input.space}: ${toErrorMessage(result.failed[0]?.error)}`\n );\n }\n return \"completed\";\n}\n\nasync function filterAgentCandidatesForPublicSpaceBeforeJoin(input: {\n candidates: SpaceJoinMembershipCandidate[];\n publicExposure: PublicSpaceExposure | null;\n}): Promise<\n | {\n status: \"ready\";\n candidates: SpaceJoinMembershipCandidate[];\n skippedAgentCount: number;\n }\n | { status: \"cancelled\" }\n> {\n if (!input.publicExposure) {\n return {\n status: \"ready\",\n candidates: input.candidates,\n skippedAgentCount: 0,\n };\n }\n\n const agentCandidates = input.candidates.filter(\n (candidate) => candidate.profileKind === \"agent\"\n );\n if (agentCandidates.length === 0) {\n return {\n status: \"ready\",\n candidates: input.candidates,\n skippedAgentCount: 0,\n };\n }\n\n const confirmed = await confirm({\n ...buildPublicSpaceBringAgentsConfirmPromptConfig({\n agentCount: agentCandidates.length,\n exposure: input.publicExposure,\n }),\n initialValue: true,\n });\n if (isCancel(confirmed)) {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (confirmed) {\n return {\n status: \"ready\",\n candidates: input.candidates,\n skippedAgentCount: 0,\n };\n }\n return {\n status: \"ready\",\n candidates: input.candidates.filter(\n (candidate) => candidate.profileKind !== \"agent\"\n ),\n skippedAgentCount: agentCandidates.length,\n };\n}\n\nfunction toErrorMessage(error: unknown): string {\n if (error instanceof Error && error.message.trim().length > 0) {\n return error.message;\n }\n return String(error);\n}\n","import { cancel, isCancel, text } from \"@clack/prompts\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport type { createPresenter } from \"../runtime/presenter/index\";\nimport {\n normalizeRoleValue,\n normalizeStoredMentionAliasValue,\n resolveSessionMentionAlias,\n resolveSessionRoleContext,\n} from \"./connect-session-meta\";\nimport type { SpaceConfig } from \"./local-state\";\n\nconst MENTION_ALIAS_TOKEN_REGEX = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;\n\ntype JoinRoleAliasBootstrapPresenter = Pick<\n ReturnType<typeof createPresenter>,\n \"event\"\n>;\n\ntype JoinBootstrapSource = \"explicit\" | \"cloud\" | \"local\" | \"none\";\n\ntype SpaceJoinCursorBootstrap = {\n role?: string;\n mentionAlias?: string;\n};\n\nexport type SpaceJoinRoleAliasBootstrapResult =\n | {\n status: \"ready\";\n role?: string;\n mentionAlias?: string;\n roleSource: JoinBootstrapSource;\n mentionAliasSource: JoinBootstrapSource;\n usedCursorBootstrap: boolean;\n }\n | { status: \"cancelled\" };\n\nexport type SpaceJoinRoleAliasBootstrapDependencies = {\n fetchSpaceCursorForBootstrap(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n }): Promise<SpaceJoinCursorBootstrap>;\n};\n\n// Join role/alias bootstrap owns join-side cursor-backed precedence,\n// first-local-join role prompting, and bootstrap summary emission only.\nexport async function resolveSpaceJoinRoleAliasBootstrap(\n input: {\n openMeldProfile: OpenMeldProfile;\n openMeldProfileId: string;\n baseUrl: string;\n space: string;\n password?: string;\n existingSpaceConfig: SpaceConfig | null;\n roleInput?: string;\n mentionAliasInput?: string;\n resolvedView: \"human\" | \"agent\";\n allowPromptRoleContext: boolean;\n presenter: JoinRoleAliasBootstrapPresenter;\n },\n dependencies: SpaceJoinRoleAliasBootstrapDependencies\n): Promise<SpaceJoinRoleAliasBootstrapResult> {\n const explicitRole = normalizeRoleValue(input.roleInput);\n const explicitMentionAliasInputProvided =\n typeof input.mentionAliasInput === \"string\";\n const explicitMentionAlias = normalizeJoinMentionAliasInput(\n input.mentionAliasInput\n );\n if (explicitMentionAliasInputProvided && !explicitMentionAlias) {\n throw new Error(\n \"invalid --mention-alias: use letters/numbers with optional . _ - (max 128 chars)\"\n );\n }\n\n const localRole = normalizeRoleValue(input.existingSpaceConfig?.role);\n const localMentionAlias = normalizeStoredMentionAliasValue({\n mentionAlias: input.existingSpaceConfig?.mentionAlias,\n profileId: input.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n profileKind: input.openMeldProfile.profileKind,\n });\n\n const cursorBootstrap = await dependencies\n .fetchSpaceCursorForBootstrap({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n })\n .catch(() => null);\n const cloudRole = normalizeRoleValue(cursorBootstrap?.role);\n const cloudMentionAlias = normalizeStoredMentionAliasValue({\n mentionAlias: cursorBootstrap?.mentionAlias,\n profileId: input.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n profileKind: input.openMeldProfile.profileKind,\n });\n\n let roleContext = resolveSessionRoleContext({\n inputRole: explicitRole,\n cloudRole,\n localRole,\n });\n let roleSource = resolveFieldBootstrapSource({\n explicitValue: explicitRole,\n cloudValue: cloudRole,\n localValue: localRole,\n });\n if (\n input.resolvedView === \"human\" &&\n input.allowPromptRoleContext &&\n input.existingSpaceConfig === null\n ) {\n const promptedRole = await resolvePromptedOptionalRoleField({\n currentValue: roleContext.role,\n message: \"Role\",\n placeholder:\n \"e.g. Responsible for final architecture direction and design reviews.\",\n });\n if (promptedRole === null) {\n return { status: \"cancelled\" };\n }\n\n roleContext = {\n ...(promptedRole ? { role: promptedRole } : {}),\n };\n roleSource = resolvePromptedFieldBootstrapSource({\n currentSource: roleSource,\n value: promptedRole,\n });\n }\n\n const mentionAlias = resolveSessionMentionAlias({\n inputMentionAlias: explicitMentionAlias,\n cloudMentionAlias,\n localMentionAlias,\n profileId: input.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n profileKind: input.openMeldProfile.profileKind,\n });\n const mentionAliasSource = resolveMentionAliasBootstrapSource({\n explicitMentionAliasInputProvided,\n explicitMentionAlias,\n cloudMentionAlias,\n localMentionAlias,\n });\n const usedCursorBootstrap =\n roleSource === \"cloud\" || mentionAliasSource === \"cloud\";\n\n emitJoinBootstrapContext({\n presenter: input.presenter,\n role: roleContext.role,\n mentionAlias,\n roleSource,\n mentionAliasSource,\n usedCursorBootstrap,\n });\n\n return {\n status: \"ready\",\n ...(roleContext.role ? { role: roleContext.role } : {}),\n ...(mentionAlias ? { mentionAlias } : {}),\n roleSource,\n mentionAliasSource,\n usedCursorBootstrap,\n };\n}\n\nfunction resolveFieldBootstrapSource(input: {\n explicitValue?: string;\n cloudValue?: string;\n localValue?: string;\n}): JoinBootstrapSource {\n if (input.explicitValue) {\n return \"explicit\";\n }\n if (input.cloudValue) {\n return \"cloud\";\n }\n if (input.localValue) {\n return \"local\";\n }\n return \"none\";\n}\n\nfunction resolvePromptedFieldBootstrapSource(input: {\n currentSource: JoinBootstrapSource;\n value?: string;\n}): JoinBootstrapSource {\n if (input.currentSource !== \"none\") {\n return input.currentSource;\n }\n if (input.value) {\n return \"explicit\";\n }\n return \"none\";\n}\n\nfunction resolveMentionAliasBootstrapSource(input: {\n explicitMentionAliasInputProvided: boolean;\n explicitMentionAlias?: string;\n cloudMentionAlias?: string;\n localMentionAlias?: string;\n}): JoinBootstrapSource {\n if (input.explicitMentionAliasInputProvided) {\n return input.explicitMentionAlias ? \"explicit\" : \"none\";\n }\n if (input.cloudMentionAlias) {\n return \"cloud\";\n }\n if (input.localMentionAlias) {\n return \"local\";\n }\n return \"none\";\n}\n\nfunction normalizeJoinMentionAliasInput(value: unknown): string | undefined {\n if (typeof value !== \"string\") {\n return undefined;\n }\n const normalized = value.trim();\n if (\n normalized.length === 0 ||\n normalized.length > 128 ||\n !MENTION_ALIAS_TOKEN_REGEX.test(normalized)\n ) {\n return undefined;\n }\n return normalized;\n}\n\nasync function resolvePromptedOptionalRoleField(input: {\n currentValue?: string;\n message: string;\n placeholder: string;\n}): Promise<string | undefined | null> {\n if (input.currentValue) {\n return input.currentValue;\n }\n\n const value = await text({\n message: `${input.message} (optional)`,\n placeholder: input.placeholder,\n });\n if (isCancel(value)) {\n cancel(\"Cancelled.\");\n return null;\n }\n\n return normalizeRoleValue(typeof value === \"string\" ? value : undefined);\n}\n\nfunction emitJoinBootstrapContext(input: {\n presenter: JoinRoleAliasBootstrapPresenter;\n role?: string;\n mentionAlias?: string;\n roleSource: JoinBootstrapSource;\n mentionAliasSource: JoinBootstrapSource;\n usedCursorBootstrap: boolean;\n}): void {\n if (!(input.role || input.mentionAlias)) {\n return;\n }\n\n input.presenter.event(\"info\", \"space.join.bootstrap_context\", {\n ...(input.role ? { role: input.role } : {}),\n ...(input.mentionAlias ? { mentionAlias: input.mentionAlias } : {}),\n roleSource: input.roleSource,\n mentionAliasSource: input.mentionAliasSource,\n usedCursorBootstrap: input.usedCursorBootstrap,\n });\n}\n","import {\n leaveSpaceResponseSchema,\n postSpaceMembersResponseSchema,\n removeSpaceMembersResponseSchema,\n} from \"@openmeld/schemas\";\nimport type {\n LeaveSpaceResponse,\n OpenMeldRequestContext,\n PostSpaceMembersResponse,\n RemoveSpaceMembersResponse,\n} from \"@openmeld/schemas/types\";\nimport { buildOpenMeldRequestContextHeadersWithAuth } from \"../config/request-headers\";\nimport {\n toSpaceLeaveUrl,\n toSpaceMembersUrl,\n toSpaceRemoveMembersUrl,\n} from \"../protocol/urls\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport { readGatewayJsonResponse } from \"./gateway-response\";\n\nexport async function postSpaceMembers(input: {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n memberProfileIds: string[];\n}): Promise<PostSpaceMembersResponse> {\n const endpoint = toSpaceMembersUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.members.add\",\n init: {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n memberProfileIds: input.memberProfileIds,\n }),\n },\n });\n return await readGatewayJsonResponse({\n response,\n schema: postSpaceMembersResponseSchema,\n invalidMessage: \"invalid add-members response\",\n });\n}\n\nexport async function removeSpaceMembers(input: {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n memberProfileIds: string[];\n}): Promise<RemoveSpaceMembersResponse> {\n const endpoint = toSpaceRemoveMembersUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.members.remove\",\n init: {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n memberProfileIds: input.memberProfileIds,\n }),\n },\n });\n return await readGatewayJsonResponse({\n response,\n schema: removeSpaceMembersResponseSchema,\n invalidMessage: \"invalid remove-members response\",\n });\n}\n\nexport async function leaveSpace(input: {\n requestContext: OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n}): Promise<LeaveSpaceResponse> {\n const endpoint = toSpaceLeaveUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.leave\",\n init: {\n method: \"POST\",\n headers,\n },\n });\n return await readGatewayJsonResponse({\n response,\n schema: leaveSpaceResponseSchema,\n invalidMessage: \"invalid leave-space response\",\n });\n}\n","import { resolveBaseUrl } from \"../config/base-url\";\nimport type { OpenMeldProfile } from \"../config/openmeld-profiles-api\";\nimport { buildOpenMeldRequestContextFromProfile } from \"../config/openmeld-request-context\";\nimport { requireOpenMeldProfile } from \"../config/resolve-openmeld-profile\";\nimport { sanitizeText } from \"../protocol/wire\";\nimport { resolveRuntimeContext } from \"../runtime/context\";\nimport { assertDispatchOwnedRuntimePublicWriteAllowed } from \"../runtime/dispatch-owned-runtime\";\nimport { formatMessage } from \"../runtime/messages\";\nimport { createPresenter } from \"../runtime/presenter/index\";\nimport { rethrowSpaceAddressingSnapshotLoadFailure } from \"./addressing-preflight\";\nimport { createCliSpaceApi } from \"./cli-space-api\";\nimport { assertFullSignalIdArgument } from \"./command-context\";\nimport {\n type CliSpaceAddressingTarget,\n prepareCliSpaceComposerSubmission,\n} from \"./composer-submission-adapter\";\nimport {\n prepareRequestedSpaceSendFiles,\n uploadPreparedSpaceFiles,\n} from \"./send-files\";\n\nexport async function runSend(input: {\n contextSelection?: import(\"@openmeld/schemas/types\").ExecutionContextSelection;\n wakeTargets?: readonly string[];\n referenceTargets?: readonly string[];\n mentionTargets?: readonly string[];\n profile?: string;\n baseUrl?: string;\n space: string;\n filePaths?: readonly string[];\n password?: string;\n plainText?: boolean;\n replyToSignalId?: string;\n text: string;\n openMeldProfile?: OpenMeldProfile;\n view?: string;\n}) {\n assertDispatchOwnedRuntimePublicWriteAllowed({\n commandLabel: \"openmeld space send\",\n });\n const hasRecipients = [\n input.wakeTargets,\n input.referenceTargets,\n input.mentionTargets,\n ].some((targets) => Boolean(targets?.length));\n if (input.plainText && hasRecipients) {\n throw new Error(\n \"--plain cannot be combined with --wake, --reference, or --mention.\"\n );\n }\n\n const runtime = await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n });\n const presenter = createPresenter(runtime);\n\n const openMeldProfile =\n input.openMeldProfile ??\n (await requireOpenMeldProfile({\n openMeldProfileId: input.profile,\n persistSelection: false,\n authAction: \"sending a message\",\n }));\n const baseUrl = await resolveBaseUrl(input.baseUrl);\n const spaceApi = createCliSpaceApi(baseUrl);\n const space = input.space.trim();\n\n assertFullSignalIdArgument({\n value: input.replyToSignalId,\n flag: \"--reply-to\",\n resolvedView: runtime.resolvedView,\n });\n const preparedFiles = await prepareRequestedSpaceSendFiles({\n filePaths: input.filePaths ?? [],\n });\n\n const owner =\n openMeldProfile.profileKind === \"agent\"\n ? String(openMeldProfile.ownerUserId ?? \"\").trim()\n : \"\";\n const ownerName =\n openMeldProfile.profileKind === \"agent\"\n ? String(openMeldProfile.ownerName ?? \"\").trim()\n : \"\";\n const profileIdentity = {\n kind: openMeldProfile.profileKind,\n profileId: openMeldProfile.openMeldProfileId,\n profileHandle: openMeldProfile.profileHandle,\n profileName: openMeldProfile.profileName,\n ...(owner ? { owner } : {}),\n ...(ownerName ? { ownerName } : {}),\n };\n\n const text =\n input.text.trim().length === 0 && preparedFiles.length > 0\n ? { ok: true as const, value: \"\" }\n : sanitizeText(input.text);\n if (!text.ok) {\n throw new Error(text.reason);\n }\n emitAgentSendProgress({\n presenter,\n resolvedView: runtime.resolvedView,\n stage: \"prepare_message\",\n summary: \"Preparing message text and explicit recipients.\",\n spaceId: space,\n });\n const { outboundMessageEnvelope, outboundText, resolvedAddressingTargets } =\n await resolveOutboundSubmission({\n wakeTargets: input.wakeTargets,\n referenceTargets: input.referenceTargets,\n mentionTargets: input.mentionTargets,\n openMeldProfile,\n password: input.password,\n plainText: input.plainText === true,\n presenter,\n resolvedView: runtime.resolvedView,\n space,\n spaceApi,\n text: text.value,\n });\n emitSendAddressingSummary({\n outboundMessageEnvelope,\n presenter,\n resolvedAddressingTargets,\n resolvedView: runtime.resolvedView,\n });\n\n presenter.line({\n code: \"send.acting_profile\",\n text: `sender: ${profileIdentity.profileId} (${profileIdentity.kind})`,\n data: {\n profileId: profileIdentity.profileId,\n profileKind: profileIdentity.kind,\n profileName: profileIdentity.profileName,\n },\n });\n\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile,\n });\n emitFileUploadProgress({\n fileCount: preparedFiles.length,\n presenter,\n resolvedView: runtime.resolvedView,\n spaceId: space,\n });\n const files = await uploadPreparedSpaceFiles({\n files: preparedFiles,\n password: input.password,\n requestContext,\n spaceApi,\n spaceId: space,\n });\n const clientMessageId = crypto.randomUUID();\n emitAgentSendProgress({\n presenter,\n resolvedView: runtime.resolvedView,\n stage: \"post_message\",\n summary: \"Posting the Space message through OpenMeld Gateway.\",\n spaceId: space,\n });\n const replyToSignalId = String(input.replyToSignalId ?? \"\").trim();\n const payload = replyToSignalId\n ? await postReplyIntoThread({\n contextSelection: input.contextSelection,\n spaceApi,\n space,\n requestContext,\n password: input.password,\n replyToSignalId,\n outboundText,\n outboundMessageEnvelope,\n clientMessageId,\n files,\n })\n : await spaceApi.postNormalMessage({\n contextSelection: input.contextSelection,\n spaceId: space,\n requestContext,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n text: outboundText,\n ...toSpaceMessageFilesField(files),\n meta: {\n clientMessageId,\n },\n ...(outboundMessageEnvelope\n ? { messageEnvelope: outboundMessageEnvelope }\n : {}),\n });\n\n presenter.data({\n code: \"send.response\",\n payload,\n });\n emitSentFileResult({\n fileCount: files.length,\n presenter,\n signalId: payload.id,\n });\n presenter.line({\n code: \"send.sent\",\n text: formatMessage(runtime.resolvedView, \"send.sent\"),\n });\n}\n\n// Post a reply into the thread rooted at replyToSignalId. Finds the existing\n// thread for that root message, or creates one if none exists yet (the CLI is\n// otherwise unable to start a thread — only web did before). Reuses the existing\n// createThread/postThreadSignal API; backend untouched.\nasync function postReplyIntoThread(input: {\n contextSelection?: import(\"@openmeld/schemas/types\").ExecutionContextSelection;\n spaceApi: ReturnType<typeof createCliSpaceApi>;\n space: string;\n requestContext: import(\"@openmeld/schemas/types\").OpenMeldRequestContext;\n password?: string;\n replyToSignalId: string;\n outboundText: string;\n outboundMessageEnvelope?: Awaited<\n ReturnType<typeof prepareCliSpaceComposerSubmission>\n >[\"outboundMessageEnvelope\"];\n clientMessageId: string;\n files: Awaited<ReturnType<typeof uploadPreparedSpaceFiles>>;\n}) {\n const threadsResponse = await input.spaceApi.listThreads({\n spaceId: input.space,\n requestContext: input.requestContext,\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n });\n const existingThread = threadsResponse.threads.find(\n (thread) => thread.rootSignalId === input.replyToSignalId\n );\n let threadId = existingThread?.threadId;\n if (!threadId) {\n const created = await input.spaceApi.createThread({\n spaceId: input.space,\n rootSignalId: input.replyToSignalId,\n clientMutationId: crypto.randomUUID(),\n requestContext: input.requestContext,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n threadId = created.thread.threadId;\n }\n const result = await input.spaceApi.postThreadSignal({\n spaceId: input.space,\n threadId,\n requestContext: input.requestContext,\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n body: {\n contextSelection: input.contextSelection,\n text: input.outboundText,\n clientMessageId: input.clientMessageId,\n ...toSpaceMessageFilesField(input.files),\n ...(input.outboundMessageEnvelope\n ? { messageEnvelope: input.outboundMessageEnvelope }\n : {}),\n },\n });\n return result.signal;\n}\n\nasync function resolveOutboundSubmission(input: {\n wakeTargets?: readonly string[];\n referenceTargets?: readonly string[];\n mentionTargets?: readonly string[];\n openMeldProfile: OpenMeldProfile;\n password?: string;\n plainText: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n space: string;\n spaceApi: ReturnType<typeof createCliSpaceApi>;\n text: string;\n}): Promise<{\n outboundMessageEnvelope?: Awaited<\n ReturnType<typeof prepareCliSpaceComposerSubmission>\n >[\"outboundMessageEnvelope\"];\n outboundText: string;\n resolvedAddressingTargets: readonly CliSpaceAddressingTarget[];\n}> {\n const preparedSubmission = await prepareCliSpaceComposerSubmission({\n wakeTargets: input.wakeTargets,\n referenceTargets: input.referenceTargets,\n mentionTargets: input.mentionTargets,\n missingSnapshotMessage:\n \"Cannot validate recipients because current Space members could not be loaded.\",\n onSnapshotLoadFailure: (error) => {\n rethrowSpaceAddressingSnapshotLoadFailure(error);\n },\n loadMembersSnapshot: async () => {\n emitAgentSendProgress({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n stage: \"load_members\",\n summary: \"Loading current Space members to validate recipients.\",\n spaceId: input.space,\n });\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n });\n return await input.spaceApi.getMembersSnapshot({\n requestContext,\n spaceId: input.space,\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n },\n text: input.text,\n });\n return {\n outboundMessageEnvelope: preparedSubmission.outboundMessageEnvelope,\n outboundText: preparedSubmission.outboundText,\n resolvedAddressingTargets: preparedSubmission.resolvedAddressingTargets,\n };\n}\n\nfunction emitSendAddressingSummary(input: {\n outboundMessageEnvelope:\n | Awaited<\n ReturnType<typeof prepareCliSpaceComposerSubmission>\n >[\"outboundMessageEnvelope\"]\n | undefined;\n presenter: ReturnType<typeof createPresenter>;\n resolvedAddressingTargets: readonly CliSpaceAddressingTarget[];\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (input.resolvedView !== \"agent\") {\n return;\n }\n const envelope = input.outboundMessageEnvelope;\n const wakeCount = envelope?.activationTargets.length ?? 0;\n const referenceCount = envelope?.referenceTargets.length ?? 0;\n const mentionCount = envelope?.mentionTargets?.length ?? 0;\n input.presenter.line({\n code: \"space.send.addressing_summary\",\n text: `Space Message Addressing: wake=${wakeCount}, reference=${referenceCount}, mention=${mentionCount}.`,\n data: {\n mentionTargetCount: mentionCount,\n referenceTargetCount: referenceCount,\n ...(input.resolvedAddressingTargets.length > 0\n ? { targets: input.resolvedAddressingTargets }\n : {}),\n wakeTargetCount: wakeCount,\n },\n });\n}\n\nfunction emitAgentSendProgress(input: {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n stage: \"prepare_message\" | \"load_members\" | \"upload_files\" | \"post_message\";\n summary: string;\n spaceId: string;\n}): void {\n if (input.resolvedView !== \"agent\") {\n return;\n }\n input.presenter.line({\n code: \"send.progress\",\n text: `${input.stage}: ${input.summary}`,\n data: {\n spaceId: input.spaceId,\n stage: input.stage,\n },\n });\n}\n\nfunction emitFileUploadProgress(input: {\n fileCount: number;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n spaceId: string;\n}): void {\n if (input.fileCount === 0) {\n return;\n }\n emitAgentSendProgress({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n stage: \"upload_files\",\n summary: `Adding ${input.fileCount} file${input.fileCount === 1 ? \"\" : \"s\"} to this Space before sending the message.`,\n spaceId: input.spaceId,\n });\n}\n\nfunction toSpaceMessageFilesField(\n files: Awaited<ReturnType<typeof uploadPreparedSpaceFiles>>\n):\n | {\n files: Awaited<ReturnType<typeof uploadPreparedSpaceFiles>>[number][];\n }\n | Record<string, never> {\n return files.length > 0 ? { files: [...files] } : {};\n}\n\nfunction emitSentFileResult(input: {\n fileCount: number;\n presenter: ReturnType<typeof createPresenter>;\n signalId: string;\n}): void {\n if (input.fileCount === 0) {\n return;\n }\n input.presenter.line({\n code: \"send.files_sent\",\n text: `Sent Space message ${input.signalId} with ${input.fileCount} file${input.fileCount === 1 ? \"\" : \"s\"}.`,\n data: {\n fileCount: input.fileCount,\n signalId: input.signalId,\n },\n });\n}\n","import {\n cancel,\n confirm,\n isCancel,\n multiselect,\n password as passwordPrompt,\n select,\n text,\n} from \"@clack/prompts\";\nimport {\n createOrganizationApi,\n type SpaceSignalsReadQuery,\n} from \"@openmeld/api-client\";\nimport type { SpaceCreator, SpaceMeta } from \"@openmeld/protocol\";\nimport {\n normalizeBuiltinAgentControllerId,\n normalizeSpacePasswordText,\n resolveInitialSpaceAccessMode,\n resolveSingleSpaceMentionLabels,\n SPACE_MEMBER_JOIN_NOTICE_PURPOSE,\n SPACE_MEMBER_REMOVE_NOTICE_PURPOSE,\n SPACE_PASSWORD_MIN_LENGTH,\n} from \"@openmeld/schemas\";\nimport type {\n AccountSpaceIndexQuery,\n LeaveSpaceResponse,\n OpenMeldRequestContext,\n OrganizationDirectoryResponse,\n PostSpaceMembersResponse,\n RemoveSpaceMembersResponse,\n SpaceMembersSnapshot,\n} from \"@openmeld/schemas/types\";\nimport {\n buildSpaceProfileAddPlan,\n type SpaceProfileAddInvalidSelection,\n type SpaceProfileAddMode,\n type SpaceProfileAddProfile,\n} from \"@openmeld/space\";\nimport pc from \"picocolors\";\nimport {\n type AgentTargetState,\n listAgentTargetStates,\n} from \"../agents/registry\";\nimport {\n type AuthenticationGuidance,\n type AuthenticationGuidanceReason,\n buildHumanAuthenticationCard,\n resolveAuthenticationGuidance,\n} from \"../auth/auth-guidance\";\nimport { buildCommandAuthenticationPromptMessage } from \"../auth/command-auth\";\nimport { getCurrentCommandCheckState } from \"../command-entry-checks/current-command-check-state\";\nimport { resolveCurrentOpenMeldAccountContext } from \"../config/account-context\";\nimport { listAccountSpaceIndex } from \"../config/account-space-index-api\";\nimport {\n deriveAuthBaseUrlFromGatewayUrl,\n resolveAuthRequestCompatibility,\n} from \"../config/auth-request-compatibility\";\nimport {\n getAuthSessionState,\n type StoredActiveOrganization,\n type StoredAuthSession,\n} from \"../config/auth-session\";\nimport { isLoopbackHostname } from \"../config/loopback-hostname\";\nimport {\n listOpenMeldProfiles,\n type OpenMeldProfile,\n} from \"../config/openmeld-profiles-api\";\nimport {\n buildOpenMeldRequestContextFromProfile,\n buildOpenMeldRequestContextFromProfileIdentity,\n} from \"../config/openmeld-request-context\";\nimport {\n updateProfileSpaceHistoryStatus,\n upsertProfileSpaceHistory,\n} from \"../config/profile-space-history-api\";\nimport {\n buildOpenMeldProfileRequestHeadersWithAuth,\n buildOpenMeldRequestContextHeadersWithAuth,\n} from \"../config/request-headers\";\nimport { resolveLocalServiceDemand } from \"../local-service/lifecycle/local-service-demand\";\nimport {\n persistAgentTransportSelection,\n resolveAgentProfileSetup,\n} from \"../profile/agent-setup-flow\";\nimport {\n createProfileByKind,\n resolveCreateProfileKind,\n resolveCreateProfileName,\n} from \"../profile/create-flow\";\nimport {\n toSpaceCreateUrl,\n toSpaceCursorUrl,\n toSpaceDeleteUrl,\n toSpacePasswordUrl,\n} from \"../protocol/urls\";\nimport {\n formatInlineOpenMeldCliCommands,\n formatOpenMeldCliCommand,\n formatOpenMeldCliTextBlock,\n formatProfileAwareOpenMeldCliCommand,\n} from \"../runtime/cli-entry-command\";\nimport { resolveRuntimeContext } from \"../runtime/context\";\nimport { assertDispatchOwnedRuntimePublicWriteAllowed } from \"../runtime/dispatch-owned-runtime\";\nimport {\n createSpaceAddMembersCurrentProfileGuideError,\n createSpaceAddMembersGuideError,\n createSpaceCreateGuideError,\n createSpaceDeleteHumanApprovalGuideError,\n createSpaceLeaveCreatorGuideError,\n createSpaceLeaveGuideError,\n createSpaceRemoveMembersCreatorGuideError,\n createSpaceRemoveMembersCurrentProfileGuideError,\n createSpaceRemoveMembersGuideError,\n createSpaceSubcommandTargetGuideError,\n createSpaceTargetGuideError,\n} from \"../runtime/dual-view-guide-catalog\";\nimport { canUseInteractivePrompts } from \"../runtime/interaction\";\nimport { formatMessage } from \"../runtime/messages\";\nimport { createPresenter } from \"../runtime/presenter/index\";\nimport {\n type ActionParticipationCandidate,\n type ActionParticipationPlan,\n planActionParticipation,\n} from \"../system/action-participation-planner\";\nimport { resolveAgentProfilePrimaryAgentControllerReport } from \"../system/agent-profile-primary-binding\";\nimport { resolveCurrentReplyReadinessSnapshot } from \"../system/current-reply-readiness-snapshot\";\nimport { ensureFormalAgentBindingForReadyLocalProfile } from \"../system/formal-agent-binding-backstop\";\nimport { runLocalParticipationOrchestrator } from \"../system/local-participation-orchestrator\";\nimport { resolveServiceParticipationReadiness } from \"../system/service-participation-readiness\";\nimport { createDelayedSpinner } from \"../ui/delayed-spinner\";\nimport { renderHumanErrorCard } from \"../ui/human-error-card\";\nimport { renderInfoCard } from \"../ui/info-card\";\nimport { promptSearchMultiselect } from \"../ui/search-select\";\nimport {\n buildSpaceCreatePasswordPromptConfig,\n resolveSpaceCreatePasswordlessAccessText,\n type SpaceCreatePasswordPromptConfig,\n} from \"../ui/space-create-password-prompt\";\nimport { promptTextEntry } from \"../ui/text-entry\";\nimport {\n resolveSpaceAddMembersProgressPhase,\n SPACE_ADD_MEMBERS_PROGRESS_HEARTBEAT_MS,\n type SpaceAddMembersProgressStage,\n} from \"./add-members-progress-contract\";\nimport { emitSpaceAgentOverview } from \"./agent-overview\";\nimport { createCliApiClientFoundation } from \"./api-client-foundation\";\nimport { createCliSpaceApi } from \"./cli-space-api\";\nimport {\n assertValidSpaceIdTarget,\n ensureSpaceCommandGatewayAuthenticationOrCancel,\n prepareAuthenticatedSpaceCommandContext,\n resolveOpenMeldProfileForSpaceCommand,\n} from \"./command-context\";\nimport {\n normalizeOptionalString,\n parseHttpErrorMessage,\n readHttpErrorField,\n readHttpRequestId,\n resolveUpstreamStatus,\n safeJsonParse,\n toErrorMessage,\n} from \"./command-http-errors\";\nimport {\n normalizeDisplayValue,\n normalizeGuideInput,\n resolveGatewayHost,\n sanitizeSingleLinePromptText,\n TRAILING_SLASHES_RE,\n} from \"./command-input-normalizers\";\nimport {\n buildKnownSpaceData,\n formatKnownSpaceDetailLines,\n formatKnownSpaceListLine,\n formatKnownSpaceName,\n type KnownSpaceOption,\n type KnownSpaceVisibilityScope,\n toKnownSpaceOptionFromAccountIndex,\n} from \"./command-known-space-projection\";\nimport {\n buildSpaceMemberRepairCommand,\n formatSpaceMemberRecoveryNextAction,\n isSpaceMemberCandidateBackgroundReplyReady,\n isSpaceMemberCandidateRepairableLocalParticipationCandidate,\n resolveSpaceMemberCandidateStatusBadges,\n resolveSpaceMemberCandidateStatusLabel,\n resolveSpaceMemberJoinOnlyNextAction,\n resolveSpaceMemberJoinOnlyReason,\n resolveSpaceMemberTerminalLocalTargetLabel,\n resolveSpaceMemberTerminalProfileLabel,\n type SpaceMemberCandidate,\n type SpaceMembershipProfileKind,\n} from \"./command-member-recovery\";\nimport {\n maybeEmitKnownSpaceDeletedNotices,\n promptHumanJoinSelectionWithoutKnownSpaces,\n promptSpaceJoinSelection,\n promptSpacePasswordTargetSelection,\n promptSpaceSelectionTarget,\n resolveSpaceVisibilitySummary,\n type SpaceDeleteTarget,\n type SpaceJoinTargetResolution,\n type SpaceSelectionTarget,\n type SpaceSelectionTargetResult,\n} from \"./command-selection-prompts\";\nimport {\n filterKnownSpacesCreatedByProfile,\n normalizeMetaForHistory,\n requireReadableSpaceConfigList,\n resolveKnownSpacesForSelectionWithLoading,\n resolveSpaceDeleteTargets,\n resolveSpaceTarget,\n SPACE_LOADING_SPINNER_MESSAGE,\n} from \"./command-target-resolution\";\n\n// biome-ignore lint/performance/noBarrelFile: command.ts preserves the public import path during the move-only split.\nexport {\n formatSpaceMemberRecoveryNextAction,\n resolveSpaceMemberJoinOnlyNextAction,\n} from \"./command-member-recovery\";\n\nimport {\n isSpaceCommandOutputHandledError,\n SpaceCommandOutputHandledError,\n} from \"./command-output-handled\";\nimport {\n fetchSpaceCursor,\n parseCreateSpaceResponse,\n parseSpaceCursorResponse,\n resolveWorkflowAckHint,\n} from \"./command-send-history-leaves\";\nimport { runConnect } from \"./connect\";\nimport { fetchSpaceRequestWithTimeout } from \"./fetch-with-timeout\";\nimport {\n type StructuredGatewayFailure,\n toStructuredGatewayFailure,\n} from \"./gateway-response\";\nimport { runTail } from \"./history\";\nimport { resolveSpaceJoinAccessBootstrap } from \"./join-access-bootstrap\";\nimport { runSpaceJoinConnectHandoff } from \"./join-connect-handoff\";\nimport {\n assertSpaceJoinTargetPreflightReady,\n buildJoinTargetMissingMessage,\n type PreparedSpaceJoinEntryContext,\n prepareSpaceJoinEntryContext,\n resolveSpaceJoinEntryTargetOutcome,\n} from \"./join-entry\";\nimport { resolveSpaceJoinMembershipBootstrap } from \"./join-membership-bootstrap\";\nimport { shouldShowSpaceJoinProgress } from \"./join-progress\";\nimport { resolveSpaceJoinRoleAliasBootstrap } from \"./join-role-alias-bootstrap\";\nimport {\n isLocalSpaceStateCorruptResult,\n listSpaceConfigs,\n readSpaceConfig,\n removeSpaceConfig,\n type SpaceConfig,\n toLocalSpaceStateIntegrityError,\n upsertSpaceConfig,\n} from \"./local-state\";\nimport { validateSpaceMemberSelectionInput } from \"./member-selection-contract\";\nimport {\n leaveSpace,\n postSpaceMembers,\n removeSpaceMembers,\n} from \"./members-mutations\";\nimport { buildSpacePrimaryMentionLabelByProfileId } from \"./mention-label-state\";\nimport { fetchSpaceMeta } from \"./meta-api\";\nimport type { SpaceCommandNavigationStatus } from \"./navigation-status\";\nimport {\n buildSpacePasswordRequirementsText,\n emitSpacePasswordPromptNotice,\n promptSpacePassword,\n resolveSpacePasswordPromptReason,\n validateSpacePasswordInput,\n} from \"./password-flow\";\nimport {\n emitSpaceCommandPreflight,\n emitSpaceFailureNextStep,\n resolveSpaceFailureGuidance,\n} from \"./preflight\";\nimport { runSend } from \"./send\";\nimport { resolveSpaceSendText } from \"./send-input\";\nimport {\n buildSpaceAddMembersHumanResultCard,\n buildSpaceRemoveMembersHumanResultCard,\n getChooseMembersToRemoveMessage,\n getChooseProfilesToBringMessage,\n} from \"./space-add-members-ui\";\nimport { buildSpaceWebUrl } from \"./web-url\";\n\nconst MAX_DELETE_PASSWORD_PROMPT_ATTEMPTS = 5;\nconst SPACE_CREATE_AUTH_CHECK_TIMEOUT_MS = 8000;\nconst SPACE_CREATE_AUTH_CHECK_LOOPBACK_TIMEOUT_MS = 1500;\nconst SPACE_ADD_MEMBERS_PROJECTION_WAIT_MAX_ATTEMPTS = 3;\nconst SPACE_ADD_MEMBERS_PROJECTION_WAIT_DELAY_MS = 500;\n\ntype SpaceCreateVisibility = \"public\" | \"private\";\n\ntype SpaceCreatePreflightBlockReason =\n | \"auth_required\"\n | \"auth_mismatch\"\n | \"organization_required\"\n | \"service_unavailable\";\n\nfunction resolveOptionalReadableSpaceConfig(\n result: Awaited<ReturnType<typeof readSpaceConfig>>,\n operation: string\n): SpaceConfig | null {\n if (result.kind === \"missing\") {\n return null;\n }\n if (isLocalSpaceStateCorruptResult(result)) {\n throw toLocalSpaceStateIntegrityError({\n operation,\n result,\n });\n }\n return result.value;\n}\n\nclass SpaceCreatePreflightBlockedError extends Error {\n readonly code = \"openmeld.space.create.preflight_blocked\";\n readonly blockReason: SpaceCreatePreflightBlockReason;\n readonly reasonText: string;\n readonly nextStep: string;\n readonly gatewayUrl: string;\n readonly authBaseUrl: string | null;\n readonly httpStatus: number | null;\n readonly errorCode: string | null;\n readonly requestId: string | null;\n readonly detailMessage: string | null;\n readonly authGuidance: AuthenticationGuidance | null;\n\n constructor(input: {\n message: string;\n blockReason: SpaceCreatePreflightBlockReason;\n reasonText: string;\n nextStep: string;\n gatewayUrl: string;\n authBaseUrl?: string | null;\n httpStatus?: number | null;\n errorCode?: string | null;\n requestId?: string | null;\n detailMessage?: string | null;\n authGuidance?: AuthenticationGuidance | null;\n }) {\n super(input.message);\n this.name = \"SpaceCreatePreflightBlockedError\";\n this.blockReason = input.blockReason;\n this.reasonText = input.reasonText;\n this.nextStep = input.nextStep;\n this.gatewayUrl = input.gatewayUrl;\n this.authBaseUrl = input.authBaseUrl ?? null;\n this.httpStatus = input.httpStatus ?? null;\n this.errorCode = input.errorCode ?? null;\n this.requestId = input.requestId ?? null;\n this.detailMessage = input.detailMessage ?? null;\n this.authGuidance = input.authGuidance ?? null;\n }\n}\n\nfunction isSpaceCreatePreflightBlockedError(\n error: unknown\n): error is SpaceCreatePreflightBlockedError {\n return (\n error instanceof SpaceCreatePreflightBlockedError ||\n (typeof error === \"object\" &&\n error !== null &&\n \"code\" in error &&\n (error as { code?: unknown }).code ===\n \"openmeld.space.create.preflight_blocked\")\n );\n}\n\nfunction createSpaceCreateAuthenticationPreflightError(input: {\n reason: AuthenticationGuidanceReason;\n gatewayUrl: string;\n authBaseUrl?: string | null;\n httpStatus?: number | null;\n errorCode?: string | null;\n requestId?: string | null;\n detailMessage?: string | null;\n}): SpaceCreatePreflightBlockedError {\n const guidance = resolveAuthenticationGuidance({\n reason: input.reason,\n action: \"creating a space\",\n authBaseUrl: input.authBaseUrl,\n gatewayUrl: input.gatewayUrl,\n });\n\n return new SpaceCreatePreflightBlockedError({\n message: guidance.commandErrorMessage,\n blockReason:\n guidance.reason === \"mismatch\" ? \"auth_mismatch\" : \"auth_required\",\n reasonText: guidance.summary,\n nextStep: guidance.errorNextStep,\n gatewayUrl: input.gatewayUrl,\n authBaseUrl: input.authBaseUrl,\n httpStatus: input.httpStatus,\n errorCode: input.errorCode,\n requestId: input.requestId,\n detailMessage: input.detailMessage,\n authGuidance: guidance,\n });\n}\n\nfunction createSpaceCreateOrganizationPreflightError(input: {\n gatewayUrl: string;\n authBaseUrl?: string | null;\n}): SpaceCreatePreflightBlockedError {\n return new SpaceCreatePreflightBlockedError({\n message:\n \"openmeld space create requires an active OpenMeld organization. Run `openmeld org switch <slug>` and retry.\",\n blockReason: \"organization_required\",\n reasonText: \"No active OpenMeld organization is selected.\",\n nextStep: \"Run `openmeld org list`, then `openmeld org switch <slug>`.\",\n gatewayUrl: input.gatewayUrl,\n authBaseUrl: input.authBaseUrl,\n });\n}\ntype SpaceCreateFlowStep =\n | \"name\"\n | \"visibility\"\n | \"guide\"\n | \"password\"\n | \"join\";\n\ntype SpaceCreateFlowValues = {\n name: string;\n visibility: SpaceCreateVisibility;\n guide?: string;\n password?: string;\n join: boolean;\n};\n\ntype SpaceCreateFlowResult =\n | { status: \"submitted\"; value: SpaceCreateFlowValues }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\ntype SpaceCreateResolvedInput = {\n name: string;\n visibility: SpaceCreateVisibility;\n guide?: string;\n password?: string;\n joinInput?: boolean;\n};\n\ntype SpaceCreateInputResolution =\n | { status: \"submitted\"; value: SpaceCreateResolvedInput }\n | { status: \"cancelled\" | \"back\" };\n\ntype SpaceDeleteConfirmationResult = \"confirmed\" | \"back\" | \"cancelled\";\n\ntype SpaceAddMembersResult = {\n added: SpaceMemberCandidate[];\n alreadyJoined: SpaceMemberCandidate[];\n failed: Array<{\n candidate: SpaceMemberCandidate;\n error: unknown;\n }>;\n warnings: Array<{\n candidate: SpaceMemberCandidate;\n error: unknown;\n }>;\n};\n\ntype SpaceRemoveMemberCandidate = {\n profileId: string;\n profileHandle?: string;\n profileName: string;\n profileKind: SpaceMembershipProfileKind;\n targetMentionLabel?: string | null;\n ownerUserId?: string | null;\n ownerName?: string | null;\n creatorProfileId?: string | null;\n};\n\ntype SpaceRemoveMembersResult = {\n removed: SpaceRemoveMemberCandidate[];\n alreadyAbsent: SpaceRemoveMemberCandidate[];\n failed: Array<{\n candidate: SpaceRemoveMemberCandidate;\n error: unknown;\n }>;\n warnings: Array<{\n candidate: SpaceRemoveMemberCandidate;\n error: unknown;\n }>;\n};\n\ntype SpaceLeaveHistoryReason = \"left_space\" | \"leave_space_already_absent\";\n\ntype SpaceLeaveResult = LeaveSpaceResponse & {\n profileSpaceHistory: {\n updated: boolean;\n reason: SpaceLeaveHistoryReason;\n warning?: StructuredGatewayFailure;\n };\n};\n\ntype ResolvedSpaceRemoveMemberCandidates = {\n activeMembers: SpaceRemoveMemberCandidate[];\n explicitFallbackById: Map<string, SpaceRemoveMemberCandidate>;\n creatorProfileIds: Set<string>;\n};\n\nfunction isSpaceMembershipProfileKind(\n profileKind: unknown\n): profileKind is SpaceMembershipProfileKind {\n return profileKind === \"human\" || profileKind === \"agent\";\n}\n\ntype SpaceCreatePostJoinContext = {\n localEcho?: boolean;\n historyLimit?: number;\n role?: string;\n mentionAlias?: string;\n rawStream?: boolean;\n skipBringProfilesPrompt?: boolean;\n output?: string;\n view?: string;\n serviceIntent?: \"space_join\" | \"space_create_join\";\n};\n\nfunction buildPostCreateJoinRequest(input: {\n openMeldProfileId: string;\n baseUrl: string;\n space: string;\n password?: string;\n outputMode: \"ndjson\" | \"text\";\n view?: string;\n postCreateJoin?: SpaceCreatePostJoinContext;\n}): Parameters<typeof runSpaceJoin>[0] {\n const joinOutput =\n input.postCreateJoin?.output === \"text\" ||\n input.postCreateJoin?.output === \"ndjson\"\n ? input.postCreateJoin.output\n : input.outputMode;\n const joinView = input.postCreateJoin?.view ?? input.view;\n\n return {\n profile: input.openMeldProfileId,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n output: joinOutput,\n view: joinView,\n ...(typeof input.postCreateJoin?.localEcho === \"boolean\"\n ? { localEcho: input.postCreateJoin.localEcho }\n : {}),\n ...(typeof input.postCreateJoin?.historyLimit === \"number\"\n ? { historyLimit: input.postCreateJoin.historyLimit }\n : {}),\n ...(typeof input.postCreateJoin?.role === \"string\"\n ? { role: input.postCreateJoin.role }\n : {}),\n ...(typeof input.postCreateJoin?.mentionAlias === \"string\"\n ? { mentionAlias: input.postCreateJoin.mentionAlias }\n : {}),\n ...(typeof input.postCreateJoin?.rawStream === \"boolean\"\n ? { rawStream: input.postCreateJoin.rawStream }\n : {}),\n ...(typeof input.postCreateJoin?.skipBringProfilesPrompt === \"boolean\"\n ? {\n skipBringProfilesPrompt: input.postCreateJoin.skipBringProfilesPrompt,\n }\n : {}),\n serviceIntent: input.postCreateJoin?.serviceIntent ?? \"space_create_join\",\n entryChecksHandled: true,\n };\n}\n\nexport async function runSpaceCreate(input: {\n profile?: string;\n baseUrl?: string;\n name?: string;\n visibility?: string;\n guide?: string;\n guidePromptHandled?: boolean;\n password?: string;\n join?: boolean;\n output?: string;\n view?: string;\n entryChecksHandled?: boolean;\n postCreateJoin?: SpaceCreatePostJoinContext;\n}): Promise<SpaceCommandNavigationStatus> {\n // OPENMELD_SETUP_TO_WAKE_PATH: HIGHEST_FACT space-create\n // Setup Agent may create or select a Space, but entering the Space UI is not\n // required. Space creation is one operation surface on the shared path.\n const { runtime, presenter, interactive } =\n await prepareSpaceCreateRuntimeState(input);\n\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\"creating a space\"),\n entryChecksHandled: input.entryChecksHandled,\n runtime,\n presenter,\n interactive,\n });\n if (context.status === \"cancelled\") {\n return \"cancelled\";\n }\n const {\n runtime: contextRuntime,\n interactive: contextInteractive,\n presenter: contextPresenter,\n baseUrl,\n } = context;\n const outputMode = input.output === \"ndjson\" ? \"ndjson\" : \"text\";\n let failureOpenMeldProfileId = input.profile;\n\n try {\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: contextRuntime.resolvedView,\n interactive: contextInteractive,\n });\n failureOpenMeldProfileId = openMeldProfile.openMeldProfileId;\n\n await emitSpaceCommandPreflight({\n presenter: contextPresenter,\n command: \"create\",\n profile: openMeldProfile,\n baseUrl,\n resolvedView: contextRuntime.resolvedView,\n humanServiceGuidanceMode: isHumanInteractiveSpaceRuntime(contextRuntime)\n ? \"suppress\"\n : \"show\",\n });\n assertNonInteractiveSpaceCreateRequiredInput({\n providedName: input.name,\n providedVisibility: input.visibility,\n interactive: contextInteractive,\n resolvedView: contextRuntime.resolvedView,\n });\n const activeOrganization = await ensureSpaceCreateAuthReady({\n baseUrl,\n });\n\n const createInput = await resolveSpaceCreateInput({\n runtime: contextRuntime,\n interactive: contextInteractive,\n presenter: contextPresenter,\n openMeldProfile,\n providedName: input.name,\n providedVisibility: input.visibility,\n providedGuide: input.guide,\n guidePromptHandled: input.guidePromptHandled,\n providedPassword: input.password,\n joinInput: input.join,\n });\n if (createInput.status !== \"submitted\") {\n return createInput.status;\n }\n\n const creator: SpaceCreator = {\n profileId: openMeldProfile.openMeldProfileId,\n profileName: openMeldProfile.profileName,\n kind: openMeldProfile.profileKind,\n profile: openMeldProfile.openMeldProfileId,\n };\n\n const createSpaceUrl = toSpaceCreateUrl(baseUrl);\n const headers = await buildOpenMeldProfileRequestHeadersWithAuth({\n requestUrl: createSpaceUrl,\n openMeldProfile,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: createSpaceUrl,\n operation: \"space.create\",\n init: {\n method: \"POST\",\n headers,\n body: JSON.stringify({\n name: createInput.value.name,\n visibility: createInput.value.visibility,\n ...(typeof createInput.value.password === \"string\"\n ? { password: createInput.value.password }\n : {}),\n ...(createInput.value.guide === undefined\n ? {}\n : { guide: createInput.value.guide }),\n }),\n },\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n const parsed = parseCreateSpaceResponse(raw);\n await upsertSpaceConfig({\n openMeldProfileId: openMeldProfile.openMeldProfileId,\n baseUrl,\n space: parsed.spaceId,\n profileHandle: openMeldProfile.profileHandle,\n profileName: openMeldProfile.profileName,\n creator: parsed.meta?.creator ?? creator,\n name:\n typeof parsed.meta?.name === \"string\"\n ? parsed.meta.name\n : createInput.value.name || null,\n spaceCreatedAt: parsed.meta?.createdAt ?? null,\n spaceUpdatedAt: parsed.meta?.updatedAt ?? null,\n passwordProtected:\n typeof parsed.meta?.passwordProtected === \"boolean\"\n ? parsed.meta.passwordProtected\n : typeof createInput.value.password === \"string\",\n guide:\n typeof parsed.meta?.guide === \"string\"\n ? parsed.meta.guide\n : createInput.value.guide,\n });\n\n emitSpaceCreateSuccessOutput({\n baseUrl,\n presenter: contextPresenter,\n parsed,\n outputMode,\n resolvedView: contextRuntime.resolvedView,\n passwordProtected: typeof createInput.value.password === \"string\",\n visibility: createInput.value.visibility,\n organization: {\n active: activeOrganization,\n },\n });\n\n await syncProfileSpaceHistoryForCreate({\n openMeldProfile,\n baseUrl,\n spaceId: parsed.spaceId,\n meta: parsed.meta,\n fallbackSpaceName: createInput.value.name,\n }).catch((error) => {\n contextPresenter.event(\n \"info\",\n \"connect.warn.profile_space_history_sync_failed\",\n {\n error: toErrorMessage(error),\n }\n );\n });\n\n const joinNow = isHumanInteractiveSpaceRuntime(contextRuntime)\n ? Boolean(createInput.value.joinInput)\n : await resolveJoinAfterCreate(\n createInput.value.joinInput,\n contextInteractive\n );\n if (contextRuntime.resolvedView === \"agent\") {\n emitSpaceCreateAgentFollowUp({\n baseUrl,\n presenter: contextPresenter,\n profileId: openMeldProfile.openMeldProfileId,\n spaceId: parsed.spaceId,\n joinRequested: joinNow,\n organization: {\n active: activeOrganization,\n },\n });\n return \"completed\";\n }\n if (!joinNow) {\n return \"completed\";\n }\n\n return await runSpaceJoin(\n buildPostCreateJoinRequest({\n openMeldProfileId: openMeldProfile.openMeldProfileId,\n baseUrl,\n space: parsed.spaceId,\n password: createInput.value.password,\n outputMode,\n view: input.view,\n postCreateJoin: input.postCreateJoin,\n })\n );\n } catch (error) {\n if (\n maybeRenderHumanSpaceCreateFailureCard({\n presenter: contextPresenter,\n error,\n outputMode,\n baseUrl,\n resolvedView: contextRuntime.resolvedView,\n })\n ) {\n throw new SpaceCommandOutputHandledError(toErrorMessage(error));\n }\n emitSpaceFailureNextStep({\n presenter: contextPresenter,\n command: \"create\",\n error,\n profileId: failureOpenMeldProfileId,\n resolvedView: contextRuntime.resolvedView,\n });\n throw error;\n }\n}\n\nfunction emitSpaceCreateAgentFollowUp(input: {\n baseUrl: string;\n presenter: ReturnType<typeof createPresenter>;\n profileId: string;\n spaceId: string;\n joinRequested: boolean;\n organization: {\n active: StoredActiveOrganization | null;\n };\n}): void {\n const spaceUrl = buildSpaceWebUrl(\n input.baseUrl,\n requireActiveOrganizationSlug(input.organization.active),\n input.spaceId\n );\n const historyCommand = formatOpenMeldCliCommand(\n `openmeld space history ${input.spaceId} --profile ${input.profileId} --kind text --brief --limit 20 --view agent`\n );\n const sendCommand = formatOpenMeldCliCommand(\n `openmeld space send ${input.spaceId} --profile ${input.profileId} \"hello\" --view agent`\n );\n input.presenter.data({\n code: \"space.create.next_commands\",\n payload: {\n spaceId: input.spaceId,\n spaceUrl,\n joinRequested: input.joinRequested,\n joinedByCreate: true,\n organization: input.organization,\n note: \"Agent View create returns after creating the Space. Use explicit follow-up commands instead of opening a long-running join session.\",\n nextCommands: [historyCommand, sendCommand],\n },\n });\n}\n\nasync function syncProfileSpaceHistoryForCreate(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n spaceId: string;\n meta?: SpaceMeta;\n fallbackSpaceName?: string;\n}): Promise<void> {\n const gatewayHost = resolveGatewayHost(input.baseUrl);\n if (!gatewayHost) {\n return;\n }\n\n const normalizedMeta = input.meta\n ? normalizeMetaForHistory(input.meta)\n : null;\n const fallbackSpaceName = normalizeOptionalString(input.fallbackSpaceName);\n const historySpaceName =\n normalizedMeta?.spaceName === undefined\n ? fallbackSpaceName\n : normalizedMeta.spaceName;\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n });\n\n await upsertProfileSpaceHistory({\n baseUrl: input.baseUrl,\n requestContext,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n spaceId: input.spaceId,\n body: {\n gatewayHost,\n ...(historySpaceName ? { spaceName: historySpaceName } : {}),\n ...(normalizedMeta?.creatorProfileId === undefined\n ? { creatorProfileId: input.openMeldProfile.openMeldProfileId }\n : { creatorProfileId: normalizedMeta.creatorProfileId }),\n ...(normalizedMeta?.creatorKind === undefined\n ? { creatorKind: input.openMeldProfile.profileKind }\n : { creatorKind: normalizedMeta.creatorKind }),\n ...(normalizedMeta?.spaceCreatedAt === undefined\n ? {}\n : { spaceCreatedAt: normalizedMeta.spaceCreatedAt }),\n ...(normalizedMeta?.spaceUpdatedAt === undefined\n ? {}\n : { spaceUpdatedAt: normalizedMeta.spaceUpdatedAt }),\n lastJoinedAt: normalizedMeta?.spaceCreatedAt ?? new Date().toISOString(),\n status: \"active\",\n },\n });\n}\n\nasync function resolveSpaceCreateInput(input: {\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n interactive: boolean;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfile: OpenMeldProfile;\n providedName?: string;\n providedVisibility?: string;\n providedGuide?: string;\n guidePromptHandled?: boolean;\n providedPassword?: string;\n joinInput?: boolean;\n}): Promise<SpaceCreateInputResolution> {\n if (isHumanInteractiveSpaceRuntime(input.runtime)) {\n const prompted = await promptInteractiveSpaceCreateFlow({\n providedName: input.providedName,\n providedVisibility: input.providedVisibility,\n providedGuide: input.providedGuide,\n guidePromptHandled: input.guidePromptHandled,\n providedPassword: input.providedPassword,\n joinInput: input.joinInput,\n });\n if (prompted.status === \"submitted\") {\n return {\n status: \"submitted\",\n value: {\n name: prompted.value.name,\n visibility: prompted.value.visibility,\n ...(prompted.value.guide === undefined\n ? {}\n : { guide: prompted.value.guide }),\n ...(prompted.value.password === undefined\n ? {}\n : { password: prompted.value.password }),\n joinInput: prompted.value.join,\n },\n };\n }\n if (prompted.status === \"back\") {\n return { status: \"back\" };\n }\n return { status: \"cancelled\" };\n }\n\n const name = await resolveCreateSpaceNameInput({\n providedName: input.providedName,\n interactive: input.interactive,\n resolvedView: input.runtime.resolvedView,\n });\n if (name === null) {\n return { status: \"cancelled\" };\n }\n\n const visibility = resolveCreateSpaceVisibilityInput({\n providedVisibility: input.providedVisibility,\n interactive: input.interactive,\n resolvedView: input.runtime.resolvedView,\n });\n\n emitSpaceCreatePasswordOptionalHint({\n presenter: input.presenter,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n resolvedView: input.runtime.resolvedView,\n providedPassword: input.providedPassword,\n interactive: input.interactive,\n visibility,\n });\n const password = await resolveCreateSpacePasswordInput({\n providedPassword: input.providedPassword,\n interactive: input.interactive,\n visibility,\n });\n if (password === null) {\n return { status: \"cancelled\" };\n }\n const normalizedGuide = normalizeGuideInput(input.providedGuide);\n\n return {\n status: \"submitted\",\n value: {\n name,\n visibility,\n ...(normalizedGuide === undefined ? {} : { guide: normalizedGuide }),\n ...(password === undefined ? {} : { password }),\n joinInput: input.joinInput,\n },\n };\n}\n\nfunction renderHumanSpaceCreateCard(input: {\n presenter: ReturnType<typeof createPresenter>;\n spaceId: string;\n spaceUrl: string;\n visibility: SpaceCreateVisibility | null;\n organization: {\n active: StoredActiveOrganization | null;\n };\n passwordProtected: boolean;\n}): void {\n const rows: Array<{ label: string; value: string }> = [\n {\n label: \"🆔 Space ID\",\n value: input.spaceId,\n },\n {\n label: \"🔗 Space URL\",\n value: input.spaceUrl,\n },\n {\n label: \"Organization\",\n value: input.organization.active\n ? `${input.organization.active.name} (${input.organization.active.slug})`\n : \"not selected\",\n },\n {\n label: \"Visibility\",\n value: input.visibility ?? \"unknown\",\n },\n ];\n\n if (input.passwordProtected) {\n rows.push({\n label: \"🔐 Password\",\n value: \"Protection enabled.\",\n });\n rows.push({\n label: \"⚠️ Important\",\n value:\n \"Save this password securely. If lost, it cannot be recovered. Reset is the only option.\",\n });\n }\n\n renderInfoCard({\n presenter: input.presenter,\n title: \"✨ Space Created\",\n codePrefix: \"space.create.card\",\n rows,\n sanitize: true,\n minContentWidth: 72,\n });\n}\n\nfunction renderHumanSpacePasswordResultCard(input: {\n presenter: ReturnType<typeof createPresenter>;\n spaceName?: string;\n spaceId: string;\n passwordProtected: boolean;\n}): void {\n const rows: Array<{ label: string; value: string }> = [\n {\n label: \"Space\",\n value: resolveSpaceCardDisplayName(input.spaceName),\n },\n {\n label: \"Space ID\",\n value: input.spaceId,\n },\n {\n label: \"Join access\",\n value: input.passwordProtected\n ? \"Password required\"\n : \"No password required\",\n },\n ];\n\n if (input.passwordProtected) {\n rows.push({\n label: \"Security note\",\n value:\n \"Save this password securely. If you lose it, you'll need to set a new one.\",\n });\n }\n\n renderInfoCard({\n presenter: input.presenter,\n title: input.passwordProtected\n ? \"✅ Password Updated\"\n : \"✅ Password Cleared\",\n codePrefix: \"space.password.card\",\n rows,\n sanitize: true,\n minContentWidth: 72,\n });\n}\n\nfunction resolveSpaceCardDisplayName(spaceName?: string): string {\n const normalized = sanitizeSingleLinePromptText(spaceName) || \"\";\n return normalized.length > 0 ? normalized : \"Untitled space\";\n}\n\nasync function ensureSpaceCreateAuthReady(input: {\n baseUrl: string;\n}): Promise<StoredActiveOrganization> {\n const authState = await getAuthSessionState({\n validateRemote: false,\n });\n\n switch (authState.state) {\n case \"missing\":\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"required\",\n gatewayUrl: input.baseUrl,\n });\n case \"expired\":\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"expired\",\n gatewayUrl: input.baseUrl,\n });\n case \"invalid\":\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"invalid\",\n gatewayUrl: input.baseUrl,\n });\n case \"revoked\":\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"revoked\",\n gatewayUrl: input.baseUrl,\n });\n case \"valid\":\n break;\n default:\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"required\",\n gatewayUrl: input.baseUrl,\n });\n }\n\n if (!authState.session) {\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"required\",\n gatewayUrl: input.baseUrl,\n });\n }\n\n const compatibility = resolveAuthRequestCompatibility({\n session: authState.session,\n requestUrl: input.baseUrl,\n });\n if (!compatibility.compatible) {\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"mismatch\",\n gatewayUrl: input.baseUrl,\n authBaseUrl: authState.session.authBaseUrl,\n });\n }\n\n await verifySpaceCreateTargetAuthSession({\n gatewayUrl: input.baseUrl,\n session: authState.session,\n });\n const activeOrganization = authState.session.activeOrganization ?? null;\n if (!activeOrganization) {\n throw createSpaceCreateOrganizationPreflightError({\n gatewayUrl: input.baseUrl,\n authBaseUrl: authState.session.authBaseUrl,\n });\n }\n\n return activeOrganization;\n}\n\nasync function verifySpaceCreateTargetAuthSession(input: {\n gatewayUrl: string;\n session: StoredAuthSession;\n}): Promise<void> {\n const authBaseUrl =\n deriveAuthBaseUrlFromGatewayUrl(input.gatewayUrl) ??\n input.session.authBaseUrl;\n const endpoint = toAuthEndpoint(authBaseUrl, \"/api/auth/get-session\");\n const timeoutMs = resolveSpaceCreateAuthCheckTimeoutMs(endpoint);\n\n let response: Response;\n try {\n response = await fetch(endpoint, {\n method: \"GET\",\n headers: {\n Authorization: `${normalizeAuthTokenType(input.session.tokenType)} ${input.session.accessToken}`,\n },\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (error) {\n throw new SpaceCreatePreflightBlockedError({\n message: \"upstream_unreachable: auth session check failed before create\",\n blockReason: \"service_unavailable\",\n reasonText: \"OpenMeld auth service is temporarily unavailable.\",\n nextStep: resolveSpaceServiceUnavailableSummary(),\n gatewayUrl: input.gatewayUrl,\n authBaseUrl,\n detailMessage: toErrorMessage(error),\n });\n }\n\n const raw = await response.text();\n const payload = safeJsonParse(raw);\n\n if (response.status === 401 || response.status === 403) {\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"required\",\n gatewayUrl: input.gatewayUrl,\n authBaseUrl,\n httpStatus: response.status,\n errorCode: readHttpErrorField(payload, \"code\") || null,\n requestId: readHttpRequestId(payload) || null,\n detailMessage: readHttpErrorField(payload, \"message\") || null,\n });\n }\n\n if (!response.ok) {\n const parsedError = parseHttpErrorMessage(\n `HTTP ${response.status}: ${raw}`\n );\n throw new SpaceCreatePreflightBlockedError({\n message: `HTTP ${response.status}: ${raw}`,\n blockReason: \"service_unavailable\",\n reasonText: parsedError\n ? resolveHumanSpaceCreateFailureReason(parsedError)\n : \"OpenMeld auth service is temporarily unavailable.\",\n nextStep:\n resolveSpaceFailureGuidance(`HTTP ${response.status}: ${raw}`)\n ?.summary ?? resolveSpaceServiceUnavailableSummary(),\n gatewayUrl: input.gatewayUrl,\n authBaseUrl,\n httpStatus: response.status,\n errorCode: readHttpErrorField(payload, \"code\") || null,\n requestId: readHttpRequestId(payload) || null,\n detailMessage: readHttpErrorField(payload, \"message\") || null,\n });\n }\n\n if (!hasActiveAuthSessionPayload(payload)) {\n throw createSpaceCreateAuthenticationPreflightError({\n reason: \"required\",\n gatewayUrl: input.gatewayUrl,\n authBaseUrl,\n });\n }\n}\n\nfunction maybeRenderHumanSpaceCreateFailureCard(input: {\n presenter: ReturnType<typeof createPresenter>;\n error: unknown;\n outputMode: \"text\" | \"ndjson\";\n baseUrl: string;\n resolvedView: \"human\" | \"agent\";\n}): boolean {\n if (input.resolvedView !== \"human\" || input.outputMode !== \"text\") {\n return false;\n }\n\n if (isSpaceCreatePreflightBlockedError(input.error)) {\n return renderHumanSpaceCreatePreflightBlockedCard({\n presenter: input.presenter,\n error: input.error,\n });\n }\n\n const parsed = parseHttpErrorMessage(input.error);\n if (!parsed) {\n return false;\n }\n\n const payload = safeJsonParse(parsed.body);\n const authenticationFailure =\n resolveSpaceCreateAuthenticationFailureFromHttpError({\n parsed,\n payload,\n gatewayUrl: input.baseUrl,\n });\n if (authenticationFailure) {\n return renderHumanSpaceCreatePreflightBlockedCard({\n presenter: input.presenter,\n error: authenticationFailure,\n });\n }\n\n const guidance = resolveSpaceFailureGuidance(input.error);\n let nextStep = \"Check the Space details, then try again.\";\n if (parsed.status >= 500) {\n nextStep = \"Try again in a moment.\";\n }\n if (guidance?.steps[0]) {\n nextStep = `Run ${guidance.steps[0]}.`;\n }\n renderHumanErrorCard({\n message: resolveHumanSpaceCreateFailureReason(parsed),\n nextStep,\n presenter: input.presenter,\n title: \"Space couldn't be created\",\n codePrefix: \"space.create.error.card\",\n });\n return true;\n}\n\nfunction resolveSpaceCreateAuthenticationFailureFromHttpError(input: {\n parsed: {\n status: number;\n body: string;\n code: string;\n message: string;\n };\n payload: unknown;\n gatewayUrl: string;\n}): SpaceCreatePreflightBlockedError | null {\n const reason = resolveSpaceCreateAuthenticationReason(input.parsed);\n if (!reason) {\n return null;\n }\n\n return createSpaceCreateAuthenticationPreflightError({\n reason,\n gatewayUrl: input.gatewayUrl,\n httpStatus: input.parsed.status,\n errorCode: readHttpErrorField(input.payload, \"code\") || input.parsed.code,\n requestId: readHttpRequestId(input.payload) || null,\n detailMessage:\n readHttpErrorField(input.payload, \"message\") || input.parsed.message,\n });\n}\n\nfunction resolveSpaceCreateAuthenticationReason(input: {\n status: number;\n code: string;\n message: string;\n}): Exclude<AuthenticationGuidanceReason, \"mismatch\"> | null {\n const text = `${input.code} ${input.message}`.toLowerCase();\n if (text.includes(\"revoked\")) {\n return \"revoked\";\n }\n if (text.includes(\"expired\")) {\n return \"expired\";\n }\n if (text.includes(\"invalid\")) {\n return \"invalid\";\n }\n if (input.status === 401) {\n return \"required\";\n }\n if (\n input.status === 403 &&\n (text.includes(\"auth.\") ||\n text.includes(\"authentication\") ||\n text.includes(\"session\") ||\n text.includes(\"sign-in\") ||\n text.includes(\"sign in\") ||\n text.includes(\"unauthenticated\"))\n ) {\n return \"required\";\n }\n return null;\n}\n\nfunction renderHumanSpaceCreatePreflightBlockedCard(input: {\n presenter: ReturnType<typeof createPresenter>;\n error: SpaceCreatePreflightBlockedError;\n}): boolean {\n if (input.error.authGuidance) {\n const card = buildHumanAuthenticationCard({\n guidance: input.error.authGuidance,\n mode: \"error\",\n });\n renderInfoCard({\n presenter: input.presenter,\n title: card.title,\n codePrefix: \"space.create.auth.card\",\n rows: card.rows,\n sanitize: true,\n minContentWidth: 76,\n });\n return true;\n }\n\n renderHumanErrorCard({\n message: input.error.reasonText,\n nextStep: input.error.nextStep,\n presenter: input.presenter,\n title: \"Space couldn't be created\",\n codePrefix: \"space.create.preflight.card\",\n });\n return true;\n}\n\nfunction resolveSpaceServiceUnavailableSummary(): string {\n return (\n resolveSpaceFailureGuidance(\"upstream_unreachable\")?.summary ??\n \"OpenMeld Cloud service is temporarily unavailable. Try again after OpenMeld is reachable.\"\n );\n}\n\nfunction resolveHumanSpaceCreateFailureReason(input: {\n status: number;\n body: string;\n code: string;\n message: string;\n}): string {\n if (isAuthUpstreamUnavailableError(input)) {\n return \"OpenMeld auth service is temporarily unavailable.\";\n }\n\n const status = resolveUpstreamStatus(input);\n if (status >= 500) {\n return \"OpenMeld service is temporarily unavailable.\";\n }\n if (status === 401) {\n return \"Authentication expired.\";\n }\n if (status === 403) {\n return \"This profile cannot create spaces on the current gateway.\";\n }\n if (input.message.trim().length > 0) {\n return input.message.trim();\n }\n if (input.code.trim().length > 0) {\n return `Space create request failed (${input.code.trim()}).`;\n }\n return \"Space create request failed.\";\n}\n\nfunction hasActiveAuthSessionPayload(payload: unknown): boolean {\n if (!payload || typeof payload !== \"object\") {\n return false;\n }\n\n const record = payload as Record<string, unknown>;\n return (\n Boolean(record.session) &&\n typeof record.session === \"object\" &&\n Boolean(record.user) &&\n typeof record.user === \"object\"\n );\n}\n\nfunction normalizeAuthTokenType(tokenType: string | undefined): string {\n const normalized = String(tokenType ?? \"\").trim();\n return normalized.length > 0 ? normalized : \"Bearer\";\n}\n\nfunction toAuthEndpoint(baseUrl: string, pathname: string): string {\n const url = new URL(baseUrl);\n const normalizedBasePath = url.pathname.replace(TRAILING_SLASHES_RE, \"\");\n const normalizedPathname = pathname.startsWith(\"/\")\n ? pathname\n : `/${pathname}`;\n url.pathname = `${normalizedBasePath}${normalizedPathname}` || \"/\";\n url.search = \"\";\n url.hash = \"\";\n return url.toString();\n}\n\nfunction resolveSpaceCreateAuthCheckTimeoutMs(endpoint: string): number {\n const url = parseUrlOrNull(endpoint);\n if (url && isLoopbackHostname(url.hostname)) {\n return SPACE_CREATE_AUTH_CHECK_LOOPBACK_TIMEOUT_MS;\n }\n return SPACE_CREATE_AUTH_CHECK_TIMEOUT_MS;\n}\n\nfunction parseUrlOrNull(value: string): URL | null {\n try {\n return new URL(value);\n } catch {\n return null;\n }\n}\n\nfunction requireActiveOrganizationSlug(\n organization: StoredActiveOrganization | null\n): string {\n const slug = normalizeOptionalString(organization?.slug);\n if (!slug) {\n throw new Error(\n \"Active organization slug is required to build a Space URL.\"\n );\n }\n return slug;\n}\n\nfunction emitSpaceCreateSuccessOutput(input: {\n baseUrl: string;\n presenter: ReturnType<typeof createPresenter>;\n parsed: ReturnType<typeof parseCreateSpaceResponse>;\n outputMode: \"text\" | \"ndjson\";\n resolvedView: \"human\" | \"agent\";\n passwordProtected: boolean;\n visibility: SpaceCreateVisibility;\n organization: {\n active: StoredActiveOrganization | null;\n };\n}): void {\n const spaceUrl = buildSpaceWebUrl(\n input.baseUrl,\n requireActiveOrganizationSlug(input.organization.active),\n input.parsed.spaceId\n );\n if (input.outputMode === \"ndjson\") {\n input.presenter.data({\n code: \"space.create.response\",\n payload: {\n ...input.parsed,\n spaceUrl,\n visibility: input.parsed.meta?.visibility ?? input.visibility,\n organization: input.organization,\n },\n });\n return;\n }\n\n if (input.resolvedView === \"human\") {\n renderHumanSpaceCreateCard({\n presenter: input.presenter,\n spaceId: input.parsed.spaceId,\n spaceUrl,\n visibility: input.parsed.meta?.visibility ?? input.visibility,\n organization: input.organization,\n passwordProtected: input.passwordProtected,\n });\n return;\n }\n\n input.presenter.line({\n code: \"space.create.created\",\n text: formatMessage(input.resolvedView, \"space.create.created\", {\n spaceId: input.parsed.spaceId,\n }),\n data: {\n spaceId: input.parsed.spaceId,\n visibility: input.parsed.meta?.visibility ?? input.visibility,\n organization: input.organization,\n },\n });\n\n input.presenter.line({\n code: \"space.create.url\",\n text: `Space URL: ${spaceUrl}`,\n data: {\n spaceId: input.parsed.spaceId,\n spaceUrl,\n organization: input.organization,\n },\n });\n\n if (!input.passwordProtected) {\n return;\n }\n\n input.presenter.line({\n code: \"space.password.warning\",\n text: formatMessage(input.resolvedView, \"space.password.warning\"),\n });\n}\n\nasync function resolveCreateSpaceNameInput(input: {\n providedName?: string;\n interactive: boolean;\n resolvedView: \"human\" | \"agent\";\n}): Promise<string | null> {\n const explicitName = String(input.providedName ?? \"\").trim();\n if (explicitName.length > 0) {\n return explicitName;\n }\n if (!input.interactive) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceCreateGuideError();\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"missing required 'name' argument for `openmeld space create`\"\n )\n );\n }\n\n for (;;) {\n const nameInput = await text({\n message: \"Space name\",\n placeholder: \"e.g. design-review\",\n });\n if (isCancel(nameInput)) {\n cancel(\"Cancelled.\");\n return null;\n }\n const name = String(nameInput ?? \"\").trim();\n if (name.length > 0) {\n return name;\n }\n process.stderr.write(\"Space name cannot be empty.\\n\");\n }\n}\n\nfunction assertNonInteractiveSpaceCreateRequiredInput(input: {\n providedName?: string;\n providedVisibility?: string;\n interactive: boolean;\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (input.interactive && input.resolvedView === \"human\") {\n return;\n }\n if (!normalizeOptionalString(input.providedName)) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceCreateGuideError();\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"missing required 'name' argument for `openmeld space create`\"\n )\n );\n }\n resolveCreateSpaceVisibilityInput(input);\n}\n\nfunction resolveCreateSpaceVisibilityInput(input: {\n providedVisibility?: string;\n interactive: boolean;\n resolvedView: \"human\" | \"agent\";\n}): SpaceCreateVisibility {\n const explicitVisibility = normalizeSpaceCreateVisibility(\n input.providedVisibility\n );\n if (explicitVisibility) {\n return explicitVisibility;\n }\n\n const rawVisibility = String(input.providedVisibility ?? \"\").trim();\n if (rawVisibility.length > 0) {\n throw new Error(\n formatOpenMeldCliTextBlock(\n `invalid --visibility value: ${rawVisibility} (use public|private)`\n )\n );\n }\n\n if (input.resolvedView === \"agent\" || !input.interactive) {\n throw createSpaceCreateGuideError(\n \"openmeld space create requires explicit --visibility public|private in agent/non-interactive mode.\"\n );\n }\n\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"missing required --visibility public|private for `openmeld space create`\"\n )\n );\n}\n\nasync function resolveCreateSpacePasswordInput(input: {\n providedPassword?: string;\n interactive: boolean;\n visibility: SpaceCreateVisibility;\n}): Promise<string | undefined | null> {\n if (typeof input.providedPassword === \"string\") {\n return normalizeSpacePasswordText(input.providedPassword);\n }\n if (!input.interactive) {\n return undefined;\n }\n\n const shouldSetPassword = await confirm({\n message: buildCreateSpacePasswordPromptMessage(input.visibility),\n initialValue: false,\n });\n if (isCancel(shouldSetPassword)) {\n cancel(\"Cancelled.\");\n return null;\n }\n if (!shouldSetPassword) {\n return undefined;\n }\n\n const password = await promptAndConfirmSpacePassword();\n return password.status === \"submitted\" ? password.value : null;\n}\n\nasync function promptInteractiveSpaceCreateFlow(input: {\n providedName?: string;\n providedVisibility?: string;\n providedGuide?: string;\n guidePromptHandled?: boolean;\n providedPassword?: string;\n joinInput?: boolean;\n}): Promise<SpaceCreateFlowResult> {\n const normalizedProvidedGuide = normalizeGuideInput(input.providedGuide);\n assertProvidedSpaceCreateVisibilityValid(input.providedVisibility);\n const steps = resolveInteractiveSpaceCreateFlowSteps({\n ...input,\n providedGuide: normalizedProvidedGuide,\n });\n const providedName = resolveProvidedSpaceCreateName(input.providedName);\n const state: Partial<SpaceCreateFlowValues> = {\n ...(providedName ? { name: providedName } : {}),\n ...buildProvidedSpaceCreateVisibility(input.providedVisibility),\n ...(normalizedProvidedGuide === undefined\n ? {}\n : { guide: normalizedProvidedGuide }),\n ...(typeof input.providedPassword === \"string\"\n ? { password: normalizeSpacePasswordText(input.providedPassword) }\n : {}),\n ...(input.joinInput === undefined ? {} : { join: input.joinInput }),\n };\n\n let stepIndex = 0;\n while (stepIndex < steps.length) {\n const step = steps[stepIndex];\n if (!step) {\n break;\n }\n\n const result = await promptInteractiveSpaceCreateFlowStep({\n state,\n step,\n });\n const navigation = resolveSpaceCreateFlowStepNavigation({\n stepIndex,\n result,\n });\n if (navigation === \"cancelled\") {\n return emitCancelledSpaceCreateFlowResult();\n }\n if (navigation === \"back\") {\n return { status: \"back\" };\n }\n if (typeof navigation === \"number\") {\n stepIndex = navigation;\n continue;\n }\n\n applySpaceCreateFlowSubmission(state, result);\n stepIndex += 1;\n }\n\n if (typeof state.name !== \"string\" || state.name.trim().length === 0) {\n throw new Error(\"Space create flow completed without a name.\");\n }\n if (!state.visibility) {\n throw new Error(\"Space create flow completed without visibility.\");\n }\n\n return {\n status: \"submitted\",\n value: {\n name: state.name,\n visibility: state.visibility,\n ...(state.guide === undefined ? {} : { guide: state.guide }),\n ...(state.password === undefined ? {} : { password: state.password }),\n join: state.join === true,\n },\n };\n}\n\nfunction resolveInteractiveSpaceCreateFlowSteps(input: {\n providedName?: string;\n providedVisibility?: string;\n providedGuide?: string;\n guidePromptHandled?: boolean;\n providedPassword?: string;\n joinInput?: boolean;\n}): SpaceCreateFlowStep[] {\n const steps: SpaceCreateFlowStep[] = [];\n const normalizedGuide = normalizeGuideInput(input.providedGuide);\n if (!resolveProvidedSpaceCreateName(input.providedName)) {\n steps.push(\"name\");\n }\n if (!normalizeSpaceCreateVisibility(input.providedVisibility)) {\n steps.push(\"visibility\");\n }\n if (normalizedGuide === undefined && input.guidePromptHandled !== true) {\n steps.push(\"guide\");\n }\n if (typeof input.providedPassword !== \"string\") {\n steps.push(\"password\");\n }\n if (input.joinInput === undefined) {\n steps.push(\"join\");\n }\n return steps;\n}\n\nfunction resolveProvidedSpaceCreateName(\n value: string | undefined\n): string | null {\n const normalized = String(value ?? \"\").trim();\n return normalized.length > 0 ? normalized : null;\n}\n\nfunction normalizePromptedSpaceGuide(value: string): string | undefined {\n const normalized = value.trim();\n return normalized.length > 0 ? normalized : undefined;\n}\n\ntype SpaceCreateFlowStepSubmission =\n | { status: \"submitted\"; step: \"name\"; value: string }\n | {\n status: \"submitted\";\n step: \"visibility\";\n value: SpaceCreateVisibility;\n }\n | { status: \"submitted\"; step: \"guide\"; value: string }\n | { status: \"submitted\"; step: \"password\"; value: string | undefined }\n | { status: \"submitted\"; step: \"join\"; value: boolean };\n\ntype SpaceCreateFlowStepPromptResult =\n | SpaceCreateFlowStepSubmission\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\nasync function promptInteractiveSpaceCreateFlowStep(input: {\n state: Partial<SpaceCreateFlowValues>;\n step: SpaceCreateFlowStep;\n}): Promise<SpaceCreateFlowStepPromptResult> {\n const { step } = input;\n if (step === \"name\") {\n const result = await promptRequiredInteractiveSpaceName();\n return result.status === \"submitted\"\n ? { status: \"submitted\", step, value: result.value }\n : result;\n }\n if (step === \"guide\") {\n const result = await promptInteractiveSpaceGuide();\n return result.status === \"submitted\"\n ? { status: \"submitted\", step, value: result.value }\n : result;\n }\n if (step === \"visibility\") {\n const result = await promptInteractiveSpaceVisibility();\n return result.status === \"submitted\"\n ? { status: \"submitted\", step, value: result.value }\n : result;\n }\n if (step === \"password\") {\n if (!input.state.visibility) {\n throw new Error(\n \"Space create password prompt requires a selected visibility.\"\n );\n }\n const result = await promptInteractiveSpaceCreatePassword(\n input.state.visibility\n );\n return result.status === \"submitted\"\n ? { status: \"submitted\", step, value: result.value }\n : result;\n }\n\n const result = await promptInteractiveSpaceJoinAfterCreate();\n return result.status === \"submitted\"\n ? { status: \"submitted\", step, value: result.value }\n : result;\n}\n\nfunction resolveSpaceCreateFlowStepNavigation(input: {\n stepIndex: number;\n result: SpaceCreateFlowStepPromptResult;\n}): \"submit\" | \"cancelled\" | \"back\" | number {\n if (input.result.status === \"submitted\") {\n return \"submit\";\n }\n if (input.result.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (input.stepIndex === 0) {\n return \"back\";\n }\n return input.stepIndex - 1;\n}\n\nfunction emitCancelledSpaceCreateFlowResult(): SpaceCreateFlowResult {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n}\n\nfunction applySpaceCreateFlowSubmission(\n state: Partial<SpaceCreateFlowValues>,\n result: SpaceCreateFlowStepPromptResult\n): void {\n if (result.status !== \"submitted\") {\n return;\n }\n\n if (result.step === \"name\") {\n state.name = result.value;\n return;\n }\n if (result.step === \"visibility\") {\n state.visibility = result.value;\n return;\n }\n if (result.step === \"guide\") {\n state.guide = normalizePromptedSpaceGuide(result.value);\n return;\n }\n if (result.step === \"password\") {\n state.password = result.value;\n return;\n }\n state.join = result.value;\n}\n\nfunction buildProvidedSpaceCreateVisibility(value: string | undefined): {\n visibility?: SpaceCreateVisibility;\n} {\n const visibility = normalizeSpaceCreateVisibility(value);\n return visibility ? { visibility } : {};\n}\n\nfunction assertProvidedSpaceCreateVisibilityValid(\n value: string | undefined\n): void {\n const rawVisibility = String(value ?? \"\").trim();\n if (rawVisibility.length === 0) {\n return;\n }\n if (normalizeSpaceCreateVisibility(value)) {\n return;\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n `invalid --visibility value: ${rawVisibility} (use public|private)`\n )\n );\n}\n\nfunction normalizeSpaceCreateVisibility(\n value: string | undefined\n): SpaceCreateVisibility | null {\n const normalized = String(value ?? \"\")\n .trim()\n .toLowerCase();\n if (normalized === \"public\" || normalized === \"private\") {\n return normalized;\n }\n return null;\n}\n\nasync function promptRequiredInteractiveSpaceName(): Promise<\n | { status: \"submitted\"; value: string }\n | { status: \"back\" }\n | { status: \"cancelled\" }\n> {\n const nameInput = await promptTextEntry({\n message: \"Space name\",\n placeholder: \"e.g. design-review\",\n allowBack: true,\n backLabel: \"Back\",\n validate: (value) =>\n value.trim().length > 0 ? null : \"Space name cannot be empty.\",\n });\n if (nameInput.status !== \"submitted\") {\n return nameInput;\n }\n return {\n status: \"submitted\",\n value: nameInput.value.trim(),\n };\n}\n\nasync function promptInteractiveSpaceVisibility(): Promise<\n | { status: \"submitted\"; value: SpaceCreateVisibility }\n | { status: \"back\" }\n | { status: \"cancelled\" }\n> {\n const action = await select({\n message: \"Organization visibility\",\n options: [\n {\n value: \"private\",\n label: \"Private to this organization\",\n },\n {\n value: \"public\",\n label: \"Visible to the organization directory\",\n },\n {\n value: \"back\",\n label: \"Back\",\n },\n ],\n initialValue: \"private\",\n });\n if (isCancel(action)) {\n return { status: \"cancelled\" };\n }\n if (action === \"back\") {\n return { status: \"back\" };\n }\n if (action !== \"private\" && action !== \"public\") {\n return { status: \"cancelled\" };\n }\n return {\n status: \"submitted\",\n value: action,\n };\n}\n\nfunction promptInteractiveSpaceGuide(): Promise<\n | { status: \"submitted\"; value: string }\n | { status: \"back\" }\n | { status: \"cancelled\" }\n> {\n return promptTextEntry({\n message: \"Space guide (optional)\",\n placeholder: \"e.g. Keep it concise, respectful, and actionable.\",\n allowBack: true,\n allowEmpty: true,\n backLabel: \"Back\",\n });\n}\n\nasync function promptInteractiveSpaceCreatePassword(\n visibility: SpaceCreateVisibility\n): Promise<\n | { status: \"submitted\"; value: string | undefined }\n | { status: \"back\" }\n | { status: \"cancelled\" }\n> {\n for (;;) {\n const promptConfig = buildCreateSpacePasswordPromptConfig(visibility);\n const action = await select({\n message: promptConfig.message,\n options: [\n {\n value: \"set\",\n label: promptConfig.setPasswordLabel,\n },\n {\n value: \"skip\",\n label: promptConfig.skipPasswordLabel,\n },\n {\n value: \"back\",\n label: \"Back\",\n },\n ],\n });\n if (isCancel(action)) {\n return { status: \"cancelled\" };\n }\n if (action === \"back\") {\n return { status: \"back\" };\n }\n if (action === \"skip\") {\n return {\n status: \"submitted\",\n value: undefined,\n };\n }\n\n const password = await promptAndConfirmSpacePassword({\n allowBack: true,\n emitCancelMessage: false,\n });\n if (password.status === \"cancelled\") {\n return password;\n }\n if (password.status === \"back\") {\n continue;\n }\n return {\n status: \"submitted\",\n value: password.value,\n };\n }\n}\n\nasync function promptInteractiveSpaceJoinAfterCreate(): Promise<\n | { status: \"submitted\"; value: boolean }\n | { status: \"back\" }\n | { status: \"cancelled\" }\n> {\n const action = await select({\n message: \"Join this space now?\",\n options: [\n {\n value: \"join\",\n label: \"Yes\",\n },\n {\n value: \"skip\",\n label: \"No\",\n },\n {\n value: \"back\",\n label: \"Back\",\n },\n ],\n initialValue: \"join\",\n });\n if (isCancel(action)) {\n return { status: \"cancelled\" };\n }\n if (action === \"back\") {\n return { status: \"back\" };\n }\n return {\n status: \"submitted\",\n value: action === \"join\",\n };\n}\n\nfunction emitSpaceCreatePasswordOptionalHint(input: {\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfileId: string;\n resolvedView: \"human\" | \"agent\";\n providedPassword?: string;\n interactive: boolean;\n visibility: SpaceCreateVisibility;\n}): void {\n if (typeof input.providedPassword === \"string\") {\n return;\n }\n if (input.interactive) {\n return;\n }\n input.presenter.line({\n code: \"space.create.password.optional_hint\",\n text: buildSpaceCreatePasswordOptionalHintText(input.visibility),\n data: {\n optional: true,\n requirements: {\n minLength: SPACE_PASSWORD_MIN_LENGTH,\n charset: \"any\",\n },\n command: formatProfileAwareOpenMeldCliCommand(\n \"openmeld space create --name <name> --visibility <public|private> --password <value>\",\n {\n profileId: input.openMeldProfileId,\n resolvedView: input.resolvedView,\n }\n ),\n },\n });\n}\n\nfunction buildSpaceCreatePasswordOptionalHintText(\n visibility: SpaceCreateVisibility\n): string {\n const initialAccessMode = resolveInitialSpaceAccessMode(visibility);\n return (\n `Password is optional. ${resolveSpaceCreatePasswordlessAccessText(initialAccessMode)} To require a password to open and join, use --password <value>. Password rule: ` +\n buildSpacePasswordRequirementsText()\n );\n}\n\nexport function buildCreateSpacePasswordPromptMessage(\n visibility: SpaceCreateVisibility\n): string {\n return buildCreateSpacePasswordPromptConfig(visibility).message;\n}\n\nexport function buildCreateSpacePasswordPromptConfig(\n visibility: SpaceCreateVisibility\n): SpaceCreatePasswordPromptConfig {\n return buildSpaceCreatePasswordPromptConfig({\n accessMode: resolveInitialSpaceAccessMode(visibility),\n minimumLength: SPACE_PASSWORD_MIN_LENGTH,\n });\n}\n\ntype SpacePasswordPromptResult =\n | { status: \"submitted\"; value: string }\n | { status: \"back\" }\n | { status: \"cancelled\" };\n\nfunction resolveCancelledSpacePasswordPromptResult(input: {\n allowBack: boolean;\n emitCancelMessage: boolean;\n}): SpacePasswordPromptResult {\n if (input.allowBack) {\n return { status: \"back\" };\n }\n if (input.emitCancelMessage) {\n cancel(\"Cancelled.\");\n }\n return { status: \"cancelled\" };\n}\n\nasync function promptConfirmedSpacePassword(input: {\n firstPassword: string;\n allowBack: boolean;\n emitCancelMessage: boolean;\n}): Promise<SpacePasswordPromptResult | { status: \"retry\" }> {\n const confirmPassword = await passwordPrompt({\n message: \"Confirm password\",\n mask: \"•\",\n clearOnError: true,\n validate: validateSpacePasswordInput,\n });\n if (isCancel(confirmPassword) || typeof confirmPassword !== \"string\") {\n return input.allowBack\n ? { status: \"retry\" }\n : resolveCancelledSpacePasswordPromptResult(input);\n }\n const firstPassword = normalizeSpacePasswordText(input.firstPassword);\n const confirmedPassword = normalizeSpacePasswordText(confirmPassword);\n if (firstPassword !== confirmedPassword) {\n process.stderr.write(\"Passwords do not match. Try again.\\n\");\n return { status: \"retry\" };\n }\n return {\n status: \"submitted\",\n value: firstPassword,\n };\n}\n\nexport async function promptAndConfirmSpacePassword(input?: {\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n}): Promise<SpacePasswordPromptResult> {\n const allowBack = input?.allowBack === true;\n const emitCancelMessage = input?.emitCancelMessage !== false;\n\n for (;;) {\n const firstPassword = await passwordPrompt({\n message: \"Create password\",\n mask: \"•\",\n clearOnError: true,\n validate: validateSpacePasswordInput,\n });\n if (isCancel(firstPassword) || typeof firstPassword !== \"string\") {\n return resolveCancelledSpacePasswordPromptResult({\n allowBack,\n emitCancelMessage,\n });\n }\n\n const confirmedPassword = await promptConfirmedSpacePassword({\n firstPassword,\n allowBack,\n emitCancelMessage,\n });\n if (confirmedPassword.status === \"retry\") {\n continue;\n }\n return confirmedPassword;\n }\n}\n\nexport async function runSpaceList(input: {\n profile?: string;\n baseUrl?: string;\n limit: number;\n json?: boolean;\n view?: string;\n entryChecksHandled?: boolean;\n}) {\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"viewing your spaces\"\n ),\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return;\n }\n const { runtime, presenter, interactive, baseUrl } = context;\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n const limit = Number.isFinite(input.limit) ? Math.max(1, input.limit) : 20;\n const scope = resolveSpaceListAccountIndexScope({\n explicitProfile: input.profile,\n openMeldProfile,\n });\n const visibilityScope: KnownSpaceVisibilityScope =\n scope === \"account\" ? \"owner\" : \"profile\";\n const index = await listAccountSpacesForCliList({\n openMeldProfile,\n baseUrl,\n limit,\n scope,\n showLoading:\n interactive && runtime.resolvedView === \"human\" && input.json !== true,\n });\n const items = toKnownSpaceOptionsFromAccountIndex(index, baseUrl);\n\n if (input.json === true) {\n presenter.data({\n code: \"space.list\",\n payload: {\n visibilityScope,\n proof: buildSpaceListProofPayload(),\n total: items.length,\n limit,\n deletedNotices: [],\n spaces: items.map((item, index) =>\n buildKnownSpaceData(item, index + 1)\n ),\n },\n });\n return;\n }\n\n if (runtime.resolvedView === \"agent\") {\n presenter.data({\n code: \"space.list.proof\",\n payload: buildSpaceListProofPayload(),\n });\n }\n\n if (items.length === 0) {\n presenter.line({\n code: \"space.list.empty\",\n text: formatInlineOpenMeldCliCommands(\n resolveSpaceListEmptyMessage(visibilityScope)\n ),\n });\n return;\n }\n\n presenter.line({\n code: \"space.list.scope\",\n text: resolveSpaceVisibilitySummary({\n visibilityScope,\n resolvedView: runtime.resolvedView,\n }),\n });\n\n for (const [index, item] of items.entries()) {\n presenter.line({\n code: \"space.list.item\",\n text: formatKnownSpaceListLine({\n index: index + 1,\n space: item,\n resolvedView: runtime.resolvedView,\n currentProfileId: openMeldProfile.openMeldProfileId,\n currentProfileName: openMeldProfile.profileName,\n currentOwnerUserId: openMeldProfile.ownerUserId,\n command: \"join\",\n }),\n data: buildKnownSpaceData(item, index + 1),\n });\n }\n}\n\nfunction resolveSpaceListAccountIndexScope(input: {\n explicitProfile?: string;\n openMeldProfile: OpenMeldProfile;\n}): AccountSpaceIndexQuery[\"scope\"] {\n if (normalizeOptionalString(input.explicitProfile)) {\n return \"profile\";\n }\n if (\n input.openMeldProfile.profileKind === \"human\" &&\n input.openMeldProfile.isDefault === true\n ) {\n return \"account\";\n }\n return \"profile\";\n}\n\nasync function listAccountSpacesForCliList(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n limit: number;\n scope: AccountSpaceIndexQuery[\"scope\"];\n showLoading: boolean;\n}) {\n const loadingSpinner = createDelayedSpinner({\n enabled: input.showLoading,\n message: SPACE_LOADING_SPINNER_MESSAGE,\n });\n loadingSpinner.start();\n\n try {\n const result = await listAccountSpaceIndex({\n baseUrl: input.baseUrl,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n }),\n limit: input.limit,\n scope: input.scope,\n selectedProfileId: input.openMeldProfile.openMeldProfileId,\n });\n loadingSpinner.complete();\n return result;\n } catch (error) {\n loadingSpinner.fail();\n throw error;\n }\n}\n\nfunction toKnownSpaceOptionsFromAccountIndex(\n index: Awaited<ReturnType<typeof listAccountSpaceIndex>>,\n baseUrl: string\n): KnownSpaceOption[] {\n return [...index.pinnedItems, ...index.spaceItems].map((item) =>\n toKnownSpaceOptionFromAccountIndex(item, baseUrl)\n );\n}\n\nfunction buildSpaceListProofPayload() {\n return {\n spaceVisible: true,\n conversationReadable: \"not_checked\",\n wakeExecutionSucceeded: \"not_checked\",\n proves:\n \"This command proves known Space records are visible to the acting profile.\",\n doesNotProve:\n \"It does not prove conversation history is readable, members are available for Wake, or a Wake produced a visible reply.\",\n nextChecks: [\n \"<OPENMELD_CLI> space history <space-id> --kind text --brief --limit 20 --view agent\",\n \"<OPENMELD_CLI> space status <space-id> --json --view agent\",\n ],\n };\n}\n\nexport async function runSpaceAddMembers(input: {\n mode?: SpaceProfileAddMode;\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n members?: string[];\n all?: boolean;\n details?: boolean;\n view?: string;\n entryChecksHandled?: boolean;\n allowBackToCaller?: boolean;\n allowCurrentProfileMember?: boolean;\n suppressResultOutput?: boolean;\n membershipSource?: \"account\" | \"organization_directory\";\n}): Promise<SpaceCommandNavigationStatus> {\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const explicitMemberIds = (input.members ?? [])\n .map((memberId) => normalizeOptionalString(memberId))\n .filter((memberId): memberId is string => Boolean(memberId));\n if (input.all === true || explicitMemberIds.length > 0) {\n validateSpaceMemberSelectionInput({\n all: input.all === true,\n command: resolveSpaceAddMembersSelectionCommand(input.mode ?? \"profiles\"),\n explicitMemberIds,\n });\n }\n const currentProfileId =\n normalizeOptionalString(input.profile) ??\n getCurrentCommandCheckState().selectedProfile?.profile?.openMeldProfileId ??\n null;\n assertSpaceAddMembersCurrentProfileNotSelected({\n allowCurrentProfileMember: input.allowCurrentProfileMember === true,\n currentProfileId,\n explicitMemberIds,\n });\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"adding members to a space\"\n ),\n checkGatewayMismatch: hasExplicitBaseUrlInput,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return \"cancelled\";\n }\n const { runtime, interactive, presenter, baseUrl } = context;\n let authenticatedGatewayUrl = context.authenticatedGatewayUrl;\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n\n if (shouldRunSpaceAddMembersDiagnosticPreflight(input, explicitMemberIds)) {\n await emitSpaceCommandPreflight({\n presenter,\n command: \"add_members\",\n profile: openMeldProfile,\n baseUrl,\n resolvedView: runtime.resolvedView,\n });\n }\n\n try {\n for (;;) {\n const target = await resolveSpaceAddMembersTarget({\n openMeldProfile,\n baseUrl,\n mode: input.mode ?? \"profiles\",\n space: input.space,\n allowPrompt: interactive,\n presenter,\n resolvedView: runtime.resolvedView,\n allowBack: input.allowBackToCaller === true,\n });\n if (target.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (target.status === \"back\") {\n return \"back\";\n }\n const outcome = await runSpaceAddMembersForTarget({\n runtime,\n presenter,\n openMeldProfile,\n target: target.target,\n baseUrl,\n hasExplicitBaseUrlInput,\n authenticatedGatewayUrl,\n password: input.password,\n mode: input.mode ?? \"profiles\",\n explicitMembers: input.members,\n selectAll: input.all === true,\n details: input.details === true,\n allowPrompt: interactive,\n allowBackToCaller: input.allowBackToCaller === true,\n allowCurrentProfileMember: input.allowCurrentProfileMember === true,\n suppressResultOutput: input.suppressResultOutput === true,\n membershipSource: input.membershipSource ?? \"account\",\n view: input.view,\n });\n if (outcome.status === \"repeat_target\") {\n authenticatedGatewayUrl = outcome.authenticatedGatewayUrl;\n continue;\n }\n return outcome.status;\n }\n } catch (error) {\n emitSpaceFailureNextStep({\n presenter,\n command: \"add_members\",\n error,\n profileId: openMeldProfile.openMeldProfileId,\n resolvedView: runtime.resolvedView,\n });\n throw error;\n }\n}\n\nfunction assertSpaceAddMembersCurrentProfileNotSelected(input: {\n allowCurrentProfileMember: boolean;\n currentProfileId: string | null;\n explicitMemberIds: readonly string[];\n}): void {\n if (\n input.currentProfileId &&\n input.explicitMemberIds.includes(input.currentProfileId) &&\n !input.allowCurrentProfileMember\n ) {\n throw createSpaceAddMembersCurrentProfileGuideError({\n profileId: input.currentProfileId,\n });\n }\n}\n\nexport async function runSpaceRemoveMembers(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n members?: string[];\n all?: boolean;\n view?: string;\n entryChecksHandled?: boolean;\n allowBackToCaller?: boolean;\n}): Promise<SpaceCommandNavigationStatus> {\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const explicitMemberIds = (input.members ?? [])\n .map((memberId) => normalizeOptionalString(memberId))\n .filter((memberId): memberId is string => Boolean(memberId));\n const currentProfileId =\n normalizeOptionalString(input.profile) ??\n getCurrentCommandCheckState().selectedProfile?.profile?.openMeldProfileId ??\n null;\n if (currentProfileId && explicitMemberIds.includes(currentProfileId)) {\n throw createSpaceRemoveMembersCurrentProfileGuideError({\n profileId: currentProfileId,\n });\n }\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"removing members from a space\"\n ),\n checkGatewayMismatch: hasExplicitBaseUrlInput,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return \"cancelled\";\n }\n const { runtime, interactive, presenter, baseUrl } = context;\n let authenticatedGatewayUrl = context.authenticatedGatewayUrl;\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n\n await emitSpaceCommandPreflight({\n presenter,\n command: \"remove_members\",\n profile: openMeldProfile,\n baseUrl,\n resolvedView: runtime.resolvedView,\n });\n\n try {\n for (;;) {\n const target = await resolveSpaceRemoveMembersTarget({\n openMeldProfile,\n baseUrl,\n space: input.space,\n allowPrompt: interactive,\n presenter,\n resolvedView: runtime.resolvedView,\n allowBack: input.allowBackToCaller === true,\n });\n if (target.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (target.status === \"back\") {\n return \"back\";\n }\n const outcome = await runSpaceRemoveMembersForTarget({\n runtime,\n presenter,\n openMeldProfile,\n target: target.target,\n baseUrl,\n hasExplicitBaseUrlInput,\n authenticatedGatewayUrl,\n password: input.password,\n explicitMembers: input.members,\n selectAll: input.all === true,\n allowPrompt: interactive,\n allowBackToCaller: input.allowBackToCaller === true,\n });\n if (outcome.status === \"repeat_target\") {\n authenticatedGatewayUrl = outcome.authenticatedGatewayUrl;\n continue;\n }\n return outcome.status;\n }\n } catch (error) {\n emitSpaceFailureNextStep({\n presenter,\n command: \"remove_members\",\n error,\n profileId: openMeldProfile.openMeldProfileId,\n resolvedView: runtime.resolvedView,\n });\n throw error;\n }\n}\n\nexport async function runSpaceLeave(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n view?: string;\n entryChecksHandled?: boolean;\n allowBackToCaller?: boolean;\n}): Promise<SpaceCommandNavigationStatus> {\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\"leaving a space\"),\n checkGatewayMismatch: hasExplicitBaseUrlInput,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return \"cancelled\";\n }\n const { runtime, interactive, presenter, baseUrl } = context;\n let authenticatedGatewayUrl = context.authenticatedGatewayUrl;\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n\n await emitSpaceCommandPreflight({\n presenter,\n command: \"leave\",\n profile: openMeldProfile,\n baseUrl,\n resolvedView: runtime.resolvedView,\n });\n\n try {\n for (;;) {\n const target = await resolveSpaceLeaveTarget({\n openMeldProfile,\n baseUrl,\n space: input.space,\n allowPrompt: interactive,\n presenter,\n resolvedView: runtime.resolvedView,\n allowBack: input.allowBackToCaller === true,\n });\n if (target.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (target.status === \"back\") {\n return \"back\";\n }\n const outcome = await runSpaceLeaveForTarget({\n runtime,\n presenter,\n openMeldProfile,\n target: target.target,\n baseUrl,\n hasExplicitBaseUrlInput,\n authenticatedGatewayUrl,\n password: input.password,\n allowPrompt: interactive,\n allowBackToCaller: input.allowBackToCaller === true,\n });\n if (outcome.status === \"repeat_target\") {\n authenticatedGatewayUrl = outcome.authenticatedGatewayUrl;\n continue;\n }\n return outcome.status;\n }\n } catch (error) {\n emitSpaceFailureNextStep({\n presenter,\n command: \"leave\",\n error,\n profileId: openMeldProfile.openMeldProfileId,\n resolvedView: runtime.resolvedView,\n });\n throw error;\n }\n}\n\nfunction shouldRunSpaceAddMembersDiagnosticPreflight(\n input: {\n all?: boolean;\n details?: boolean;\n },\n explicitMemberIds: readonly string[]\n): boolean {\n return (\n input.details === true ||\n input.all === true ||\n explicitMemberIds.length === 0\n );\n}\n\nasync function runSpaceAddMembersForTarget(input: {\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfile: OpenMeldProfile;\n target: SpaceSelectionTarget;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n authenticatedGatewayUrl: string | null;\n password?: string;\n mode: SpaceProfileAddMode;\n explicitMembers?: string[];\n selectAll: boolean;\n details: boolean;\n allowPrompt: boolean;\n allowBackToCaller: boolean;\n allowCurrentProfileMember: boolean;\n suppressResultOutput: boolean;\n membershipSource: \"account\" | \"organization_directory\";\n view?: string;\n}): Promise<\n | {\n status: SpaceCommandNavigationStatus;\n }\n | {\n status: \"repeat_target\";\n authenticatedGatewayUrl: string | null;\n }\n> {\n // OPENMELD_SETUP_TO_WAKE_PATH: HIGHEST_FACT space-membership\n // Membership connects the default human profile and user-confirmed Agent\n // Profiles to a Space. Membership is separate from Wake availability.\n const targetBaseUrl = input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (input.target.baseUrl ?? input.baseUrl);\n const authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: targetBaseUrl,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"adding members to a space\"\n ),\n allowPrompt: input.allowPrompt,\n authenticatedGatewayUrl: input.authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return { status: \"cancelled\" };\n }\n\n const addMembersProgress = {\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n spaceId: input.target.space,\n command: resolveSpaceAddMembersSelectionCommand(input.mode),\n profileAddMode: input.mode,\n };\n const explicitMemberIds = normalizeRequestedMemberIds(input.explicitMembers);\n const progress =\n input.details || explicitMemberIds.length === 0\n ? addMembersProgress\n : undefined;\n const includeSelectedLocalParticipation =\n progress !== undefined || explicitMemberIds.length === 0;\n const candidates = await resolveSpaceMemberCandidatesForAdd({\n currentProfile: input.openMeldProfile,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n space: input.target.space,\n baseUrl: targetBaseUrl,\n password: input.password,\n explicitMemberIds,\n progress,\n mode: input.mode,\n includeLocalParticipation: includeSelectedLocalParticipation,\n allowCurrentProfileMember: input.allowCurrentProfileMember,\n membershipSource: input.membershipSource,\n });\n if (candidates.length === 0 && explicitMemberIds.length === 0) {\n input.presenter.line({\n code: \"space.add_members.no_candidates\",\n text: \"No additional profiles are available to add.\",\n data: { spaceId: input.target.space },\n });\n return { status: \"completed\" };\n }\n\n const selectedProfileIds = await resolveSpaceAddMemberSelection({\n space: input.target.space,\n candidates,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n explicitMembers: input.explicitMembers,\n selectAll: input.selectAll,\n mode: input.mode,\n allowPrompt: input.allowPrompt,\n resolvedView: input.runtime.resolvedView,\n presenter: input.presenter,\n allowBack: input.allowBackToCaller,\n allowCurrentProfileMember: input.allowCurrentProfileMember,\n emitCancelMessage: !input.allowBackToCaller,\n });\n if (selectedProfileIds === null) {\n return input.allowBackToCaller\n ? {\n status: \"repeat_target\",\n authenticatedGatewayUrl,\n }\n : { status: \"cancelled\" };\n }\n if (selectedProfileIds.length === 0) {\n return { status: \"completed\" };\n }\n\n const selectedCandidates = resolveSelectedSpaceMemberCandidates({\n candidates,\n selectedProfileIds,\n });\n if (selectedCandidates.length === 0) {\n return { status: \"completed\" };\n }\n\n const servicePreparationResult =\n await prepareSpaceAddMembersLocalParticipationIfRequested({\n openMeldProfile: input.openMeldProfile,\n candidates: selectedCandidates,\n enabled: includeSelectedLocalParticipation,\n progress,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n allowPrompt: input.allowPrompt,\n spaceId: input.target.space,\n view: input.view,\n });\n if (servicePreparationResult.status === \"cancelled\") {\n return input.allowBackToCaller\n ? {\n status: \"repeat_target\",\n authenticatedGatewayUrl,\n }\n : { status: \"cancelled\" };\n }\n const preparedCandidates = servicePreparationResult.candidates;\n\n emitSpaceAddMembersProgressIfRequested(progress, {\n stage: \"add_members\",\n phase: \"write_membership\",\n summary: \"Adding selected profiles to the Space.\",\n profileIds: preparedCandidates.map((candidate) => candidate.profileId),\n });\n const result = await applySpaceAddMembers({\n actorProfile: input.openMeldProfile,\n candidates: preparedCandidates,\n space: input.target.space,\n spaceName: input.target.name,\n baseUrl: targetBaseUrl,\n password: input.password,\n membershipSource: input.membershipSource,\n });\n\n await waitForAddedMembersWakeProjection({\n actorProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n password: input.password,\n progress,\n result,\n space: input.target.space,\n });\n\n emitSpaceAddMembersProgressIfRequested(progress, {\n stage: \"record_join_notices\",\n phase: \"write_join_notices\",\n summary: \"Recording visible join notices for newly added members.\",\n profileIds: result.added.map((candidate) => candidate.profileId),\n });\n const joinNoticeSummary = await persistSpaceAddMembersJoinNotices({\n actorProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n space: input.target.space,\n password: input.password,\n addedMembers: result.added,\n });\n emitSpaceAddMembersResultIfRequested({\n suppressResultOutput: input.suppressResultOutput,\n mode: input.mode,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n space: input.target.space,\n selectedCount: preparedCandidates.length,\n result,\n joinNoticeSummary,\n });\n\n if (result.failed.length > 0 && result.added.length === 0) {\n throw new Error(\n `failed to add members for space ${input.target.space}: ${toErrorMessage(result.failed[0]?.error)}`\n );\n }\n\n const joinNow = await resolveJoinAfterCreate(\n undefined,\n input.allowPrompt && input.runtime.resolvedView === \"human\"\n );\n if (!joinNow) {\n return { status: \"completed\" };\n }\n\n await runSpaceJoin({\n profile: input.openMeldProfile.openMeldProfileId,\n baseUrl: targetBaseUrl,\n space: input.target.space,\n password: input.password,\n output: \"text\",\n view: input.view,\n skipBringProfilesPrompt: true,\n entryChecksHandled: true,\n });\n return { status: \"completed\" };\n}\n\nasync function prepareSpaceAddMembersLocalParticipationIfRequested(input: {\n openMeldProfile: OpenMeldProfile;\n candidates: SpaceMemberCandidate[];\n enabled: boolean;\n progress?: SpaceAddMembersProgressContext;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowPrompt: boolean;\n spaceId: string;\n view?: string;\n}): Promise<\n | {\n status: \"continue\";\n candidates: SpaceMemberCandidate[];\n }\n | {\n status: \"cancelled\";\n }\n> {\n if (!input.enabled) {\n return {\n status: \"continue\",\n candidates: input.candidates,\n };\n }\n\n const localCandidates = input.candidates.filter(\n (candidate) => candidate.openMeldProfile !== undefined\n );\n if (localCandidates.length === 0) {\n return {\n status: \"continue\",\n candidates: input.candidates,\n };\n }\n\n emitSpaceAddMembersProgressIfRequested(input.progress, {\n stage: \"check_local_wake_readiness\",\n phase: \"start\",\n summary:\n \"Checking whether selected agent profiles can handle work from this computer. Members can still be added if local setup needs attention.\",\n profileIds: localCandidates.map((candidate) => candidate.profileId),\n });\n const localResult = await ensureSpaceMemberCandidatesLocalParticipationReady({\n openMeldProfile: input.openMeldProfile,\n candidates: localCandidates,\n progress: input.progress,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n allowPrompt: input.allowPrompt,\n spaceId: input.spaceId,\n view: input.view,\n });\n if (localResult.status === \"cancelled\") {\n return localResult;\n }\n const preparedLocalCandidateById = new Map(\n localResult.candidates.map((candidate) => [candidate.profileId, candidate])\n );\n return {\n status: \"continue\",\n candidates: input.candidates.map(\n (candidate) =>\n preparedLocalCandidateById.get(candidate.profileId) ?? candidate\n ),\n };\n}\n\ntype SpaceAddMembersProgressContext = {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n spaceId: string;\n command: \"add-agents\" | \"add-human-profiles\" | \"add-members\";\n profileAddMode: SpaceProfileAddMode;\n};\n\nfunction emitSpaceAddMembersProgressIfRequested(\n progress: SpaceAddMembersProgressContext | undefined,\n input: {\n stage: SpaceAddMembersProgressStage;\n phase: string;\n summary: string;\n profileId?: string;\n profileIds?: readonly string[];\n }\n): void {\n if (!progress) {\n return;\n }\n emitAgentSpaceAddMembersProgress({\n ...progress,\n ...input,\n });\n}\n\nfunction emitAgentSpaceAddMembersProgress(\n input: SpaceAddMembersProgressContext & {\n stage: SpaceAddMembersProgressStage;\n phase: string;\n summary: string;\n profileId?: string;\n profileIds?: readonly string[];\n }\n): void {\n if (input.resolvedView !== \"agent\") {\n return;\n }\n const phaseContract = resolveSpaceAddMembersProgressPhase({\n stage: input.stage,\n phase: input.phase,\n });\n input.presenter.line({\n code: \"space.add_members.progress\",\n text: `${input.stage}/${input.phase}: ${input.summary}`,\n data: {\n stage: input.stage,\n phase: input.phase,\n spaceId: input.spaceId,\n command: input.command,\n profileAddMode: input.profileAddMode,\n owner: phaseContract.owner,\n waitingFor: phaseContract.waitingFor,\n factSource: phaseContract.factSource,\n doesNotMeanReady: true,\n ...(input.profileId ? { profileId: input.profileId } : {}),\n ...(input.profileIds ? { profileIds: input.profileIds } : {}),\n },\n });\n}\n\nasync function runSpaceAddMembersProgressHeartbeat<T>(\n input: SpaceAddMembersProgressContext & {\n stage: SpaceAddMembersProgressStage;\n phase: string;\n summary: string;\n profileId?: string;\n profileIds?: readonly string[];\n operation: () => Promise<T>;\n }\n): Promise<T> {\n if (input.resolvedView !== \"agent\") {\n return await input.operation();\n }\n\n const timer = setInterval(() => {\n emitAgentSpaceAddMembersProgress(input);\n }, SPACE_ADD_MEMBERS_PROGRESS_HEARTBEAT_MS);\n (timer as { unref?: () => void }).unref?.();\n try {\n return await input.operation();\n } finally {\n clearInterval(timer);\n }\n}\n\nfunction buildSpaceAddMembersLocalWakePlanSummary(\n plan: ActionParticipationPlan\n): string {\n const selectedAgentCount = plan.assessments.filter(\n (assessment) => assessment.profileKind === \"agent\"\n ).length;\n if (selectedAgentCount === 0) {\n return \"No selected members need local Wake setup on this computer.\";\n }\n\n const counts = new Map<string, number>();\n for (const assessment of plan.assessments) {\n if (assessment.profileKind !== \"agent\") {\n continue;\n }\n counts.set(\n assessment.localParticipationState,\n (counts.get(assessment.localParticipationState) ?? 0) + 1\n );\n }\n const parts = [\n formatLocalWakePlanCount(\n counts.get(\"ready\") ?? 0,\n \"can handle work from this device\"\n ),\n formatLocalWakePlanCount(\n counts.get(\"needs_agent_prepare\") ?? 0,\n \"need agent preparation\"\n ),\n formatLocalWakePlanCount(\n counts.get(\"needs_openmeld_service\") ?? 0,\n \"need OpenMeld Service\"\n ),\n formatLocalWakePlanCount(\n counts.get(\"membership_only\") ?? 0,\n \"will be added as members only\"\n ),\n formatLocalWakePlanCount(\n counts.get(\"not_needed\") ?? 0,\n \"do not need local agent setup\"\n ),\n ].filter((part): part is string => Boolean(part));\n\n return `Local agent plan: ${parts.join(\", \")}. Adding members is separate from local agent participation on this computer.`;\n}\n\nfunction formatLocalWakePlanCount(count: number, label: string): string | null {\n return count > 0 ? `${String(count)} ${label}` : null;\n}\n\nasync function runSpaceRemoveMembersForTarget(input: {\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfile: OpenMeldProfile;\n target: SpaceSelectionTarget;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n authenticatedGatewayUrl: string | null;\n password?: string;\n explicitMembers?: string[];\n selectAll: boolean;\n allowPrompt: boolean;\n allowBackToCaller: boolean;\n}): Promise<\n | {\n status: SpaceCommandNavigationStatus;\n }\n | {\n status: \"repeat_target\";\n authenticatedGatewayUrl: string | null;\n }\n> {\n const targetBaseUrl = input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (input.target.baseUrl ?? input.baseUrl);\n const authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: targetBaseUrl,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"removing members from a space\"\n ),\n allowPrompt: input.allowPrompt,\n authenticatedGatewayUrl: input.authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return { status: \"cancelled\" };\n }\n\n const candidates = await resolveSpaceMemberCandidatesForRemove({\n currentProfile: input.openMeldProfile,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n space: input.target.space,\n baseUrl: targetBaseUrl,\n password: input.password,\n });\n if (candidates.activeMembers.length === 0 && !input.explicitMembers?.length) {\n input.presenter.line({\n code: \"space.remove_members.no_candidates\",\n text: \"No removable members are available in this space.\",\n data: { spaceId: input.target.space },\n });\n return { status: \"completed\" };\n }\n\n const selectedCandidates = await resolveSpaceRemoveMemberSelection({\n space: input.target.space,\n candidates,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n explicitMembers: input.explicitMembers,\n selectAll: input.selectAll,\n allowPrompt: input.allowPrompt,\n resolvedView: input.runtime.resolvedView,\n presenter: input.presenter,\n allowBack: input.allowBackToCaller,\n emitCancelMessage: !input.allowBackToCaller,\n });\n if (selectedCandidates === null) {\n return input.allowBackToCaller\n ? {\n status: \"repeat_target\",\n authenticatedGatewayUrl,\n }\n : { status: \"cancelled\" };\n }\n if (selectedCandidates.length === 0) {\n return { status: \"completed\" };\n }\n\n const result = await applySpaceRemoveMembers({\n actorProfile: input.openMeldProfile,\n candidates: selectedCandidates,\n space: input.target.space,\n baseUrl: targetBaseUrl,\n password: input.password,\n });\n const removeNoticeSummary = await persistSpaceRemoveMemberNotices({\n actorProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n space: input.target.space,\n password: input.password,\n removedMembers: result.removed,\n });\n emitSpaceRemoveMembersResult({\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n space: input.target.space,\n selectedCount: selectedCandidates.length,\n result,\n removeNoticeSummary,\n });\n\n if (result.failed.length > 0 && result.removed.length === 0) {\n throw new Error(\n `failed to remove members for space ${input.target.space}: ${toErrorMessage(result.failed[0]?.error)}`\n );\n }\n\n return { status: \"completed\" };\n}\n\nasync function runSpaceLeaveForTarget(input: {\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfile: OpenMeldProfile;\n target: SpaceSelectionTarget;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n authenticatedGatewayUrl: string | null;\n password?: string;\n allowPrompt: boolean;\n allowBackToCaller: boolean;\n}): Promise<\n | {\n status: SpaceCommandNavigationStatus;\n }\n | {\n status: \"repeat_target\";\n authenticatedGatewayUrl: string | null;\n }\n> {\n const targetBaseUrl = input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (input.target.baseUrl ?? input.baseUrl);\n const authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: targetBaseUrl,\n promptMessage: buildCommandAuthenticationPromptMessage(\"leaving a space\"),\n allowPrompt: input.allowPrompt,\n authenticatedGatewayUrl: input.authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return { status: \"cancelled\" };\n }\n\n const confirmed = await confirmSpaceLeave({\n target: input.target,\n allowPrompt: input.allowPrompt,\n resolvedView: input.runtime.resolvedView,\n });\n if (confirmed === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n if (confirmed === \"back\") {\n return input.allowBackToCaller\n ? {\n status: \"repeat_target\",\n authenticatedGatewayUrl,\n }\n : { status: \"cancelled\" };\n }\n\n const result = await applySpaceLeave({\n actorProfile: input.openMeldProfile,\n space: input.target.space,\n baseUrl: targetBaseUrl,\n password: input.password,\n }).catch((error) => {\n throw mapSpaceLeaveFailureToGuideError({\n error,\n spaceId: input.target.space,\n });\n });\n emitSpaceLeaveResult({\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n space: input.target.space,\n result,\n });\n return { status: \"completed\" };\n}\n\nfunction resolveSelectedSpaceMemberCandidates(input: {\n candidates: SpaceMemberCandidate[];\n selectedProfileIds: string[];\n}): SpaceMemberCandidate[] {\n return input.selectedProfileIds\n .map((profileId) =>\n input.candidates.find((candidate) => candidate.profileId === profileId)\n )\n .filter((candidate): candidate is SpaceMemberCandidate =>\n Boolean(candidate)\n );\n}\n\nasync function ensureSpaceMemberCandidatesLocalParticipationReady(input: {\n openMeldProfile: OpenMeldProfile;\n candidates: SpaceMemberCandidate[];\n gatewayUrl?: string;\n progress?: SpaceAddMembersProgressContext;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowPrompt: boolean;\n spaceId: string;\n view?: string;\n}): Promise<\n | {\n status: \"continue\";\n candidates: SpaceMemberCandidate[];\n }\n | {\n status: \"cancelled\";\n }\n> {\n let preparedCandidates = await refreshSpaceMemberCandidatesLocalReadiness(\n input.candidates,\n input.progress\n );\n const localDemand =\n input.resolvedView === \"human\"\n ? await resolveLocalServiceDemand({\n ownerUserId: input.openMeldProfile.ownerUserId,\n }).catch(() => null)\n : null;\n while (true) {\n const participationPlan = planActionParticipation({\n intent: \"space_add_members\",\n candidates: preparedCandidates.map(\n toActionParticipationCandidateFromSpaceMemberCandidate\n ),\n });\n if (input.progress) {\n emitAgentSpaceAddMembersProgress({\n ...input.progress,\n stage: \"plan_local_wake_participation\",\n phase: \"plan\",\n summary: buildSpaceAddMembersLocalWakePlanSummary(participationPlan),\n profileIds: preparedCandidates.map((candidate) => candidate.profileId),\n });\n }\n const orchestratorResult = await runLocalParticipationOrchestrator({\n intent: \"space_add_members\",\n plan: participationPlan,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n allowPrompt: input.allowPrompt,\n gatewayUrl: input.gatewayUrl,\n localDemand,\n forceServicePrompt: participationPlan.explicitLocalAgentCount > 0,\n profilesToPrepare: preparedCandidates\n .filter((candidate) =>\n participationPlan.assessments.some(\n (assessment) =>\n assessment.profileId === candidate.profileId &&\n assessment.localParticipationState === \"needs_agent_prepare\"\n )\n )\n .map((candidate) => candidate.openMeldProfile)\n .filter((profile): profile is OpenMeldProfile => Boolean(profile)),\n view: input.view,\n });\n if (orchestratorResult.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n if (orchestratorResult.status !== \"recheck_required\") {\n break;\n }\n preparedCandidates = await refreshSpaceMemberCandidatesLocalReadiness(\n preparedCandidates,\n input.progress\n );\n }\n\n if (input.progress) {\n emitAgentSpaceAddMembersProgress({\n ...input.progress,\n stage: \"confirm_local_wake_bindings\",\n phase: \"start\",\n summary:\n \"Confirming available local agent profiles have Wake bindings before adding them.\",\n profileIds: preparedCandidates.map((candidate) => candidate.profileId),\n });\n }\n preparedCandidates = await ensureFormalBindingsForReadySpaceMemberCandidates(\n preparedCandidates,\n input.progress\n );\n\n emitSpaceMemberJoinOnlyWarnings({\n candidates: preparedCandidates,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n });\n\n const finalPlan = planActionParticipation({\n intent: \"space_add_members\",\n candidates: preparedCandidates.map(\n toActionParticipationCandidateFromSpaceMemberCandidate\n ),\n });\n if (finalPlan.shouldOfferServiceGate) {\n input.presenter.line({\n code:\n input.resolvedView === \"human\" && input.allowPrompt\n ? \"space.add_members.service.declined\"\n : \"space.add_members.service.deferred\",\n text: formatInlineOpenMeldCliCommands(\n \"OpenMeld will add these profiles to the Space. Local agent participation can be checked separately with `openmeld service status`.\"\n ),\n });\n }\n return {\n status: \"continue\",\n candidates: preparedCandidates,\n };\n}\n\nasync function ensureFormalBindingsForReadySpaceMemberCandidates(\n candidates: SpaceMemberCandidate[],\n progress?: SpaceAddMembersProgressContext\n): Promise<SpaceMemberCandidate[]> {\n const nextCandidates: SpaceMemberCandidate[] = [];\n for (const candidate of candidates) {\n if (\n !isSpaceMemberCandidateBackgroundReplyReady(candidate) ||\n candidate.openMeldProfile?.profileKind !== \"agent\"\n ) {\n nextCandidates.push(candidate);\n continue;\n }\n\n // This same add-members operation already read Core's current primary\n // Binding verdict. Do not submit the same runtime evidence and Binding again.\n if (candidate.localParticipationBindingConfirmed === true) {\n nextCandidates.push(candidate);\n continue;\n }\n\n const candidateOpenMeldProfile = candidate.openMeldProfile;\n if (progress) {\n emitAgentSpaceAddMembersProgress({\n ...progress,\n stage: \"confirm_local_wake_bindings\",\n phase: \"profile_binding_sync\",\n summary: `Checking ${resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n )}: validating gateway-chain diagnostics, submitting local runtime evidence, writing the Agent Profile binding, and waiting for Core execution readiness projection.`,\n profileId: candidate.profileId,\n profileIds: [candidate.profileId],\n });\n }\n const result = progress\n ? await runSpaceAddMembersProgressHeartbeat({\n ...progress,\n stage: \"confirm_local_wake_bindings\",\n phase: \"profile_binding_sync_wait\",\n summary: `Still checking ${resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n )}: local runtime evidence, Binding write, and Core projection confirmation are still in progress.`,\n profileId: candidate.profileId,\n profileIds: [candidate.profileId],\n operation: async () =>\n await ensureFormalAgentBindingForReadyLocalProfile({\n profile: candidateOpenMeldProfile,\n }),\n })\n : await ensureFormalAgentBindingForReadyLocalProfile({\n profile: candidateOpenMeldProfile,\n });\n if (result.status === \"ready\") {\n if (progress) {\n emitAgentSpaceAddMembersProgress({\n ...progress,\n stage: \"confirm_local_wake_bindings\",\n phase: \"profile_binding_confirmed\",\n summary: `${resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n )}: local participation binding is confirmed. This is not a final Wake outcome.`,\n profileId: candidate.profileId,\n profileIds: [candidate.profileId],\n });\n }\n nextCandidates.push({\n ...candidate,\n localParticipationBindingConfirmed: true,\n });\n continue;\n }\n\n if (progress) {\n emitAgentSpaceAddMembersProgress({\n ...progress,\n stage: \"confirm_local_wake_bindings\",\n phase: \"profile_binding_not_confirmed\",\n summary: `${resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n )}: local participation binding was not confirmed; membership will continue with follow-up diagnostics.`,\n profileId: candidate.profileId,\n profileIds: [candidate.profileId],\n });\n }\n nextCandidates.push({\n ...candidate,\n localParticipationBindingConfirmed: false,\n localParticipationReadiness: null,\n localParticipationReasonCodes: result.reasonCodes,\n localParticipationReasonText: result.reasonText,\n });\n }\n return nextCandidates;\n}\n\nfunction emitSpaceMemberJoinOnlyWarnings(input: {\n candidates: readonly SpaceMemberCandidate[];\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (input.resolvedView !== \"human\") {\n return;\n }\n\n for (const candidate of input.candidates) {\n const warning = buildSpaceMemberJoinOnlyWarning(candidate);\n if (!warning) {\n continue;\n }\n input.presenter.line({\n code: \"space.add_members.local_participation.join_only_warning\",\n text: warning,\n });\n }\n}\n\nfunction buildSpaceMemberJoinOnlyWarning(\n candidate: SpaceMemberCandidate\n): string | null {\n if (candidate.profileKind !== \"agent\") {\n return null;\n }\n if (candidate.localParticipationChecked !== true) {\n return null;\n }\n\n if (isSpaceMemberCandidateBackgroundReplyReady(candidate)) {\n return null;\n }\n\n const profileLabel = resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n );\n if (isSpaceMemberCandidateRepairableLocalParticipationCandidate(candidate)) {\n const agentLabel = resolveSpaceMemberTerminalLocalTargetLabel({\n displayName: candidate.localTargetDisplayName,\n agentId: candidate.localTargetAgentId,\n });\n const nextStep = buildSpaceMemberRepairCommand({\n agentId: candidate.localTargetAgentId,\n profileId: candidate.profileId,\n });\n return `${profileLabel} can join this space now. ${agentLabel} still needs local setup on this device before it can handle work from the Space. Use \\`${nextStep}\\` to repair the local agent.`;\n }\n\n const nextAction = resolveSpaceMemberJoinOnlyNextAction(candidate);\n const reason = resolveSpaceMemberJoinOnlyReason(candidate);\n return `${profileLabel} can join this space now. OpenMeld has not confirmed its local reply path on this device yet. ${reason} ${formatSpaceMemberRecoveryNextAction(nextAction)}`;\n}\n\nasync function refreshSpaceMemberCandidatesLocalReadiness(\n candidates: SpaceMemberCandidate[],\n progress?: SpaceAddMembersProgressContext,\n options: {\n stage?: Extract<\n SpaceAddMembersProgressStage,\n \"resolve_candidates\" | \"check_local_wake_readiness\"\n >;\n } = {}\n): Promise<SpaceMemberCandidate[]> {\n const stage = options.stage ?? \"check_local_wake_readiness\";\n if (progress) {\n emitAgentSpaceAddMembersProgress({\n ...progress,\n stage,\n phase: \"read_local_targets\",\n summary:\n stage === \"resolve_candidates\"\n ? \"Reading local agent controller state on this computer before showing candidate profiles.\"\n : \"Reading local agent controller state on this computer before checking selected profiles.\",\n profileIds: candidates.map((candidate) => candidate.profileId),\n });\n }\n const localTargetStates = progress\n ? await runSpaceAddMembersProgressHeartbeat({\n ...progress,\n stage,\n phase: \"read_local_targets_wait\",\n summary:\n stage === \"resolve_candidates\"\n ? \"Still reading local agent controller state on this computer before showing candidate profiles.\"\n : \"Still reading local agent controller state on this computer before checking selected profiles.\",\n profileIds: candidates.map((candidate) => candidate.profileId),\n operation: async () => await listAgentTargetStates().catch(() => []),\n })\n : await listAgentTargetStates().catch(() => []);\n if (localTargetStates.length === 0) {\n return await Promise.all(\n candidates.map(async (candidate) => {\n const normalizedCandidate = {\n ...candidate,\n localTargetDisplayName: candidate.localTargetDisplayName ?? null,\n localTargetLaunchStatus: candidate.localTargetLaunchStatus ?? null,\n localTargetSelectable: candidate.localTargetSelectable ?? false,\n };\n return await enrichSpaceMemberCandidateLocalParticipationReadiness(\n normalizedCandidate,\n progress,\n { stage }\n );\n })\n );\n }\n const localTargetStateById = new Map(\n localTargetStates.map((state) => [state.agentId, state] as const)\n );\n\n return await Promise.all(\n candidates.map(async (candidate) => {\n const localTargetAgentId = resolveSpaceMemberCandidateLocalTargetAgentId({\n profileKind: candidate.profileKind,\n agentControllerRef: candidate.agentControllerRef,\n controllerEnabled: candidate.controllerEnabled,\n });\n const localTargetState = localTargetAgentId\n ? (localTargetStateById.get(localTargetAgentId) ?? null)\n : null;\n return await enrichSpaceMemberCandidateLocalParticipationReadiness(\n {\n ...candidate,\n localTargetAgentId,\n localTargetDisplayName: localTargetState?.displayName ?? null,\n localTargetLaunchStatus: localTargetState?.launchStatus ?? null,\n localTargetSelectable: localTargetState?.selectable ?? false,\n },\n progress,\n { stage }\n );\n })\n );\n}\n\nasync function enrichSpaceMemberCandidateLocalParticipationReadiness(\n candidate: SpaceMemberCandidate,\n progress?: SpaceAddMembersProgressContext,\n options: {\n stage?: Extract<\n SpaceAddMembersProgressStage,\n \"resolve_candidates\" | \"check_local_wake_readiness\"\n >;\n } = {}\n): Promise<SpaceMemberCandidate> {\n if (\n candidate.profileKind !== \"agent\" ||\n !candidate.openMeldProfile ||\n candidate.controllerEnabled !== true ||\n typeof candidate.agentControllerRef !== \"string\" ||\n candidate.agentControllerRef.trim().length === 0\n ) {\n return {\n ...candidate,\n localParticipationBindingConfirmed: false,\n localParticipationChecked: true,\n localParticipationReadiness: null,\n localParticipationReasonCodes: [],\n localParticipationReasonText: null,\n };\n }\n const candidateOpenMeldProfile = candidate.openMeldProfile;\n\n let snapshot: Awaited<\n ReturnType<typeof resolveCurrentReplyReadinessSnapshot>\n > | null = null;\n const stage = options.stage ?? \"check_local_wake_readiness\";\n try {\n if (progress) {\n emitAgentSpaceAddMembersProgress({\n ...progress,\n stage,\n phase: \"read_profile_readiness\",\n summary: `Checking local Wake evidence for ${resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n )}. This checks local participation evidence only, not final Wake readiness.`,\n profileId: candidate.profileId,\n profileIds: [candidate.profileId],\n });\n }\n snapshot = progress\n ? await runSpaceAddMembersProgressHeartbeat({\n ...progress,\n stage,\n phase: \"read_profile_readiness_wait\",\n summary: `Still checking local Wake evidence for ${resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n )}. This is local participation evidence only, not final Wake readiness.`,\n profileId: candidate.profileId,\n profileIds: [candidate.profileId],\n operation: async () =>\n await resolveCurrentReplyReadinessSnapshot({\n checkGatewayChain: false,\n ownerUserId: candidateOpenMeldProfile.ownerUserId,\n profile: candidateOpenMeldProfile,\n }),\n })\n : await resolveCurrentReplyReadinessSnapshot({\n checkGatewayChain: false,\n ownerUserId: candidateOpenMeldProfile.ownerUserId,\n profile: candidateOpenMeldProfile,\n });\n } catch {\n snapshot = null;\n }\n if (!snapshot) {\n return {\n ...candidate,\n localParticipationBindingConfirmed: false,\n localParticipationChecked: true,\n localParticipationReadiness: null,\n localParticipationReasonCodes: [],\n localParticipationReasonText: null,\n };\n }\n\n const readinessSummary = resolveServiceParticipationReadiness({\n deviceReplyReadiness: snapshot.deviceReplyReadiness,\n inventory: snapshot.inventory,\n runtimeStatus: snapshot.displayRuntimeStatus ?? snapshot.runtimeStatus,\n });\n\n return {\n ...candidate,\n localParticipationBindingConfirmed:\n snapshot.agentReplyReadiness?.replyReadiness === \"ready\",\n localParticipationChecked: true,\n localParticipationReadiness: readinessSummary.serviceReadiness,\n localParticipationReasonCodes: [\n ...snapshot.deviceReplyReadiness.reasonCodes,\n ],\n localParticipationReasonText: snapshot.deviceReplyReadiness.reasonText,\n };\n}\n\nfunction isSpaceMemberCandidateRunnableLocalParticipationCandidate(\n candidate: Pick<\n SpaceMemberCandidate,\n | \"profileKind\"\n | \"agentControllerRef\"\n | \"controllerEnabled\"\n | \"localTargetSelectable\"\n | \"localParticipationReadiness\"\n >\n): boolean {\n return (\n candidate.profileKind === \"agent\" &&\n candidate.controllerEnabled === true &&\n typeof candidate.agentControllerRef === \"string\" &&\n candidate.agentControllerRef.trim().length > 0 &&\n candidate.localTargetSelectable === true &&\n (candidate.localParticipationReadiness === \"ready\" ||\n candidate.localParticipationReadiness === \"not_running\" ||\n candidate.localParticipationReadiness === \"not_installed\")\n );\n}\n\nfunction toActionParticipationCandidateFromSpaceMemberCandidate(\n candidate: SpaceMemberCandidate\n): ActionParticipationCandidate {\n return {\n profileId: candidate.profileId,\n profileName: candidate.profileName,\n profileKind: candidate.profileKind,\n localTargetSelectable: candidate.localTargetSelectable,\n localTargetLaunchStatus: candidate.localTargetLaunchStatus,\n localParticipationReadiness: candidate.localParticipationReadiness,\n localParticipationReasonCodes: candidate.localParticipationReasonCodes,\n };\n}\n\nexport async function runSpaceJoin(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n output?: string;\n rawStream?: boolean;\n view?: string;\n allowPrompt?: boolean;\n localEcho?: boolean;\n historyLimit?: number;\n role?: string;\n mentionAlias?: string;\n skipBringProfilesPrompt?: boolean;\n serviceIntent?: \"space_join\" | \"space_create_join\";\n entryChecksHandled?: boolean;\n}): Promise<\"completed\" | \"cancelled\" | \"back\"> {\n let failureRuntime: Awaited<ReturnType<typeof resolveRuntimeContext>> | null =\n null;\n let failurePresenter: ReturnType<typeof createPresenter> | null = null;\n\n try {\n const entryContext = await prepareSpaceJoinEntryContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n space: input.space,\n allowPrompt: input.allowPrompt,\n output: input.output,\n rawStream: input.rawStream,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (entryContext.status === \"cancelled\") {\n return \"cancelled\";\n }\n failureRuntime = entryContext.runtime;\n failurePresenter = entryContext.presenter;\n\n return await runSpaceJoinTargetLoop({\n openMeldProfileId: entryContext.openMeldProfile.openMeldProfileId,\n openMeldProfile: entryContext.openMeldProfile,\n runtime: entryContext.runtime,\n presenter: entryContext.presenter,\n baseUrl: entryContext.baseUrl,\n localDemand: entryContext.localDemand,\n authenticatedGatewayUrl: entryContext.authenticatedGatewayUrl,\n space: input.space,\n password: input.password,\n output: input.output,\n view: input.view,\n allowPrompt: input.allowPrompt,\n allowPromptForSpaceTarget: entryContext.allowPromptForSpaceTarget,\n allowPromptForRoleContext: entryContext.allowPromptForRoleContext,\n canPromptPreJoinActions: entryContext.canPromptPreJoinActions,\n allowBackToTargetSelection: entryContext.allowBackToTargetSelection,\n skipBringProfilesPrompt: input.skipBringProfilesPrompt === true,\n hasExplicitBaseUrlInput: entryContext.hasExplicitBaseUrlInput,\n showProgress: shouldShowSpaceJoinProgress({\n resolvedView: entryContext.runtime.resolvedView,\n interactive:\n entryContext.allowPromptForSpaceTarget &&\n canUseInteractivePrompts(entryContext.runtime),\n output: input.output,\n rawStream: input.rawStream,\n }),\n localEcho: input.localEcho ?? false,\n historyLimit: input.historyLimit,\n role: input.role,\n mentionAlias: input.mentionAlias,\n rawStream: input.rawStream === true,\n serviceIntent: input.serviceIntent ?? \"space_join\",\n });\n } catch (error) {\n const runtime =\n failureRuntime ??\n (await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n }));\n const presenter = failurePresenter ?? createPresenter(runtime);\n if (isSpaceCommandOutputHandledError(error)) {\n throw error;\n }\n emitSpaceFailureNextStep({\n presenter,\n command: \"join\",\n error,\n profileId: runtime.openMeldProfileId ?? input.profile,\n resolvedView: runtime.resolvedView,\n });\n throw error;\n }\n}\n\nasync function runSpaceJoinTargetLoop(input: {\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n baseUrl: string;\n localDemand: PreparedSpaceJoinEntryContext[\"localDemand\"];\n authenticatedGatewayUrl: string | null;\n space?: string;\n password?: string;\n output?: string;\n view?: string;\n allowPrompt?: boolean;\n allowPromptForSpaceTarget: boolean;\n allowPromptForRoleContext: boolean;\n canPromptPreJoinActions: boolean;\n allowBackToTargetSelection: boolean;\n skipBringProfilesPrompt: boolean;\n hasExplicitBaseUrlInput: boolean;\n showProgress: boolean;\n localEcho: boolean;\n historyLimit?: number;\n role?: string;\n mentionAlias?: string;\n rawStream: boolean;\n serviceIntent: \"space_join\" | \"space_create_join\";\n}): Promise<\"completed\" | \"cancelled\" | \"back\"> {\n let authenticatedGatewayUrl = input.authenticatedGatewayUrl;\n const openMeldProfileId = input.openMeldProfileId;\n\n for (;;) {\n const targetResult = await resolveSpaceJoinEntryTargetOutcome({\n resolveTarget: async () =>\n await resolveSpaceJoinTarget({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n allowPrompt: input.allowPromptForSpaceTarget,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n }),\n runCreate: async () => {\n return await runSpaceCreate({\n profile: input.openMeldProfile.openMeldProfileId,\n baseUrl: input.baseUrl,\n join: true,\n output: input.output,\n view: input.view,\n entryChecksHandled: true,\n postCreateJoin: {\n localEcho: input.localEcho,\n historyLimit: input.historyLimit,\n role: input.role,\n mentionAlias: input.mentionAlias,\n rawStream: input.rawStream,\n skipBringProfilesPrompt: input.skipBringProfilesPrompt,\n output: input.output,\n view: input.view,\n serviceIntent: \"space_create_join\",\n },\n });\n },\n });\n if (targetResult.status !== \"submitted\") {\n return targetResult.status;\n }\n\n const target = targetResult.target;\n const existingSpaceConfig = resolveOptionalReadableSpaceConfig(\n await readSpaceConfig({\n openMeldProfileId,\n space: target.space,\n }),\n \"reading an existing local space config before join\"\n );\n const targetBaseUrl = input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (target.baseUrl ?? input.baseUrl);\n const preflightResult = await assertSpaceJoinTargetPreflightReady({\n openMeldProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n allowPrompt: input.canPromptPreJoinActions,\n localDemand: input.localDemand,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n serviceIntent: input.serviceIntent,\n showProgress: input.showProgress,\n view: input.view,\n });\n if (preflightResult === \"cancelled\") {\n return \"cancelled\";\n }\n authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: targetBaseUrl,\n promptMessage:\n buildCommandAuthenticationPromptMessage(\"joining a space\"),\n allowPrompt: input.allowPromptForSpaceTarget,\n authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return \"cancelled\";\n }\n\n const accessBootstrap = await resolveSpaceJoinAccessBootstrap({\n openMeldProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n space: target.space,\n initialPassword: input.password,\n resolvedView: input.runtime.resolvedView,\n presenter: input.presenter,\n canPromptJoinPassword: input.canPromptPreJoinActions,\n canConfirmPublicSpaceJoin: input.canPromptPreJoinActions,\n });\n if (accessBootstrap.status === \"cancelled\") {\n return \"cancelled\";\n }\n const membershipBootstrap = await resolveSpaceJoinMembershipBootstrap(\n {\n openMeldProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n space: target.space,\n password: accessBootstrap.password,\n publicExposure: accessBootstrap.publicExposure,\n canPromptPreJoinActions: input.canPromptPreJoinActions,\n skipBringProfilesPrompt: input.skipBringProfilesPrompt,\n allowBackToTargetSelection: input.allowBackToTargetSelection,\n resolvedView: input.runtime.resolvedView,\n presenter: input.presenter,\n },\n {\n resolveSpaceMemberCandidatesForAdd,\n resolveSelectedSpaceMemberCandidates,\n normalizeRequestedMemberIds,\n sortSpaceMemberCandidatesForPrompt,\n buildHumanSpaceMemberCandidateSearchItem,\n createProfileByKind,\n resolveCreateProfileKind,\n resolveCreateProfileName,\n resolveAgentProfileSetup,\n persistAgentTransportSelection,\n prepareSpaceMemberCandidatesLocalParticipation: async ({\n actorProfile,\n candidates,\n presenter,\n resolvedView,\n }) =>\n await ensureSpaceMemberCandidatesLocalParticipationReady({\n openMeldProfile: actorProfile,\n candidates,\n gatewayUrl: targetBaseUrl,\n presenter,\n resolvedView,\n allowPrompt: input.canPromptPreJoinActions,\n spaceId: target.space,\n view: input.view,\n }),\n applySpaceAddMembers,\n persistSpaceAddMembersJoinNotices,\n emitSpaceAddMembersResult,\n }\n );\n if (membershipBootstrap.status === \"back\") {\n continue;\n }\n if (membershipBootstrap.status === \"cancelled\") {\n return \"cancelled\";\n }\n const roleAliasBootstrap = await resolveSpaceJoinRoleAliasBootstrap(\n {\n openMeldProfile: input.openMeldProfile,\n openMeldProfileId,\n baseUrl: targetBaseUrl,\n space: target.space,\n password: accessBootstrap.password,\n existingSpaceConfig,\n roleInput: input.role,\n mentionAliasInput: input.mentionAlias,\n resolvedView: input.runtime.resolvedView,\n allowPromptRoleContext: input.allowPromptForRoleContext,\n presenter: input.presenter,\n },\n {\n fetchSpaceCursorForBootstrap: async ({\n openMeldProfile,\n baseUrl,\n space,\n password,\n }) =>\n await fetchSpaceCursor({\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile,\n }),\n baseUrl,\n space,\n password,\n }),\n }\n );\n if (roleAliasBootstrap.status === \"cancelled\") {\n return \"cancelled\";\n }\n\n const joinConnectionState = await runSpaceJoinConnectHandoff({\n openMeldProfileId,\n openMeldProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n space: target.space,\n initialPassword: accessBootstrap.password,\n output: input.output,\n localEcho: input.localEcho,\n historyLimit: input.historyLimit,\n role: roleAliasBootstrap.role,\n mentionAlias: roleAliasBootstrap.mentionAlias,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n canPromptJoinPassword: input.canPromptPreJoinActions,\n rawStream: input.rawStream,\n });\n if (joinConnectionState === \"cancelled\") {\n return \"cancelled\";\n }\n\n return \"completed\";\n }\n}\n\nasync function prepareSpaceCreateRuntimeState(input: {\n profile?: string;\n view?: string;\n name?: string;\n visibility?: string;\n}): Promise<{\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n interactive: boolean;\n}> {\n const runtime = await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n });\n const presenter = createPresenter(runtime);\n const interactive = canUseInteractivePrompts(runtime);\n const missingName = String(input.name ?? \"\").trim().length === 0;\n const missingVisibility = String(input.visibility ?? \"\").trim().length === 0;\n if (runtime.resolvedView === \"agent\" && (missingName || missingVisibility)) {\n emitSpaceAgentOverview({\n presenter,\n resolvedView: runtime.resolvedView,\n command: \"create\",\n });\n throw createSpaceCreateGuideError(\n missingName\n ? undefined\n : \"openmeld space create requires explicit --visibility public|private in agent/non-interactive mode.\"\n );\n }\n\n return {\n runtime,\n presenter,\n interactive,\n };\n}\n\nasync function resolveSpaceJoinTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space?: string;\n allowPrompt: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): Promise<SpaceJoinTargetResolution> {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (explicitSpace) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n const known = requireReadableSpaceConfigList(\n await listSpaceConfigs({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n }),\n \"listing known local spaces for join target resolution\"\n );\n const matched = known.find((item) => item.space === explicitSpace);\n return {\n status: \"submitted\",\n value: {\n space: explicitSpace,\n ...(matched?.baseUrl ? { baseUrl: matched.baseUrl } : {}),\n },\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceTargetGuideError(\"join\");\n }\n throw new Error(\n buildJoinTargetMissingMessage({\n resolvedView: input.resolvedView,\n })\n );\n }\n\n const knownResult = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"join\",\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n const known = knownResult.items;\n const inlineDeletedNotices =\n input.resolvedView === \"human\" && known.length > 0\n ? knownResult.deletedNotices\n : [];\n if (inlineDeletedNotices.length === 0) {\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: knownResult.deletedNotices,\n });\n }\n if (known.length === 0 && input.resolvedView === \"human\") {\n return promptHumanJoinSelectionWithoutKnownSpaces(\n knownResult.visibilityScope\n );\n }\n\n const target = await promptSpaceJoinSelection({\n known,\n command: \"join\",\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n visibilityScope: knownResult.visibilityScope,\n deletedNotices: inlineDeletedNotices,\n });\n return target;\n}\n\nexport async function runSpaceWatch(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n output?: string;\n view?: string;\n historyLimit?: number;\n rawStream?: boolean;\n entryChecksHandled?: boolean;\n}) {\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\"watching a space\"),\n checkGatewayMismatch: hasExplicitBaseUrlInput,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return;\n }\n const { runtime, interactive, baseUrl } = context;\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n const openMeldProfileId = openMeldProfile.openMeldProfileId;\n const target = await resolveSpaceTarget({\n openMeldProfile,\n baseUrl,\n space: input.space,\n command: \"watch\",\n allowPrompt: interactive,\n presenter: context.presenter,\n resolvedView: runtime.resolvedView,\n });\n if (!target) {\n return;\n }\n const targetBaseUrl = hasExplicitBaseUrlInput\n ? baseUrl\n : (target.baseUrl ?? baseUrl);\n const authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime,\n gatewayUrl: targetBaseUrl,\n promptMessage:\n buildCommandAuthenticationPromptMessage(\"watching a space\"),\n allowPrompt: interactive,\n authenticatedGatewayUrl: context.authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return;\n }\n\n await runConnect({\n profile: openMeldProfileId,\n openMeldProfile,\n baseUrl: targetBaseUrl,\n space: target.space,\n password: input.password,\n connectionMode: \"watch\",\n stdio:\n runtime.resolvedView === \"human\" &&\n interactive &&\n input.output !== \"ndjson\",\n output: input.output,\n historyLimit: input.historyLimit,\n rawStream: input.rawStream === true,\n view: input.view,\n });\n}\n\nexport async function runSpaceDelete(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n view?: string;\n entryChecksHandled?: boolean;\n allowBackToCaller?: boolean;\n}): Promise<SpaceCommandNavigationStatus> {\n // TODO(approval-flow): when web/email approval is available, replace this\n // local confirmation gate with an out-of-band approval token flow.\n const runtime = await resolveRuntimeContext({\n profile: input.profile,\n view: input.view,\n });\n\n if (runtime.resolvedView === \"agent\") {\n throw createSpaceDeleteHumanApprovalGuideError(\n \"agent sessions cannot delete spaces directly.\"\n );\n }\n if (!canUseInteractivePrompts(runtime)) {\n throw new Error(\n \"space delete requires an interactive human TTY session for confirmation\"\n );\n }\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\"deleting spaces\"),\n checkGatewayMismatch: hasExplicitBaseUrlInput,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return \"cancelled\";\n }\n const { presenter, baseUrl, authenticatedGatewayUrl } = context;\n\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive: true,\n });\n if (openMeldProfile.profileKind !== \"human\") {\n throw createSpaceDeleteHumanApprovalGuideError(\n \"space delete requires a huma OpenMeld profile.\"\n );\n }\n\n const openMeldProfileId = openMeldProfile.openMeldProfileId;\n const accountContext = await resolveCurrentOpenMeldAccountContext().catch(\n () => null\n );\n const ownerUserIdForDelete =\n normalizeOptionalString(openMeldProfile.ownerUserId) ??\n normalizeOptionalString(accountContext?.user?.id) ??\n undefined;\n for (;;) {\n const targets = await resolveSpaceDeleteTargets({\n openMeldProfile: {\n ...openMeldProfile,\n ownerUserId: ownerUserIdForDelete ?? openMeldProfile.ownerUserId,\n },\n baseUrl,\n space: input.space,\n allowPrompt: true,\n presenter,\n resolvedView: runtime.resolvedView,\n allowBack: true,\n });\n if (targets.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (targets.status === \"back\") {\n if (input.allowBackToCaller === true) {\n return \"back\";\n }\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n const outcome = await runSpaceDeleteAttempt({\n targets: targets.targets,\n currentProfileId: openMeldProfileId,\n currentProfileName: openMeldProfile.profileName,\n allowBackToSelection: targets.allowBackToSelection,\n runtime,\n presenter,\n openMeldProfileId,\n openMeldProfile,\n baseUrl,\n hasExplicitBaseUrlInput,\n authenticatedGatewayUrl,\n password: input.password,\n });\n if (outcome === \"back\") {\n continue;\n }\n return outcome;\n }\n}\n\nasync function runSpaceDeleteAttempt(input: {\n targets: SpaceDeleteTarget[];\n currentProfileId: string;\n currentProfileName: string;\n allowBackToSelection: boolean;\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n authenticatedGatewayUrl?: string | null;\n password?: string;\n}): Promise<SpaceCommandNavigationStatus> {\n const confirmation = await confirmDeleteTargets({\n targets: input.targets,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n allowBack: input.allowBackToSelection,\n });\n if (confirmation === \"cancelled\") {\n return \"cancelled\";\n }\n if (confirmation === \"back\") {\n return \"back\";\n }\n\n const deleteResult = await deleteConfirmedSpaceTargets({\n targets: input.targets,\n runtime: input.runtime,\n presenter: input.presenter,\n openMeldProfileId: input.openMeldProfileId,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n hasExplicitBaseUrlInput: input.hasExplicitBaseUrlInput,\n authenticatedGatewayUrl: input.authenticatedGatewayUrl,\n password: input.password,\n });\n if (deleteResult.status === \"cancelled\") {\n return \"cancelled\";\n }\n if (deleteResult.failures.length === 0) {\n return \"completed\";\n }\n\n renderSpaceDeleteBatchFailureSummary({\n presenter: input.presenter,\n totalCount: input.targets.length,\n deletedCount: deleteResult.deletedCount,\n failures: deleteResult.failures,\n resolvedView: input.runtime.resolvedView,\n });\n if (deleteResult.deletedCount > 0) {\n return \"completed\";\n }\n\n const firstFailure = deleteResult.failures[0];\n if (!firstFailure) {\n throw new Error(\"Delete failed.\");\n }\n throw new Error(buildDeleteBatchFailureMessage(firstFailure));\n}\n\nasync function deleteConfirmedSpaceTargets(input: {\n targets: SpaceDeleteTarget[];\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n presenter: ReturnType<typeof createPresenter>;\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n authenticatedGatewayUrl?: string | null;\n password?: string;\n}): Promise<\n | { status: \"cancelled\" }\n | {\n status: \"completed\";\n deletedCount: number;\n failures: SpaceDeleteFailure[];\n }\n> {\n const failures: SpaceDeleteFailure[] = [];\n let deletedCount = 0;\n let authenticatedGatewayUrl =\n input.authenticatedGatewayUrl ??\n (input.hasExplicitBaseUrlInput ? input.baseUrl : null);\n\n for (const target of input.targets) {\n try {\n const targetBaseUrl = input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (target.baseUrl ?? input.baseUrl);\n authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: targetBaseUrl,\n promptMessage:\n buildCommandAuthenticationPromptMessage(\"deleting spaces\"),\n allowPrompt: true,\n authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return {\n status: \"cancelled\",\n };\n }\n const deleted = await deleteSpaceTargetWithCleanup({\n target,\n openMeldProfileId: input.openMeldProfileId,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n hasExplicitBaseUrlInput: input.hasExplicitBaseUrlInput,\n password: input.password,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n });\n if (!deleted) {\n return {\n status: \"cancelled\",\n };\n }\n deletedCount += 1;\n } catch (error) {\n failures.push({ target, error });\n }\n }\n\n return {\n status: \"completed\",\n deletedCount,\n failures,\n };\n}\n\nasync function confirmDeleteTargets(input: {\n targets: SpaceDeleteTarget[];\n currentProfileId: string;\n currentProfileName: string;\n allowBack?: boolean;\n}): Promise<SpaceDeleteConfirmationResult> {\n if (input.allowBack !== true) {\n const confirmed = await confirm({\n message: buildDeleteConfirmationMessage({\n targets: input.targets,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n }),\n initialValue: false,\n });\n if (isCancel(confirmed) || !confirmed) {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n\n const typedConfirmation = await text({\n message: \"Type DELETE to confirm permanent deletion\",\n placeholder: \"DELETE\",\n });\n if (isCancel(typedConfirmation)) {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n if (!isDeleteConfirmationValue(typedConfirmation)) {\n cancel(\"Cancelled: confirmation keyword mismatch.\");\n return \"cancelled\";\n }\n return \"confirmed\";\n }\n\n for (;;) {\n const decision = await select({\n message: buildDeleteConfirmationMessage({\n targets: input.targets,\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n }),\n options: [\n {\n value: \"confirm\",\n label: \"Delete permanently\",\n hint: \"Continue to final confirmation\",\n },\n ...(input.allowBack === true\n ? [{ value: \"back\", label: \"Back\" as const }]\n : []),\n {\n value: \"cancel\",\n label: \"Cancel\",\n },\n ],\n });\n if (isCancel(decision) || decision === \"cancel\") {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n if (decision === \"back\") {\n return \"back\";\n }\n\n const typedConfirmation = await promptTextEntry({\n message: \"Type DELETE to confirm permanent deletion\",\n placeholder: \"DELETE\",\n allowBack: input.allowBack === true,\n backLabel: \"Back\",\n validate: (value) =>\n isDeleteConfirmationValue(value)\n ? null\n : \"Type DELETE exactly to continue.\",\n });\n if (typedConfirmation.status === \"cancelled\") {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n if (typedConfirmation.status === \"back\") {\n continue;\n }\n return \"confirmed\";\n }\n}\n\nasync function deleteSpaceTargetWithCleanup(input: {\n target: SpaceDeleteTarget;\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n password?: string;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): Promise<boolean> {\n const targetBaseUrl = input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (input.target.baseUrl ?? input.baseUrl);\n const deleted = await deleteSpaceWithHumanFallback({\n target: input.target,\n openMeldProfileId: input.openMeldProfileId,\n openMeldProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n password: input.password,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n });\n if (!deleted) {\n return false;\n }\n await removeSpaceConfig({\n openMeldProfileId: input.openMeldProfileId,\n space: input.target.space,\n }).catch(() => undefined);\n await markDeletedSpaceInHistory({\n target: input.target,\n openMeldProfile: input.openMeldProfile,\n baseUrl: targetBaseUrl,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n });\n input.presenter.line({\n code: \"space.delete.deleted\",\n text: `space deleted: ${input.target.space}`,\n data: { spaceId: input.target.space },\n });\n return true;\n}\n\nasync function deleteSpaceWithHumanFallback(input: {\n target: SpaceDeleteTarget;\n openMeldProfileId: string;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n password?: string;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): Promise<boolean> {\n const approvedAgentCreatorProfileId =\n input.target.creatorKind === \"agent\"\n ? (normalizeOptionalString(input.target.creatorProfileId) ?? undefined)\n : undefined;\n let nextDeletePassword = input.password;\n let lastPasswordError: unknown = null;\n\n for (\n let attempt = 0;\n attempt < MAX_DELETE_PASSWORD_PROMPT_ATTEMPTS;\n attempt += 1\n ) {\n try {\n await deleteSpace({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n space: input.target.space,\n password: nextDeletePassword,\n approvedAgentCreatorProfileId,\n });\n return true;\n } catch (error) {\n const friendlyDeleteBlockedError = buildHumanSpaceDeleteBlockedError({\n error,\n target: input.target,\n resolvedView: input.resolvedView,\n });\n if (friendlyDeleteBlockedError) {\n renderHumanSpaceDeleteBlockedCard({\n presenter: input.presenter,\n target: input.target,\n });\n throw friendlyDeleteBlockedError;\n }\n\n const passwordPromptReason = resolveSpacePasswordPromptReason(error);\n if (!passwordPromptReason) {\n throw error;\n }\n\n emitSpacePasswordPromptNotice({\n presenter: input.presenter,\n reason: passwordPromptReason,\n codePrefix: \"space.delete.password\",\n requiredText: \"This space is protected. Enter password to delete it.\",\n });\n lastPasswordError = error;\n const promptedPassword = await promptSpacePassword();\n if (promptedPassword === null) {\n return false;\n }\n nextDeletePassword = promptedPassword;\n }\n }\n\n throw lastPasswordError ?? new Error(\"Delete failed.\");\n}\n\ntype SpaceDeleteFailure = {\n target: SpaceDeleteTarget;\n error: unknown;\n};\n\nfunction renderSpaceDeleteBatchFailureSummary(input: {\n presenter: ReturnType<typeof createPresenter>;\n totalCount: number;\n deletedCount: number;\n failures: SpaceDeleteFailure[];\n resolvedView: \"human\" | \"agent\";\n}): void {\n const failedCount = input.failures.length;\n const reason = resolveDeleteBatchFailureReason(input.failures);\n const failedTargets = summarizeFailedDeleteTargets(input.failures);\n\n if (input.resolvedView === \"human\") {\n renderHumanErrorCard({\n message: `OpenMeld deleted ${String(input.deletedCount)} of ${String(input.totalCount)} Spaces, but couldn't delete ${failedTargets}: ${reason}`,\n nextStep:\n input.deletedCount > 0\n ? \"Try deleting those Spaces again.\"\n : \"Try again in a moment.\",\n presenter: input.presenter,\n title:\n input.deletedCount > 0\n ? \"Some Spaces weren't deleted\"\n : \"Spaces couldn't be deleted\",\n codePrefix: \"space.delete.batch_result\",\n });\n return;\n }\n\n input.presenter.line({\n code: \"space.delete.batch_result\",\n text: `delete result: deleted ${String(input.deletedCount)}/${String(input.totalCount)}; failed ${String(failedCount)} (${reason})`,\n data: {\n deletedCount: input.deletedCount,\n totalCount: input.totalCount,\n failedCount,\n reason,\n failedTargets,\n },\n });\n}\n\nfunction buildDeleteBatchFailureMessage(failure: SpaceDeleteFailure): string {\n const parsed = parseHttpErrorMessage(failure.error);\n if (!parsed) {\n return toErrorMessage(failure.error);\n }\n\n if (isAuthUpstreamUnavailableError(parsed)) {\n return \"Delete failed: OpenMeld auth service is temporarily unavailable. Retry in a moment.\";\n }\n const status = resolveUpstreamStatus(parsed);\n if (status >= 500) {\n return \"Delete failed: OpenMeld service is temporarily unavailable. Retry in a moment.\";\n }\n if (status === 404) {\n return \"Delete failed: space not found (it may have already been deleted).\";\n }\n const passwordPromptReason = resolveSpacePasswordPromptReason(failure.error);\n if (passwordPromptReason === \"required\") {\n return \"Delete failed: this space requires a password. Retry with `--password`.\";\n }\n if (passwordPromptReason === \"invalid\") {\n return \"Delete failed: space password is incorrect. Retry with the correct password.\";\n }\n if (status === 401) {\n const guidance = resolveAuthenticationGuidance({\n reason: \"expired\",\n action: \"deleting a space\",\n });\n return formatInlineOpenMeldCliCommands(\n `Delete failed: ${guidance.summary} ${guidance.errorNextStep}`\n );\n }\n return toErrorMessage(failure.error);\n}\n\nfunction resolveDeleteBatchFailureReason(\n failures: SpaceDeleteFailure[]\n): string {\n const reasons = failures\n .map((item) => resolveDeleteFailureReason(item.error))\n .filter((value) => value.length > 0);\n if (reasons.length === 0) {\n return \"Some delete requests failed.\";\n }\n const unique = Array.from(new Set(reasons));\n if (unique.length === 1) {\n return unique[0] ?? \"Some delete requests failed.\";\n }\n return \"Some delete requests failed for different reasons.\";\n}\n\nfunction resolveDeleteFailureReason(error: unknown): string {\n const parsed = parseHttpErrorMessage(error);\n if (!parsed) {\n return \"Unknown error.\";\n }\n if (isAuthUpstreamUnavailableError(parsed)) {\n return \"OpenMeld auth service is temporarily unavailable.\";\n }\n\n const status = resolveUpstreamStatus(parsed);\n if (status >= 500) {\n return \"OpenMeld service is temporarily unavailable.\";\n }\n if (status === 404) {\n return \"Space not found or already deleted.\";\n }\n const passwordPromptReason = resolveSpacePasswordPromptReason(error);\n if (passwordPromptReason === \"required\") {\n return \"Space password is required.\";\n }\n if (passwordPromptReason === \"invalid\") {\n return \"Space password is invalid.\";\n }\n if (status === 401) {\n return \"Authentication expired.\";\n }\n if (status === 403 && isSpaceDeleteOwnerRestrictionError(parsed)) {\n return \"Only spaces created by your user can be deleted.\";\n }\n return \"Delete request failed.\";\n}\n\nfunction isAuthUpstreamUnavailableError(input: {\n status: number;\n code: string;\n message: string;\n body: string;\n}): boolean {\n if (resolveUpstreamStatus(input) !== 502) {\n return false;\n }\n const combined =\n `${input.code}\\n${input.message}\\n${input.body}`.toLowerCase();\n return combined.includes(\"auth upstream unavailable\");\n}\n\nfunction summarizeFailedDeleteTargets(failures: SpaceDeleteFailure[]): string {\n const MAX_VISIBLE = 3;\n const names = failures.slice(0, MAX_VISIBLE).map((item) => {\n const label = normalizeOptionalString(item.target.name);\n if (label) {\n return label;\n }\n return item.target.space;\n });\n if (failures.length <= MAX_VISIBLE) {\n return names.join(\", \");\n }\n return `${names.join(\", \")} (+${String(failures.length - MAX_VISIBLE)} more)`;\n}\n\nasync function markDeletedSpaceInHistory(input: {\n target: SpaceDeleteTarget;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): Promise<void> {\n const gatewayHost = resolveGatewayHost(input.baseUrl);\n if (!gatewayHost) {\n input.presenter.line({\n code: \"connect.warn.profile_space_history_sync_failed\",\n text: formatMessage(\n input.resolvedView,\n \"connect.warn.profile_space_history_sync_failed\",\n {\n error: \"failed to resolve gateway host from base url\",\n }\n ),\n });\n return;\n }\n await updateProfileSpaceHistoryStatus({\n baseUrl: input.baseUrl,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n }),\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n spaceId: input.target.space,\n body: {\n gatewayHost,\n status: \"removed\",\n reason: \"space_deleted_by_user\",\n },\n }).catch((error) => {\n input.presenter.line({\n code: \"connect.warn.profile_space_history_sync_failed\",\n text: formatMessage(\n input.resolvedView,\n \"connect.warn.profile_space_history_sync_failed\",\n {\n error: toErrorMessage(error),\n }\n ),\n });\n });\n}\n\nexport async function runSpacePassword(input: {\n profile?: string;\n baseUrl?: string;\n space?: string;\n password?: string;\n clear?: boolean;\n view?: string;\n entryChecksHandled?: boolean;\n allowBackToCaller?: boolean;\n}): Promise<SpaceCommandNavigationStatus> {\n const hasExplicitBaseUrlInput = String(input.baseUrl ?? \"\").trim().length > 0;\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"changing a space password\"\n ),\n checkGatewayMismatch: hasExplicitBaseUrlInput,\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return \"cancelled\";\n }\n const { runtime, interactive: allowPrompt, presenter, baseUrl } = context;\n const hasExplicitMutationInput =\n input.clear === true || typeof input.password === \"string\";\n const initialMutationInput =\n hasExplicitMutationInput || !allowPrompt\n ? await resolveSpacePasswordMutationInput({\n clear: input.clear,\n password: input.password,\n allowPrompt,\n resolvedView: runtime.resolvedView,\n allowBackToCaller: input.allowBackToCaller === true,\n })\n : null;\n if (\n (hasExplicitMutationInput || !allowPrompt) &&\n initialMutationInput?.status !== \"submitted\"\n ) {\n return initialMutationInput?.status ?? \"cancelled\";\n }\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive: allowPrompt,\n });\n let nextInitialMutationInput =\n initialMutationInput?.status === \"submitted\"\n ? initialMutationInput.value\n : undefined;\n\n for (;;) {\n const outcome = await runSpacePasswordAttempt({\n input,\n runtime,\n allowPrompt,\n openMeldProfile,\n baseUrl,\n hasExplicitBaseUrlInput,\n presenter,\n authenticatedGatewayUrl: context.authenticatedGatewayUrl,\n nextInitialMutationInput,\n });\n if (outcome.status === \"repeat\") {\n nextInitialMutationInput = outcome.nextInitialMutationInput;\n continue;\n }\n return outcome.status;\n }\n}\n\nasync function runSpacePasswordAttempt(input: {\n input: {\n clear?: boolean;\n password?: string;\n space?: string;\n allowBackToCaller?: boolean;\n };\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>;\n allowPrompt: boolean;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n hasExplicitBaseUrlInput: boolean;\n presenter: ReturnType<typeof createPresenter>;\n authenticatedGatewayUrl: string | null;\n nextInitialMutationInput?: { clear: boolean; password?: string };\n}): Promise<\n | { status: SpaceCommandNavigationStatus }\n | {\n status: \"repeat\";\n nextInitialMutationInput?: { clear: boolean; password?: string };\n }\n> {\n const resolvedInput = await resolveSpacePasswordExecutionInput({\n clear: input.input.clear,\n password: input.input.password,\n allowPrompt: input.allowPrompt,\n resolvedView: input.runtime.resolvedView,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n explicitSpace: input.input.space,\n hasExplicitBaseUrlInput: input.hasExplicitBaseUrlInput,\n presenter: input.presenter,\n initialMutationInput: input.nextInitialMutationInput,\n allowBackToCaller: input.input.allowBackToCaller === true,\n });\n if (resolvedInput.status !== \"submitted\") {\n if (resolvedInput.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n return input.nextInitialMutationInput\n ? { status: \"repeat\" }\n : {\n status: input.input.allowBackToCaller === true ? \"back\" : \"cancelled\",\n };\n }\n\n const resolvedPasswordInput = resolvedInput.value;\n const authenticatedGatewayUrl =\n await ensureSpaceCommandGatewayAuthenticationOrCancel({\n runtime: input.runtime,\n gatewayUrl: resolvedPasswordInput.target.baseUrl,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"changing a space password\"\n ),\n allowPrompt: input.allowPrompt,\n authenticatedGatewayUrl: input.authenticatedGatewayUrl,\n });\n if (!authenticatedGatewayUrl) {\n return { status: \"cancelled\" };\n }\n\n const nextPassword = await resolveSpacePasswordValueForExecution({\n resolvedPasswordInput,\n allowBackToCaller: input.input.allowBackToCaller === true,\n });\n if (nextPassword.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n if (nextPassword.status === \"back\") {\n return input.input.allowBackToCaller === true\n ? {\n status: \"repeat\",\n nextInitialMutationInput: {\n clear: resolvedPasswordInput.clear,\n },\n }\n : { status: \"cancelled\" };\n }\n\n const endpoint = toSpacePasswordUrl(\n resolvedPasswordInput.target.baseUrl,\n resolvedPasswordInput.target.space\n );\n const headers = await buildOpenMeldProfileRequestHeadersWithAuth({\n requestUrl: endpoint,\n openMeldProfile: input.openMeldProfile,\n });\n await executeSpacePasswordMutation({\n clear: resolvedPasswordInput.clear,\n endpoint,\n headers,\n password: nextPassword.value,\n target: resolvedPasswordInput.target,\n openMeldProfile: input.openMeldProfile,\n presenter: input.presenter,\n resolvedView: input.runtime.resolvedView,\n });\n return { status: \"completed\" };\n}\n\nfunction resolveSpacePasswordValueForExecution(input: {\n resolvedPasswordInput: {\n clear: boolean;\n password?: string;\n target: { space: string; baseUrl: string; name?: string };\n };\n allowBackToCaller: boolean;\n}): Promise<SpacePasswordPromptResult> {\n if (\n input.resolvedPasswordInput.clear ||\n typeof input.resolvedPasswordInput.password === \"string\"\n ) {\n return Promise.resolve({\n status: \"submitted\",\n value:\n typeof input.resolvedPasswordInput.password === \"string\"\n ? normalizeSpacePasswordText(input.resolvedPasswordInput.password)\n : \"\",\n });\n }\n return promptAndConfirmSpacePassword({\n allowBack: input.allowBackToCaller,\n emitCancelMessage: !input.allowBackToCaller,\n });\n}\n\nasync function executeSpacePasswordMutation(input: {\n clear: boolean;\n endpoint: string;\n headers: Record<string, string>;\n password?: string;\n target: { space: string; baseUrl: string; name?: string };\n openMeldProfile: OpenMeldProfile;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n}): Promise<void> {\n const passwordProtected = !input.clear;\n const requestHeaders = { ...input.headers };\n const response = await fetchSpaceRequestWithTimeout({\n url: input.endpoint,\n operation: input.clear ? \"space.password.clear\" : \"space.password.upsert\",\n init: input.clear\n ? {\n method: \"DELETE\",\n headers: requestHeaders,\n }\n : {\n method: \"PUT\",\n headers: {\n ...requestHeaders,\n \"content-type\": \"application/json\",\n },\n body: JSON.stringify({\n password:\n typeof input.password === \"string\"\n ? normalizeSpacePasswordText(input.password)\n : \"\",\n }),\n },\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n await upsertSpaceConfig({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n baseUrl: input.target.baseUrl,\n space: input.target.space,\n profileName: input.openMeldProfile.profileName,\n passwordProtected,\n });\n emitSpacePasswordMutationSuccess({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n spaceName: input.target.name,\n spaceId: input.target.space,\n passwordProtected,\n });\n}\n\nfunction emitSpacePasswordMutationSuccess(input: {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n spaceName?: string;\n spaceId: string;\n passwordProtected: boolean;\n}): void {\n if (input.resolvedView === \"human\") {\n renderHumanSpacePasswordResultCard({\n presenter: input.presenter,\n spaceName: input.spaceName,\n spaceId: input.spaceId,\n passwordProtected: input.passwordProtected,\n });\n return;\n }\n\n input.presenter.line({\n code: input.passwordProtected\n ? \"space.password.updated\"\n : \"space.password.cleared\",\n text: formatMessage(\n input.resolvedView,\n input.passwordProtected\n ? \"space.password.updated\"\n : \"space.password.cleared\",\n {\n spaceId: input.spaceId,\n }\n ),\n data: {\n spaceId: input.spaceId,\n passwordProtected: input.passwordProtected,\n },\n });\n if (!input.passwordProtected) {\n return;\n }\n input.presenter.line({\n code: \"space.password.warning\",\n text: formatMessage(input.resolvedView, \"space.password.warning\"),\n });\n}\n\nasync function resolveSpacePasswordMutationInput(input: {\n clear?: boolean;\n password?: string;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n allowBackToCaller?: boolean;\n}): Promise<\n | { status: \"submitted\"; value: { clear: boolean; password?: string } }\n | { status: \"back\" }\n | { status: \"cancelled\" }\n> {\n const hasPasswordInput = typeof input.password === \"string\";\n if (input.clear === true && hasPasswordInput) {\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"`openmeld space password`: use either --password <value> or --clear, not both\"\n )\n );\n }\n if (input.clear === true) {\n return { status: \"submitted\", value: { clear: true } };\n }\n if (hasPasswordInput) {\n return {\n status: \"submitted\",\n value: {\n clear: false,\n password: normalizeSpacePasswordText(input.password ?? \"\"),\n },\n };\n }\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceSubcommandTargetGuideError(\"password\");\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"`openmeld space password` requires --password <value> or --clear\"\n )\n );\n }\n\n const action = await select({\n message: \"Password action\",\n options: [\n { value: \"set\", label: \"Set password\" },\n { value: \"clear\", label: \"Clear password\" },\n { value: \"back\", label: \"Back\" },\n ],\n });\n if (isCancel(action)) {\n cancel(\"Cancelled.\");\n return { status: \"cancelled\" };\n }\n if (action === \"back\") {\n if (input.allowBackToCaller !== true) {\n cancel(\"Cancelled.\");\n }\n return {\n status: input.allowBackToCaller === true ? \"back\" : \"cancelled\",\n };\n }\n\n if (action === \"clear\") {\n return { status: \"submitted\", value: { clear: true } };\n }\n return { status: \"submitted\", value: { clear: false } };\n}\n\nasync function resolveSpacePasswordExecutionInput(input: {\n clear?: boolean;\n password?: string;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n explicitSpace?: string;\n hasExplicitBaseUrlInput: boolean;\n presenter: ReturnType<typeof createPresenter>;\n initialMutationInput?: { clear: boolean; password?: string };\n allowBackToCaller?: boolean;\n}): Promise<\n | {\n status: \"submitted\";\n value: {\n clear: boolean;\n password?: string;\n target: { space: string; baseUrl: string; name?: string };\n };\n }\n | {\n status: \"back\" | \"cancelled\";\n }\n> {\n if (input.initialMutationInput) {\n const target = await resolveSpacePasswordTarget({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n explicitSpace: input.explicitSpace,\n clear: input.initialMutationInput.clear,\n hasExplicitBaseUrlInput: input.hasExplicitBaseUrlInput,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n allowPrompt: input.allowPrompt,\n });\n if (target.status !== \"submitted\") {\n return target;\n }\n return {\n status: \"submitted\",\n value: {\n clear: input.initialMutationInput.clear,\n ...(typeof input.initialMutationInput.password === \"string\"\n ? { password: input.initialMutationInput.password }\n : {}),\n target: target.target,\n },\n };\n }\n\n for (;;) {\n const mutationInput = await resolveSpacePasswordMutationInput({\n clear: input.clear,\n password: input.password,\n allowPrompt: input.allowPrompt,\n resolvedView: input.resolvedView,\n allowBackToCaller: input.allowBackToCaller === true,\n });\n if (mutationInput.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n if (mutationInput.status === \"back\") {\n return { status: \"back\" };\n }\n const target = await resolveSpacePasswordTarget({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n explicitSpace: input.explicitSpace,\n clear: mutationInput.value.clear,\n hasExplicitBaseUrlInput: input.hasExplicitBaseUrlInput,\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n allowPrompt: input.allowPrompt,\n });\n if (target.status === \"cancelled\") {\n return { status: \"cancelled\" };\n }\n if (target.status === \"back\") {\n continue;\n }\n return {\n status: \"submitted\",\n value: {\n clear: mutationInput.value.clear,\n ...(typeof mutationInput.value.password === \"string\"\n ? { password: mutationInput.value.password }\n : {}),\n target: target.target,\n },\n };\n }\n}\n\nasync function resolveSpacePasswordTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n explicitSpace?: string;\n clear: boolean;\n hasExplicitBaseUrlInput: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowPrompt: boolean;\n}): Promise<\n | {\n status: \"submitted\";\n target: { space: string; baseUrl: string; name?: string };\n }\n | {\n status: \"back\";\n }\n | {\n status: \"cancelled\";\n }\n> {\n const explicitSpace = String(input.explicitSpace ?? \"\").trim();\n if (explicitSpace.length > 0) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n const known = requireReadableSpaceConfigList(\n await listSpaceConfigs({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n }),\n \"listing known local spaces for password target resolution\"\n );\n const matched = known.find((item) => item.space === explicitSpace);\n return {\n status: \"submitted\",\n target: {\n space: explicitSpace,\n baseUrl: input.baseUrl,\n ...(matched?.name ? { name: matched.name } : {}),\n },\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceSubcommandTargetGuideError(\"password\");\n }\n throw new Error(\n formatMessage(input.resolvedView, \"space.target.missing\", {\n command: \"password\",\n })\n );\n }\n\n const known = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"password\",\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n const ownCreatedSpaces = filterKnownSpacesCreatedByProfile({\n known: known.items,\n profileId: input.openMeldProfile.openMeldProfileId,\n });\n const knownSpacesForAction = await resolveKnownSpacesForPasswordSelection({\n known: ownCreatedSpaces,\n clear: input.clear,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n });\n const inlineDeletedNotices =\n input.resolvedView === \"human\" &&\n known.items.length > 0 &&\n knownSpacesForAction.length > 0\n ? known.deletedNotices\n : [];\n if (inlineDeletedNotices.length === 0) {\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: known.deletedNotices,\n });\n }\n const target = await promptSpacePasswordTargetSelection({\n known: knownSpacesForAction,\n deletedNotices: inlineDeletedNotices,\n command: \"password\",\n passwordAction: input.clear ? \"clear\" : \"set\",\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n visibilityScope: known.visibilityScope,\n });\n if (target.status !== \"submitted\") {\n return target;\n }\n return {\n status: \"submitted\",\n target: {\n space: target.target.space,\n baseUrl: input.hasExplicitBaseUrlInput\n ? input.baseUrl\n : (target.target.baseUrl ?? input.baseUrl),\n ...(target.target.name ? { name: target.target.name } : {}),\n },\n };\n}\n\nasync function resolveSpaceAddMembersTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n mode: SpaceProfileAddMode;\n space?: string;\n allowPrompt: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowBack?: boolean;\n}): Promise<SpaceSelectionTargetResult> {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (explicitSpace.length > 0) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n return {\n status: \"submitted\",\n target: {\n space: explicitSpace,\n baseUrl: input.baseUrl,\n },\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceAddMembersGuideError(\n resolveSpaceAddMembersMissingArgumentsSummary(input.mode),\n resolveSpaceAddMembersCommandEntryName(input.mode)\n );\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n `\\`openmeld space ${resolveSpaceAddMembersSelectionCommand(input.mode)}\\` requires explicit <space-id> in non-interactive mode`\n )\n );\n }\n\n const known = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"add_members\",\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n if (!(input.resolvedView === \"human\" && known.items.length > 0)) {\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: known.deletedNotices,\n });\n }\n return promptSpaceSelectionTarget({\n known: known.items,\n deletedNotices: known.deletedNotices,\n command: \"add_members\",\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n visibilityScope: known.visibilityScope,\n allowBack: input.allowBack === true,\n });\n}\n\nasync function resolveSpaceRemoveMembersTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space?: string;\n allowPrompt: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowBack?: boolean;\n}): Promise<SpaceSelectionTargetResult> {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (explicitSpace.length > 0) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n return {\n status: \"submitted\",\n target: {\n space: explicitSpace,\n baseUrl: input.baseUrl,\n },\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceRemoveMembersGuideError();\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"`openmeld space remove-members` requires explicit <space-id> in non-interactive mode\"\n )\n );\n }\n\n const known = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"remove_members\",\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n if (!(input.resolvedView === \"human\" && known.items.length > 0)) {\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: known.deletedNotices,\n });\n }\n return promptSpaceSelectionTarget({\n known: known.items,\n deletedNotices: known.deletedNotices,\n command: \"remove_members\",\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n visibilityScope: known.visibilityScope,\n allowBack: input.allowBack === true,\n });\n}\n\nasync function resolveSpaceLeaveTarget(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space?: string;\n allowPrompt: boolean;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n allowBack?: boolean;\n}): Promise<SpaceSelectionTargetResult> {\n const explicitSpace = String(input.space ?? \"\").trim();\n if (explicitSpace.length > 0) {\n assertValidSpaceIdTarget({\n space: explicitSpace,\n resolvedView: input.resolvedView,\n });\n return {\n status: \"submitted\",\n target: {\n space: explicitSpace,\n baseUrl: input.baseUrl,\n },\n };\n }\n\n if (!input.allowPrompt) {\n if (input.resolvedView === \"agent\") {\n throw createSpaceLeaveGuideError();\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"`openmeld space leave` requires explicit <space-id> in non-interactive mode\"\n )\n );\n }\n\n const known = await resolveKnownSpacesForSelectionWithLoading({\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n command: \"leave\",\n showLoading: input.allowPrompt && input.resolvedView === \"human\",\n });\n if (!(input.resolvedView === \"human\" && known.items.length > 0)) {\n await maybeEmitKnownSpaceDeletedNotices({\n presenter: input.presenter,\n resolvedView: input.resolvedView,\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n deletedNotices: known.deletedNotices,\n });\n }\n return promptSpaceSelectionTarget({\n known: known.items,\n deletedNotices: known.deletedNotices,\n command: \"leave\",\n resolvedView: input.resolvedView,\n currentProfileId: input.openMeldProfile.openMeldProfileId,\n currentProfileName: input.openMeldProfile.profileName,\n currentOwnerUserId: input.openMeldProfile.ownerUserId,\n visibilityScope: known.visibilityScope,\n allowBack: input.allowBack === true,\n });\n}\n\nasync function confirmSpaceLeave(input: {\n target: SpaceSelectionTarget;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n}): Promise<\"confirmed\" | \"back\" | \"cancelled\"> {\n if (!(input.allowPrompt && input.resolvedView === \"human\")) {\n return \"confirmed\";\n }\n\n const label =\n normalizeOptionalString(input.target.name) ?? input.target.space;\n const confirmed = await confirm({\n message: `Leave space ${label}? You will stop seeing this space in your active list.`,\n initialValue: false,\n });\n if (isCancel(confirmed)) {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n if (confirmed !== true) {\n cancel(\"Cancelled.\");\n return \"cancelled\";\n }\n return \"confirmed\";\n}\n\nfunction mapSpaceLeaveFailureToGuideError(input: {\n error: unknown;\n spaceId: string;\n}): Error {\n const failure = toStructuredGatewayFailure(input.error);\n if (failure.code === \"space.leave_space.creator_forbidden\") {\n return createSpaceLeaveCreatorGuideError({\n spaceId: input.spaceId,\n message: failure.message,\n });\n }\n return input.error instanceof Error\n ? input.error\n : new Error(String(input.error));\n}\n\nasync function resolveSpaceMemberCandidatesForAdd(input: {\n currentProfile: OpenMeldProfile;\n currentOwnerUserId?: string;\n explicitMemberIds?: readonly string[];\n includeLocalParticipation?: boolean;\n allowCurrentProfileMember?: boolean;\n mode: SpaceProfileAddMode;\n space: string;\n baseUrl: string;\n password?: string;\n progress?: SpaceAddMembersProgressContext;\n membershipSource?: \"account\" | \"organization_directory\";\n}): Promise<SpaceMemberCandidate[]> {\n const explicitMemberIds = normalizeRequestedMemberIds(\n input.explicitMemberIds\n );\n const includeLocalParticipation = input.includeLocalParticipation !== false;\n const membershipSource = input.membershipSource ?? \"account\";\n\n if (input.progress) {\n emitAgentSpaceAddMembersProgress({\n ...input.progress,\n stage: \"resolve_candidates\",\n phase: \"read_profiles\",\n summary: \"Reading active local profile identities for this Space.\",\n });\n }\n const profiles = await listOpenMeldProfiles();\n if (input.progress && includeLocalParticipation) {\n emitAgentSpaceAddMembersProgress({\n ...input.progress,\n stage: \"resolve_candidates\",\n phase: \"read_local_targets\",\n summary:\n \"Reading local agent controller state for candidate profiles before selection.\",\n });\n }\n const localTargetStates =\n await listSpaceAddMembersLocalTargetStatesIfRequested({\n includeLocalParticipation,\n progress: input.progress,\n });\n const localTargetStateById = new Map(\n localTargetStates.map((state) => [state.agentId, state] as const)\n );\n const ownerProfileNameByOwnerUserId =\n buildOwnerProfileNameByOwnerUserId(profiles);\n if (input.progress) {\n emitAgentSpaceAddMembersProgress({\n ...input.progress,\n stage: \"resolve_candidates\",\n phase: \"read_space_members\",\n summary: \"Reading current Space membership before selecting profiles.\",\n });\n }\n const membersSnapshot = await createCliSpaceApi(\n input.baseUrl\n ).getMembersSnapshot({\n spaceId: input.space,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.currentProfile,\n }),\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n });\n const memberProfileIds = new Set(\n [...membersSnapshot.humans, ...membersSnapshot.agents].map(\n (member) => member.profileId\n )\n );\n const organizationDirectory =\n membershipSource === \"organization_directory\" &&\n explicitMemberIds.length > 0\n ? await createOrganizationApi(\n createCliApiClientFoundation(input.baseUrl)\n ).getCurrentDirectory()\n : null;\n const plan = buildSpaceProfileAddPlan({\n actingProfileId: input.currentProfile.openMeldProfileId,\n allowCurrentProfile: input.allowCurrentProfileMember === true,\n currentMembers: [...membersSnapshot.humans, ...membersSnapshot.agents],\n currentOwnerUserId: input.currentOwnerUserId,\n mode: input.mode,\n profiles: profiles.map(toSpaceProfileAddProfile),\n selector:\n explicitMemberIds.length > 0\n ? { kind: \"profile_ids\", profileIds: explicitMemberIds }\n : { kind: \"none\" },\n });\n if (\n membershipSource === \"account\" &&\n explicitMemberIds.length > 0 &&\n plan.invalidSelections.length > 0\n ) {\n throw new Error(\n `invalid ${resolveSpaceAddMembersProfileLabel(input.mode)} profile ID(s): ${formatSpaceProfileAddInvalidSelections(\n plan.invalidSelections\n )} (must be your selectable ${resolveSpaceAddMembersProfileLabel(input.mode)} profiles and cannot be the current profile)`\n );\n }\n const profileById = new Map(\n profiles.map((profile) => [profile.openMeldProfileId, profile] as const)\n );\n const candidatePlanEntries =\n explicitMemberIds.length > 0 ? plan.selectedCandidates : plan.candidates;\n const candidateProfiles = candidatePlanEntries\n .filter(\n (candidate) =>\n candidate.excludedReason === null &&\n isSpaceMembershipProfileKind(candidate.profileKind)\n )\n .map((candidate) => profileById.get(candidate.profileId))\n .filter(\n (\n profile\n ): profile is OpenMeldProfile & {\n profileKind: SpaceMembershipProfileKind;\n } =>\n profile !== undefined &&\n isSpaceMembershipProfileKind(profile.profileKind)\n );\n\n const candidates = await Promise.all(\n candidateProfiles.map((profile) =>\n buildSpaceMemberCandidateFromProfile({\n baseUrl: input.baseUrl,\n profile,\n localTargetStateById,\n ownerProfileName:\n ownerProfileNameByOwnerUserId.get(profile.ownerUserId) ?? undefined,\n alreadyJoined: memberProfileIds.has(profile.openMeldProfileId),\n progress: input.progress,\n includeLocalParticipation,\n })\n )\n );\n const directoryProfileById = organizationDirectory\n ? buildOrganizationDirectoryProfileById(organizationDirectory)\n : new Map<string, OrganizationDirectoryCandidateProfile>();\n const annotatedLocalCandidates = candidates.map((candidate) => {\n const directoryProfile = directoryProfileById.get(candidate.profileId);\n return membershipSource === \"organization_directory\"\n ? {\n ...candidate,\n organizationDirectoryProfile: directoryProfile !== undefined,\n isOrganizationCenterAgent:\n directoryProfile?.isOrganizationCenterAgent === true,\n }\n : candidate;\n });\n const resolvedCandidates =\n membershipSource === \"organization_directory\" &&\n explicitMemberIds.length > 0 &&\n organizationDirectory\n ? resolveExplicitOrganizationDirectoryCandidates({\n actingProfileId: input.currentProfile.openMeldProfileId,\n allowCurrentProfileMember: input.allowCurrentProfileMember === true,\n directory: organizationDirectory,\n explicitMemberIds,\n localCandidates: annotatedLocalCandidates,\n memberProfileIds,\n mode: input.mode,\n })\n : annotatedLocalCandidates;\n if (!includeLocalParticipation) {\n return resolvedCandidates;\n }\n\n return await refreshSpaceMemberCandidatesLocalReadiness(\n resolvedCandidates.filter(\n (candidate) => candidate.openMeldProfile !== undefined\n ),\n input.progress,\n { stage: \"resolve_candidates\" }\n ).then((localCandidates) => {\n const localCandidateById = new Map(\n localCandidates.map((candidate) => [candidate.profileId, candidate])\n );\n return resolvedCandidates.map(\n (candidate) => localCandidateById.get(candidate.profileId) ?? candidate\n );\n });\n}\n\ntype OrganizationDirectoryCandidateProfile = {\n profileId: string;\n profileHandle: string;\n profileKind: SpaceMembershipProfileKind;\n profileName: string;\n status: \"active\" | \"disabled\";\n ownerUserId: string | null;\n ownerName?: string;\n isOrganizationCenterAgent: boolean;\n};\n\nfunction buildOrganizationDirectoryProfileById(\n directory: OrganizationDirectoryResponse\n): Map<string, OrganizationDirectoryCandidateProfile> {\n const profiles: OrganizationDirectoryCandidateProfile[] = [\n ...directory.agentProfiles.map((profile) => ({\n profileId: profile.profileId,\n profileHandle: profile.profileHandle,\n profileKind: profile.profileKind,\n profileName: profile.profileName,\n status: profile.status,\n ownerUserId: profile.ownerUserId,\n ...(profile.ownerName ? { ownerName: profile.ownerName } : {}),\n isOrganizationCenterAgent: profile.isCenterAgent === true,\n })),\n ...directory.members.flatMap((member) =>\n member.humanProfile\n ? [\n {\n profileId: member.humanProfile.profileId,\n profileHandle: member.humanProfile.profileHandle,\n profileKind: \"human\" as const,\n profileName: member.humanProfile.profileName,\n status: member.humanProfile.status,\n ownerUserId: member.userId,\n ownerName: member.user.name,\n isOrganizationCenterAgent: false,\n },\n ]\n : []\n ),\n ];\n return new Map(profiles.map((profile) => [profile.profileId, profile]));\n}\n\nfunction resolveExplicitOrganizationDirectoryCandidates(input: {\n actingProfileId: string;\n allowCurrentProfileMember: boolean;\n directory: OrganizationDirectoryResponse;\n explicitMemberIds: readonly string[];\n localCandidates: SpaceMemberCandidate[];\n memberProfileIds: ReadonlySet<string>;\n mode: SpaceProfileAddMode;\n}): SpaceMemberCandidate[] {\n const directoryProfileById = buildOrganizationDirectoryProfileById(\n input.directory\n );\n const localCandidateById = new Map(\n input.localCandidates.map((candidate) => [candidate.profileId, candidate])\n );\n const selectableProfileById = new Map<string, SpaceProfileAddProfile>(\n [...directoryProfileById.values()].map((profile) => [\n profile.profileId,\n {\n ownerName: profile.ownerName,\n ownerUserId: profile.ownerUserId,\n profileId: profile.profileId,\n profileKind: profile.profileKind,\n profileName: profile.profileName,\n status: profile.status,\n },\n ])\n );\n for (const candidate of input.localCandidates) {\n if (!selectableProfileById.has(candidate.profileId)) {\n selectableProfileById.set(candidate.profileId, {\n ownerName: candidate.ownerName,\n ownerUserId: candidate.ownerUserId,\n profileId: candidate.profileId,\n profileKind: candidate.profileKind,\n profileName: candidate.profileName,\n status: \"active\",\n });\n }\n }\n const selectionPlan = buildSpaceProfileAddPlan({\n actingProfileId: input.actingProfileId,\n allowCurrentProfile: input.allowCurrentProfileMember,\n currentMembers: [],\n mode: input.mode,\n profiles: [...selectableProfileById.values()],\n selector: { kind: \"profile_ids\", profileIds: input.explicitMemberIds },\n });\n if (selectionPlan.invalidSelections.length > 0) {\n throw new Error(\n `invalid ${resolveSpaceAddMembersProfileLabel(input.mode)} profile ID(s): ${formatSpaceProfileAddInvalidSelections(\n selectionPlan.invalidSelections\n )} (must be your active selectable profiles or active profiles in the current Organization Directory, and cannot be the current profile)`\n );\n }\n return selectionPlan.selectedProfileIds.map((profileId) => {\n const directoryProfile = directoryProfileById.get(profileId);\n const localCandidate = localCandidateById.get(profileId);\n if (localCandidate) {\n return {\n ...localCandidate,\n organizationDirectoryProfile: directoryProfile !== undefined,\n isOrganizationCenterAgent:\n directoryProfile?.isOrganizationCenterAgent === true,\n };\n }\n if (!directoryProfile) {\n throw new Error(\n `Selected profile disappeared while resolving ${profileId}`\n );\n }\n return {\n profileId: directoryProfile.profileId,\n profileHandle: directoryProfile.profileHandle,\n profileName: directoryProfile.profileName,\n profileKind: directoryProfile.profileKind,\n ownerUserId: directoryProfile.ownerUserId ?? undefined,\n ownerName: directoryProfile.ownerName,\n alreadyJoined: input.memberProfileIds.has(directoryProfile.profileId),\n needsActivation: false,\n organizationDirectoryProfile: true,\n isOrganizationCenterAgent: directoryProfile.isOrganizationCenterAgent,\n localParticipationChecked: false,\n localParticipationReasonCodes: [],\n localParticipationReadiness: null,\n localParticipationReasonText: null,\n };\n });\n}\n\nfunction formatSpaceProfileAddInvalidSelections(\n invalidSelections: readonly SpaceProfileAddInvalidSelection[]\n): string {\n return invalidSelections\n .map(\n (selection) =>\n `${selection.profileId} (${formatSpaceProfileAddInvalidSelectionReason(\n selection.reason\n )})`\n )\n .join(\", \");\n}\n\nfunction formatSpaceProfileAddInvalidSelectionReason(\n reason: SpaceProfileAddInvalidSelection[\"reason\"]\n): string {\n switch (reason) {\n case \"current_acting_profile\":\n return \"this is the current acting profile\";\n case \"different_owner\":\n return \"this profile belongs to a different account\";\n case \"inactive_profile\":\n return \"this profile is not active\";\n case \"kind_mismatch\":\n return \"this profile kind does not match this command\";\n case \"not_found\":\n return \"this profile was not found in this account\";\n case \"unsupported_profile_kind\":\n return \"this profile kind cannot be a Space member\";\n default:\n assertNeverSpaceProfileAddInvalidSelectionReason(reason);\n }\n}\n\nfunction assertNeverSpaceProfileAddInvalidSelectionReason(value: never): never {\n throw new Error(\n `unexpected space profile add invalid reason: ${String(value)}`\n );\n}\n\nasync function listSpaceAddMembersLocalTargetStatesIfRequested(input: {\n includeLocalParticipation: boolean;\n progress?: SpaceAddMembersProgressContext;\n}): Promise<AgentTargetState[]> {\n if (!input.includeLocalParticipation) {\n return [];\n }\n if (!input.progress) {\n return await listAgentTargetStates().catch(() => []);\n }\n return await runSpaceAddMembersProgressHeartbeat({\n ...input.progress,\n stage: \"resolve_candidates\",\n phase: \"read_local_targets_wait\",\n summary:\n \"Still reading local agent controller state for candidate profiles before selection.\",\n operation: async () => await listAgentTargetStates().catch(() => []),\n });\n}\n\nasync function resolveSpaceMemberCandidateAgentControllerReportIfRequested(input: {\n baseUrl: string;\n includeLocalParticipation: boolean;\n profile: OpenMeldProfile;\n progress?: SpaceAddMembersProgressContext;\n}): Promise<Awaited<\n ReturnType<typeof resolveAgentProfilePrimaryAgentControllerReport>\n> | null> {\n if (!input.includeLocalParticipation) {\n return null;\n }\n if (!input.progress) {\n return await resolveAgentProfilePrimaryAgentControllerReport({\n baseUrl: input.baseUrl,\n profile: input.profile,\n }).catch(() => null);\n }\n return await runSpaceAddMembersProgressHeartbeat({\n ...input.progress,\n stage: \"resolve_candidates\",\n phase: \"read_agent_controller_report_wait\",\n summary: `Still reading execution target projection for ${resolveSpaceMemberTerminalProfileLabel(\n input.profile.profileName\n )}.`,\n profileId: input.profile.openMeldProfileId,\n profileIds: [input.profile.openMeldProfileId],\n operation: async () =>\n await resolveAgentProfilePrimaryAgentControllerReport({\n baseUrl: input.baseUrl,\n profile: input.profile,\n }).catch(() => null),\n });\n}\n\nasync function buildSpaceMemberCandidateFromProfile(input: {\n baseUrl: string;\n profile: OpenMeldProfile & { profileKind: SpaceMembershipProfileKind };\n localTargetStateById: ReadonlyMap<string, AgentTargetState>;\n ownerProfileName?: string;\n alreadyJoined: boolean;\n progress?: SpaceAddMembersProgressContext;\n includeLocalParticipation?: boolean;\n}): Promise<SpaceMemberCandidate> {\n const includeLocalParticipation = input.includeLocalParticipation !== false;\n if (input.progress && includeLocalParticipation) {\n emitAgentSpaceAddMembersProgress({\n ...input.progress,\n stage: \"resolve_candidates\",\n phase: \"read_agent_controller_report\",\n summary: `Reading execution target projection for ${resolveSpaceMemberTerminalProfileLabel(\n input.profile.profileName\n )}.`,\n profileId: input.profile.openMeldProfileId,\n profileIds: [input.profile.openMeldProfileId],\n });\n }\n const executionTarget =\n await resolveSpaceMemberCandidateAgentControllerReportIfRequested({\n baseUrl: input.baseUrl,\n includeLocalParticipation,\n profile: input.profile,\n progress: input.progress,\n });\n const agentControllerRef = executionTarget?.agentControllerRef ?? undefined;\n const controllerEnabled =\n executionTarget?.bindingState === \"enabled_primary\" &&\n executionTarget.routable;\n const localTargetAgentId = resolveSpaceMemberCandidateLocalTargetAgentId({\n profileKind: input.profile.profileKind,\n agentControllerRef,\n controllerEnabled,\n });\n const localTargetState = localTargetAgentId\n ? (input.localTargetStateById.get(localTargetAgentId) ?? null)\n : null;\n\n return {\n openMeldProfile: input.profile,\n profileId: input.profile.openMeldProfileId,\n profileHandle: input.profile.profileHandle,\n profileName: input.profile.profileName,\n profileKind: input.profile.profileKind,\n ownerProfileName: input.ownerProfileName,\n ownerUserId: input.profile.ownerUserId,\n ownerName: input.profile.ownerName,\n agentControllerRef,\n controllerEnabled,\n localTargetAgentId,\n localTargetDisplayName: localTargetState?.displayName ?? null,\n localTargetLaunchStatus: localTargetState?.launchStatus ?? null,\n localTargetSelectable: localTargetState?.selectable ?? false,\n localParticipationReadiness: null,\n localParticipationChecked: false,\n localParticipationReasonCodes: [],\n localParticipationReasonText: null,\n alreadyJoined: input.alreadyJoined,\n needsActivation: false,\n };\n}\n\nfunction resolveSpaceMemberCandidateLocalTargetAgentId(input: {\n profileKind: SpaceMembershipProfileKind;\n agentControllerRef?: string | null;\n controllerEnabled?: boolean | null;\n}): string | null {\n if (\n input.profileKind !== \"agent\" ||\n input.controllerEnabled !== true ||\n typeof input.agentControllerRef !== \"string\"\n ) {\n return null;\n }\n const agentControllerRef = input.agentControllerRef.trim();\n if (!agentControllerRef) {\n return null;\n }\n if (agentControllerRef.startsWith(\"builtin:\")) {\n const builtinAgentId =\n normalizeBuiltinAgentControllerId(agentControllerRef);\n return builtinAgentId || null;\n }\n return agentControllerRef;\n}\n\nfunction toSpaceProfileAddProfile(\n profile: OpenMeldProfile\n): SpaceProfileAddProfile {\n return {\n createdAt: profile.createdAt,\n isDefault: profile.isDefault,\n lastUsedAt: profile.lastUsedAt,\n ownerName: profile.ownerName,\n ownerUserId: profile.ownerUserId,\n profileId: profile.openMeldProfileId,\n profileKind: profile.profileKind,\n profileName: profile.profileName,\n status: profile.status,\n };\n}\n\nasync function resolveSpaceMemberCandidatesForRemove(input: {\n currentProfile: OpenMeldProfile;\n currentOwnerUserId?: string;\n space: string;\n baseUrl: string;\n password?: string;\n}): Promise<ResolvedSpaceRemoveMemberCandidates> {\n const membersSnapshot = await createCliSpaceApi(\n input.baseUrl\n ).getMembersSnapshot({\n spaceId: input.space,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.currentProfile,\n }),\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n });\n\n const currentOwnerUserId = normalizeOptionalString(input.currentOwnerUserId);\n const creatorProfileIds = new Set<string>();\n const allProfiles = await listOpenMeldProfiles();\n const localProfileById = new Map(\n allProfiles.map((profile) => [profile.openMeldProfileId, profile] as const)\n );\n const snapshotMembers = [\n ...membersSnapshot.humans,\n ...membersSnapshot.agents,\n ].filter((member) => member.status === \"active\");\n const targetMentionLabelByProfileId =\n buildSpacePrimaryMentionLabelByProfileId(membersSnapshot);\n for (const member of snapshotMembers) {\n if (member.memberSource === \"space_creator\") {\n creatorProfileIds.add(member.profileId);\n }\n }\n\n const activeMembers = snapshotMembers\n .filter((member) => {\n if (!currentOwnerUserId) {\n return true;\n }\n return normalizeOptionalString(member.ownerUserId) === currentOwnerUserId;\n })\n .filter(\n (member) => member.profileId !== input.currentProfile.openMeldProfileId\n )\n .filter((member) => member.memberSource !== \"space_creator\")\n .map((member) =>\n hydrateSpaceRemoveMemberCandidate({\n candidate: toSpaceRemoveMemberCandidateFromSnapshot({\n member,\n targetMentionLabel:\n targetMentionLabelByProfileId.get(member.profileId) ?? null,\n }),\n profile: localProfileById.get(member.profileId),\n })\n )\n .sort((left, right) => {\n const byName = left.profileName.localeCompare(right.profileName);\n if (byName !== 0) {\n return byName;\n }\n return left.profileId.localeCompare(right.profileId);\n });\n\n const explicitFallbackById = new Map<string, SpaceRemoveMemberCandidate>();\n for (const profile of allProfiles) {\n const { profileKind } = profile;\n if (\n profile.status !== \"active\" ||\n !isSpaceMembershipProfileKind(profileKind)\n ) {\n continue;\n }\n if (profile.openMeldProfileId === input.currentProfile.openMeldProfileId) {\n continue;\n }\n if (\n currentOwnerUserId &&\n normalizeOptionalString(profile.ownerUserId) !== currentOwnerUserId\n ) {\n continue;\n }\n explicitFallbackById.set(\n profile.openMeldProfileId,\n toSpaceRemoveMemberCandidateFromProfile({\n ...profile,\n profileKind,\n })\n );\n }\n\n return {\n activeMembers,\n explicitFallbackById,\n creatorProfileIds,\n };\n}\n\nfunction buildOwnerProfileNameByOwnerUserId(\n profiles: readonly OpenMeldProfile[]\n): Map<string, string> {\n const ownerProfileMap = new Map<string, string>();\n const activeProfiles = profiles.filter(\n (profile) => profile.status === \"active\"\n );\n const activeHumanProfiles = activeProfiles.filter(\n (profile): profile is OpenMeldProfile & { profileKind: \"human\" } =>\n profile.profileKind === \"human\"\n );\n\n for (const profile of activeHumanProfiles) {\n const ownerUserId = normalizeOptionalString(profile.ownerUserId);\n const profileName = normalizeOptionalString(profile.profileName);\n if (!(ownerUserId && profileName)) {\n continue;\n }\n if (!ownerProfileMap.has(ownerUserId)) {\n ownerProfileMap.set(ownerUserId, profileName);\n continue;\n }\n if (profile.isDefault === true) {\n ownerProfileMap.set(ownerUserId, profileName);\n }\n }\n\n return ownerProfileMap;\n}\n\nfunction resolveSpaceAddMemberSelection(input: {\n space: string;\n candidates: SpaceMemberCandidate[];\n currentProfileId: string;\n explicitMembers?: string[];\n selectAll: boolean;\n mode: SpaceProfileAddMode;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n presenter: ReturnType<typeof createPresenter>;\n initialSelectedProfileIds?: string[];\n requiredSelection?: boolean;\n allowCurrentProfileMember?: boolean;\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n}): Promise<string[] | null> {\n const explicitMemberIds = normalizeRequestedMemberIds(input.explicitMembers);\n const candidateById = new Map(\n input.candidates.map(\n (candidate) => [candidate.profileId, candidate] as const\n )\n );\n const initialSelectedProfileIds = normalizeRequestedMemberIds(\n input.initialSelectedProfileIds\n ).filter((profileId) => {\n const candidate = candidateById.get(profileId);\n return candidate?.alreadyJoined === false;\n });\n const explicitSelection = resolveExplicitSpaceAddMemberSelection({\n space: input.space,\n candidates: input.candidates,\n currentProfileId: input.currentProfileId,\n explicitMemberIds,\n selectAll: input.selectAll,\n mode: input.mode,\n presenter: input.presenter,\n candidateById,\n allowCurrentProfileMember: input.allowCurrentProfileMember === true,\n });\n if (explicitSelection !== undefined) {\n return Promise.resolve(explicitSelection);\n }\n\n ensureSpaceAddMemberPromptAllowed({\n allowPrompt: input.allowPrompt,\n mode: input.mode,\n resolvedView: input.resolvedView,\n });\n\n const selectableCount = input.candidates.filter(\n (candidate) => !candidate.alreadyJoined\n ).length;\n if (selectableCount === 0) {\n input.presenter.line({\n code: \"space.add_members.none_selectable\",\n text: \"All eligible profiles are already in this space.\",\n data: { spaceId: input.space },\n });\n return Promise.resolve([]);\n }\n\n return promptInteractiveSpaceAddMemberSelection({\n candidates: input.candidates,\n resolvedView: input.resolvedView,\n requiredSelection: input.requiredSelection,\n allowBack: input.allowBack,\n emitCancelMessage: input.emitCancelMessage,\n initialSelectedProfileIds,\n });\n}\n\nfunction resolveExplicitSpaceAddMemberSelection(input: {\n space: string;\n candidates: SpaceMemberCandidate[];\n currentProfileId: string;\n explicitMemberIds: string[];\n selectAll: boolean;\n mode: SpaceProfileAddMode;\n presenter: ReturnType<typeof createPresenter>;\n candidateById: ReadonlyMap<string, SpaceMemberCandidate>;\n allowCurrentProfileMember: boolean;\n}): string[] | undefined {\n if (input.selectAll || input.explicitMemberIds.length > 0) {\n validateSpaceMemberSelectionInput({\n all: input.selectAll,\n command: resolveSpaceAddMembersSelectionCommand(input.mode),\n explicitMemberIds: input.explicitMemberIds,\n });\n }\n\n if (input.explicitMemberIds.length > 0) {\n if (\n input.explicitMemberIds.includes(input.currentProfileId) &&\n !input.allowCurrentProfileMember\n ) {\n throw createSpaceAddMembersCurrentProfileGuideError({\n profileId: input.currentProfileId,\n });\n }\n const invalid = input.explicitMemberIds.filter(\n (profileId) => !input.candidateById.has(profileId)\n );\n if (invalid.length > 0) {\n throw new Error(\n `invalid ${resolveSpaceAddMembersProfileLabel(input.mode)} profile ID(s): ${invalid.join(\", \")} (must be your selectable ${resolveSpaceAddMembersProfileLabel(input.mode)} profiles and cannot be the current profile)`\n );\n }\n return input.explicitMemberIds;\n }\n\n if (!input.selectAll) {\n return undefined;\n }\n\n const selectable = input.candidates\n .filter((candidate) => !candidate.alreadyJoined)\n .map((candidate) => candidate.profileId);\n if (selectable.length === 0) {\n input.presenter.line({\n code: \"space.add_members.all_already_joined\",\n text: \"All eligible profiles are already in this space.\",\n data: { spaceId: input.space },\n });\n return [];\n }\n return selectable;\n}\n\nfunction resolveSpaceAddMembersSelectionCommand(\n mode: SpaceProfileAddMode\n): \"add-agents\" | \"add-human-profiles\" | \"add-members\" {\n switch (mode) {\n case \"agents\":\n return \"add-agents\";\n case \"human_profiles\":\n return \"add-human-profiles\";\n case \"profiles\":\n return \"add-members\";\n default:\n assertNeverSpaceAddMembersMode(mode);\n }\n}\n\nfunction resolveSpaceAddMembersCommandEntryName(\n mode: SpaceProfileAddMode\n): \"space.add-agents\" | \"space.add-human-profiles\" | \"space.add-members\" {\n switch (mode) {\n case \"agents\":\n return \"space.add-agents\";\n case \"human_profiles\":\n return \"space.add-human-profiles\";\n case \"profiles\":\n return \"space.add-members\";\n default:\n assertNeverSpaceAddMembersMode(mode);\n }\n}\n\nfunction resolveSpaceAddMembersMissingArgumentsSummary(\n mode: SpaceProfileAddMode\n): string {\n switch (mode) {\n case \"agents\":\n return \"openmeld space add-agents in agent/non-interactive mode requires explicit space and Agent Profile arguments.\";\n case \"human_profiles\":\n return \"openmeld space add-human-profiles in agent/non-interactive mode requires explicit space and Human Profile arguments.\";\n case \"profiles\":\n return \"openmeld space add-members in agent/non-interactive mode requires explicit space and member arguments.\";\n default:\n assertNeverSpaceAddMembersMode(mode);\n }\n}\n\nfunction resolveSpaceAddMembersSelectorRequiredText(\n mode: SpaceProfileAddMode\n): string {\n switch (mode) {\n case \"agents\":\n return \"`openmeld space add-agents` requires --agent-profile <agent-profile-id...> or --all in non-interactive mode\";\n case \"human_profiles\":\n return \"`openmeld space add-human-profiles` requires --human-profile <human-profile-id...> or --all in non-interactive mode\";\n case \"profiles\":\n return \"`openmeld space add-members` requires --member <profile-id...> or --all in non-interactive mode\";\n default:\n assertNeverSpaceAddMembersMode(mode);\n }\n}\n\nfunction resolveSpaceAddMembersProfileLabel(mode: SpaceProfileAddMode): string {\n switch (mode) {\n case \"agents\":\n return \"agent\";\n case \"human_profiles\":\n return \"human\";\n case \"profiles\":\n return \"member\";\n default:\n assertNeverSpaceAddMembersMode(mode);\n }\n}\n\nfunction ensureSpaceAddMemberPromptAllowed(input: {\n allowPrompt: boolean;\n mode: SpaceProfileAddMode;\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (input.allowPrompt) {\n return;\n }\n\n if (input.resolvedView === \"agent\") {\n throw createSpaceAddMembersGuideError(\n resolveSpaceAddMembersMissingArgumentsSummary(input.mode),\n resolveSpaceAddMembersCommandEntryName(input.mode)\n );\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n resolveSpaceAddMembersSelectorRequiredText(input.mode)\n )\n );\n}\n\nfunction assertNeverSpaceAddMembersMode(value: never): never {\n throw new Error(`unexpected space add-members mode: ${String(value)}`);\n}\n\nasync function promptInteractiveSpaceAddMemberSelection(input: {\n candidates: SpaceMemberCandidate[];\n resolvedView: \"human\" | \"agent\";\n requiredSelection?: boolean;\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n initialSelectedProfileIds: string[];\n}): Promise<string[] | null> {\n const orderedCandidates = sortSpaceMemberCandidatesForPrompt({\n candidates: input.candidates,\n initialSelectedProfileIds: input.initialSelectedProfileIds,\n });\n if (input.resolvedView === \"human\") {\n return promptHumanSpaceAddMemberSelection({\n candidates: orderedCandidates,\n requiredSelection: input.requiredSelection,\n allowBack: input.allowBack,\n emitCancelMessage: input.emitCancelMessage,\n initialSelectedProfileIds: input.initialSelectedProfileIds,\n });\n }\n\n const selected = await multiselect({\n message: getChooseProfilesToBringMessage(),\n options: orderedCandidates.map((candidate) => ({\n value: candidate.profileId,\n label: formatSpaceMemberCandidateLabel(candidate),\n hint: formatSpaceMemberCandidateHint(candidate),\n disabled: candidate.alreadyJoined,\n })),\n required: input.requiredSelection ?? true,\n ...(input.initialSelectedProfileIds.length > 0\n ? { initialValues: input.initialSelectedProfileIds }\n : {}),\n });\n if (isCancel(selected)) {\n if (input.emitCancelMessage !== false) {\n cancel(\"Cancelled.\");\n }\n return null;\n }\n\n const normalized = normalizeRequestedMemberIds(selected);\n return normalized.length > 0 ? normalized : [];\n}\n\nasync function promptHumanSpaceAddMemberSelection(input: {\n candidates: SpaceMemberCandidate[];\n requiredSelection?: boolean;\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n initialSelectedProfileIds: string[];\n}): Promise<string[] | null> {\n const selected = await promptSearchMultiselect({\n message: getChooseProfilesToBringMessage(),\n items: input.candidates.map((candidate) =>\n buildHumanSpaceMemberCandidateSearchItem(candidate)\n ),\n maxVisible: 8,\n required: input.requiredSelection ?? true,\n allowBack: input.allowBack === true,\n backLabel: \"Back\",\n ...(input.initialSelectedProfileIds.length > 0\n ? { initialSelectedValues: input.initialSelectedProfileIds }\n : {}),\n });\n if (selected.status !== \"submitted\") {\n if (input.emitCancelMessage !== false) {\n cancel(\"Cancelled.\");\n }\n return null;\n }\n\n const normalized = normalizeRequestedMemberIds(selected.value);\n return normalized.length > 0 ? normalized : [];\n}\n\nfunction sortSpaceMemberCandidatesForPrompt(input: {\n candidates: SpaceMemberCandidate[];\n initialSelectedProfileIds: string[];\n}): SpaceMemberCandidate[] {\n if (input.initialSelectedProfileIds.length === 0) {\n return input.candidates;\n }\n\n const selectedProfileIds = new Set(input.initialSelectedProfileIds);\n return [...input.candidates].sort((left, right) => {\n const leftSelected = selectedProfileIds.has(left.profileId);\n const rightSelected = selectedProfileIds.has(right.profileId);\n if (leftSelected === rightSelected) {\n return 0;\n }\n return leftSelected ? -1 : 1;\n });\n}\n\nasync function resolveSpaceRemoveMemberSelection(input: {\n space: string;\n candidates: ResolvedSpaceRemoveMemberCandidates;\n currentProfileId: string;\n explicitMembers?: string[];\n selectAll: boolean;\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n presenter: ReturnType<typeof createPresenter>;\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n}): Promise<SpaceRemoveMemberCandidate[] | null> {\n const explicitMemberIds = normalizeRequestedMemberIds(input.explicitMembers);\n const activeCandidateById = new Map(\n input.candidates.activeMembers.map(\n (candidate) => [candidate.profileId, candidate] as const\n )\n );\n const explicitSelection = resolveExplicitSpaceRemoveMemberSelection({\n space: input.space,\n activeCandidates: input.candidates.activeMembers,\n explicitFallbackById: input.candidates.explicitFallbackById,\n creatorProfileIds: input.candidates.creatorProfileIds,\n currentProfileId: input.currentProfileId,\n explicitMemberIds,\n selectAll: input.selectAll,\n presenter: input.presenter,\n });\n if (explicitSelection !== undefined) {\n return explicitSelection;\n }\n\n ensureSpaceRemoveMemberPromptAllowed({\n allowPrompt: input.allowPrompt,\n resolvedView: input.resolvedView,\n });\n\n if (input.candidates.activeMembers.length === 0) {\n input.presenter.line({\n code: \"space.remove_members.none_selectable\",\n text: \"No removable members are available in this space.\",\n data: { spaceId: input.space },\n });\n return [];\n }\n\n const selectedProfileIds = await promptInteractiveSpaceRemoveMemberSelection({\n candidates: input.candidates.activeMembers,\n resolvedView: input.resolvedView,\n allowBack: input.allowBack,\n emitCancelMessage: input.emitCancelMessage,\n });\n if (selectedProfileIds === null) {\n return null;\n }\n\n return selectedProfileIds\n .map((profileId) => activeCandidateById.get(profileId))\n .filter((candidate): candidate is SpaceRemoveMemberCandidate =>\n Boolean(candidate)\n );\n}\n\nfunction resolveExplicitSpaceRemoveMemberSelection(input: {\n space: string;\n activeCandidates: SpaceRemoveMemberCandidate[];\n explicitFallbackById: ReadonlyMap<string, SpaceRemoveMemberCandidate>;\n creatorProfileIds: ReadonlySet<string>;\n currentProfileId: string;\n explicitMemberIds: string[];\n selectAll: boolean;\n presenter: ReturnType<typeof createPresenter>;\n}): SpaceRemoveMemberCandidate[] | undefined {\n if (input.selectAll || input.explicitMemberIds.length > 0) {\n validateSpaceMemberSelectionInput({\n all: input.selectAll,\n command: \"remove-members\",\n explicitMemberIds: input.explicitMemberIds,\n });\n }\n\n const combinedCandidateById = new Map<string, SpaceRemoveMemberCandidate>();\n for (const [profileId, candidate] of input.explicitFallbackById) {\n combinedCandidateById.set(profileId, candidate);\n }\n for (const candidate of input.activeCandidates) {\n combinedCandidateById.set(candidate.profileId, candidate);\n }\n\n if (input.explicitMemberIds.length > 0) {\n if (input.explicitMemberIds.includes(input.currentProfileId)) {\n throw createSpaceRemoveMembersCurrentProfileGuideError({\n profileId: input.currentProfileId,\n });\n }\n const creatorProfileId = input.explicitMemberIds.find((profileId) =>\n input.creatorProfileIds.has(profileId)\n );\n if (creatorProfileId) {\n throw createSpaceRemoveMembersCreatorGuideError({\n profileId: creatorProfileId,\n });\n }\n const invalid = input.explicitMemberIds.filter(\n (profileId) => !combinedCandidateById.has(profileId)\n );\n if (invalid.length > 0) {\n throw new Error(\n `invalid member profile ID(s): ${invalid.join(\", \")} (must be removable members you manage for this space)`\n );\n }\n return input.explicitMemberIds\n .map((profileId) => combinedCandidateById.get(profileId))\n .filter((candidate): candidate is SpaceRemoveMemberCandidate =>\n Boolean(candidate)\n );\n }\n\n if (!input.selectAll) {\n return undefined;\n }\n\n if (input.activeCandidates.length === 0) {\n input.presenter.line({\n code: \"space.remove_members.all_absent\",\n text: \"No removable members are currently active in this space.\",\n data: { spaceId: input.space },\n });\n return [];\n }\n return input.activeCandidates;\n}\n\nfunction ensureSpaceRemoveMemberPromptAllowed(input: {\n allowPrompt: boolean;\n resolvedView: \"human\" | \"agent\";\n}): void {\n if (input.allowPrompt) {\n return;\n }\n\n if (input.resolvedView === \"agent\") {\n throw createSpaceRemoveMembersGuideError();\n }\n throw new Error(\n formatOpenMeldCliTextBlock(\n \"`openmeld space remove-members` requires --member <profile-id...> or --all in non-interactive mode\"\n )\n );\n}\n\nasync function promptInteractiveSpaceRemoveMemberSelection(input: {\n candidates: SpaceRemoveMemberCandidate[];\n resolvedView: \"human\" | \"agent\";\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n}): Promise<string[] | null> {\n if (input.resolvedView === \"human\") {\n return promptHumanSpaceRemoveMemberSelection(input);\n }\n\n const selected = await multiselect({\n message: getChooseMembersToRemoveMessage(),\n options: input.candidates.map((candidate) => ({\n value: candidate.profileId,\n label: formatSpaceRemoveMemberCandidateLabel(candidate),\n hint: formatSpaceRemoveMemberCandidateHint(candidate),\n })),\n required: true,\n });\n if (isCancel(selected)) {\n if (input.emitCancelMessage !== false) {\n cancel(\"Cancelled.\");\n }\n return null;\n }\n const normalized = normalizeRequestedMemberIds(selected);\n return normalized.length > 0 ? normalized : [];\n}\n\nasync function promptHumanSpaceRemoveMemberSelection(input: {\n candidates: SpaceRemoveMemberCandidate[];\n allowBack?: boolean;\n emitCancelMessage?: boolean;\n}): Promise<string[] | null> {\n const selected = await promptSearchMultiselect({\n message: getChooseMembersToRemoveMessage(),\n items: input.candidates.map((candidate) =>\n buildHumanSpaceRemoveMemberCandidateSearchItem(candidate)\n ),\n maxVisible: 8,\n required: true,\n allowBack: input.allowBack === true,\n backLabel: \"Back\",\n });\n if (selected.status !== \"submitted\") {\n if (input.emitCancelMessage !== false) {\n cancel(\"Cancelled.\");\n }\n return null;\n }\n const normalized = normalizeRequestedMemberIds(selected.value);\n return normalized.length > 0 ? normalized : [];\n}\n\nasync function applySpaceAddMembers(input: {\n actorProfile: OpenMeldProfile;\n candidates: SpaceMemberCandidate[];\n space: string;\n spaceName?: string | null;\n baseUrl: string;\n password?: string;\n membershipSource?: \"account\" | \"organization_directory\";\n}): Promise<SpaceAddMembersResult> {\n const result: SpaceAddMembersResult = {\n added: [],\n alreadyJoined: [],\n failed: [],\n warnings: [],\n };\n const gatewayHost = resolveGatewayHost(input.baseUrl);\n if (!gatewayHost) {\n throw new Error(`invalid gateway baseUrl: ${input.baseUrl}`);\n }\n\n const selectedCandidates = input.candidates.filter(\n (candidate) => !candidate.alreadyJoined\n );\n for (const candidate of input.candidates) {\n if (candidate.alreadyJoined) {\n result.alreadyJoined.push(candidate);\n }\n }\n if (selectedCandidates.length === 0) {\n return result;\n }\n\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n });\n const requestId = requestContext.actorContext.requestId;\n let response: PostSpaceMembersResponse;\n try {\n response = await postSelectedSpaceMembers({\n baseUrl: input.baseUrl,\n candidates: selectedCandidates,\n membershipSource: input.membershipSource ?? \"account\",\n password: input.password,\n requestContext,\n space: input.space,\n });\n } catch (error) {\n for (const candidate of selectedCandidates) {\n result.failed.push({\n candidate,\n error,\n });\n }\n return result;\n }\n\n const addedProfileIds = new Set(response.addedMemberIds);\n const alreadyMemberProfileIds = new Set(response.alreadyMemberIds);\n const responseItemByProfileId = new Map(\n response.items.map((item) => [item.profileId, item] as const)\n );\n const lastJoinedAt = new Date().toISOString();\n const spaceName = normalizeOptionalString(input.spaceName);\n\n for (const candidate of selectedCandidates) {\n const nextCandidate = hydrateSpaceMemberCandidateFromResponseItem({\n candidate,\n item: responseItemByProfileId.get(candidate.profileId),\n });\n if (addedProfileIds.has(candidate.profileId)) {\n result.added.push(nextCandidate);\n continue;\n }\n if (alreadyMemberProfileIds.has(candidate.profileId)) {\n result.alreadyJoined.push(nextCandidate);\n }\n }\n\n for (const candidate of result.added.filter(\n (addedCandidate) => addedCandidate.openMeldProfile !== undefined\n )) {\n try {\n await upsertProfileSpaceHistory({\n baseUrl: input.baseUrl,\n requestContext: buildSpaceMemberHistoryRequestContext({\n candidate,\n requestId,\n }),\n openMeldProfileId: candidate.profileId,\n profileName: candidate.profileName,\n spaceId: input.space,\n body: {\n gatewayHost,\n ...(spaceName ? { spaceName } : {}),\n status: \"active\",\n lastJoinedAt,\n },\n });\n } catch (error) {\n result.warnings.push({\n candidate,\n error,\n });\n }\n }\n\n return result;\n}\n\nasync function postSelectedSpaceMembers(input: {\n baseUrl: string;\n candidates: SpaceMemberCandidate[];\n membershipSource: \"account\" | \"organization_directory\";\n password?: string;\n requestContext: OpenMeldRequestContext;\n space: string;\n}): Promise<PostSpaceMembersResponse> {\n const memberProfileIds = input.candidates.map(\n (candidate) => candidate.profileId\n );\n if (input.membershipSource === \"account\") {\n return await postSpaceMembers({\n requestContext: input.requestContext,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n memberProfileIds,\n });\n }\n\n const accountOnlyCandidates = input.candidates.filter(\n (candidate) => candidate.organizationDirectoryProfile !== true\n );\n if (\n accountOnlyCandidates.length > 0 &&\n accountOnlyCandidates.length === input.candidates.length\n ) {\n return await postSpaceMembers({\n requestContext: input.requestContext,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n memberProfileIds,\n });\n }\n if (accountOnlyCandidates.length > 0) {\n throw new Error(\n \"Cannot combine Organization Directory profiles with account-only profiles in one membership request. Add them with separate commands.\"\n );\n }\n\n const centerAgentProfileIds = input.candidates\n .filter((candidate) => candidate.isOrganizationCenterAgent === true)\n .map((candidate) => candidate.profileId);\n if (centerAgentProfileIds.length > 1) {\n throw new Error(\n \"Organization Directory returned more than one Center Agent candidate.\"\n );\n }\n return await createCliSpaceApi(\n input.baseUrl\n ).addOrganizationDirectoryProfilesToSpace({\n requestContext: input.requestContext,\n spaceId: input.space,\n directoryProfileIds: memberProfileIds,\n ...(centerAgentProfileIds[0]\n ? { expectedCenterAgentProfileId: centerAgentProfileIds[0] }\n : {}),\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n });\n}\n\nfunction hydrateSpaceMemberCandidateFromResponseItem(input: {\n candidate: SpaceMemberCandidate;\n item?: PostSpaceMembersResponse[\"items\"][number] | undefined;\n}): SpaceMemberCandidate {\n if (!input.item) {\n return input.candidate;\n }\n\n return {\n ...input.candidate,\n profileName: input.item.profileName,\n profileKind: input.item.profileKind,\n ownerUserId: normalizeOptionalString(input.item.ownerUserId) ?? undefined,\n ownerName: normalizeOptionalString(input.item.ownerName) ?? undefined,\n targetMentionLabel: resolvePrimaryMentionLabelFromSpaceMemberItem(\n input.item\n ),\n ...(input.item.profileKind === \"agent\"\n ? {\n agentControllerRef:\n normalizeOptionalString(input.item.agentControllerRef) ??\n input.candidate.agentControllerRef,\n }\n : {}),\n };\n}\n\nfunction resolvePrimaryMentionLabelFromSpaceMemberItem(\n item: PostSpaceMembersResponse[\"items\"][number]\n): string {\n const mentionAlias = normalizeOptionalString(item.mentionAlias);\n if (mentionAlias) {\n return mentionAlias;\n }\n return resolveSingleSpaceMentionLabels({\n mentionAlias,\n profileId: item.profileId,\n profileName: item.profileName,\n }).primaryMentionLabel;\n}\n\nasync function waitForAddedMembersWakeProjection(input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n progress?: SpaceAddMembersProgressContext;\n result: SpaceAddMembersResult;\n}): Promise<void> {\n const expectedWakeableProfileIds = resolveExpectedWakeProjectionProfileIds(\n input.result\n );\n if (expectedWakeableProfileIds.length === 0) {\n return;\n }\n\n emitSpaceAddMembersProgressIfRequested(input.progress, {\n stage: \"add_members\",\n phase: \"confirm_membership_projection\",\n summary:\n \"Confirming the Space can see newly added wakeable members before returning.\",\n profileIds: expectedWakeableProfileIds,\n });\n\n const expected = new Set(expectedWakeableProfileIds);\n for (\n let attempt = 0;\n attempt < SPACE_ADD_MEMBERS_PROJECTION_WAIT_MAX_ATTEMPTS;\n attempt += 1\n ) {\n if (attempt > 0) {\n await delay(SPACE_ADD_MEMBERS_PROJECTION_WAIT_DELAY_MS);\n }\n\n let membersSnapshot: SpaceMembersSnapshot;\n try {\n membersSnapshot = await createCliSpaceApi(\n input.baseUrl\n ).getMembersSnapshot({\n spaceId: input.space,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n }),\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n } catch {\n return;\n }\n\n if (hasExpectedWakeProjection(membersSnapshot, expected)) {\n return;\n }\n }\n}\n\nfunction resolveExpectedWakeProjectionProfileIds(\n result: SpaceAddMembersResult\n): string[] {\n return result.added\n .filter(\n (candidate) =>\n candidate.profileKind === \"agent\" &&\n candidate.localParticipationReadiness === \"ready\"\n )\n .map((candidate) => candidate.profileId);\n}\n\nfunction hasExpectedWakeProjection(\n membersSnapshot: SpaceMembersSnapshot,\n expectedProfileIds: ReadonlySet<string>\n): boolean {\n const wakeableProfileIds = new Set(\n membersSnapshot.agents\n .filter(\n (member) =>\n member.status === \"active\" &&\n member.agentWakeAvailability?.status === \"available_for_wake\"\n )\n .map((member) => member.profileId)\n );\n\n for (const profileId of expectedProfileIds) {\n if (!wakeableProfileIds.has(profileId)) {\n return false;\n }\n }\n return true;\n}\n\nasync function delay(ms: number): Promise<void> {\n await new Promise((resolve) => setTimeout(resolve, ms));\n}\n\nfunction emitSpaceAddMembersResultIfRequested(\n input: Parameters<typeof emitSpaceAddMembersResult>[0] & {\n suppressResultOutput: boolean;\n }\n): void {\n if (input.suppressResultOutput) {\n return;\n }\n const { suppressResultOutput: _suppressResultOutput, ...resultInput } = input;\n emitSpaceAddMembersResult(resultInput);\n}\n\nfunction emitSpaceAddMembersResult(input: {\n mode: SpaceProfileAddMode;\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n space: string;\n selectedCount: number;\n result: SpaceAddMembersResult;\n joinNoticeSummary: SpaceAddMembersJoinNoticeSummary;\n}): void {\n const localParticipationFollowUps = input.result.added\n .map((candidate) => buildSpaceMemberJoinedFollowUp(candidate))\n .filter(\n (\n followUp\n ): followUp is {\n profileId: string;\n reasonCodes: string[];\n text: string;\n } => followUp !== null\n );\n if (input.resolvedView === \"agent\") {\n input.presenter.data({\n code: \"space.add_members\",\n payload: {\n command: resolveSpaceAddMembersSelectionCommand(input.mode),\n profileAddMode: input.mode,\n spaceId: input.space,\n selectedCount: input.selectedCount,\n addedMemberIds: input.result.added.map((item) => item.profileId),\n alreadyJoinedMemberIds: input.result.alreadyJoined.map(\n (item) => item.profileId\n ),\n failedMembers: input.result.failed.map((item) => ({\n profileId: item.candidate.profileId,\n message: toErrorMessage(item.error),\n })),\n warningMembers: input.result.warnings.map((item) => ({\n profileId: item.candidate.profileId,\n message: toErrorMessage(item.error),\n })),\n joinNotice: {\n recordedCount: input.joinNoticeSummary.recordedCount,\n failedCount: input.joinNoticeSummary.failedCount,\n ...(input.joinNoticeSummary.firstFailure\n ? {\n firstFailure: input.joinNoticeSummary.firstFailure,\n }\n : {}),\n },\n localParticipationFollowUps: localParticipationFollowUps.map(\n (followUp) => ({\n profileId: followUp.profileId,\n reasonCodes: followUp.reasonCodes,\n message: followUp.text,\n })\n ),\n },\n });\n return;\n }\n\n const card = buildSpaceAddMembersHumanResultCard({\n added: input.result.added,\n alreadyJoined: input.result.alreadyJoined,\n broadcastJoinNoticeCount: input.joinNoticeSummary.recordedCount,\n });\n renderInfoCard({\n presenter: input.presenter,\n title: card.title,\n codePrefix: \"space.add_members.card\",\n rows: card.rows,\n sanitize: true,\n minContentWidth: 56,\n });\n\n for (const followUp of localParticipationFollowUps) {\n input.presenter.line({\n code: \"space.add_members.local_participation_follow_up\",\n text: followUp.text,\n });\n }\n\n if (input.result.failed.length > 0) {\n for (const failure of input.result.failed) {\n input.presenter.line({\n code: \"space.add_members.failed\",\n text: `${failure.candidate.profileId}: ${toErrorMessage(failure.error)}`,\n });\n }\n }\n if (input.result.warnings.length > 0) {\n for (const warning of input.result.warnings) {\n input.presenter.line({\n code: \"space.add_members.warning\",\n text: `warn: ${warning.candidate.profileId}: ${toErrorMessage(warning.error)}`,\n });\n }\n }\n if (input.joinNoticeSummary.failedCount > 0) {\n emitSpaceNoticeFailure({\n presenter: input.presenter,\n summaryCode: \"space.add_members.notice_failed\",\n requestIdCode: \"space.add_members.notice_failed.request_id\",\n countDataKey: \"failedJoinNoticeCount\",\n spaceId: input.space,\n failureCount: input.joinNoticeSummary.failedCount,\n noticeKind: \"join\",\n firstFailure: input.joinNoticeSummary.firstFailure,\n });\n }\n}\n\nfunction buildSpaceMemberJoinedFollowUp(candidate: SpaceMemberCandidate): {\n profileId: string;\n reasonCodes: string[];\n text: string;\n} | null {\n if (candidate.profileKind !== \"agent\") {\n return null;\n }\n if (candidate.localParticipationChecked !== true) {\n return null;\n }\n\n if (isSpaceMemberCandidateRepairableLocalParticipationCandidate(candidate)) {\n const repairCommand = buildSpaceMemberRepairCommand({\n agentId: candidate.localTargetAgentId,\n profileId: candidate.profileId,\n });\n const profileLabel = resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n );\n const agentLabel = resolveSpaceMemberTerminalLocalTargetLabel({\n displayName: candidate.localTargetDisplayName,\n agentId: candidate.localTargetAgentId,\n });\n return {\n profileId: candidate.profileId,\n reasonCodes: candidate.localParticipationReasonCodes ?? [],\n text: `${profileLabel} joined this space. ${agentLabel} still needs repair on this device before it can handle work from the Space. Use \\`${repairCommand}\\` to repair the local agent.`,\n };\n }\n\n if (!isSpaceMemberCandidateRunnableLocalParticipationCandidate(candidate)) {\n const profileLabel = resolveSpaceMemberTerminalProfileLabel(\n candidate.profileName\n );\n const nextAction = resolveSpaceMemberJoinOnlyNextAction(candidate);\n return {\n profileId: candidate.profileId,\n reasonCodes: candidate.localParticipationReasonCodes ?? [],\n text: `${profileLabel} joined this space. OpenMeld has not confirmed its local reply path on this device yet. ${formatSpaceMemberRecoveryNextAction(nextAction)}`,\n };\n }\n\n return null;\n}\n\nasync function applySpaceRemoveMembers(input: {\n actorProfile: OpenMeldProfile;\n candidates: SpaceRemoveMemberCandidate[];\n space: string;\n baseUrl: string;\n password?: string;\n}): Promise<SpaceRemoveMembersResult> {\n const result: SpaceRemoveMembersResult = {\n removed: [],\n alreadyAbsent: [],\n failed: [],\n warnings: [],\n };\n const gatewayHost = resolveGatewayHost(input.baseUrl);\n if (!gatewayHost) {\n throw new Error(`invalid gateway baseUrl: ${input.baseUrl}`);\n }\n if (input.candidates.length === 0) {\n return result;\n }\n\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n });\n const requestId = requestContext.actorContext.requestId;\n let response: RemoveSpaceMembersResponse;\n try {\n response = await removeSpaceMembers({\n requestContext,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n memberProfileIds: input.candidates.map(\n (candidate) => candidate.profileId\n ),\n });\n } catch (error) {\n for (const candidate of input.candidates) {\n result.failed.push({\n candidate,\n error,\n });\n }\n return result;\n }\n\n const removedProfileIds = new Set(response.removedMemberIds);\n const alreadyAbsentProfileIds = new Set(response.alreadyAbsentMemberIds);\n for (const candidate of input.candidates) {\n if (removedProfileIds.has(candidate.profileId)) {\n result.removed.push(candidate);\n continue;\n }\n if (alreadyAbsentProfileIds.has(candidate.profileId)) {\n result.alreadyAbsent.push(candidate);\n }\n }\n\n for (const candidate of result.removed) {\n try {\n await updateProfileSpaceHistoryStatus({\n baseUrl: input.baseUrl,\n requestContext: buildSpaceMemberHistoryRequestContext({\n candidate,\n requestId,\n }),\n openMeldProfileId: candidate.profileId,\n profileName: candidate.profileName,\n spaceId: input.space,\n body: {\n gatewayHost,\n status: \"removed\",\n reason: \"removed_by_member\",\n },\n });\n } catch (error) {\n result.warnings.push({\n candidate,\n error,\n });\n }\n }\n\n return result;\n}\n\nasync function applySpaceLeave(input: {\n actorProfile: OpenMeldProfile;\n space: string;\n baseUrl: string;\n password?: string;\n}): Promise<SpaceLeaveResult> {\n const gatewayHost = resolveGatewayHost(input.baseUrl);\n if (!gatewayHost) {\n throw new Error(`invalid gateway baseUrl: ${input.baseUrl}`);\n }\n\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n });\n const response = await leaveSpace({\n requestContext,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n });\n const reason = resolveSpaceLeaveHistoryReason(response.status);\n const historyResult: SpaceLeaveResult[\"profileSpaceHistory\"] = {\n updated: true,\n reason,\n };\n\n try {\n await updateProfileSpaceHistoryStatus({\n baseUrl: input.baseUrl,\n requestContext,\n openMeldProfileId: input.actorProfile.openMeldProfileId,\n profileName: input.actorProfile.profileName,\n spaceId: input.space,\n body: {\n gatewayHost,\n status: \"removed\",\n reason,\n },\n });\n } catch (error) {\n historyResult.updated = false;\n historyResult.warning = toStructuredGatewayFailure(error);\n }\n\n return {\n ...response,\n profileSpaceHistory: historyResult,\n };\n}\n\nfunction resolveSpaceLeaveHistoryReason(\n status: LeaveSpaceResponse[\"status\"]\n): SpaceLeaveHistoryReason {\n return status === \"already_absent\"\n ? \"leave_space_already_absent\"\n : \"left_space\";\n}\n\nfunction emitSpaceRemoveMembersResult(input: {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n space: string;\n selectedCount: number;\n result: SpaceRemoveMembersResult;\n removeNoticeSummary: SpaceRemoveMembersNoticeSummary;\n}): void {\n if (input.resolvedView === \"agent\") {\n input.presenter.data({\n code: \"space.remove_members\",\n payload: {\n spaceId: input.space,\n selectedCount: input.selectedCount,\n removedMemberIds: input.result.removed.map((item) => item.profileId),\n alreadyAbsentMemberIds: input.result.alreadyAbsent.map(\n (item) => item.profileId\n ),\n failedMembers: input.result.failed.map((item) => ({\n profileId: item.candidate.profileId,\n message: toErrorMessage(item.error),\n })),\n warningMembers: input.result.warnings.map((item) => ({\n profileId: item.candidate.profileId,\n message: toErrorMessage(item.error),\n })),\n removeNotice: {\n recordedCount: input.removeNoticeSummary.recordedCount,\n failedCount: input.removeNoticeSummary.failedCount,\n ...(input.removeNoticeSummary.firstFailure\n ? {\n firstFailure: input.removeNoticeSummary.firstFailure,\n }\n : {}),\n },\n },\n });\n return;\n }\n\n const card = buildSpaceRemoveMembersHumanResultCard({\n removed: input.result.removed,\n alreadyAbsent: input.result.alreadyAbsent,\n broadcastRemoveNoticeCount: input.removeNoticeSummary.recordedCount,\n });\n renderInfoCard({\n presenter: input.presenter,\n title: card.title,\n codePrefix: \"space.remove_members.card\",\n rows: card.rows,\n sanitize: true,\n minContentWidth: 56,\n });\n\n if (input.result.failed.length > 0) {\n for (const failure of input.result.failed) {\n input.presenter.line({\n code: \"space.remove_members.failed\",\n text: `${failure.candidate.profileId}: ${toErrorMessage(failure.error)}`,\n });\n }\n }\n if (input.result.warnings.length > 0) {\n for (const warning of input.result.warnings) {\n input.presenter.line({\n code: \"space.remove_members.warning\",\n text: `warn: ${warning.candidate.profileId}: ${toErrorMessage(warning.error)}`,\n });\n }\n }\n if (input.removeNoticeSummary.failedCount > 0) {\n emitSpaceNoticeFailure({\n presenter: input.presenter,\n summaryCode: \"space.remove_members.notice_failed\",\n requestIdCode: \"space.remove_members.notice_failed.request_id\",\n countDataKey: \"failedRemoveNoticeCount\",\n spaceId: input.space,\n failureCount: input.removeNoticeSummary.failedCount,\n noticeKind: \"removal\",\n firstFailure: input.removeNoticeSummary.firstFailure,\n });\n }\n}\n\nfunction emitSpaceLeaveResult(input: {\n presenter: ReturnType<typeof createPresenter>;\n resolvedView: \"human\" | \"agent\";\n space: string;\n result: SpaceLeaveResult;\n}): void {\n if (input.resolvedView === \"agent\") {\n input.presenter.data({\n code: \"space.leave\",\n payload: {\n spaceId: input.space,\n leftProfileId: input.result.leftProfileId,\n status: input.result.status,\n profileSpaceHistory: input.result.profileSpaceHistory,\n },\n });\n return;\n }\n\n const statusText =\n input.result.status === \"already_absent\"\n ? \"You were already absent from this space.\"\n : \"You left this space.\";\n renderInfoCard({\n presenter: input.presenter,\n title: \"Left Space\",\n codePrefix: \"space.leave.card\",\n rows: [\n {\n label: \"Space\",\n value: input.space,\n },\n {\n label: \"Profile\",\n value: input.result.leftProfileId,\n },\n {\n label: \"Status\",\n value: statusText,\n },\n ],\n sanitize: true,\n minContentWidth: 56,\n });\n\n if (!input.result.profileSpaceHistory.updated) {\n input.presenter.line({\n code: \"space.leave.warning\",\n text: `warn: profile-space-history was not updated: ${input.result.profileSpaceHistory.warning?.message ?? \"Unknown error.\"}`,\n data: {\n warning: input.result.profileSpaceHistory.warning ?? null,\n },\n });\n }\n}\n\ntype SpaceAddMembersJoinNoticeSummary = {\n recordedCount: number;\n failedCount: number;\n firstFailure?: StructuredGatewayFailure;\n};\n\ntype SpaceRemoveMembersNoticeSummary = {\n recordedCount: number;\n failedCount: number;\n firstFailure?: StructuredGatewayFailure;\n};\n\nfunction emitSpaceNoticeFailure(input: {\n presenter: ReturnType<typeof createPresenter>;\n summaryCode: string;\n requestIdCode: string;\n countDataKey: \"failedJoinNoticeCount\" | \"failedRemoveNoticeCount\";\n spaceId: string;\n failureCount: number;\n noticeKind: \"join\" | \"removal\";\n firstFailure?: StructuredGatewayFailure;\n}): void {\n let noticeLabel = \"removal notices\";\n if (input.noticeKind === \"join\") {\n noticeLabel = input.failureCount === 1 ? \"join notice\" : \"join notices\";\n } else if (input.failureCount === 1) {\n noticeLabel = \"removal notice\";\n }\n const message = input.firstFailure?.message ?? \"unknown\";\n\n if (input.presenter.view === \"human\") {\n input.presenter.line({\n code: input.summaryCode,\n text: `OpenMeld updated the Space members, but couldn't post ${String(input.failureCount)} ${noticeLabel}. The membership change is already saved.`,\n });\n return;\n }\n\n input.presenter.line({\n code: input.summaryCode,\n text: `warn: failed to broadcast ${String(input.failureCount)} ${noticeLabel}: ${message}`,\n data: {\n spaceId: input.spaceId,\n [input.countDataKey]: input.failureCount,\n ...(input.firstFailure?.code ? { code: input.firstFailure.code } : {}),\n ...(input.firstFailure?.status !== null &&\n input.firstFailure?.status !== undefined\n ? { status: input.firstFailure.status }\n : {}),\n },\n });\n\n if (input.firstFailure?.requestId) {\n input.presenter.line({\n code: input.requestIdCode,\n text: `Request ID: ${input.firstFailure.requestId}`,\n data: {\n spaceId: input.spaceId,\n requestId: input.firstFailure.requestId,\n },\n });\n }\n}\n\nasync function persistSpaceAddMembersJoinNotices(input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n addedMembers: SpaceMemberCandidate[];\n}): Promise<SpaceAddMembersJoinNoticeSummary> {\n if (input.addedMembers.length === 0) {\n return {\n recordedCount: 0,\n failedCount: 0,\n };\n }\n\n const failures: Array<{\n member: SpaceMemberCandidate;\n error: unknown;\n }> = [];\n let targetMentionLabelByProfileId = buildKnownMentionLabelByProfileId(\n input.addedMembers\n );\n if (\n !hasMentionLabelsForAllMembers(\n input.addedMembers,\n targetMentionLabelByProfileId\n )\n ) {\n try {\n const membersSnapshot = await createCliSpaceApi(\n input.baseUrl\n ).getMembersSnapshot({\n spaceId: input.space,\n requestContext: buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n }),\n ...(input.password === undefined\n ? {}\n : { spacePassword: input.password }),\n });\n targetMentionLabelByProfileId =\n buildSpacePrimaryMentionLabelByProfileId(membersSnapshot);\n } catch (error) {\n return {\n recordedCount: 0,\n failedCount: input.addedMembers.length,\n firstFailure: toStructuredGatewayFailure(error),\n };\n }\n }\n\n for (const member of input.addedMembers) {\n const targetMentionLabel = targetMentionLabelByProfileId.get(\n member.profileId\n );\n if (!targetMentionLabel) {\n failures.push({\n member,\n error: new Error(\n `Missing canonical mention label for added member ${member.profileId} in post-mutation snapshot.`\n ),\n });\n continue;\n }\n try {\n await postSpaceAddMemberJoinNotice({\n actorProfile: input.actorProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n member: {\n ...member,\n targetMentionLabel,\n },\n });\n } catch (error) {\n failures.push({ member, error });\n }\n }\n\n return {\n recordedCount: input.addedMembers.length - failures.length,\n failedCount: failures.length,\n ...(failures[0]\n ? { firstFailure: toStructuredGatewayFailure(failures[0].error) }\n : {}),\n };\n}\n\nfunction buildKnownMentionLabelByProfileId(\n members: SpaceMemberCandidate[]\n): ReadonlyMap<string, string> {\n const labelsByProfileId = new Map<string, string>();\n for (const member of members) {\n const targetMentionLabel = normalizeOptionalString(\n member.targetMentionLabel\n );\n if (targetMentionLabel) {\n labelsByProfileId.set(member.profileId, targetMentionLabel);\n }\n }\n return labelsByProfileId;\n}\n\nfunction hasMentionLabelsForAllMembers(\n members: SpaceMemberCandidate[],\n labelsByProfileId: ReadonlyMap<string, string>\n): boolean {\n return members.every((member) => labelsByProfileId.has(member.profileId));\n}\n\nasync function postSpaceAddMemberJoinNotice(input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n member: SpaceMemberCandidate & { targetMentionLabel: string };\n}): Promise<void> {\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n });\n await createCliSpaceApi(input.baseUrl).postNormalMessage({\n spaceId: input.space,\n requestContext,\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n text: buildSpaceAddMemberJoinNoticeText({\n actorProfile: input.actorProfile,\n member: input.member,\n }),\n meta: {\n purpose: SPACE_MEMBER_JOIN_NOTICE_PURPOSE,\n targetProfileId: input.member.profileId,\n targetProfileKind: input.member.profileKind,\n targetProfileName: input.member.profileName,\n targetMentionLabel: input.member.targetMentionLabel,\n addedByProfileId: input.actorProfile.openMeldProfileId,\n addedByDisplayName: input.actorProfile.profileName,\n },\n });\n}\n\nasync function persistSpaceRemoveMemberNotices(input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n removedMembers: SpaceRemoveMemberCandidate[];\n}): Promise<SpaceRemoveMembersNoticeSummary> {\n if (input.removedMembers.length === 0) {\n return {\n recordedCount: 0,\n failedCount: 0,\n };\n }\n\n const failures: Array<{\n member: SpaceRemoveMemberCandidate;\n error: unknown;\n }> = [];\n for (const member of input.removedMembers) {\n if (!member.targetMentionLabel) {\n failures.push({\n member,\n error: new Error(\n `Missing canonical mention label for removed member ${member.profileId} in pre-mutation snapshot.`\n ),\n });\n continue;\n }\n try {\n await postSpaceRemoveMemberNotice({\n actorProfile: input.actorProfile,\n baseUrl: input.baseUrl,\n space: input.space,\n password: input.password,\n member: {\n ...member,\n targetMentionLabel: member.targetMentionLabel,\n },\n });\n } catch (error) {\n failures.push({ member, error });\n }\n }\n\n return {\n recordedCount: input.removedMembers.length - failures.length,\n failedCount: failures.length,\n ...(failures[0]\n ? { firstFailure: toStructuredGatewayFailure(failures[0].error) }\n : {}),\n };\n}\n\nasync function postSpaceRemoveMemberNotice(input: {\n actorProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n member: SpaceRemoveMemberCandidate & { targetMentionLabel: string };\n}): Promise<void> {\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.actorProfile,\n });\n await createCliSpaceApi(input.baseUrl).postNormalMessage({\n spaceId: input.space,\n requestContext,\n ...(input.password === undefined ? {} : { spacePassword: input.password }),\n text: buildSpaceRemoveMemberNoticeText({\n actorProfile: input.actorProfile,\n member: input.member,\n }),\n meta: {\n purpose: SPACE_MEMBER_REMOVE_NOTICE_PURPOSE,\n targetProfileId: input.member.profileId,\n targetProfileKind: input.member.profileKind,\n targetProfileName: input.member.profileName,\n targetMentionLabel: input.member.targetMentionLabel,\n removedByProfileId: input.actorProfile.openMeldProfileId,\n removedByDisplayName: input.actorProfile.profileName,\n },\n });\n}\n\nfunction buildSpaceAddMemberJoinNoticeText(input: {\n actorProfile: OpenMeldProfile;\n member: SpaceMemberCandidate;\n}): string {\n return `${input.actorProfile.profileName} added ${resolveSpaceAddMemberNoticeProfileNameLabel(input.member)} to this space.`;\n}\n\nfunction buildSpaceRemoveMemberNoticeText(input: {\n actorProfile: OpenMeldProfile;\n member: SpaceRemoveMemberCandidate;\n}): string {\n return `${input.actorProfile.profileName} removed ${resolveSpaceRemoveMemberNoticeProfileNameLabel(input.member)} from this space.`;\n}\n\nfunction resolveSpaceAddMemberNoticeProfileNameLabel(\n member: SpaceMemberCandidate\n): string {\n if (member.profileKind !== \"agent\") {\n return member.profileName;\n }\n return `🤖 ${member.profileName}`;\n}\n\nfunction resolveSpaceRemoveMemberNoticeProfileNameLabel(\n member: SpaceRemoveMemberCandidate\n): string {\n if (member.profileKind !== \"agent\") {\n return member.profileName;\n }\n return `🤖 ${member.profileName}`;\n}\n\nfunction buildSpaceMemberHistoryRequestContext(input: {\n candidate:\n | Pick<\n SpaceMemberCandidate,\n | \"profileId\"\n | \"profileHandle\"\n | \"profileName\"\n | \"profileKind\"\n | \"ownerUserId\"\n | \"ownerName\"\n | \"agentControllerRef\"\n >\n | Pick<\n SpaceRemoveMemberCandidate,\n | \"profileId\"\n | \"profileHandle\"\n | \"profileName\"\n | \"profileKind\"\n | \"ownerUserId\"\n | \"ownerName\"\n >;\n requestId: string;\n}): OpenMeldRequestContext {\n return buildOpenMeldRequestContextFromProfileIdentity({\n requestId: input.requestId,\n profileIdentity: {\n openMeldProfileId: input.candidate.profileId,\n profileKind: input.candidate.profileKind,\n ...(input.candidate.profileHandle\n ? { profileHandle: input.candidate.profileHandle }\n : {}),\n profileName: input.candidate.profileName,\n ...(input.candidate.ownerUserId\n ? { ownerUserId: input.candidate.ownerUserId }\n : {}),\n ...(input.candidate.ownerName\n ? { ownerName: input.candidate.ownerName }\n : {}),\n ...(\"agentControllerRef\" in input.candidate &&\n input.candidate.agentControllerRef\n ? { agentControllerRef: input.candidate.agentControllerRef }\n : {}),\n },\n });\n}\n\nfunction formatSpaceRemoveMemberCandidateLabel(\n candidate: SpaceRemoveMemberCandidate\n): string {\n return `${sanitizeSingleLinePromptText(candidate.profileName)} (${sanitizeSingleLinePromptText(candidate.profileKind)}) · ${sanitizeSingleLinePromptText(candidate.profileId)}`;\n}\n\nfunction formatSpaceRemoveMemberCandidateHint(\n candidate: SpaceRemoveMemberCandidate\n): string {\n if (candidate.profileKind === \"agent\") {\n return \"Selectable agent member\";\n }\n return \"Selectable human member\";\n}\n\nfunction buildHumanSpaceRemoveMemberCandidateSearchItem(\n candidate: SpaceRemoveMemberCandidate\n): {\n value: string;\n label: string;\n detail: string;\n searchText: string;\n disabled: boolean;\n} {\n return {\n value: candidate.profileId,\n label: `${sanitizeSingleLinePromptText(candidate.profileName)} (${sanitizeSingleLinePromptText(candidate.profileKind)})`,\n detail: buildHumanSpaceRemoveMemberCandidateDetail(candidate),\n searchText: buildHumanSpaceRemoveMemberCandidateSearchText(candidate),\n disabled: false,\n };\n}\n\nfunction buildHumanSpaceRemoveMemberCandidateDetail(\n candidate: SpaceRemoveMemberCandidate\n): string {\n return `ID ${sanitizeSingleLinePromptText(candidate.profileId)}`;\n}\n\nfunction buildHumanSpaceRemoveMemberCandidateSearchText(\n candidate: SpaceRemoveMemberCandidate\n): string {\n return [\n sanitizeSingleLinePromptText(candidate.profileId),\n sanitizeSingleLinePromptText(candidate.profileName),\n sanitizeSingleLinePromptText(candidate.profileKind),\n sanitizeSingleLinePromptText(\n normalizeOptionalString(candidate.profileHandle)\n ),\n sanitizeSingleLinePromptText(normalizeOptionalString(candidate.ownerName)),\n sanitizeSingleLinePromptText(\n normalizeOptionalString(candidate.ownerUserId)\n ),\n ]\n .filter((value): value is string => typeof value === \"string\")\n .join(\"\\n\");\n}\n\nfunction formatSpaceMemberCandidateLabel(\n candidate: SpaceMemberCandidate\n): string {\n const label = `${sanitizeSingleLinePromptText(candidate.profileName)} (${sanitizeSingleLinePromptText(candidate.profileKind)}) · ${sanitizeSingleLinePromptText(candidate.profileId)}`;\n return candidate.alreadyJoined ? pc.strikethrough(label) : label;\n}\n\nfunction formatSpaceMemberCandidateHint(\n candidate: SpaceMemberCandidate\n): string {\n if (candidate.alreadyJoined) {\n return \"Already in this space\";\n }\n if (candidate.needsActivation) {\n return \"Needs mention setup\";\n }\n return resolveSpaceMemberCandidateStatusLabel(candidate) ?? \"Selectable\";\n}\n\nfunction buildHumanSpaceMemberCandidateSearchItem(\n candidate: SpaceMemberCandidate\n): {\n value: string;\n label: string;\n detail: string;\n searchText: string;\n disabled: boolean;\n} {\n return {\n value: candidate.profileId,\n label: `${sanitizeSingleLinePromptText(candidate.profileName)} (${sanitizeSingleLinePromptText(candidate.profileKind)})`,\n detail: buildHumanSpaceMemberCandidateDetail(candidate),\n searchText: buildHumanSpaceMemberCandidateSearchText(candidate),\n disabled: candidate.alreadyJoined,\n };\n}\n\nfunction buildHumanSpaceMemberCandidateDetail(\n candidate: SpaceMemberCandidate\n): string {\n const statuses: string[] = [];\n if (candidate.alreadyJoined === true) {\n statuses.push(\"already in this space\");\n } else if (candidate.needsActivation) {\n statuses.push(\"needs mention setup\");\n }\n const agentStatuses = resolveSpaceMemberCandidateStatusBadges(candidate);\n statuses.push(...agentStatuses.map((status) => status.toLowerCase()));\n\n return statuses.length > 0\n ? `ID ${sanitizeSingleLinePromptText(candidate.profileId)} · ${statuses.map((status) => sanitizeSingleLinePromptText(status)).join(\" · \")}`\n : `ID ${sanitizeSingleLinePromptText(candidate.profileId)}`;\n}\n\nfunction buildHumanSpaceMemberCandidateSearchText(\n candidate: SpaceMemberCandidate\n): string {\n return [\n sanitizeSingleLinePromptText(candidate.profileId),\n sanitizeSingleLinePromptText(candidate.profileName),\n sanitizeSingleLinePromptText(candidate.profileKind),\n sanitizeSingleLinePromptText(\n normalizeOptionalString(candidate.ownerProfileName)\n ),\n sanitizeSingleLinePromptText(normalizeOptionalString(candidate.ownerName)),\n sanitizeSingleLinePromptText(\n normalizeOptionalString(candidate.ownerUserId)\n ),\n sanitizeSingleLinePromptText(\n normalizeOptionalString(candidate.agentControllerRef)\n ),\n ...resolveSpaceMemberCandidateStatusBadges(candidate),\n candidate.alreadyJoined ? \"already in this space\" : null,\n candidate.needsActivation ? \"needs mention setup\" : null,\n ]\n .filter((value): value is string => typeof value === \"string\")\n .join(\"\\n\");\n}\n\nfunction normalizeRequestedMemberIds(value: unknown): string[] {\n if (!Array.isArray(value)) {\n return [];\n }\n\n const ids: string[] = [];\n for (const item of value) {\n const profileId = String(item ?? \"\").trim();\n if (!profileId || ids.includes(profileId)) {\n continue;\n }\n ids.push(profileId);\n }\n return ids;\n}\n\nfunction toSpaceRemoveMemberCandidateFromSnapshot(input: {\n member:\n | SpaceMembersSnapshot[\"humans\"][number]\n | SpaceMembersSnapshot[\"agents\"][number];\n targetMentionLabel?: string | null;\n}): SpaceRemoveMemberCandidate {\n return {\n profileId: input.member.profileId,\n profileName: input.member.profileName,\n profileKind: input.member.profileKind,\n targetMentionLabel: normalizeOptionalString(input.targetMentionLabel),\n ownerUserId: normalizeOptionalString(input.member.ownerUserId),\n ownerName: normalizeOptionalString(input.member.ownerName),\n creatorProfileId:\n input.member.memberSource === \"space_creator\"\n ? normalizeOptionalString(input.member.profileId)\n : null,\n };\n}\n\nfunction hydrateSpaceRemoveMemberCandidate(input: {\n candidate: SpaceRemoveMemberCandidate;\n profile?: OpenMeldProfile | undefined;\n}): SpaceRemoveMemberCandidate {\n if (input.candidate.profileHandle) {\n return input.candidate;\n }\n\n const profileHandle = normalizeOptionalString(input.profile?.profileHandle);\n if (!profileHandle) {\n return input.candidate;\n }\n\n return {\n ...input.candidate,\n profileHandle,\n };\n}\n\nfunction toSpaceRemoveMemberCandidateFromProfile(\n profile: OpenMeldProfile & { profileKind: SpaceMembershipProfileKind }\n): SpaceRemoveMemberCandidate {\n return {\n profileId: profile.openMeldProfileId,\n profileHandle: profile.profileHandle,\n profileName: profile.profileName,\n profileKind: profile.profileKind,\n targetMentionLabel: null,\n ownerUserId: normalizeOptionalString(profile.ownerUserId),\n ownerName: normalizeOptionalString(profile.ownerName),\n creatorProfileId: null,\n };\n}\n\nasync function resolveKnownSpacesForPasswordSelection(input: {\n known: KnownSpaceOption[];\n clear: boolean;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n}): Promise<KnownSpaceOption[]> {\n const knownWithPasswordState = await Promise.all(\n input.known.map((item) =>\n hydrateKnownSpacePasswordProtection({\n item,\n openMeldProfile: input.openMeldProfile,\n baseUrl: input.baseUrl,\n })\n )\n );\n return knownWithPasswordState.filter(\n (item) => item.passwordProtected === input.clear\n );\n}\n\nasync function hydrateKnownSpacePasswordProtection(input: {\n item: KnownSpaceOption;\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n}): Promise<KnownSpaceOption> {\n if (typeof input.item.passwordProtected === \"boolean\") {\n return input.item;\n }\n\n const targetBaseUrl = input.item.baseUrl ?? input.baseUrl;\n const requestContext = buildOpenMeldRequestContextFromProfile({\n openMeldProfile: input.openMeldProfile,\n });\n try {\n const meta = await fetchSpaceMeta({\n requestContext,\n baseUrl: targetBaseUrl,\n space: input.item.space,\n });\n const passwordProtected =\n typeof meta.passwordProtected === \"boolean\"\n ? meta.passwordProtected\n : false;\n await syncKnownSpacePasswordProtectionCache({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n baseUrl: targetBaseUrl,\n space: input.item.space,\n passwordProtected,\n }).catch(() => undefined);\n return {\n ...input.item,\n passwordProtected,\n };\n } catch (error) {\n const passwordProtected =\n resolveKnownSpacePasswordProtectionFromMetaError(error);\n if (passwordProtected === null) {\n return input.item;\n }\n await syncKnownSpacePasswordProtectionCache({\n openMeldProfileId: input.openMeldProfile.openMeldProfileId,\n profileName: input.openMeldProfile.profileName,\n baseUrl: targetBaseUrl,\n space: input.item.space,\n passwordProtected,\n }).catch(() => undefined);\n return {\n ...input.item,\n passwordProtected,\n };\n }\n}\n\nfunction resolveKnownSpacePasswordProtectionFromMetaError(\n error: unknown\n): boolean | null {\n const reason = resolveSpacePasswordPromptReason(error);\n if (reason === \"required\" || reason === \"invalid\") {\n return true;\n }\n return null;\n}\n\nasync function syncKnownSpacePasswordProtectionCache(input: {\n openMeldProfileId: string;\n profileName: string;\n baseUrl: string;\n space: string;\n passwordProtected: boolean;\n}): Promise<void> {\n await upsertSpaceConfig({\n openMeldProfileId: input.openMeldProfileId,\n baseUrl: input.baseUrl,\n space: input.space,\n profileName: input.profileName,\n passwordProtected: input.passwordProtected,\n });\n}\n\nexport async function runSpaceSend(input: {\n contextSelection?: import(\"@openmeld/schemas/types\").ExecutionContextSelection;\n wakeTargets?: readonly string[];\n referenceTargets?: readonly string[];\n mentionTargets?: readonly string[];\n profile?: string;\n baseUrl?: string;\n space: string;\n filePaths?: readonly string[];\n password?: string;\n text?: string;\n stdin?: boolean;\n textFile?: string;\n plainText?: boolean;\n replyToSignalId?: string;\n view?: string;\n entryChecksHandled?: boolean;\n}) {\n assertDispatchOwnedRuntimePublicWriteAllowed({\n commandLabel: \"openmeld space send\",\n });\n\n const normalizedSpace = input.space.trim();\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\"sending a message\"),\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return;\n }\n const { runtime, presenter, interactive, baseUrl } = context;\n assertValidSpaceIdTarget({\n space: normalizedSpace,\n resolvedView: runtime.resolvedView,\n });\n\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n await emitSpaceCommandPreflight({\n presenter,\n command: \"send\",\n profile: openMeldProfile,\n baseUrl,\n resolvedView: runtime.resolvedView,\n });\n if (runtime.resolvedView === \"agent\") {\n presenter.line({\n code: \"space.send.profile_consistency_hint\",\n text: \"Profile guard: keep profile consistent unless intentional switch.\",\n });\n }\n const text = await resolveSpaceSendText({\n allowEmpty: (input.filePaths?.length ?? 0) > 0,\n text: input.text,\n stdin: input.stdin,\n file: input.textFile,\n });\n if (runtime.resolvedView === \"agent\") {\n const workflowAckHint = resolveWorkflowAckHint(text);\n if (workflowAckHint) {\n presenter.line({\n code: \"space.send.owner_directive_ack_hint\",\n text: workflowAckHint,\n });\n }\n }\n try {\n await runSend({\n contextSelection: input.contextSelection,\n wakeTargets: input.wakeTargets,\n referenceTargets: input.referenceTargets,\n mentionTargets: input.mentionTargets,\n profile: openMeldProfile.openMeldProfileId,\n baseUrl,\n space: normalizedSpace,\n filePaths: input.filePaths,\n password: input.password,\n plainText: input.plainText === true,\n replyToSignalId: input.replyToSignalId,\n text,\n openMeldProfile,\n view: input.view,\n });\n } catch (error) {\n emitSpaceFailureNextStep({\n presenter,\n command: \"send\",\n error,\n profileId: openMeldProfile.openMeldProfileId,\n resolvedView: runtime.resolvedView,\n });\n throw error;\n }\n}\n\nexport async function runSpaceHistory(input: {\n profile?: string;\n baseUrl?: string;\n space: string;\n password?: string;\n limit: number;\n brief?: boolean;\n json: boolean;\n rawStream?: boolean;\n view?: string;\n afterSignalId?: string;\n aroundSignalId?: string;\n beforeCount?: number;\n afterCount?: number;\n fromProfileIds?: readonly string[];\n kinds?: readonly NonNullable<SpaceSignalsReadQuery[\"kinds\"]>[number][];\n entryChecksHandled?: boolean;\n}) {\n const context = await prepareAuthenticatedSpaceCommandContext({\n profile: input.profile,\n baseUrl: input.baseUrl,\n view: input.view,\n promptMessage: buildCommandAuthenticationPromptMessage(\n \"reading space history\"\n ),\n entryChecksHandled: input.entryChecksHandled,\n });\n if (context.status === \"cancelled\") {\n return;\n }\n const { runtime, interactive, baseUrl } = context;\n assertValidSpaceIdTarget({\n space: input.space,\n resolvedView: runtime.resolvedView,\n });\n\n const openMeldProfile = await resolveOpenMeldProfileForSpaceCommand({\n openMeldProfileId: input.profile,\n resolvedView: runtime.resolvedView,\n interactive,\n });\n await runTail({\n profile: openMeldProfile.openMeldProfileId,\n baseUrl,\n space: input.space,\n password: input.password,\n limit: input.limit,\n brief: input.brief === true,\n json: input.json,\n rawStream: input.rawStream === true,\n openMeldProfile,\n view: input.view,\n afterSignalId: input.afterSignalId,\n aroundSignalId: input.aroundSignalId,\n beforeCount: input.beforeCount,\n afterCount: input.afterCount,\n fromProfileIds: input.fromProfileIds,\n kinds: input.kinds,\n });\n}\n\nasync function resolveJoinAfterCreate(\n joinInput: boolean | undefined,\n allowPrompt: boolean\n): Promise<boolean> {\n if (joinInput !== undefined) {\n return joinInput;\n }\n if (!allowPrompt) {\n return false;\n }\n const confirmed = await confirm({\n message: \"Join this space now?\",\n initialValue: true,\n });\n if (isCancel(confirmed)) {\n cancel(\"Cancelled.\");\n return false;\n }\n return confirmed;\n}\n\nfunction toKnownSpaceOptionFromDeleteTarget(\n target: SpaceDeleteTarget\n): KnownSpaceOption {\n return {\n source: \"local\",\n space: target.space,\n ...(target.baseUrl ? { baseUrl: target.baseUrl } : {}),\n ...(target.name === undefined ? {} : { name: target.name }),\n ...(target.creatorProfileName === undefined\n ? {}\n : { creatorProfileName: target.creatorProfileName }),\n ...(target.creatorProfileId === undefined\n ? {}\n : { creatorProfileId: target.creatorProfileId }),\n ...(target.creatorOwnerUserId === undefined\n ? {}\n : { creatorOwnerUserId: target.creatorOwnerUserId }),\n ...(target.creatorKind === undefined\n ? {}\n : { creatorKind: target.creatorKind }),\n };\n}\n\nfunction resolveSpaceListEmptyMessage(\n visibilityScope: KnownSpaceVisibilityScope\n): string {\n if (visibilityScope === \"owner\") {\n return formatInlineOpenMeldCliCommands(\n \"No spaces found across the profiles you own yet. Create one with: `openmeld space create --name <name> --visibility private`\"\n );\n }\n return formatInlineOpenMeldCliCommands(\n \"No spaces found for this profile yet. Create one with: `openmeld space create --name <name> --visibility private`\"\n );\n}\n\nfunction buildDeleteConfirmationMessage(input: {\n targets: SpaceDeleteTarget[];\n currentProfileId: string;\n currentProfileName: string;\n}): string {\n const count = input.targets.length;\n const title =\n count === 1\n ? \"Delete this space permanently?\"\n : `Delete ${String(count)} spaces permanently?`;\n const lines = [\n title,\n \"This action permanently deletes space data for everyone.\",\n ];\n\n for (const [index, target] of input.targets.entries()) {\n const knownSpace = toKnownSpaceOptionFromDeleteTarget(target);\n lines.push(\n `${String(index + 1)}. ${formatKnownSpaceName({\n space: knownSpace,\n resolvedView: \"human\",\n currentProfileId: input.currentProfileId,\n command: \"delete\",\n })}`\n );\n lines.push(\n ...formatKnownSpaceDetailLines({\n space: knownSpace,\n resolvedView: \"human\",\n currentProfileId: input.currentProfileId,\n currentProfileName: input.currentProfileName,\n detailVariant: \"delete_confirmation\",\n command: \"delete\",\n }).map((line) => ` ${line}`)\n );\n }\n\n return lines.join(\"\\n\");\n}\n\nfunction buildHumanSpaceDeleteBlockedError(input: {\n error: unknown;\n target: SpaceDeleteTarget;\n resolvedView: \"human\" | \"agent\";\n}): Error | null {\n if (input.resolvedView !== \"human\") {\n return null;\n }\n const parsed = parseHttpErrorMessage(input.error);\n if (!parsed) {\n return null;\n }\n\n const status = resolveUpstreamStatus(parsed);\n if (status !== 403) {\n return null;\n }\n if (!isSpaceDeleteOwnerRestrictionError(parsed)) {\n return null;\n }\n\n const spaceName = normalizeDisplayValue(input.target.name, \"this space\");\n return new Error(\n `Delete blocked: this human profile can only delete its own spaces or your owned agent-created spaces (${spaceName}).`\n );\n}\n\nfunction isSpaceDeleteOwnerRestrictionError(input: {\n code: string;\n message: string;\n}): boolean {\n const code = input.code.toLowerCase();\n const message = input.message.toLowerCase();\n return (\n code === \"space.human_confirmation_required\" ||\n message.includes(\"owner human confirmation\") ||\n message.includes(\"only owner human can delete\") ||\n message.includes(\"only space creator can delete\")\n );\n}\n\nfunction renderHumanSpaceDeleteBlockedCard(input: {\n presenter: ReturnType<typeof createPresenter>;\n target: SpaceDeleteTarget;\n}): void {\n renderHumanErrorCard({\n message:\n \"You can only delete a Space created by this profile or by one of your own agents.\",\n nextStep: \"Switch to the profile that created the Space, then try again.\",\n presenter: input.presenter,\n title: \"Space couldn't be deleted\",\n codePrefix: \"space.delete.blocked\",\n });\n}\n\nfunction normalizeDeleteConfirmationValue(value: unknown): string {\n return String(value ?? \"\")\n .trim()\n .toLowerCase();\n}\n\nfunction isDeleteConfirmationValue(value: unknown): boolean {\n return normalizeDeleteConfirmationValue(value) === \"delete\";\n}\n\nasync function deleteSpace(input: {\n openMeldProfile: OpenMeldProfile;\n baseUrl: string;\n space: string;\n password?: string;\n approvedAgentCreatorProfileId?: string;\n}): Promise<{ spaceId: string; deleted: true }> {\n const endpoint = toSpaceDeleteUrl(input.baseUrl, input.space);\n const headers = await buildOpenMeldProfileRequestHeadersWithAuth({\n requestUrl: endpoint,\n openMeldProfile: input.openMeldProfile,\n spacePassword: input.password,\n });\n const approvedAgentCreatorProfileId = normalizeOptionalString(\n input.approvedAgentCreatorProfileId\n );\n if (approvedAgentCreatorProfileId) {\n headers[\"content-type\"] = \"application/json\";\n }\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.delete\",\n init: {\n method: \"DELETE\",\n headers,\n ...(approvedAgentCreatorProfileId\n ? {\n body: JSON.stringify({\n approvedAgentCreatorProfileId,\n }),\n }\n : {}),\n },\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n let parsed: { spaceId?: unknown; deleted?: unknown };\n try {\n parsed = JSON.parse(raw) as { spaceId?: unknown; deleted?: unknown };\n } catch {\n throw new Error(\"deleteSpace received invalid response payload\");\n }\n if (\n typeof parsed.spaceId !== \"string\" ||\n parsed.spaceId.trim().length === 0 ||\n parsed.deleted !== true\n ) {\n throw new Error(\"deleteSpace received invalid response payload\");\n }\n return {\n spaceId: parsed.spaceId.trim(),\n deleted: true as const,\n };\n}\n\nasync function _updateSpaceCursorMentionAlias(input: {\n requestContext: import(\"@openmeld/schemas/types\").OpenMeldRequestContext;\n baseUrl: string;\n space: string;\n password?: string;\n mentionAlias: string;\n}): Promise<{\n role?: string;\n mentionAlias?: string;\n}> {\n const endpoint = toSpaceCursorUrl(\n input.baseUrl,\n input.space,\n input.requestContext.actorContext.openMeldProfileId\n );\n const headers = await buildOpenMeldRequestContextHeadersWithAuth({\n requestUrl: endpoint,\n requestContext: input.requestContext,\n spacePassword: input.password,\n });\n headers[\"content-type\"] = \"application/json\";\n\n const response = await fetchSpaceRequestWithTimeout({\n url: endpoint,\n operation: \"space.update_cursor_alias\",\n init: {\n method: \"PATCH\",\n headers,\n body: JSON.stringify({ mentionAlias: input.mentionAlias }),\n },\n });\n const raw = await response.text();\n if (!response.ok) {\n throw new Error(`HTTP ${response.status}: ${raw}`);\n }\n\n return parseSpaceCursorResponse({\n raw,\n endpoint,\n operation: \"updateSpaceCursor\",\n });\n}\n\nfunction isHumanInteractiveSpaceRuntime(\n runtime: Awaited<ReturnType<typeof resolveRuntimeContext>>\n): boolean {\n return runtime.resolvedView === \"human\" && canUseInteractivePrompts(runtime);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAGA,MAAM,8BAA8B,IAAI,OAAO,CAAC,CAAC,IAAI,CAAC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;EACA;EACA;EACA;EACA;EACA;CACF;CACA,MAAM;EACJ;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;CACF;CACA,MAAM;EACJ;EACA;EACA;EACA;EACA;EACA;CACF;CACA,SAAS;EACP;EACA;EACA;EACA;CACF;CACA,UAAU;EACR;EACA;EACA;EACA;CACF;CACA,cAAc;EACZ;EACA;EACA;EACA;CACF;CACA,iBAAiB;EACf;EACA;EACA;EACA;EACA;EACA;CACF;CACA,QAAQ;EACN;EACA;EACA;EACA;CACF;CACA,SAAS;EACP;EACA;EACA;EACA;CACF;CACA,QAAQ;EACN;EACA;EACA;EACA;CACF;CACA,UAAU;EACR;EACA;EACA;EACA;EACA;CACF;CACA,OAAO;EACL;EACA;EACA;EACA;EACA;CACF;CACA,aAAa;CACb,YAAY;CACZ,oBAAoB;CACpB,gBAAgB;EACd;EACA;EACA;EACA;EACA;CACF;CACA,OAAO;EACL;EACA;EACA;EACA;EACA;EACA;EACA;CACF;CACA,QAAQ;EACN;EACA;EACA;EACA;EACA;CACF;CACA,MAAM;EAAC;EAAgB;EAAiB;CAAa;AACvD;AAEF,MAAM,qBAAgE;CACpE,MAAM;CACN,QACE;CACF,MAAM;CACN,OACE;CACF,MAAM;CACN,SACE;CACF,UACE;CACF,cACE;CACF,iBACE;CACF,QACE;CACF,SACE;CACF,QACE;CACF,UACE;CACF,OACE;CACF,aACE;CACF,YACE;CACF,oBACE;CACF,gBACE;CACF,OACE;CACF,QACE;CACF,MAAM;AACR;AAEA,MAAM,sBAAsB;CAC1B;CACA;CACA;AACF;AAEA,MAAM,mBAAmB,CACvB,mHACF;AAEA,SAAgB,uBAAuB,OAI9B;CACP,IAAI,MAAM,iBAAiB,SACzB;CAGF,MAAM,UAAU,KAAK;EACnB,MAAM,SAAS,MAAM,QAAQ;EAC7B,SAAS,2BACP,+BAA+B,MAAM,OAAO,CAC9C;CACF,CAAC;AACH;AAEA,SAAgB,0BACd,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