@songsid/agend 2.4.0-beta.22 → 2.4.0-beta.24

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 (284) hide show
  1. package/dist/agent-cli-instructions.md +4 -3
  2. package/dist/agent-cli.js +32 -2
  3. package/dist/agent-cli.js.map +1 -1
  4. package/dist/agent-file-read.js +2 -2
  5. package/dist/agent-file-read.js.map +1 -1
  6. package/dist/agent-whats-new.js +17 -1
  7. package/dist/agent-whats-new.js.map +1 -1
  8. package/dist/auth-api.d.ts +2 -0
  9. package/dist/auth-api.js +5 -2
  10. package/dist/auth-api.js.map +1 -1
  11. package/dist/authority/web-authority.d.ts +17 -3
  12. package/dist/authority/web-authority.js +56 -3
  13. package/dist/authority/web-authority.js.map +1 -1
  14. package/dist/backend/claude-code.d.ts +15 -0
  15. package/dist/backend/claude-code.js +8 -3
  16. package/dist/backend/claude-code.js.map +1 -1
  17. package/dist/backend/claude-mcp-carry.d.ts +63 -0
  18. package/dist/backend/claude-mcp-carry.js +242 -0
  19. package/dist/backend/claude-mcp-carry.js.map +1 -0
  20. package/dist/build-provenance.json +1 -1
  21. package/dist/channel/mcp-tools.js +15 -7
  22. package/dist/channel/mcp-tools.js.map +1 -1
  23. package/dist/classic-channel-manager.d.ts +1 -1
  24. package/dist/classic-channel-manager.js +2 -2
  25. package/dist/classic-channel-manager.js.map +1 -1
  26. package/dist/config-validator.js +6 -0
  27. package/dist/config-validator.js.map +1 -1
  28. package/dist/contact-auth-api.js +3 -1
  29. package/dist/contact-auth-api.js.map +1 -1
  30. package/dist/contact-auth-service.js +1 -1
  31. package/dist/contact-auth-service.js.map +1 -1
  32. package/dist/contact-auth-store.d.ts +28 -2
  33. package/dist/contact-auth-store.js +72 -4
  34. package/dist/contact-auth-store.js.map +1 -1
  35. package/dist/contact-change-proposals.d.ts +18 -1
  36. package/dist/contact-change-proposals.js +38 -4
  37. package/dist/contact-change-proposals.js.map +1 -1
  38. package/dist/contact-state-view.d.ts +103 -0
  39. package/dist/contact-state-view.js +80 -0
  40. package/dist/contact-state-view.js.map +1 -0
  41. package/dist/daemon.d.ts +11 -0
  42. package/dist/daemon.js +66 -15
  43. package/dist/daemon.js.map +1 -1
  44. package/dist/dashboard-permissions.d.ts +8 -0
  45. package/dist/dashboard-permissions.js +8 -0
  46. package/dist/dashboard-permissions.js.map +1 -1
  47. package/dist/delivery-outbox.d.ts +15 -1
  48. package/dist/delivery-outbox.js +60 -2
  49. package/dist/delivery-outbox.js.map +1 -1
  50. package/dist/fleet-manager.d.ts +157 -15
  51. package/dist/fleet-manager.js +522 -78
  52. package/dist/fleet-manager.js.map +1 -1
  53. package/dist/general-knowledge/skills/admin/SKILL.md +52 -0
  54. package/dist/general-knowledge/skills/concepts/SKILL.md +31 -21
  55. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +6 -0
  56. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +6 -3
  57. package/dist/general-knowledge/skills/fleet-config/SKILL.md +3 -3
  58. package/dist/general-knowledge/skills/hub/SKILL.md +6 -1
  59. package/dist/general-knowledge/skills/instance-lifecycle/SKILL.md +1 -1
  60. package/dist/general-knowledge/skills/task-board/SKILL.md +17 -0
  61. package/dist/general-knowledge/skills/web-appearance/SKILL.md +4 -0
  62. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +75 -12
  63. package/dist/general-knowledge/skills/worker-collaboration/SKILL.md +1 -1
  64. package/dist/general-role.d.ts +1 -1
  65. package/dist/general-role.js +1 -0
  66. package/dist/general-role.js.map +1 -1
  67. package/dist/hub/client.js +6 -1
  68. package/dist/hub/client.js.map +1 -1
  69. package/dist/hub/compose/member.d.ts +2 -1
  70. package/dist/hub/compose/member.js +3 -2
  71. package/dist/hub/compose/member.js.map +1 -1
  72. package/dist/hub/compose/server.js +2 -1
  73. package/dist/hub/compose/server.js.map +1 -1
  74. package/dist/hub/http/compose.js +5 -0
  75. package/dist/hub/http/compose.js.map +1 -1
  76. package/dist/hub/protocol.d.ts +21 -0
  77. package/dist/hub/protocol.js +3 -0
  78. package/dist/hub/protocol.js.map +1 -1
  79. package/dist/hub/question-close-model.d.ts +17 -0
  80. package/dist/hub/question-close-model.js +7 -0
  81. package/dist/hub/question-close-model.js.map +1 -0
  82. package/dist/hub/representative.d.ts +5 -0
  83. package/dist/hub/representative.js +51 -1
  84. package/dist/hub/representative.js.map +1 -1
  85. package/dist/hub/rooms/direct-view.js +1 -0
  86. package/dist/hub/rooms/direct-view.js.map +1 -1
  87. package/dist/hub/rooms/types.d.ts +1 -1
  88. package/dist/hub/rooms.d.ts +3 -0
  89. package/dist/hub/rooms.js +27 -1
  90. package/dist/hub/rooms.js.map +1 -1
  91. package/dist/hub/server.js +6 -1
  92. package/dist/hub/server.js.map +1 -1
  93. package/dist/hub/types.d.ts +2 -2
  94. package/dist/human-delivery-receipts.d.ts +12 -2
  95. package/dist/human-delivery-receipts.js +19 -4
  96. package/dist/human-delivery-receipts.js.map +1 -1
  97. package/dist/instance-lifecycle.d.ts +2 -0
  98. package/dist/instance-lifecycle.js +29 -1
  99. package/dist/instance-lifecycle.js.map +1 -1
  100. package/dist/instructions.d.ts +1 -1
  101. package/dist/instructions.js +1 -1
  102. package/dist/instructions.js.map +1 -1
  103. package/dist/locale.js +110 -12
  104. package/dist/locale.js.map +1 -1
  105. package/dist/needs-you-hub.d.ts +3 -0
  106. package/dist/needs-you-hub.js +31 -5
  107. package/dist/needs-you-hub.js.map +1 -1
  108. package/dist/needs-you.d.ts +16 -1
  109. package/dist/needs-you.js +7 -1
  110. package/dist/needs-you.js.map +1 -1
  111. package/dist/office-share-page.js +2 -2
  112. package/dist/office-share-page.js.map +1 -1
  113. package/dist/office-share.js +2 -1
  114. package/dist/office-share.js.map +1 -1
  115. package/dist/outbound-handlers.d.ts +4 -0
  116. package/dist/outbound-handlers.js +69 -11
  117. package/dist/outbound-handlers.js.map +1 -1
  118. package/dist/outbound-schemas.d.ts +5 -1
  119. package/dist/outbound-schemas.js +10 -7
  120. package/dist/outbound-schemas.js.map +1 -1
  121. package/dist/public-web-gateway.js +21 -0
  122. package/dist/public-web-gateway.js.map +1 -1
  123. package/dist/reply-buttons-controller.d.ts +2 -1
  124. package/dist/reply-buttons-controller.js +1 -1
  125. package/dist/reply-buttons-controller.js.map +1 -1
  126. package/dist/request-context-compatibility.d.ts +20 -0
  127. package/dist/request-context-compatibility.js +74 -0
  128. package/dist/request-context-compatibility.js.map +1 -0
  129. package/dist/request-context-protocol.d.ts +137 -0
  130. package/dist/request-context-protocol.js +38 -0
  131. package/dist/request-context-protocol.js.map +1 -0
  132. package/dist/request-context-store.d.ts +25 -0
  133. package/dist/request-context-store.js +137 -0
  134. package/dist/request-context-store.js.map +1 -0
  135. package/dist/scheduler/db.js +26 -0
  136. package/dist/scheduler/db.js.map +1 -1
  137. package/dist/scheduler/task-board-text.d.ts +2 -0
  138. package/dist/scheduler/task-board-text.js +12 -0
  139. package/dist/scheduler/task-board-text.js.map +1 -1
  140. package/dist/scheduler/task-board.d.ts +102 -2
  141. package/dist/scheduler/task-board.js +242 -24
  142. package/dist/scheduler/task-board.js.map +1 -1
  143. package/dist/scheduler/task-files.d.ts +80 -0
  144. package/dist/scheduler/task-files.js +357 -0
  145. package/dist/scheduler/task-files.js.map +1 -0
  146. package/dist/settings-api.d.ts +2 -0
  147. package/dist/settings-api.js +6 -1
  148. package/dist/settings-api.js.map +1 -1
  149. package/dist/settings-baseline.d.ts +1 -0
  150. package/dist/settings-baseline.js +1 -1
  151. package/dist/settings-baseline.js.map +1 -1
  152. package/dist/settings-effect.d.ts +2 -0
  153. package/dist/settings-effect.js +5 -1
  154. package/dist/settings-effect.js.map +1 -1
  155. package/dist/task-attach-client.d.ts +43 -0
  156. package/dist/task-attach-client.js +125 -0
  157. package/dist/task-attach-client.js.map +1 -0
  158. package/dist/task-board-tool.d.ts +12 -0
  159. package/dist/task-board-tool.js +107 -6
  160. package/dist/task-board-tool.js.map +1 -1
  161. package/dist/task-file-limits.d.ts +15 -0
  162. package/dist/task-file-limits.js +21 -0
  163. package/dist/task-file-limits.js.map +1 -0
  164. package/dist/tool-permissions.d.ts +32 -0
  165. package/dist/tool-permissions.js +64 -1
  166. package/dist/tool-permissions.js.map +1 -1
  167. package/dist/types.d.ts +6 -0
  168. package/dist/ui/accounts-keepalive.js +2 -1
  169. package/dist/ui/agent-details-settings.js +7 -5
  170. package/dist/ui/agent-who-can-use-strings.js +125 -0
  171. package/dist/ui/agent-who-can-use.js +238 -0
  172. package/dist/ui/chat-activity.js +2 -1
  173. package/dist/ui/chat-pins.js +2 -1
  174. package/dist/ui/claude-credentials.js +2 -1
  175. package/dist/ui/contact-auth-strings.js +28 -17
  176. package/dist/ui/contact-authorizations.js +6 -4
  177. package/dist/ui/contact-needs.js +6 -1
  178. package/dist/ui/contact-permissions.js +6 -4
  179. package/dist/ui/contact-tool-groups.js +1 -1
  180. package/dist/ui/contact-verify-need.js +46 -0
  181. package/dist/ui/fleet-cache.js +2 -1
  182. package/dist/ui/fleet-office-card.js +23 -5
  183. package/dist/ui/fleet-office-editor.js +5 -5
  184. package/dist/ui/fleet-office-pack.d.ts +10 -0
  185. package/dist/ui/fleet-office-pack.js +65 -2
  186. package/dist/ui/fleet-office-skin.js +52 -14
  187. package/dist/ui/fleet-office-store.js +33 -2
  188. package/dist/ui/fleet-office-vehicles.js +130 -0
  189. package/dist/ui/fleet-office-zones.js +27 -10
  190. package/dist/ui/fleet-office.js +128 -40
  191. package/dist/ui/fleet-org.js +6 -1
  192. package/dist/ui/fleet-tab-icons.js +19 -0
  193. package/dist/ui/fleet-task-activity.js +11 -83
  194. package/dist/ui/fleet-task-archive.js +111 -0
  195. package/dist/ui/fleet-task-card.js +6 -4
  196. package/dist/ui/fleet-task-common.js +2 -2
  197. package/dist/ui/fleet-task-edit.js +8 -1
  198. package/dist/ui/fleet-task-files.js +196 -0
  199. package/dist/ui/fleet-task-md.js +98 -0
  200. package/dist/ui/fleet-task-menu.js +1 -1
  201. package/dist/ui/fleet-task-stats.js +2 -2
  202. package/dist/ui/fleet-task-view.js +14 -9
  203. package/dist/ui/fleet-tasks.js +42 -18
  204. package/dist/ui/fleet-usage.js +2 -1
  205. package/dist/ui/hub-admin-overview.js +2 -1
  206. package/dist/ui/hub-agent-intro.js +2 -1
  207. package/dist/ui/hub-assistant-admin.js +2 -1
  208. package/dist/ui/hub-directory-notices.js +2 -1
  209. package/dist/ui/hub-enrolment-code.js +2 -1
  210. package/dist/ui/hub-my-agents.js +2 -1
  211. package/dist/ui/hub-quick-pairing.js +2 -1
  212. package/dist/ui/hub-role-audit.js +2 -1
  213. package/dist/ui/hub-role-forms.js +3 -2
  214. package/dist/ui/hub-role-view.js +3 -2
  215. package/dist/ui/hub-roles.js +2 -1
  216. package/dist/ui/hub-room-agent-strings.js +2 -1
  217. package/dist/ui/hub-room-list.js +2 -1
  218. package/dist/ui/hub-room-owner-requests.js +2 -1
  219. package/dist/ui/hub-room-pins.js +2 -1
  220. package/dist/ui/hub-room-strings.js +2 -2
  221. package/dist/ui/hub-room-thread.js +1 -1
  222. package/dist/ui/log-row.js +4 -3
  223. package/dist/ui/office-share-dialog.js +2 -1
  224. package/dist/ui/office-share-page.js +2 -1
  225. package/dist/ui/page-share-dialog.js +3 -2
  226. package/dist/ui/panel-chat.js +2 -1
  227. package/dist/ui/panel-details.js +5 -2
  228. package/dist/ui/panel-fleet.js +10 -5
  229. package/dist/ui/panel-hub.js +2 -1
  230. package/dist/ui/panel-needs.js +34 -6
  231. package/dist/ui/panel-notices.js +2 -1
  232. package/dist/ui/panel-runtimes.js +2 -1
  233. package/dist/ui/panel-settings.js +15 -1
  234. package/dist/ui/panel-windows-cli.js +3 -2
  235. package/dist/ui/runtime-cli-install.js +2 -1
  236. package/dist/ui/settings-appearance.js +2 -1
  237. package/dist/ui/settings-guests.js +4 -3
  238. package/dist/ui/settings-hub-member-address.js +2 -1
  239. package/dist/ui/settings-hub-setup.js +2 -1
  240. package/dist/ui/settings-hub-web-address.js +2 -1
  241. package/dist/ui/settings-hub.js +2 -1
  242. package/dist/ui/settings-registry.js +1 -0
  243. package/dist/ui/settings-shared-strings.js +9 -0
  244. package/dist/ui/settings-shared.js +6 -1
  245. package/dist/ui/settings-update.js +2 -1
  246. package/dist/ui/settings-web-authority.js +2 -1
  247. package/dist/ui/shared/agent-sheet.js +2 -1
  248. package/dist/ui/shared/app-i18n.js +2 -2
  249. package/dist/ui/shared/app-needs.js +8 -1
  250. package/dist/ui/shared/app-session.js +4 -3
  251. package/dist/ui/shared/app-shell.js +6 -2
  252. package/dist/ui/shared/app.css +93 -11
  253. package/dist/ui/shared/chat-strings.js +4 -4
  254. package/dist/ui/shared/chat-time.js +7 -4
  255. package/dist/ui/shared/clock-text.js +57 -0
  256. package/dist/ui/shared/device-roles.js +6 -5
  257. package/dist/ui/shared/instance-nav.js +17 -22
  258. package/dist/ui/shared/task-board.css +64 -0
  259. package/dist/ui/shared/usage-dialog.js +2 -1
  260. package/dist/ui/shared/view-strings.js +0 -14
  261. package/dist/ui/shared/web-authorize.js +3 -2
  262. package/dist/ui/subagent-row.js +2 -1
  263. package/dist/web-api.d.ts +18 -2
  264. package/dist/web-api.js +159 -27
  265. package/dist/web-api.js.map +1 -1
  266. package/dist/web-login.d.ts +6 -1
  267. package/dist/web-login.js +8 -3
  268. package/dist/web-login.js.map +1 -1
  269. package/dist/web-office-acts.d.ts +16 -0
  270. package/dist/web-office-acts.js +27 -9
  271. package/dist/web-office-acts.js.map +1 -1
  272. package/dist/web-office-pack-read.js +1 -1
  273. package/dist/web-office-pack-read.js.map +1 -1
  274. package/dist/web-office-skins.d.ts +5 -3
  275. package/dist/web-office-skins.js +20 -16
  276. package/dist/web-office-skins.js.map +1 -1
  277. package/dist/web-session-authorization.d.ts +3 -0
  278. package/dist/web-session-authorization.js +1 -1
  279. package/dist/web-session-authorization.js.map +1 -1
  280. package/dist/web-settings-patch.d.ts +27 -0
  281. package/dist/web-settings-patch.js +67 -0
  282. package/dist/web-settings-patch.js.map +1 -1
  283. package/dist/workflow-templates/default.md +1 -0
  284. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
- import { prepareContactChange } from "./contact-change-proposals.js";
1
+ import { prepareContactChange, shortContactTicketId } from "./contact-change-proposals.js";
2
+ import { contactStateView, ownContactRequestsView } from "./contact-state-view.js";
2
3
  import { detectMonitoringPlatform } from './host-monitoring-defaults.js';
3
4
  import { SharedDefaultAdoption } from "./shared-default-adoption.js";
4
5
  import { scopedDefaultModel } from "./model-defaults.js";
@@ -50,7 +51,7 @@ import { loginNoticeMode, normalizeNoticeDelivery, setNoticeMode } from "./notic
50
51
  import { DEFAULT_REPLY_TRIGGERS } from "./reply-triggers.js";
51
52
  import { WorkingRecoveryCoordinator, WORKING_RECOVERY_KIND, buildWorkingRecoveryPrompt } from "./working-recovery.js";
52
53
  import { PUBLIC_TUNNEL_TOKEN_ENV, PUBLIC_TUNNEL_TOKEN_HINT, normalizePublicTunnelToken } from "./public-tunnel-config.js";
53
- import { humanOwnerObjectId, webHumanOrigin } from "./human-delivery-receipts.js";
54
+ import { humanOwnerObjectId, webHumanOrigin, isWebSessionIdentity } from "./human-delivery-receipts.js";
54
55
  import { SettingsBaselines } from "./settings-baseline.js";
55
56
  import { hubPilotTrustSettings } from "./hub-pilot-trust-settings.js";
56
57
  import { hubMembershipSettings } from "./hub-membership-settings.js";
@@ -395,7 +396,7 @@ import { DeviceLoginRequests } from "./web-device-login.js";
395
396
  import { findSigninKnownEntry, addSigninKnownDevice } from "./web-signin-device.js";
396
397
  import { adminKey, HOST_ADMIN_KEY, isOutsideLinkOwner, OUTSIDE_LINK_OWNER, OUTSIDE_LINK_RETRY_MS, OUTSIDE_OWN_CLOSES, outsideDuration, outsideTimer, TOTP_SIGNIN_OVER_PUBLIC_LINK, TOTP_STEP_SECONDS, WEB_REMOTE_ACCESS_FILE, WebRemoteAccess } from "./web-remote-access.js";
397
398
  import { evaluateSettingsRole } from "./authority/settings-role.js";
398
- import { authorityNow, classifyWebPeer, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
399
+ import { authorityNow, classifyWebPeer, evaluateGuestIdentity, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
399
400
  import { AuthorityStateStore, namedLinkLastTurnedOff } from "./authority/authority-state.js";
400
401
  import { SessionAuthorizations } from "./authority/session-authorizations.js";
401
402
  import { SessionAuthorizationRequests } from "./web-session-authorization.js";
@@ -421,6 +422,7 @@ import { APPLY_FLEET_TARGET, ApplyJobStore, viewOf, } from "./apply-job.js";
421
422
  import { kiroHome } from "./backend/kiro-kas-store.js";
422
423
  import { CHAT_PROFILE_LOGIN_BACKENDS, claudeStoreEnded, credentialHomeSpec, credentialProfileHome, credentialProfileLaunch, credentialProfileLogin, credentialProfileLoginCommand, credentialProfileStoreHome, credentialSwitchCarriesConversation, credentialSwitchStartsFresh, instanceCredentialProfile, listConfiguredProfiles, resolveCredentialProfile } from "./backend/credential-profile.js";
423
424
  import { carryClaudeConversation } from "./backend/claude-carry.js";
425
+ import { carryClaudeMcpServers, claudeJsonFor, dismissClaudeMcpMissing, recordClaudeMcpBeforeSwitch } from "./backend/claude-mcp-carry.js";
424
426
  import { classicProfile, mergeBackendOptions, profileKey, profileName, profileOf, readClassicBindings, readClassicBindingsStrict } from "./classic-bindings.js";
425
427
  import { ACCOUNT_CLIS, PROFILE_CLIS, accountUsage, buildAccountsView, profilesOnDisk } from "./accounts-view.js";
426
428
  import { accountFolderExists, addAccountProfile, removeAccountProfile } from "./accounts-profiles.js";
@@ -637,6 +639,7 @@ function callbackPrefix(callbackData) {
637
639
  }
638
640
  const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
639
641
  const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
642
+ const CLASSIC_MODE_CALLBACK_PREFIX = "classic-mode:";
640
643
  const MODEL_SELECT_CALLBACK_PREFIX = "model-select:";
641
644
  const EFFORT_SELECT_CALLBACK_PREFIX = "effort-select:";
642
645
  const BACKEND_SELECT_CALLBACK_PREFIX = "backend-select:";
@@ -659,6 +662,13 @@ const KIRO_MIGRATE_CALLBACK_PREFIX = "kiro-migrate:";
659
662
  /** M-3140: Update now on a Hub-recommended-version notice in General ("hub-update:" + 32 hex + ":update" = 50 bytes). */
660
663
  const HUB_UPDATE_CALLBACK_PREFIX = "hub-update:";
661
664
  const HUB_SHARING_CALLBACK_PREFIX = "hub-share:";
665
+ /** M-3680: a held contact request's card in General ("contact-ticket:" + 32 hex + ":approve" = 55 bytes, under Telegram's 64). */
666
+ const CONTACT_TICKET_PREFIX = "contact-ticket:";
667
+ /** How many requests' cards are remembered (one card per request; a decided one is forgotten at once). */
668
+ const HELD_CARDS_KEPT = 512;
669
+ /** A held request's card, retired after it was decided elsewhere (the dashboard, Needs you, another card) or closed. */
670
+ const heldCardOutcome = (state) => t(state === "approved" ? "contactHeld.approvedElsewhere"
671
+ : state === "declined" ? "contactHeld.declinedElsewhere" : state === "expired" ? "contactHeld.expired" : "contactHeld.closed");
662
672
  const HUB_FLEET_UPDATE_CALLBACK_PREFIX = "hub-fleet-update:";
663
673
  const KIRO_RECONCILE_CALLBACK_PREFIX = "kiro-reconcile:";
664
674
  /** #2692: a fleet admin's Approve / Reject on an agent's pending skin-pack change, in General. */
@@ -2826,7 +2836,7 @@ export class FleetManager {
2826
2836
  : this.getInstanceAdapterId(agent) === actor.adapter_id && this.isFleetAdmin(actor.user_id, actor.adapter_id),
2827
2837
  }, caller.agent, receiptId),
2828
2838
  attachExposures: api => this.attachHubMemberExposures(api),
2829
- attachAttention: (read, retry) => this.attachHubExecutionAttention(read, retry),
2839
+ attachAttention: (read, retry, close) => this.attachHubExecutionAttention(read, retry, close),
2830
2840
  updates: { idle: () => this.hubUpdateIdle(), busy: () => !!this.webUpdateOwned || isUpdateInProgress(this.dataDir),
2831
2841
  canInstall: () => this.hubUpdateCanInstall(), launch: (row, control) => this.launchHubUpdate(row, control),
2832
2842
  active: id => this.hubUpdateOwned?.id === id, outcome: row => this.hubUpdateOutcome(row), notify: n => this.recordHubUpdateNotice(n) },
@@ -3868,6 +3878,7 @@ export class FleetManager {
3868
3878
  signInKeepAlive = null;
3869
3879
  hubExecutionAttention = null;
3870
3880
  /** M-3632: the member's "Try again" for a held Hub question (null while no member runs). */
3881
+ hubHeldClose = null;
3871
3882
  hubHeldRetry = null;
3872
3883
  missedOfflineStore = null;
3873
3884
  configHistory = null;
@@ -4580,6 +4591,7 @@ export class FleetManager {
4580
4591
  generalLocation: input => this.previewGeneralLocation(input),
4581
4592
  hubMembership: raw => hubMembershipSettings(raw),
4582
4593
  hubPageSharing: raw => hubPageSharingSettings(raw),
4594
+ guestDerivedScopes: () => this.guestDerivedScopes(),
4583
4595
  hostMonitoringAvailable: () => this.hostMonitoringAvailable(),
4584
4596
  hubPilotTrust: raw => hubPilotTrustSettings(raw, RUNNING_AGEND_VERSION),
4585
4597
  // S3c (S-55): a Hub exposure publish's confirmation summary, while a member composition is attached.
@@ -4986,7 +4998,7 @@ export class FleetManager {
4986
4998
  } };
4987
4999
  }
4988
5000
  /**
4989
- * alpha.2 (M-2300; #2973's agent requests, junsion's §6): on a fleet with no chat connection there is no General to
5001
+ * alpha.2 (M-2300; #2973's agent requests, a colleague's §6): on a fleet with no chat connection there is no General to
4990
5002
  * post an agent's Windows request in — it waited for `agend settings confirm` on the host. Its owner (decision
4991
5003
  * 28c2d3a3: the `agend web --code` session on this computer, web-verified) now sees and decides it from the web's
4992
5004
  * Needs you. The authority is asked from the request each time, and again at execution by the store (`current`):
@@ -6081,6 +6093,8 @@ export class FleetManager {
6081
6093
  const badge = row?.payload.contactTicket;
6082
6094
  const ticket = badge?.id ? outbox.contactAuthorizations.get(badge.id) : undefined;
6083
6095
  if (ticket && ticket.deliveryId === row?.deliveryId) {
6096
+ // M-3716: the approval notice waits for this delivery to settle.
6097
+ queueMicrotask(() => this.sweepContactAuthorizationOutcomes());
6084
6098
  const state = event.state === "delivered" ? "delivered" : ["failed", "uncertain", "cancelled", "reconciliation_pending"].includes(event.state ?? "") ? "unknown" : "approved";
6085
6099
  for (const instance of new Set([ticket.source, ticket.target])) {
6086
6100
  this.webChatHistory?.updateContactTicket(instance, ticket.id, state);
@@ -6350,6 +6364,15 @@ export class FleetManager {
6350
6364
  sender: ticket.source, text: ticket.message, ts: new Date().toISOString(), contactTicket: { id: ticket.id, state: "approved" } });
6351
6365
  }
6352
6366
  this.emitSseEvent("contact-auth", { instance, ...(ticketId ? { ticketId } : {}), revision });
6367
+ // M-3680: a card never stands in the way of the hold (or a decision) that called this.
6368
+ if (ticket) {
6369
+ try {
6370
+ this.syncHeldTicketCard(ticket);
6371
+ }
6372
+ catch (err) {
6373
+ this.logger?.warn?.({ err: err?.message, ticket: ticket.id }, "Held contact request card failed");
6374
+ }
6375
+ }
6353
6376
  this.needsYou?.poke();
6354
6377
  this.emitSseEvent("needs", { items: this.needsYouItems() });
6355
6378
  },
@@ -6477,6 +6500,26 @@ export class FleetManager {
6477
6500
  return this.contactPermissions(name, actor);
6478
6501
  }
6479
6502
  /** General can propose only. The platform callback supplies the human actor. */
6503
+ /** M-3693: what contact permissions hold now, for General (read-only; no write, no identity computed here). */
6504
+ contactState(agent) {
6505
+ const store = this.contactService().host.store;
6506
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll?.() ?? []).map(room => room.instanceName)])];
6507
+ return contactStateView({
6508
+ store, names: () => names, now: () => Date.now(), generation: n => this.contactGeneration(n),
6509
+ label: n => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || n,
6510
+ roomMode: n => { const room = this.contactRoom(n); return room ? room.restrictedMode ? "restricted" : "legacy" : undefined; },
6511
+ }, agent ? { agent } : {});
6512
+ }
6513
+ /** M-3716: the caller's OWN held requests (delivery_status { held_requests: true }); the caller is the authenticated agent. */
6514
+ ownContactRequests(agent) {
6515
+ const outbox = this.deliveryOutbox;
6516
+ if (!outbox?.isOpen)
6517
+ return { requests: [], note: "Contact requests are unavailable right now." };
6518
+ return ownContactRequestsView(outbox.contactAuthorizations.requestsBy(agent), {
6519
+ label: n => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || n,
6520
+ delivery: ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined,
6521
+ });
6522
+ }
6480
6523
  async requestContactChange(requester, raw, callerCurrent) {
6481
6524
  if (!callerCurrent() || this.fleetConfig?.instances[requester]?.general_topic !== true)
6482
6525
  throw Error("general-only");
@@ -6563,6 +6606,123 @@ export class FleetManager {
6563
6606
  await this.retireNonceButtons(entry, entry.messageId ?? data.messageId, text);
6564
6607
  return true;
6565
6608
  }
6609
+ /**
6610
+ * M-3680 (the user, 11-25): a fleet agent's send held for approval reaches an administrator in General on the target's
6611
+ * Discord or Telegram, as a card with Approve once / Decline — until then a held request had no chat path (the live
6612
+ * Needs you message lists it without buttons). One card per request. Whoever clicks must be one who may decide it
6613
+ * (ContactAuthService.view(...).canDecide, read at the click); the decision is theirs, never the bot's. A request decided
6614
+ * anywhere else (the web, another card) retires its card. #4448 (R21079937): a ClassicBot room's request to a fleet agent
6615
+ * gets the same card, in the General of the target's connection; a room's request to anything else gets none.
6616
+ */
6617
+ /** Requests whose card was posted or tried: forgotten when the request is decided, and at most HELD_CARDS_KEPT. */
6618
+ heldTicketCards;
6619
+ syncHeldTicketCard(ticket) {
6620
+ const posted = (this.heldTicketCards ??= new Set());
6621
+ if (ticket.state !== "pending") {
6622
+ posted.delete(ticket.id);
6623
+ for (const [nonce, entry] of [...(this.pendingNonceButtons ?? [])]) {
6624
+ if (entry.prefix !== CONTACT_TICKET_PREFIX || entry.contactTicketId !== ticket.id)
6625
+ continue;
6626
+ this.pendingNonceButtons.delete(nonce);
6627
+ if (entry.timer)
6628
+ clearTimeout(entry.timer);
6629
+ // #4438 review: a card still being posted has no message yet; postHeldTicketCard retires it once it has one.
6630
+ if (entry.messageId)
6631
+ void this.retireNonceButtons(entry, entry.messageId, heldCardOutcome(ticket.state));
6632
+ }
6633
+ return;
6634
+ }
6635
+ // A fleet agent's send, or (R21079937, 11-25: a room's request was in no list and had no card) a ClassicBot room's send
6636
+ // to a fleet agent — the card goes to the General of the TARGET's connection either way (postHeldTicketCard).
6637
+ const room = !this.fleetConfig?.instances[ticket.source] && !!this.contactRoom(ticket.source);
6638
+ if (posted.has(ticket.id) || (!this.fleetConfig?.instances[ticket.source] && !room) || (room && !this.fleetConfig?.instances[ticket.target]))
6639
+ return;
6640
+ posted.add(ticket.id);
6641
+ for (const old of posted) {
6642
+ if (posted.size <= HELD_CARDS_KEPT)
6643
+ break;
6644
+ posted.delete(old);
6645
+ }
6646
+ void this.postHeldTicketCard(ticket).catch((err) => this.logger?.warn?.({ err: err?.message, ticket: ticket.id }, "Could not post a held contact request to General"));
6647
+ }
6648
+ async postHeldTicketCard(ticket) {
6649
+ const adapter = this.contactAdapter(ticket.target);
6650
+ if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6651
+ return;
6652
+ const routes = Object.keys(this.fleetConfig?.instances ?? {}).flatMap(n => {
6653
+ const route = this.settingsGeneralRoute(n, adapter.type, new Set());
6654
+ return route && route.adapterId === adapter.id && route.adapter === adapter ? [{ name: n, ...route }] : [];
6655
+ });
6656
+ if (routes.length !== 1) {
6657
+ this.logger.info({ ticket: ticket.id, routes: routes.length }, "No single General for a held contact request's card");
6658
+ return;
6659
+ }
6660
+ // A ClassicBot room by its own name (its display name, else its channel's), as Fleet lists it.
6661
+ const route = routes[0], label = (n) => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || this.contactRoom(n)?.name || n;
6662
+ const shortId = /^R[a-f0-9]{8}-/.test(ticket.id) ? ticket.id.slice(0, 9) : ticket.id;
6663
+ const left = Date.parse(ticket.expiresAt) - Date.now();
6664
+ const text = ticket.message.length > 300 ? `${ticket.message.slice(0, 299)}…` : ticket.message;
6665
+ const posting = this.postNonceButtonPromptOrThrow({ prefix: CONTACT_TICKET_PREFIX, alertType: "clear_confirm", instanceName: route.name,
6666
+ adapter: route.adapter, adapterId: route.adapterId, chatId: route.chatId, threadId: route.topic,
6667
+ message: [t("contactHeld.title", label(ticket.source), label(ticket.target)), `> ${text.replace(/\n+/g, " ")}`,
6668
+ t("contactHeld.meta", shortId, ticket.verb, left < 2 * 3_600_000 ? t("contactHeld.minutes", Math.max(1, Math.round(left / 60_000))) : t("contactHeld.hours", Math.round(left / 3_600_000))),
6669
+ t("contactHeld.hint")].join("\n"),
6670
+ choices: [{ action: "approve", label: t("contactHeld.approve") }, { action: "decline", label: t("contactHeld.decline") }],
6671
+ expiredText: t("contactHeld.expired"), timeoutMs: Math.max(60_000, Math.min(left, 24 * 3_600_000)),
6672
+ extra: { contactTicketId: ticket.id } });
6673
+ // The entry is armed before the platform answers (postNonceButtonPromptOrThrow sets it synchronously).
6674
+ const entry = [...this.pendingNonceButtons.values()].find(e => e.prefix === CONTACT_TICKET_PREFIX && e.contactTicketId === ticket.id);
6675
+ const nonce = await posting;
6676
+ // #4438 review: decided elsewhere, or expired, while the card was being posted — it had no message to retire then; it
6677
+ // has one now. A card still armed for a request still waiting stays.
6678
+ if (!entry?.messageId)
6679
+ return;
6680
+ const fresh = this.contactService().host.store.get(ticket.id), armed = this.pendingNonceButtons.get(nonce) === entry;
6681
+ if (armed && fresh?.state === "pending")
6682
+ return;
6683
+ if (armed) {
6684
+ this.pendingNonceButtons.delete(nonce);
6685
+ if (entry.timer)
6686
+ clearTimeout(entry.timer);
6687
+ }
6688
+ await this.retireNonceButtons(entry, entry.messageId, !fresh || fresh.state === "pending" ? t("contactHeld.expired") : heldCardOutcome(fresh.state));
6689
+ }
6690
+ async handleContactTicketCallback(data, adapterId, adapter) {
6691
+ if (!data.callbackData.startsWith(CONTACT_TICKET_PREFIX))
6692
+ return false;
6693
+ const person = data.userId && adapter && this.adapters.get(adapterId) === adapter && adapter.id === adapterId
6694
+ && (adapter.type === "discord" || adapter.type === "telegram") && data.userId !== adapter.getBotUserId?.()
6695
+ ? { platform: adapter.type, adapterId, userId: data.userId, label: data.username || data.userId } : null;
6696
+ const service = this.contactService();
6697
+ const mayDecide = (entry) => {
6698
+ const ticket = person && entry.contactTicketId ? service.host.store.get(entry.contactTicketId) : undefined;
6699
+ try {
6700
+ return !!ticket && !!person && service.view(ticket, person).canDecide;
6701
+ }
6702
+ catch {
6703
+ return false;
6704
+ }
6705
+ };
6706
+ const claimed = this.consumeNonceCallback(CONTACT_TICKET_PREFIX, /^contact-ticket:([0-9a-f]{32}):(approve|decline)$/, data, adapterId, adapter, undefined, (_user, entry) => !!entry.messageId && !this.webPromptClicks.has(data) && mayDecide(entry));
6707
+ if (claimed === null)
6708
+ return false;
6709
+ if (claimed === "consumed")
6710
+ return true;
6711
+ const { entry, action } = claimed;
6712
+ const ticket = entry.contactTicketId ? service.host.store.get(entry.contactTicketId) : undefined;
6713
+ let text = t("contactHeld.closed");
6714
+ if (ticket?.state === "pending" && person) {
6715
+ try {
6716
+ const decided = this.decideContactAuthorization(ticket.id, { revision: ticket.revision, decision: action === "approve" ? "approve-once" : "decline" }, person);
6717
+ text = t(decided.state === "approved" ? "contactHeld.approved" : "contactHeld.declined", person.label);
6718
+ }
6719
+ catch {
6720
+ text = t("contactHeld.failed");
6721
+ }
6722
+ }
6723
+ await this.retireNonceButtons(entry, entry.messageId ?? data.messageId, text);
6724
+ return true;
6725
+ }
6566
6726
  contactAuthorization(id, actor) {
6567
6727
  const service = this.contactService(), ticket = service.host.store.get(id);
6568
6728
  if (!ticket)
@@ -6594,14 +6754,30 @@ export class FleetManager {
6594
6754
  if (!outbox?.isOpen || this.shuttingDown)
6595
6755
  return;
6596
6756
  try {
6597
- outbox.contactAuthorizations.notifyOutcomes(ticket => {
6598
- outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(ticket.state === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
6599
- });
6757
+ outbox.contactAuthorizations.notifyOutcomes((ticket, outcome) => {
6758
+ if (outcome === "declined" || outcome === "expired") {
6759
+ outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
6760
+ return;
6761
+ }
6762
+ // M-3716 (the user, 11-25): the requester learns who approved it, when, and whether the target has it.
6763
+ const by = ticket.decidedBy, when = ticket.decidedAt ? `${ticket.decidedAt.slice(0, 16).replace("T", " ")} UTC` : "";
6764
+ const who = !by ? "?" : by.platform === "host" ? t("contactProposal.host")
6765
+ : `${by.label}${getLocale() === "zh-TW" ? "(" : " ("}${by.platform === "discord" ? "Discord" : "Telegram"}${getLocale() === "zh-TW" ? ")" : ")"}`;
6766
+ outbox.admitSystemNotice(ticket.source, `contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
6767
+ }, ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined);
6600
6768
  }
6601
6769
  catch (err) {
6602
6770
  this.logger.error({ err }, "Contact outcome notice sweep failed; durable state will retry");
6603
6771
  }
6604
6772
  }
6773
+ /**
6774
+ * M-3710: how many contact requests wait, and since when — no ids, people or text. Needs you tells an admin session with
6775
+ * no verified person behind it (contactActor null) that they exist, so a request is never silently missing there.
6776
+ */
6777
+ contactPendingCount() {
6778
+ const pending = this.contactService().host.store.pending();
6779
+ return { count: pending.length, since: pending.reduce((at, ticket) => Math.min(at, Date.parse(ticket.createdAt) || at), Date.now()) };
6780
+ }
6605
6781
  contactNeeds(actor) {
6606
6782
  const service = this.contactService();
6607
6783
  const pending = service.host.store.pending()
@@ -6737,7 +6913,7 @@ export class FleetManager {
6737
6913
  if (!item.authority || !state)
6738
6914
  return item;
6739
6915
  const authority = this.receiptAuthorityNow(item.authority, state);
6740
- return { ...item, authority, ...(authority.downgraded ? { source_instance: "human:web:unknown" } : {}) };
6916
+ return { ...item, authority, ...(authority.downgraded && !isWebSessionIdentity(item.origin?.web_identity) ? { source_instance: "human:web:unknown" } : {}) };
6741
6917
  };
6742
6918
  // #1641: a sender that sees only `queued` cannot tell "next in line" from "the target is stuck": say which.
6743
6919
  return {
@@ -9466,10 +9642,11 @@ export class FleetManager {
9466
9642
  throw Error("Contact origin storage unavailable");
9467
9643
  if (contactStore && (this.contactRoom(instanceName)?.restrictedMode === true || contactStore.origin(instanceName))) {
9468
9644
  const authority = origin.authority;
9469
- const actor = origin.platform === "web" ? (authority?.kind === "web-verified" ? authority.actor : null)
9645
+ const identity = origin.platform === "web" && isWebSessionIdentity(origin.web_identity) ? origin.web_identity : undefined;
9646
+ const actor = origin.platform === "web" ? identity ?? (authority?.kind === "web-verified" ? authority.actor : null)
9470
9647
  : { adapter_id: origin.adapter_id, user_id: origin.user_id };
9471
9648
  const adapter = actor?.adapter_id ? this.adapters.get(actor.adapter_id) : undefined;
9472
- const platform = origin.platform === "web" ? adapter?.type : origin.platform;
9649
+ const platform = origin.platform === "web" ? identity?.platform ?? adapter?.type : origin.platform;
9473
9650
  const person = actor?.adapter_id && actor.user_id
9474
9651
  && (platform === "discord" || platform === "telegram" || (actor.adapter_id === "host" && actor.user_id === "operator"))
9475
9652
  ? { platform: actor.adapter_id === "host" ? "host" : platform,
@@ -9665,6 +9842,16 @@ export class FleetManager {
9665
9842
  isFleetAdmin(userId, adapterId) {
9666
9843
  return this.adminGate(userId, adapterId) === "ok";
9667
9844
  }
9845
+ /**
9846
+ * Free mode at /start is the fleet-admin allowlist of the adapter that owns the room (adminGate).
9847
+ * A ClassicBot admin (`classicBot.yaml` admin_users) is not enough. A stub with no fleet and no worlds
9848
+ * is not an admin: the menu offers Restricted only.
9849
+ */
9850
+ canChooseFreeMode(userId, adapterId) {
9851
+ if (!this.fleetConfig && !this.worlds)
9852
+ return false;
9853
+ return this.adminGate(userId, adapterId) === "ok";
9854
+ }
9668
9855
  /** Whether this adapter has any fleet admin at all (an empty allowlist means the admin commands are off). */
9669
9856
  hasFleetAdmins(adapterId) {
9670
9857
  return (this.adminListOf(adapterId)?.length ?? 0) > 0;
@@ -11541,6 +11728,25 @@ export class FleetManager {
11541
11728
  this.writeFreshStartMarker(name);
11542
11729
  return null;
11543
11730
  }
11731
+ // M-3749: the agent's own MCP servers (user scope, and local scope for its folder) go along too, merged — whatever
11732
+ // becomes of the conversation. A failure is logged; the next launch's check tells the agent what it lacks.
11733
+ if (sw.backend === "claude-code") {
11734
+ const profileDir = (profile) => profile ? credentialProfileHome(this.dataDir, sw.backend, profile) : null;
11735
+ try {
11736
+ // What it has in the profile it leaves now (added this session too), so the next launch can say what is missing.
11737
+ recordClaudeMcpBeforeSwitch({ instanceDir: this.getInstanceDir(name), configDir: claudeConfigDirFor(profileDir(sw.from)),
11738
+ jsonPath: claudeJsonFor(profileDir(sw.from)), workingDirectory: sw.workingDirectory ?? "" });
11739
+ const mcp = carryClaudeMcpServers({ fromProfileDir: profileDir(sw.from), toProfileDir: profileDir(sw.to), workingDirectory: sw.workingDirectory ?? "" });
11740
+ const where = { name, from: sw.from ?? "default", to: sw.to ?? "default" };
11741
+ if (!mcp.carried)
11742
+ this.logger.warn({ ...where, reason: mcp.reason }, "MCP servers not carried to the new credential profile");
11743
+ else if (mcp.user.length || mcp.local.length || mcp.keptTarget.length)
11744
+ this.logger.info({ ...where, user: mcp.user, local: mcp.local, keptTarget: mcp.keptTarget }, "MCP servers carried to the new credential profile");
11745
+ }
11746
+ catch (err) {
11747
+ this.logger.warn({ name, err: err.message }, "MCP servers not carried to the new credential profile");
11748
+ }
11749
+ }
11544
11750
  let sessionId = null;
11545
11751
  try {
11546
11752
  sessionId = readFileSync(join(this.getInstanceDir(name), "session-id"), "utf-8");
@@ -12373,6 +12579,17 @@ export class FleetManager {
12373
12579
  return { enabled: cfg?.enabled === true, chat: cfg?.chat !== false, explicit: cfg?.grants !== undefined, instances: Object.keys(this.fleetConfig?.instances ?? {}).sort(), rooms, connections, guests,
12374
12580
  audit: this.guestAudit() };
12375
12581
  }
12582
+ /**
12583
+ * M-3734: each guest's agents now, as guestOverview lists them (#1920's derived access while no grants are saved) — the
12584
+ * scopes "Start from today's guests" on an agent's page is checked against, as it is admitted and as it applies.
12585
+ */
12586
+ guestDerivedScopes() {
12587
+ const out = Object.create(null);
12588
+ for (const g of this.guestOverview().guests)
12589
+ if (g.scope.length)
12590
+ out[`${g.adapterId}:${g.userId}`] = [...g.scope];
12591
+ return out;
12592
+ }
12376
12593
  /** #2667: the ClassicBot rooms' instance names now — what a settings save's validation knows besides fleet.yaml's instances. */
12377
12594
  classicRoomNames() {
12378
12595
  return (this.classicChannels?.getAll() ?? []).map((r) => r.instanceName);
@@ -12616,7 +12833,8 @@ export class FleetManager {
12616
12833
  // guest there) — most guests are not on the host's network. Its closing withdraws that audience (revokeAudience).
12617
12834
  const open = this.publicWebLink?.openSignin() ?? null;
12618
12835
  // One code per account (a new one replaces only its own); at the cap, refused — never another guest's evicted.
12619
- const login = codes.issue({ epoch: tokenEpoch(token), audiences: ["local", ...(open ? [open.exposureId] : [])],
12836
+ // M-3651: private — the account's DM, else this slash command's ephemeral answer, else withdrawn (below): verified at sign-in.
12837
+ const login = codes.issue({ epoch: tokenEpoch(token), audiences: ["local", ...(open ? [open.exposureId] : [])], private: true,
12620
12838
  recipient: { adapterId: owner.adapterId, userId: owner.userId, ...(ask.username ? { username: ask.username } : {}) } });
12621
12839
  if (!login) {
12622
12840
  await say(t("web.guest_busy"));
@@ -12785,7 +13003,7 @@ export class FleetManager {
12785
13003
  const current = () => !this.shuttingDown && this.webToken === token && this.adapters.get(account.adapterId) === adapter
12786
13004
  && this.guestRevokes === revokes && (this.guestAccountRevokes.get(key) ?? 0) === accountRevokes && this.guestSignInAllowed(account)
12787
13005
  && (!viaLink || linkOpen()) && this.returningDevices.current(device, tokenEpoch(token));
12788
- const issued = codes.issue({ epoch: tokenEpoch(token), recipient: account, audiences: [viaLink ? input.exposureId : "local"] });
13006
+ const issued = codes.issue({ epoch: tokenEpoch(token), recipient: account, audiences: [viaLink ? input.exposureId : "local"], private: true }); // M-3651: by DM only (withdrawn otherwise)
12789
13007
  if (!issued)
12790
13008
  return { kind: "limited", retryAfterMs: 60_000 }; // the guests' cap: never someone's evicted
12791
13009
  this.guestCodeInFlight.add(key);
@@ -15883,11 +16101,14 @@ export class FleetManager {
15883
16101
  }
15884
16102
  const channelName = msg.username || chatId;
15885
16103
  if (requestedBackend) {
15886
- // Advisory before the new-room policy is persisted, including direct /start BACKEND.
15887
- await msgAdapter?.sendText(chatId, this.getClassicStartWarning(requestedBackend));
15888
- // handleClassicStart binds the instance to this adapter authoritatively.
15889
- const reply = await this.handleClassicStart(chatId, channelName, msg.userId, undefined, msg.adapterId, requestedBackend);
15890
- await msgAdapter?.sendText(chatId, reply);
16104
+ // The backend is only half of /start. The room waits for Restricted or Free.
16105
+ await this.beginClassicModeSelection({
16106
+ command: "start",
16107
+ channelId: chatId,
16108
+ channelName,
16109
+ userId: msg.userId,
16110
+ respond: async (reply) => (await msgAdapter?.sendText(chatId, reply))?.messageId,
16111
+ }, msgAdapter ?? undefined, requestedBackend, msg.adapterId);
15891
16112
  }
15892
16113
  else if (msgAdapter) {
15893
16114
  await this.beginClassicBackendSelection({
@@ -20945,6 +21166,8 @@ export class FleetManager {
20945
21166
  return true;
20946
21167
  if (await this.handleContactChangeCallback(data, adapterId, adapter))
20947
21168
  return true;
21169
+ if (await this.handleContactTicketCallback(data, adapterId, adapter))
21170
+ return true;
20948
21171
  if (await this.handleSettingsChangeCallback(data, adapterId, adapter))
20949
21172
  return true;
20950
21173
  if (await this.handleKiroMigrateCallback(data, adapterId, adapter))
@@ -20979,6 +21202,8 @@ export class FleetManager {
20979
21202
  return true;
20980
21203
  if (await this.handleClassicBackendSelection(data))
20981
21204
  return true;
21205
+ if (await this.handleClassicModeSelection(data))
21206
+ return true;
20982
21207
  if (await this.handleModelSelection(data, adapterId))
20983
21208
  return true;
20984
21209
  if (await this.handleEffortSelection(data, adapterId))
@@ -21016,20 +21241,64 @@ export class FleetManager {
21016
21241
  this.needsPauseCache.delete(name);
21017
21242
  this.needsYou?.poke();
21018
21243
  }
21244
+ /** M-3749: the credential profile a Claude config dir belongs to, for people and agents: its name, or "default". */
21245
+ claudeProfileLabel(configDir) {
21246
+ const dir = resolvePath(configDir);
21247
+ return dirname(dir) === resolvePath(dirname(credentialProfileHome(this.dataDir, "claude-code", "x"))) ? basename(dir) : "default";
21248
+ }
21249
+ /**
21250
+ * M-3749: a launch found MCP servers the agent had under its previous profile and does not have now. Told to the agent
21251
+ * once per set (the outbox key), held until it is delivered; Needs you lists it from the daemon (instancesForNeeds).
21252
+ */
21253
+ onMcpMissing(name, missing) {
21254
+ if (!missing?.names.length)
21255
+ return;
21256
+ try {
21257
+ this.ensureDeliveryOutbox();
21258
+ const outbox = this.deliveryOutbox;
21259
+ if (!outbox)
21260
+ return;
21261
+ const digest = createHash("sha256").update(`${missing.fromConfigDir}\u0000${missing.toConfigDir}\u0000${missing.names.join(",")}`).digest("hex").slice(0, 16);
21262
+ const text = t("inst.mcp_missing", this.claudeProfileLabel(missing.fromConfigDir), this.claudeProfileLabel(missing.toConfigDir), missing.names.join(t("needs.mcp_missing_sep")));
21263
+ outbox.admitSystemNotice(name, `mcp-missing:${name}:${digest}`, text, new Date(missing.since));
21264
+ }
21265
+ catch (err) {
21266
+ this.logger.warn({ err, name }, "Could not queue the MCP-missing notice");
21267
+ }
21268
+ }
21269
+ /** M-3749: a person dismissed an agent's missing-MCP item (web or chat Acknowledge). false: nothing was outstanding. */
21270
+ acknowledgeMcpMissing(name) {
21271
+ const daemon = this.daemons.get(name);
21272
+ if (daemon?.dismissMcpMissing)
21273
+ return daemon.dismissMcpMissing();
21274
+ dismissClaudeMcpMissing(this.getInstanceDir(name));
21275
+ return false;
21276
+ }
21019
21277
  /** The list for the web: every world's items, and those of instances with no world (#1386 §5.0). */
21020
21278
  needsYouItems() {
21021
21279
  return this.needsYou?.webItems() ?? [];
21022
21280
  }
21023
- /** Enabled member composition supplies only a local attention reader, never an approval/execution callback. */
21024
- attachHubExecutionAttention(read, retry = null) {
21281
+ /** Enabled member composition supplies held-work readers and explicit owner retry/close operations. */
21282
+ attachHubExecutionAttention(read, retry = null, close = undefined) {
21025
21283
  this.hubExecutionAttention = read;
21026
21284
  this.hubHeldRetry = read ? retry : null;
21285
+ this.hubHeldClose = read ? close ?? null : null;
21027
21286
  this.needsYou?.poke();
21028
21287
  }
21029
21288
  /**
21030
21289
  * M-3632: Needs you → "Try again" on held Hub work (`hub:hold:<row>`). The question goes back through the member's whole
21031
21290
  * hand-off, including the Hub's begin lease; nothing is delivered without it.
21032
21291
  */
21292
+ async closeHubHeld(itemId, actor) {
21293
+ const item = this.hubExecutionAttention?.().find(i => `hub:${i.id}` === itemId && i.kind === "hold");
21294
+ if (!item || !this.hubHeldClose)
21295
+ return { status: 404, code: "not-found" };
21296
+ if (!this.contactAdminOf(item.agent, actor))
21297
+ return { status: 403, code: "forbidden" };
21298
+ const code = await this.hubHeldClose(item.id);
21299
+ this.needsYou?.poke();
21300
+ return { status: code === "closed" || code === "answered" ? 200 : code === "not-found" ? 404 : 503, code };
21301
+ }
21033
21302
  retryHubHeld(itemId) {
21034
21303
  const id = itemId.startsWith("hub:") ? itemId.slice(4) : itemId;
21035
21304
  if (!this.hubHeldRetry || !id.startsWith("hold:"))
@@ -21289,6 +21558,7 @@ export class FleetManager {
21289
21558
  signIn: pauseReason === "auth" ? this.signInFor(name) : null,
21290
21559
  modelSwitch: this.modelObservationForInstance(name)?.active ?? null,
21291
21560
  usageHold: this.daemons.get(name)?.usageHold?.() ?? null,
21561
+ mcpMissing: (() => { const m = this.daemons.get(name)?.mcpMissing?.(); return m ? { names: m.names, from: this.claudeProfileLabel(m.fromConfigDir), to: this.claudeProfileLabel(m.toConfigDir), since: m.since } : null; })(),
21292
21562
  nativeDeliveryHold: this.daemons.get(name)?.nativeDeliveryHold?.() ?? null,
21293
21563
  generalLocation: this.generalLocationAttention(name),
21294
21564
  paneRecovery: (() => {
@@ -21384,6 +21654,7 @@ export class FleetManager {
21384
21654
  id: m.id, instance: m.instance, owner: m.adapterId, username: m.username, place: m.place, preview: m.preview, since: m.since,
21385
21655
  })),
21386
21656
  acknowledgeMissed: (id, by) => this.missedOfflineStore?.acknowledge(id, by) ?? false,
21657
+ acknowledgeMcpMissing: instance => this.acknowledgeMcpMissing(instance),
21387
21658
  tasks: () => this.needsYouTaskItems(),
21388
21659
  backendSignIns: () => this.needsYouBackendSignIns(),
21389
21660
  signInKeepAlive: () => this.keepAliveAttention(),
@@ -21935,9 +22206,26 @@ export class FleetManager {
21935
22206
  * #1939 S1: the design's §3 for one web request (authority/web-authority.ts), with this fleet's admins, policy and
21936
22207
  * token; `instance` once the body has named it. Observe only: receipts record it, no agent acts on it yet.
21937
22208
  */
22209
+ /** A signed-in account is recognizable before verification; this supplies no action authority. */
22210
+ webSessionIdentity(session) {
22211
+ const owner = session.owner;
22212
+ if (owner) {
22213
+ const adapter = this.adapters.get(owner.adapterId) ?? this.worlds?.get(owner.adapterId)?.adapter;
22214
+ const channels = this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : []);
22215
+ const platform = adapter?.type ?? channels.find(channel => (channel.id ?? channel.type) === owner.adapterId)?.type;
22216
+ if (platform !== "discord" && platform !== "telegram")
22217
+ return;
22218
+ return Object.freeze({ platform, adapter_id: owner.adapterId, user_id: owner.userId, session_handle: session.handle });
22219
+ }
22220
+ if (session.tier === "admin" && (session.host === true || session.remote === "totp") && this.isWebOnlyFleet()) {
22221
+ return Object.freeze({ platform: "host", adapter_id: "host", user_id: "operator", session_handle: session.handle });
22222
+ }
22223
+ return;
22224
+ }
21938
22225
  webAuthority(input) {
21939
22226
  const state = this.webAuthorityState();
21940
- return evaluateWebAuthority({
22227
+ // M-3651: a guest's session is asked only whether it is its account, verified (`web-guest`, identity only).
22228
+ return (input.session?.tier === "guest" ? evaluateGuestIdentity : evaluateWebAuthority)({
21941
22229
  session: input.session, gateway: input.gateway, peer: input.peer,
21942
22230
  tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null,
21943
22231
  ...(input.instance !== undefined ? { target: { adapterId: this.getInstanceAdapterId(input.instance) } } : {}),
@@ -21975,6 +22263,42 @@ export class FleetManager {
21975
22263
  return { ok: false, refusal: check.refusal };
21976
22264
  const live = new Set(this.webSessions?.list(undefined, () => true).map(r => r.handle) ?? []);
21977
22265
  store.prune(a => a.epoch === state.epoch && now <= Math.min(a.until, a.authorizedAt + policy.maxSessionMs) && live.has(a.handle));
22266
+ const authorized = store.authorize(session.handle, session.owner, now, state.epoch, now + policy.maxSessionMs, peer);
22267
+ // M-3710: Needs you is projected per session — this one now sees the contact requests it may decide, not just their count.
22268
+ try {
22269
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
22270
+ }
22271
+ catch (err) {
22272
+ this.logger.warn({ err: err?.message }, "Needs you refresh after a web authorization failed");
22273
+ }
22274
+ return { ok: true, ...authorized };
22275
+ }
22276
+ /** M-3651 (auth-api's /auth/session): until when this guest session is verified as its account now; null when it is not. */
22277
+ guestVerifiedUntil(req, session) {
22278
+ if (session.tier !== "guest")
22279
+ return null;
22280
+ const v = this.webSessionAuthorization({ session, gateway: !!gatewayRequestContext(req), peer: webPeerOf(req) });
22281
+ return v.state === "verified" ? v.until : null;
22282
+ }
22283
+ /**
22284
+ * M-3651: a guest session that signed in with a code AgEnD delivered privately to its own account — recorded as that
22285
+ * account's authorization of it, judged by evaluateGuestIdentity (the switch, the links, "Only this computer", the token):
22286
+ * its messages then carry `web-guest`, who it is and never more. Only at sign-in: a guest is never sent a Confirm card.
22287
+ */
22288
+ authorizeGuestSession(session, peer, gateway) {
22289
+ const store = this.sessionAuthorizationStore();
22290
+ const state = this.webAuthorityState(), now = Date.now(), policy = webAuthorityPolicy(this.fleetConfig?.web);
22291
+ if (!store || !session.owner || session.tier !== "guest")
22292
+ return { ok: false, refusal: !store ? "disabled" : "no_account" };
22293
+ const check = evaluateGuestIdentity({
22294
+ session, gateway, peer, tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null, isAdmin: () => false,
22295
+ authorization: { handle: session.handle, owner: session.owner, authorizedAt: now, until: now + policy.maxSessionMs, epoch: state.epoch },
22296
+ policy: { ...policy, enabled: state.enabled, loopbackOnly: state.loopbackOnly, namedLink: state.namedLink, quickLink: state.quickLink }, epoch: state.epoch, now,
22297
+ });
22298
+ if (check.refusal)
22299
+ return { ok: false, refusal: check.refusal };
22300
+ const live = new Set(this.webSessions?.list(undefined, () => true).map(r => r.handle) ?? []);
22301
+ store.prune(a => a.epoch === state.epoch && now <= Math.min(a.until, a.authorizedAt + policy.maxSessionMs) && live.has(a.handle));
21978
22302
  return { ok: true, ...store.authorize(session.handle, session.owner, now, state.epoch, now + policy.maxSessionMs, peer) };
21979
22303
  }
21980
22304
  /**
@@ -21985,15 +22309,17 @@ export class FleetManager {
21985
22309
  * at once, with Not me (noteAuthorized). Re-verifying once that authorization has run out still takes the card.
21986
22310
  */
21987
22311
  authorizeSignedInSession(session, peer, gateway) {
21988
- if (session.tier !== "admin" || !session.owner || session.host)
22312
+ if ((session.tier !== "admin" && session.tier !== "guest") || !session.owner || session.host)
21989
22313
  return;
21990
- const r = this.authorizeWebSession(session, peer, gateway);
22314
+ // M-3651: a guest's private code verifies who it is (web-guest), never an admin's authority.
22315
+ const r = session.tier === "guest" ? this.authorizeGuestSession(session, peer, gateway) : this.authorizeWebSession(session, peer, gateway);
21991
22316
  if (!r.ok) {
21992
22317
  this.logger.info({ handle: session.handle, refusal: r.refusal }, "Web session signed in with a private code, not verified");
21993
22318
  return;
21994
22319
  }
21995
22320
  this.logger.info({ handle: session.handle, durable: r.durable }, "Web session verified at sign-in (a private code)");
21996
- void this.sessionAuthorizationRequests().noteAuthorized({ handle: session.handle, owner: session.owner, label: session.label, peer, until: Math.min(r.authorization.until, session.absoluteExpiry) })
22321
+ void this.sessionAuthorizationRequests().noteAuthorized({ handle: session.handle, owner: session.owner, label: session.label, peer, until: Math.min(r.authorization.until, session.absoluteExpiry),
22322
+ ...(session.tier === "guest" ? { guest: true } : {}) })
21997
22323
  .catch(err => this.logger.warn({ err: err?.message }, "Web sign-in notice failed"));
21998
22324
  }
21999
22325
  /**
@@ -22638,7 +22964,10 @@ export class FleetManager {
22638
22964
  return this.authorizationRequests;
22639
22965
  const adapterOf = (adapterId) => this.adapters.get(adapterId) ?? this.worlds.get(adapterId)?.adapter;
22640
22966
  // The host's clock, with its zone: the person may read the DM on a phone in another one.
22641
- const when = (ms) => new Date(ms).toLocaleString(undefined, { timeZoneName: "short" });
22967
+ // M-3730: zh-TW is a 24-hour clock (2026/11/25 00:19:00 [GMT+8]), never 上午12:19; English is unchanged.
22968
+ const when = (ms) => getLocale() === "zh-TW"
22969
+ ? new Date(ms).toLocaleString("zh-TW", { year: "numeric", month: "numeric", day: "numeric", hour: "2-digit", minute: "2-digit", second: "2-digit", hourCycle: "h23", timeZoneName: "short" })
22970
+ : new Date(ms).toLocaleString(undefined, { timeZoneName: "short" });
22642
22971
  const quickHost = () => { try {
22643
22972
  const u = this.publicWebLink?.openSignin()?.url;
22644
22973
  return u ? new URL(u).host : "?";
@@ -22700,7 +23029,7 @@ export class FleetManager {
22700
23029
  text: {
22701
23030
  ask: (c) => t("web_auth.card_ask", c.label, where(c.peer), when(c.askedAt), when(c.until)),
22702
23031
  confirmed: (c) => t("web_auth.card_confirmed", c.label, where(c.peer), when(c.until)),
22703
- signedIn: (c) => t("web_auth.signed_in", c.label, where(c.peer), when(c.until)),
23032
+ signedIn: (c) => t(c.guest ? "web_auth.signed_in_guest" : "web_auth.signed_in", c.label, where(c.peer), when(c.until)),
22704
23033
  signedInHint: () => t("web_auth.signed_in_hint"),
22705
23034
  denied: (c) => t("web_auth.card_denied", c.label),
22706
23035
  expired: (c) => t("web_auth.card_expired", c.label),
@@ -22834,7 +23163,7 @@ export class FleetManager {
22834
23163
  // #1827: a /steer or /btw reaches the agent as the web person who wrote it.
22835
23164
  chatId: this.getGroupIdForInstance(instance) || "", messageId: newWebMessageId(),
22836
23165
  username: opts.person?.name ?? WEB_NAME_FALLBACK, userId: opts.person?.userId ?? WEB_NAME_FALLBACK,
22837
- threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority),
23166
+ threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority, opts.identity),
22838
23167
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
22839
23168
  };
22840
23169
  };
@@ -30133,11 +30462,30 @@ export class FleetManager {
30133
30462
  return undefined;
30134
30463
  return t("classic.backend_not_installed", backend, installation.binary, installation.install);
30135
30464
  }
30136
- /** Coverage is not proven before launch; disclose the fallback without blocking an unsupported CLI. */
30137
- getClassicStartWarning(backend) {
30138
- return [t("classic.restricted_start_notice"), this.getMissingBackendWarning(backend)].filter(Boolean).join("\n\n");
30465
+ /** Discord buttons when the interaction can draw them; otherwise the adapter's own chooser. Never the backend select. */
30466
+ classicModePoster(data, adapter) {
30467
+ if (data.respondButtons)
30468
+ return (text, choices) => data.respondButtons(text, choices);
30469
+ if (adapter?.promptUser)
30470
+ return (text, choices) => adapter.promptUser(data.channelId, text, choices);
30471
+ return undefined;
30139
30472
  }
30140
- /** Handle Discord's required static slash choice, warning before a likely startup failure. */
30473
+ /** Where the finished start (and a hold notice) lands: the Discord interaction, or the Telegram menu message. */
30474
+ classicStartComplete(data, adapter) {
30475
+ if (data.retireButtons)
30476
+ return async (text) => { await data.retireButtons(text); };
30477
+ return async (text, messageId) => {
30478
+ if (messageId && adapter?.editMessageRemoveButtons) {
30479
+ try {
30480
+ await adapter.editMessageRemoveButtons(data.channelId, messageId, text);
30481
+ return;
30482
+ }
30483
+ catch { /* fall back to a new message */ }
30484
+ }
30485
+ await data.respond(text);
30486
+ };
30487
+ }
30488
+ /** Handle Discord's required static slash choice. The room waits for the mode menu. */
30141
30489
  async handleClassicStartSlash(data, adapterId) {
30142
30490
  return withSpawnHoldReply(text => data.respond(text), () => this.handleClassicStartSlashCore(data, adapterId));
30143
30491
  }
@@ -30157,15 +30505,10 @@ export class FleetManager {
30157
30505
  await data.respond(blocker);
30158
30506
  return;
30159
30507
  }
30160
- const warning = this.getClassicStartWarning(requestedBackend);
30161
- // Keep the deferred ephemeral response useful even if daemon startup later
30162
- // fails because the executable is absent. This is advisory, not a gate.
30163
- if (warning)
30164
- await data.respond(warning);
30165
- const reply = await this.handleClassicStart(data.channelId, data.channelName, data.userId, data.guildId, adapterId, requestedBackend);
30166
- await data.respond(warning ? `${warning}\n\n${reply}` : reply);
30508
+ // A missing binary is advisory and stays on the mode menu. The room is not created yet.
30509
+ await this.beginClassicModeSelection(data, undefined, requestedBackend, adapterId);
30167
30510
  }
30168
- /** Present platform-native backend choices, then start on selection or timeout. */
30511
+ /** Present platform-native backend choices. A choice opens the mode menu; a timeout or a failed menu creates nothing. */
30169
30512
  async beginClassicBackendSelection(data, adapter) {
30170
30513
  const adapterId = adapter.id;
30171
30514
  const blocker = this.validateClassicStart(data.channelId, data.userId, data.guildId, adapterId);
@@ -30178,18 +30521,7 @@ export class FleetManager {
30178
30521
  id: `${CLASSIC_BACKEND_CALLBACK_PREFIX}${nonce}:${choice.id}`,
30179
30522
  label: `${this.isBackendInstalled(choice.id) ? "✅" : "❌"} ${choice.label}`,
30180
30523
  }));
30181
- const complete = data.respondChoices
30182
- ? async (text) => { await data.respond(text); }
30183
- : async (text, messageId) => {
30184
- if (messageId && adapter.editMessageRemoveButtons) {
30185
- try {
30186
- await adapter.editMessageRemoveButtons(data.channelId, messageId, text);
30187
- return;
30188
- }
30189
- catch { /* fall back to a new message */ }
30190
- }
30191
- await data.respond(text);
30192
- };
30524
+ const complete = this.classicStartComplete(data, adapter);
30193
30525
  const timer = setTimeout(() => {
30194
30526
  // Timeout: cancel the selection — do NOT fall back to default.
30195
30527
  const p = this.pendingClassicStarts.get(nonce);
@@ -30201,27 +30533,38 @@ export class FleetManager {
30201
30533
  timer.unref?.();
30202
30534
  const pending = {
30203
30535
  channelId: data.channelId,
30204
- channelName: data.channelName,
30536
+ channelName: data.channelName || data.channelId,
30205
30537
  userId: data.userId,
30206
30538
  guildId: data.guildId,
30207
30539
  adapterId,
30208
30540
  timer,
30209
30541
  complete,
30542
+ phase: "backend",
30543
+ showMenu: this.classicModePoster(data, adapter),
30210
30544
  };
30211
30545
  this.pendingClassicStarts.set(nonce, pending);
30212
30546
  try {
30547
+ const prompt = t("classic.choose_backend");
30213
30548
  pending.messageId = data.respondChoices
30214
- ? await data.respondChoices(`${t("classic.choose_backend")}\n\n${t("classic.restricted_start_notice")}`, choices)
30215
- : await adapter.promptUser(data.channelId, `${t("classic.choose_backend")}\n\n${t("classic.restricted_start_notice")}`, choices);
30549
+ ? await data.respondChoices(prompt, choices)
30550
+ : await adapter.promptUser(data.channelId, prompt, choices);
30216
30551
  }
30217
30552
  catch (err) {
30218
- // A menu transport failure should not make /start unusable: consume the
30219
- // pending request and immediately use the configured default.
30220
- this.logger.warn({ err, channelId: data.channelId, adapterId }, "Classic backend menu failed; using default");
30221
- await this.finishClassicBackendSelection(nonce);
30553
+ // No silent default backend and no silent Restricted room.
30554
+ this.logger.warn({ err, channelId: data.channelId, adapterId }, "Classic backend menu failed; nothing created");
30555
+ await this.cancelClassicPending(nonce, t("classic.backend_menu_failed"));
30222
30556
  }
30223
30557
  }
30224
- /** Consume a selection callback. Returns true for all ClassicBot callback IDs, including stale ones. */
30558
+ /** Drop a pending /start without creating a room. */
30559
+ async cancelClassicPending(nonce, text) {
30560
+ const pending = this.pendingClassicStarts.get(nonce);
30561
+ if (!pending)
30562
+ return;
30563
+ this.pendingClassicStarts.delete(nonce);
30564
+ clearTimeout(pending.timer);
30565
+ await pending.complete(text, pending.messageId);
30566
+ }
30567
+ /** Consume a backend click. Returns true for every classic-backend id, including a stale one. */
30225
30568
  async handleClassicBackendSelection(data) {
30226
30569
  if (!data.callbackData.startsWith(CLASSIC_BACKEND_CALLBACK_PREFIX))
30227
30570
  return false;
@@ -30229,11 +30572,12 @@ export class FleetManager {
30229
30572
  if (!match)
30230
30573
  return true;
30231
30574
  const pending = this.pendingClassicStarts.get(match[1]);
30232
- if (!pending)
30575
+ if (!pending || pending.phase === "mode")
30233
30576
  return true;
30234
30577
  // Telegram keyboards are visible to everyone in a group. Only the user who
30235
- // issued /start may consume the pending selection.
30236
- if (data.userId && data.userId !== pending.userId)
30578
+ // issued /start may consume the pending selection. No user id fails closed:
30579
+ // choosing the backend is part of creating the room.
30580
+ if (!data.userId || data.userId !== pending.userId)
30237
30581
  return true;
30238
30582
  const callbackChannelId = data.threadId ?? data.chatId;
30239
30583
  if (callbackChannelId !== pending.channelId && data.chatId !== pending.channelId)
@@ -30241,25 +30585,125 @@ export class FleetManager {
30241
30585
  await this.finishClassicBackendSelection(match[1], match[2]);
30242
30586
  return true;
30243
30587
  }
30244
- /** Atomically claim one pending request so timeout/click races create at most one instance. */
30588
+ /** The backend is chosen. Retire that menu and ask for the mode. Nothing is registered here. */
30245
30589
  async finishClassicBackendSelection(nonce, backend) {
30246
30590
  const pending = this.pendingClassicStarts.get(nonce);
30247
- if (!pending)
30591
+ if (!pending || pending.phase === "mode")
30248
30592
  return;
30249
30593
  this.pendingClassicStarts.delete(nonce);
30250
30594
  clearTimeout(pending.timer);
30251
- const selectedBackend = isSelectableClassicBackend(backend) ? backend : undefined;
30252
- const effectiveBackend = selectedBackend
30253
- ?? this.classicChannels?.getDefaults().backend
30254
- ?? this.fleetConfig?.defaults?.backend
30255
- ?? "claude-code";
30256
- const warning = this.getClassicStartWarning(effectiveBackend);
30257
- // Show the warning before starting so it survives a missing-binary startup
30258
- // failure. The selected backend is still attempted as requested.
30259
- if (warning)
30260
- await pending.complete(warning, pending.messageId);
30261
- const reply = await withSpawnHoldReply(text => pending.complete(text, pending.messageId), () => this.handleClassicStart(pending.channelId, pending.channelName, pending.userId, pending.guildId, pending.adapterId, selectedBackend));
30262
- await pending.complete(warning ? `${warning}\n\n${reply}` : reply, pending.messageId);
30595
+ if (!isSelectableClassicBackend(backend)) {
30596
+ await pending.complete(t("classic.backend_required"), pending.messageId);
30597
+ return;
30598
+ }
30599
+ // The grant can be revoked while the backend menu is up. Do not offer a mode, or create a room, after that.
30600
+ const blocker = this.validateClassicStart(pending.channelId, pending.userId, pending.guildId, pending.adapterId);
30601
+ if (blocker) {
30602
+ await pending.complete(blocker, pending.messageId);
30603
+ return;
30604
+ }
30605
+ await pending.complete(t("classic.backend_chosen", backend), pending.messageId);
30606
+ await this.openClassicModeMenu(pending, backend);
30607
+ }
30608
+ /** After a backend is known (slash, `/start BACKEND`, or a backend click). The room waits for a mode click. */
30609
+ async beginClassicModeSelection(data, adapter, backend, adapterId) {
30610
+ const ownerId = adapterId ?? adapter?.id;
30611
+ const blocker = this.validateClassicStart(data.channelId, data.userId, data.guildId, ownerId);
30612
+ if (blocker) {
30613
+ await data.respond(blocker);
30614
+ return;
30615
+ }
30616
+ await this.openClassicModeMenu({
30617
+ channelId: data.channelId,
30618
+ channelName: data.channelName || data.channelId,
30619
+ userId: data.userId,
30620
+ guildId: data.guildId,
30621
+ adapterId: ownerId,
30622
+ complete: this.classicStartComplete(data, adapter),
30623
+ showMenu: this.classicModePoster(data, adapter),
30624
+ }, backend);
30625
+ }
30626
+ /** For a fleet admin, Free is first and labeled recommended. Restricted stays a button.
30627
+ * Anyone else sees only Restricted. Either way the room waits for a tap. */
30628
+ async openClassicModeMenu(origin, backend) {
30629
+ const free = this.canChooseFreeMode(origin.userId, origin.adapterId);
30630
+ const missing = this.getMissingBackendWarning(backend);
30631
+ const prompt = [missing, t(free ? "classic.choose_mode" : "classic.choose_mode_fixed")].filter(Boolean).join("\n\n");
30632
+ if (!origin.showMenu) {
30633
+ await origin.complete(t("classic.mode_menu_failed"));
30634
+ return;
30635
+ }
30636
+ const nonce = randomBytes(6).toString("hex");
30637
+ const restrictedChoice = {
30638
+ id: `${CLASSIC_MODE_CALLBACK_PREFIX}${nonce}:restricted`,
30639
+ label: t("classic.mode_restricted"),
30640
+ };
30641
+ const choices = free
30642
+ ? [{ id: `${CLASSIC_MODE_CALLBACK_PREFIX}${nonce}:free`, label: t("classic.mode_free_recommended") }, restrictedChoice]
30643
+ : [restrictedChoice];
30644
+ const timer = setTimeout(() => {
30645
+ const pending = this.pendingClassicStarts.get(nonce);
30646
+ if (!pending)
30647
+ return;
30648
+ this.pendingClassicStarts.delete(nonce);
30649
+ pending.complete(t("classic.mode_selection_expired"), pending.messageId).catch(() => { });
30650
+ }, CLASSIC_BACKEND_SELECTION_TIMEOUT_MS);
30651
+ timer.unref?.();
30652
+ const pending = {
30653
+ channelId: origin.channelId,
30654
+ channelName: origin.channelName || origin.channelId,
30655
+ userId: origin.userId,
30656
+ guildId: origin.guildId,
30657
+ adapterId: origin.adapterId,
30658
+ timer,
30659
+ complete: origin.complete,
30660
+ phase: "mode",
30661
+ backend,
30662
+ showMenu: origin.showMenu,
30663
+ };
30664
+ this.pendingClassicStarts.set(nonce, pending);
30665
+ try {
30666
+ pending.messageId = await origin.showMenu(prompt, choices);
30667
+ }
30668
+ catch (err) {
30669
+ this.logger.warn({ err, channelId: origin.channelId, adapterId: origin.adapterId }, "Classic mode menu failed; nothing created");
30670
+ await this.cancelClassicPending(nonce, t("classic.mode_menu_failed"));
30671
+ }
30672
+ }
30673
+ /** Consume a mode click. A Free click from anyone else is ignored and the menu stays up. */
30674
+ async handleClassicModeSelection(data) {
30675
+ if (!data.callbackData.startsWith(CLASSIC_MODE_CALLBACK_PREFIX))
30676
+ return false;
30677
+ const match = data.callbackData.match(/^classic-mode:([0-9a-f]+):(restricted|free)$/);
30678
+ if (!match)
30679
+ return true;
30680
+ const pending = this.pendingClassicStarts.get(match[1]);
30681
+ if (!pending || pending.phase !== "mode")
30682
+ return true;
30683
+ // Same identity rule as the backend click. A missing user id must not settle
30684
+ // Restricted or Free, including Free opened by a fleet admin.
30685
+ if (!data.userId || data.userId !== pending.userId)
30686
+ return true;
30687
+ const callbackChannelId = data.threadId ?? data.chatId;
30688
+ if (callbackChannelId !== pending.channelId && data.chatId !== pending.channelId)
30689
+ return true;
30690
+ if (match[2] === "free" && !this.canChooseFreeMode(pending.userId, pending.adapterId)) {
30691
+ data.ack?.(t("classic.mode_free_admin_only"));
30692
+ return true;
30693
+ }
30694
+ await this.finishClassicModeSelection(match[1], match[2] === "restricted");
30695
+ return true;
30696
+ }
30697
+ /** Claim the mode choice and create the room. A second click or the timeout finds nothing. */
30698
+ async finishClassicModeSelection(nonce, restricted) {
30699
+ const pending = this.pendingClassicStarts.get(nonce);
30700
+ if (!pending || pending.phase !== "mode" || !pending.backend)
30701
+ return;
30702
+ this.pendingClassicStarts.delete(nonce);
30703
+ clearTimeout(pending.timer);
30704
+ const missing = this.getMissingBackendWarning(pending.backend);
30705
+ const reply = await withSpawnHoldReply(text => pending.complete(text, pending.messageId), () => this.handleClassicStart(pending.channelId, pending.channelName, pending.userId, pending.guildId, pending.adapterId, pending.backend, restricted));
30706
+ await pending.complete(missing ? `${missing}\n\n${reply}` : reply, pending.messageId);
30263
30707
  }
30264
30708
  /** Start a classic channel instance with lightweight config */
30265
30709
  async startClassicInstance(instanceName, backend, preTaskCommand, model, autoPauseAfter, transition, execution) {
@@ -30309,7 +30753,7 @@ export class FleetManager {
30309
30753
  await this.startInstance(instanceName, config, topicMode, "classic", false, transition);
30310
30754
  }
30311
30755
  /** Handle /start slash command — register classic channel */
30312
- async handleClassicStart(channelId, channelName, userId, guildId, adapterId, backend) {
30756
+ async handleClassicStart(channelId, channelName, userId, guildId, adapterId, backend, restricted = true) {
30313
30757
  const blocker = this.validateClassicStart(channelId, userId, guildId, adapterId);
30314
30758
  if (blocker)
30315
30759
  return blocker;
@@ -30319,7 +30763,7 @@ export class FleetManager {
30319
30763
  const instanceName = classicChannels.deriveInstanceName(channelName || channelId, channelId, adapterId);
30320
30764
  clearPausedMarker(this.getInstanceDir(instanceName));
30321
30765
  const selectedBackend = isSelectableClassicBackend(backend) ? backend : undefined;
30322
- classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend);
30766
+ classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend, restricted);
30323
30767
  // Bind this classic instance to the bot that started it (authoritative), so
30324
30768
  // replies/cancel go out through that bot even though every same-guild bot
30325
30769
  // also sees the channel's messages.