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

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 (172) hide show
  1. package/dist/agent-whats-new.js +6 -0
  2. package/dist/agent-whats-new.js.map +1 -1
  3. package/dist/auth-api.d.ts +2 -0
  4. package/dist/auth-api.js +5 -2
  5. package/dist/auth-api.js.map +1 -1
  6. package/dist/authority/web-authority.d.ts +17 -3
  7. package/dist/authority/web-authority.js +56 -3
  8. package/dist/authority/web-authority.js.map +1 -1
  9. package/dist/build-provenance.json +1 -1
  10. package/dist/channel/mcp-tools.js +8 -1
  11. package/dist/channel/mcp-tools.js.map +1 -1
  12. package/dist/classic-channel-manager.d.ts +1 -1
  13. package/dist/classic-channel-manager.js +2 -2
  14. package/dist/classic-channel-manager.js.map +1 -1
  15. package/dist/contact-auth-api.js +3 -1
  16. package/dist/contact-auth-api.js.map +1 -1
  17. package/dist/contact-auth-service.js +1 -1
  18. package/dist/contact-auth-service.js.map +1 -1
  19. package/dist/contact-auth-store.d.ts +28 -2
  20. package/dist/contact-auth-store.js +72 -4
  21. package/dist/contact-auth-store.js.map +1 -1
  22. package/dist/contact-change-proposals.d.ts +18 -1
  23. package/dist/contact-change-proposals.js +38 -4
  24. package/dist/contact-change-proposals.js.map +1 -1
  25. package/dist/contact-state-view.d.ts +103 -0
  26. package/dist/contact-state-view.js +80 -0
  27. package/dist/contact-state-view.js.map +1 -0
  28. package/dist/fleet-manager.d.ts +143 -15
  29. package/dist/fleet-manager.js +455 -78
  30. package/dist/fleet-manager.js.map +1 -1
  31. package/dist/general-knowledge/skills/admin/SKILL.md +52 -0
  32. package/dist/general-knowledge/skills/concepts/SKILL.md +14 -17
  33. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +6 -3
  34. package/dist/general-knowledge/skills/hub/SKILL.md +6 -1
  35. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +54 -9
  36. package/dist/general-knowledge/skills/worker-collaboration/SKILL.md +1 -1
  37. package/dist/general-role.d.ts +1 -1
  38. package/dist/general-role.js +1 -0
  39. package/dist/general-role.js.map +1 -1
  40. package/dist/hub/client.js +6 -1
  41. package/dist/hub/client.js.map +1 -1
  42. package/dist/hub/compose/member.d.ts +2 -1
  43. package/dist/hub/compose/member.js +3 -2
  44. package/dist/hub/compose/member.js.map +1 -1
  45. package/dist/hub/compose/server.js +2 -1
  46. package/dist/hub/compose/server.js.map +1 -1
  47. package/dist/hub/group-policy/resources.d.ts +1 -1
  48. package/dist/hub/http/compose.js +5 -0
  49. package/dist/hub/http/compose.js.map +1 -1
  50. package/dist/hub/protocol.d.ts +21 -0
  51. package/dist/hub/protocol.js +3 -0
  52. package/dist/hub/protocol.js.map +1 -1
  53. package/dist/hub/question-close-model.d.ts +17 -0
  54. package/dist/hub/question-close-model.js +7 -0
  55. package/dist/hub/question-close-model.js.map +1 -0
  56. package/dist/hub/representative.d.ts +5 -0
  57. package/dist/hub/representative.js +51 -1
  58. package/dist/hub/representative.js.map +1 -1
  59. package/dist/hub/rooms/direct-view.js +1 -0
  60. package/dist/hub/rooms/direct-view.js.map +1 -1
  61. package/dist/hub/rooms/types.d.ts +1 -1
  62. package/dist/hub/rooms.d.ts +3 -0
  63. package/dist/hub/rooms.js +27 -1
  64. package/dist/hub/rooms.js.map +1 -1
  65. package/dist/hub/server.js +6 -1
  66. package/dist/hub/server.js.map +1 -1
  67. package/dist/hub/types.d.ts +2 -2
  68. package/dist/human-delivery-receipts.d.ts +12 -2
  69. package/dist/human-delivery-receipts.js +19 -4
  70. package/dist/human-delivery-receipts.js.map +1 -1
  71. package/dist/instructions.d.ts +1 -1
  72. package/dist/instructions.js +1 -1
  73. package/dist/instructions.js.map +1 -1
  74. package/dist/locale.js +100 -12
  75. package/dist/locale.js.map +1 -1
  76. package/dist/needs-you.d.ts +2 -0
  77. package/dist/needs-you.js +2 -1
  78. package/dist/needs-you.js.map +1 -1
  79. package/dist/office-share-page.js +1 -1
  80. package/dist/office-share-page.js.map +1 -1
  81. package/dist/outbound-handlers.d.ts +4 -0
  82. package/dist/outbound-handlers.js +40 -5
  83. package/dist/outbound-handlers.js.map +1 -1
  84. package/dist/outbound-schemas.d.ts +2 -1
  85. package/dist/outbound-schemas.js +3 -2
  86. package/dist/outbound-schemas.js.map +1 -1
  87. package/dist/public-web-gateway.js +18 -0
  88. package/dist/public-web-gateway.js.map +1 -1
  89. package/dist/reply-buttons-controller.d.ts +2 -1
  90. package/dist/reply-buttons-controller.js +1 -1
  91. package/dist/reply-buttons-controller.js.map +1 -1
  92. package/dist/tool-permissions.js +1 -1
  93. package/dist/tool-permissions.js.map +1 -1
  94. package/dist/ui/accounts-keepalive.js +2 -1
  95. package/dist/ui/chat-activity.js +2 -1
  96. package/dist/ui/chat-pins.js +2 -1
  97. package/dist/ui/claude-credentials.js +2 -1
  98. package/dist/ui/contact-auth-strings.js +28 -17
  99. package/dist/ui/contact-authorizations.js +6 -4
  100. package/dist/ui/contact-needs.js +6 -1
  101. package/dist/ui/contact-permissions.js +6 -4
  102. package/dist/ui/contact-tool-groups.js +1 -1
  103. package/dist/ui/contact-verify-need.js +46 -0
  104. package/dist/ui/fleet-cache.js +2 -1
  105. package/dist/ui/fleet-office-skin.js +10 -6
  106. package/dist/ui/fleet-office-zones.js +22 -9
  107. package/dist/ui/fleet-office.js +16 -9
  108. package/dist/ui/fleet-org.js +6 -1
  109. package/dist/ui/fleet-tab-icons.js +19 -0
  110. package/dist/ui/fleet-task-activity.js +2 -1
  111. package/dist/ui/fleet-task-view.js +2 -1
  112. package/dist/ui/fleet-usage.js +2 -1
  113. package/dist/ui/hub-admin-overview.js +2 -1
  114. package/dist/ui/hub-agent-intro.js +2 -1
  115. package/dist/ui/hub-assistant-admin.js +2 -1
  116. package/dist/ui/hub-directory-notices.js +2 -1
  117. package/dist/ui/hub-enrolment-code.js +2 -1
  118. package/dist/ui/hub-my-agents.js +2 -1
  119. package/dist/ui/hub-quick-pairing.js +2 -1
  120. package/dist/ui/hub-role-audit.js +2 -1
  121. package/dist/ui/hub-role-forms.js +3 -2
  122. package/dist/ui/hub-role-view.js +3 -2
  123. package/dist/ui/hub-roles.js +2 -1
  124. package/dist/ui/hub-room-agent-strings.js +2 -1
  125. package/dist/ui/hub-room-list.js +2 -1
  126. package/dist/ui/hub-room-owner-requests.js +2 -1
  127. package/dist/ui/hub-room-pins.js +2 -1
  128. package/dist/ui/hub-room-strings.js +2 -2
  129. package/dist/ui/hub-room-thread.js +1 -1
  130. package/dist/ui/log-row.js +4 -3
  131. package/dist/ui/office-share-dialog.js +2 -1
  132. package/dist/ui/office-share-page.js +2 -1
  133. package/dist/ui/page-share-dialog.js +3 -2
  134. package/dist/ui/panel-chat.js +2 -1
  135. package/dist/ui/panel-details.js +2 -1
  136. package/dist/ui/panel-fleet.js +10 -5
  137. package/dist/ui/panel-hub.js +2 -1
  138. package/dist/ui/panel-needs.js +31 -3
  139. package/dist/ui/panel-notices.js +2 -1
  140. package/dist/ui/panel-runtimes.js +2 -1
  141. package/dist/ui/panel-windows-cli.js +3 -2
  142. package/dist/ui/runtime-cli-install.js +2 -1
  143. package/dist/ui/settings-appearance.js +2 -1
  144. package/dist/ui/settings-guests.js +4 -3
  145. package/dist/ui/settings-hub-member-address.js +2 -1
  146. package/dist/ui/settings-hub-setup.js +2 -1
  147. package/dist/ui/settings-hub-web-address.js +2 -1
  148. package/dist/ui/settings-hub.js +2 -1
  149. package/dist/ui/settings-update.js +2 -1
  150. package/dist/ui/settings-web-authority.js +2 -1
  151. package/dist/ui/shared/agent-sheet.js +2 -1
  152. package/dist/ui/shared/app-session.js +4 -3
  153. package/dist/ui/shared/app-shell.js +6 -2
  154. package/dist/ui/shared/app.css +38 -8
  155. package/dist/ui/shared/chat-time.js +7 -4
  156. package/dist/ui/shared/clock-text.js +57 -0
  157. package/dist/ui/shared/device-roles.js +6 -5
  158. package/dist/ui/shared/instance-nav.js +17 -22
  159. package/dist/ui/shared/usage-dialog.js +2 -1
  160. package/dist/ui/shared/view-strings.js +0 -14
  161. package/dist/ui/shared/web-authorize.js +3 -2
  162. package/dist/ui/subagent-row.js +2 -1
  163. package/dist/web-api.d.ts +15 -2
  164. package/dist/web-api.js +62 -13
  165. package/dist/web-api.js.map +1 -1
  166. package/dist/web-login.d.ts +6 -1
  167. package/dist/web-login.js +8 -3
  168. package/dist/web-login.js.map +1 -1
  169. package/dist/web-session-authorization.d.ts +3 -0
  170. package/dist/web-session-authorization.js +1 -1
  171. package/dist/web-session-authorization.js.map +1 -1
  172. 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";
@@ -637,6 +638,7 @@ function callbackPrefix(callbackData) {
637
638
  }
638
639
  const CLASSIC_BACKEND_SELECTION_TIMEOUT_MS = 60_000;
639
640
  const CLASSIC_BACKEND_CALLBACK_PREFIX = "classic-backend:";
641
+ const CLASSIC_MODE_CALLBACK_PREFIX = "classic-mode:";
640
642
  const MODEL_SELECT_CALLBACK_PREFIX = "model-select:";
641
643
  const EFFORT_SELECT_CALLBACK_PREFIX = "effort-select:";
642
644
  const BACKEND_SELECT_CALLBACK_PREFIX = "backend-select:";
@@ -659,6 +661,13 @@ const KIRO_MIGRATE_CALLBACK_PREFIX = "kiro-migrate:";
659
661
  /** M-3140: Update now on a Hub-recommended-version notice in General ("hub-update:" + 32 hex + ":update" = 50 bytes). */
660
662
  const HUB_UPDATE_CALLBACK_PREFIX = "hub-update:";
661
663
  const HUB_SHARING_CALLBACK_PREFIX = "hub-share:";
664
+ /** M-3680: a held contact request's card in General ("contact-ticket:" + 32 hex + ":approve" = 55 bytes, under Telegram's 64). */
665
+ const CONTACT_TICKET_PREFIX = "contact-ticket:";
666
+ /** How many requests' cards are remembered (one card per request; a decided one is forgotten at once). */
667
+ const HELD_CARDS_KEPT = 512;
668
+ /** A held request's card, retired after it was decided elsewhere (the dashboard, Needs you, another card) or closed. */
669
+ const heldCardOutcome = (state) => t(state === "approved" ? "contactHeld.approvedElsewhere"
670
+ : state === "declined" ? "contactHeld.declinedElsewhere" : state === "expired" ? "contactHeld.expired" : "contactHeld.closed");
662
671
  const HUB_FLEET_UPDATE_CALLBACK_PREFIX = "hub-fleet-update:";
663
672
  const KIRO_RECONCILE_CALLBACK_PREFIX = "kiro-reconcile:";
664
673
  /** #2692: a fleet admin's Approve / Reject on an agent's pending skin-pack change, in General. */
@@ -2826,7 +2835,7 @@ export class FleetManager {
2826
2835
  : this.getInstanceAdapterId(agent) === actor.adapter_id && this.isFleetAdmin(actor.user_id, actor.adapter_id),
2827
2836
  }, caller.agent, receiptId),
2828
2837
  attachExposures: api => this.attachHubMemberExposures(api),
2829
- attachAttention: (read, retry) => this.attachHubExecutionAttention(read, retry),
2838
+ attachAttention: (read, retry, close) => this.attachHubExecutionAttention(read, retry, close),
2830
2839
  updates: { idle: () => this.hubUpdateIdle(), busy: () => !!this.webUpdateOwned || isUpdateInProgress(this.dataDir),
2831
2840
  canInstall: () => this.hubUpdateCanInstall(), launch: (row, control) => this.launchHubUpdate(row, control),
2832
2841
  active: id => this.hubUpdateOwned?.id === id, outcome: row => this.hubUpdateOutcome(row), notify: n => this.recordHubUpdateNotice(n) },
@@ -3868,6 +3877,7 @@ export class FleetManager {
3868
3877
  signInKeepAlive = null;
3869
3878
  hubExecutionAttention = null;
3870
3879
  /** M-3632: the member's "Try again" for a held Hub question (null while no member runs). */
3880
+ hubHeldClose = null;
3871
3881
  hubHeldRetry = null;
3872
3882
  missedOfflineStore = null;
3873
3883
  configHistory = null;
@@ -4986,7 +4996,7 @@ export class FleetManager {
4986
4996
  } };
4987
4997
  }
4988
4998
  /**
4989
- * alpha.2 (M-2300; #2973's agent requests, junsion's §6): on a fleet with no chat connection there is no General to
4999
+ * 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
5000
  * post an agent's Windows request in — it waited for `agend settings confirm` on the host. Its owner (decision
4991
5001
  * 28c2d3a3: the `agend web --code` session on this computer, web-verified) now sees and decides it from the web's
4992
5002
  * Needs you. The authority is asked from the request each time, and again at execution by the store (`current`):
@@ -6081,6 +6091,8 @@ export class FleetManager {
6081
6091
  const badge = row?.payload.contactTicket;
6082
6092
  const ticket = badge?.id ? outbox.contactAuthorizations.get(badge.id) : undefined;
6083
6093
  if (ticket && ticket.deliveryId === row?.deliveryId) {
6094
+ // M-3716: the approval notice waits for this delivery to settle.
6095
+ queueMicrotask(() => this.sweepContactAuthorizationOutcomes());
6084
6096
  const state = event.state === "delivered" ? "delivered" : ["failed", "uncertain", "cancelled", "reconciliation_pending"].includes(event.state ?? "") ? "unknown" : "approved";
6085
6097
  for (const instance of new Set([ticket.source, ticket.target])) {
6086
6098
  this.webChatHistory?.updateContactTicket(instance, ticket.id, state);
@@ -6350,6 +6362,15 @@ export class FleetManager {
6350
6362
  sender: ticket.source, text: ticket.message, ts: new Date().toISOString(), contactTicket: { id: ticket.id, state: "approved" } });
6351
6363
  }
6352
6364
  this.emitSseEvent("contact-auth", { instance, ...(ticketId ? { ticketId } : {}), revision });
6365
+ // M-3680: a card never stands in the way of the hold (or a decision) that called this.
6366
+ if (ticket) {
6367
+ try {
6368
+ this.syncHeldTicketCard(ticket);
6369
+ }
6370
+ catch (err) {
6371
+ this.logger?.warn?.({ err: err?.message, ticket: ticket.id }, "Held contact request card failed");
6372
+ }
6373
+ }
6353
6374
  this.needsYou?.poke();
6354
6375
  this.emitSseEvent("needs", { items: this.needsYouItems() });
6355
6376
  },
@@ -6477,6 +6498,26 @@ export class FleetManager {
6477
6498
  return this.contactPermissions(name, actor);
6478
6499
  }
6479
6500
  /** General can propose only. The platform callback supplies the human actor. */
6501
+ /** M-3693: what contact permissions hold now, for General (read-only; no write, no identity computed here). */
6502
+ contactState(agent) {
6503
+ const store = this.contactService().host.store;
6504
+ const names = [...new Set([...Object.keys(this.fleetConfig?.instances ?? {}), ...(this.classicChannels?.getAll?.() ?? []).map(room => room.instanceName)])];
6505
+ return contactStateView({
6506
+ store, names: () => names, now: () => Date.now(), generation: n => this.contactGeneration(n),
6507
+ label: n => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || n,
6508
+ roomMode: n => { const room = this.contactRoom(n); return room ? room.restrictedMode ? "restricted" : "legacy" : undefined; },
6509
+ }, agent ? { agent } : {});
6510
+ }
6511
+ /** M-3716: the caller's OWN held requests (delivery_status { held_requests: true }); the caller is the authenticated agent. */
6512
+ ownContactRequests(agent) {
6513
+ const outbox = this.deliveryOutbox;
6514
+ if (!outbox?.isOpen)
6515
+ return { requests: [], note: "Contact requests are unavailable right now." };
6516
+ return ownContactRequestsView(outbox.contactAuthorizations.requestsBy(agent), {
6517
+ label: n => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || n,
6518
+ delivery: ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined,
6519
+ });
6520
+ }
6480
6521
  async requestContactChange(requester, raw, callerCurrent) {
6481
6522
  if (!callerCurrent() || this.fleetConfig?.instances[requester]?.general_topic !== true)
6482
6523
  throw Error("general-only");
@@ -6563,6 +6604,123 @@ export class FleetManager {
6563
6604
  await this.retireNonceButtons(entry, entry.messageId ?? data.messageId, text);
6564
6605
  return true;
6565
6606
  }
6607
+ /**
6608
+ * M-3680 (the user, 11-25): a fleet agent's send held for approval reaches an administrator in General on the target's
6609
+ * Discord or Telegram, as a card with Approve once / Decline — until then a held request had no chat path (the live
6610
+ * Needs you message lists it without buttons). One card per request. Whoever clicks must be one who may decide it
6611
+ * (ContactAuthService.view(...).canDecide, read at the click); the decision is theirs, never the bot's. A request decided
6612
+ * anywhere else (the web, another card) retires its card. #4448 (R21079937): a ClassicBot room's request to a fleet agent
6613
+ * gets the same card, in the General of the target's connection; a room's request to anything else gets none.
6614
+ */
6615
+ /** Requests whose card was posted or tried: forgotten when the request is decided, and at most HELD_CARDS_KEPT. */
6616
+ heldTicketCards;
6617
+ syncHeldTicketCard(ticket) {
6618
+ const posted = (this.heldTicketCards ??= new Set());
6619
+ if (ticket.state !== "pending") {
6620
+ posted.delete(ticket.id);
6621
+ for (const [nonce, entry] of [...(this.pendingNonceButtons ?? [])]) {
6622
+ if (entry.prefix !== CONTACT_TICKET_PREFIX || entry.contactTicketId !== ticket.id)
6623
+ continue;
6624
+ this.pendingNonceButtons.delete(nonce);
6625
+ if (entry.timer)
6626
+ clearTimeout(entry.timer);
6627
+ // #4438 review: a card still being posted has no message yet; postHeldTicketCard retires it once it has one.
6628
+ if (entry.messageId)
6629
+ void this.retireNonceButtons(entry, entry.messageId, heldCardOutcome(ticket.state));
6630
+ }
6631
+ return;
6632
+ }
6633
+ // 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
6634
+ // to a fleet agent — the card goes to the General of the TARGET's connection either way (postHeldTicketCard).
6635
+ const room = !this.fleetConfig?.instances[ticket.source] && !!this.contactRoom(ticket.source);
6636
+ if (posted.has(ticket.id) || (!this.fleetConfig?.instances[ticket.source] && !room) || (room && !this.fleetConfig?.instances[ticket.target]))
6637
+ return;
6638
+ posted.add(ticket.id);
6639
+ for (const old of posted) {
6640
+ if (posted.size <= HELD_CARDS_KEPT)
6641
+ break;
6642
+ posted.delete(old);
6643
+ }
6644
+ void this.postHeldTicketCard(ticket).catch((err) => this.logger?.warn?.({ err: err?.message, ticket: ticket.id }, "Could not post a held contact request to General"));
6645
+ }
6646
+ async postHeldTicketCard(ticket) {
6647
+ const adapter = this.contactAdapter(ticket.target);
6648
+ if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6649
+ return;
6650
+ const routes = Object.keys(this.fleetConfig?.instances ?? {}).flatMap(n => {
6651
+ const route = this.settingsGeneralRoute(n, adapter.type, new Set());
6652
+ return route && route.adapterId === adapter.id && route.adapter === adapter ? [{ name: n, ...route }] : [];
6653
+ });
6654
+ if (routes.length !== 1) {
6655
+ this.logger.info({ ticket: ticket.id, routes: routes.length }, "No single General for a held contact request's card");
6656
+ return;
6657
+ }
6658
+ // A ClassicBot room by its own name (its display name, else its channel's), as Fleet lists it.
6659
+ const route = routes[0], label = (n) => this.fleetConfig?.instances[n]?.display_name || this.contactRoom(n)?.displayName || this.contactRoom(n)?.name || n;
6660
+ const shortId = /^R[a-f0-9]{8}-/.test(ticket.id) ? ticket.id.slice(0, 9) : ticket.id;
6661
+ const left = Date.parse(ticket.expiresAt) - Date.now();
6662
+ const text = ticket.message.length > 300 ? `${ticket.message.slice(0, 299)}…` : ticket.message;
6663
+ const posting = this.postNonceButtonPromptOrThrow({ prefix: CONTACT_TICKET_PREFIX, alertType: "clear_confirm", instanceName: route.name,
6664
+ adapter: route.adapter, adapterId: route.adapterId, chatId: route.chatId, threadId: route.topic,
6665
+ message: [t("contactHeld.title", label(ticket.source), label(ticket.target)), `> ${text.replace(/\n+/g, " ")}`,
6666
+ 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))),
6667
+ t("contactHeld.hint")].join("\n"),
6668
+ choices: [{ action: "approve", label: t("contactHeld.approve") }, { action: "decline", label: t("contactHeld.decline") }],
6669
+ expiredText: t("contactHeld.expired"), timeoutMs: Math.max(60_000, Math.min(left, 24 * 3_600_000)),
6670
+ extra: { contactTicketId: ticket.id } });
6671
+ // The entry is armed before the platform answers (postNonceButtonPromptOrThrow sets it synchronously).
6672
+ const entry = [...this.pendingNonceButtons.values()].find(e => e.prefix === CONTACT_TICKET_PREFIX && e.contactTicketId === ticket.id);
6673
+ const nonce = await posting;
6674
+ // #4438 review: decided elsewhere, or expired, while the card was being posted — it had no message to retire then; it
6675
+ // has one now. A card still armed for a request still waiting stays.
6676
+ if (!entry?.messageId)
6677
+ return;
6678
+ const fresh = this.contactService().host.store.get(ticket.id), armed = this.pendingNonceButtons.get(nonce) === entry;
6679
+ if (armed && fresh?.state === "pending")
6680
+ return;
6681
+ if (armed) {
6682
+ this.pendingNonceButtons.delete(nonce);
6683
+ if (entry.timer)
6684
+ clearTimeout(entry.timer);
6685
+ }
6686
+ await this.retireNonceButtons(entry, entry.messageId, !fresh || fresh.state === "pending" ? t("contactHeld.expired") : heldCardOutcome(fresh.state));
6687
+ }
6688
+ async handleContactTicketCallback(data, adapterId, adapter) {
6689
+ if (!data.callbackData.startsWith(CONTACT_TICKET_PREFIX))
6690
+ return false;
6691
+ const person = data.userId && adapter && this.adapters.get(adapterId) === adapter && adapter.id === adapterId
6692
+ && (adapter.type === "discord" || adapter.type === "telegram") && data.userId !== adapter.getBotUserId?.()
6693
+ ? { platform: adapter.type, adapterId, userId: data.userId, label: data.username || data.userId } : null;
6694
+ const service = this.contactService();
6695
+ const mayDecide = (entry) => {
6696
+ const ticket = person && entry.contactTicketId ? service.host.store.get(entry.contactTicketId) : undefined;
6697
+ try {
6698
+ return !!ticket && !!person && service.view(ticket, person).canDecide;
6699
+ }
6700
+ catch {
6701
+ return false;
6702
+ }
6703
+ };
6704
+ 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));
6705
+ if (claimed === null)
6706
+ return false;
6707
+ if (claimed === "consumed")
6708
+ return true;
6709
+ const { entry, action } = claimed;
6710
+ const ticket = entry.contactTicketId ? service.host.store.get(entry.contactTicketId) : undefined;
6711
+ let text = t("contactHeld.closed");
6712
+ if (ticket?.state === "pending" && person) {
6713
+ try {
6714
+ const decided = this.decideContactAuthorization(ticket.id, { revision: ticket.revision, decision: action === "approve" ? "approve-once" : "decline" }, person);
6715
+ text = t(decided.state === "approved" ? "contactHeld.approved" : "contactHeld.declined", person.label);
6716
+ }
6717
+ catch {
6718
+ text = t("contactHeld.failed");
6719
+ }
6720
+ }
6721
+ await this.retireNonceButtons(entry, entry.messageId ?? data.messageId, text);
6722
+ return true;
6723
+ }
6566
6724
  contactAuthorization(id, actor) {
6567
6725
  const service = this.contactService(), ticket = service.host.store.get(id);
6568
6726
  if (!ticket)
@@ -6594,14 +6752,30 @@ export class FleetManager {
6594
6752
  if (!outbox?.isOpen || this.shuttingDown)
6595
6753
  return;
6596
6754
  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
- });
6755
+ outbox.contactAuthorizations.notifyOutcomes((ticket, outcome) => {
6756
+ if (outcome === "declined" || outcome === "expired") {
6757
+ outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(outcome === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
6758
+ return;
6759
+ }
6760
+ // M-3716 (the user, 11-25): the requester learns who approved it, when, and whether the target has it.
6761
+ const by = ticket.decidedBy, when = ticket.decidedAt ? `${ticket.decidedAt.slice(0, 16).replace("T", " ")} UTC` : "";
6762
+ const who = !by ? "?" : by.platform === "host" ? t("contactProposal.host")
6763
+ : `${by.label}${getLocale() === "zh-TW" ? "(" : " ("}${by.platform === "discord" ? "Discord" : "Telegram"}${getLocale() === "zh-TW" ? ")" : ")"}`;
6764
+ outbox.admitSystemNotice(ticket.source, `contact-approval:${ticket.id}`, t(`contact.noticeApproved_${outcome}`, shortContactTicketId(ticket.id), ticket.target, who, when));
6765
+ }, ticket => ticket.deliveryId ? outbox.get(ticket.deliveryId)?.state : undefined);
6600
6766
  }
6601
6767
  catch (err) {
6602
6768
  this.logger.error({ err }, "Contact outcome notice sweep failed; durable state will retry");
6603
6769
  }
6604
6770
  }
6771
+ /**
6772
+ * M-3710: how many contact requests wait, and since when — no ids, people or text. Needs you tells an admin session with
6773
+ * no verified person behind it (contactActor null) that they exist, so a request is never silently missing there.
6774
+ */
6775
+ contactPendingCount() {
6776
+ const pending = this.contactService().host.store.pending();
6777
+ return { count: pending.length, since: pending.reduce((at, ticket) => Math.min(at, Date.parse(ticket.createdAt) || at), Date.now()) };
6778
+ }
6605
6779
  contactNeeds(actor) {
6606
6780
  const service = this.contactService();
6607
6781
  const pending = service.host.store.pending()
@@ -6737,7 +6911,7 @@ export class FleetManager {
6737
6911
  if (!item.authority || !state)
6738
6912
  return item;
6739
6913
  const authority = this.receiptAuthorityNow(item.authority, state);
6740
- return { ...item, authority, ...(authority.downgraded ? { source_instance: "human:web:unknown" } : {}) };
6914
+ return { ...item, authority, ...(authority.downgraded && !isWebSessionIdentity(item.origin?.web_identity) ? { source_instance: "human:web:unknown" } : {}) };
6741
6915
  };
6742
6916
  // #1641: a sender that sees only `queued` cannot tell "next in line" from "the target is stuck": say which.
6743
6917
  return {
@@ -9466,10 +9640,11 @@ export class FleetManager {
9466
9640
  throw Error("Contact origin storage unavailable");
9467
9641
  if (contactStore && (this.contactRoom(instanceName)?.restrictedMode === true || contactStore.origin(instanceName))) {
9468
9642
  const authority = origin.authority;
9469
- const actor = origin.platform === "web" ? (authority?.kind === "web-verified" ? authority.actor : null)
9643
+ const identity = origin.platform === "web" && isWebSessionIdentity(origin.web_identity) ? origin.web_identity : undefined;
9644
+ const actor = origin.platform === "web" ? identity ?? (authority?.kind === "web-verified" ? authority.actor : null)
9470
9645
  : { adapter_id: origin.adapter_id, user_id: origin.user_id };
9471
9646
  const adapter = actor?.adapter_id ? this.adapters.get(actor.adapter_id) : undefined;
9472
- const platform = origin.platform === "web" ? adapter?.type : origin.platform;
9647
+ const platform = origin.platform === "web" ? identity?.platform ?? adapter?.type : origin.platform;
9473
9648
  const person = actor?.adapter_id && actor.user_id
9474
9649
  && (platform === "discord" || platform === "telegram" || (actor.adapter_id === "host" && actor.user_id === "operator"))
9475
9650
  ? { platform: actor.adapter_id === "host" ? "host" : platform,
@@ -9665,6 +9840,16 @@ export class FleetManager {
9665
9840
  isFleetAdmin(userId, adapterId) {
9666
9841
  return this.adminGate(userId, adapterId) === "ok";
9667
9842
  }
9843
+ /**
9844
+ * Free mode at /start is the fleet-admin allowlist of the adapter that owns the room (adminGate).
9845
+ * A ClassicBot admin (`classicBot.yaml` admin_users) is not enough. A stub with no fleet and no worlds
9846
+ * is not an admin: the menu offers Restricted only.
9847
+ */
9848
+ canChooseFreeMode(userId, adapterId) {
9849
+ if (!this.fleetConfig && !this.worlds)
9850
+ return false;
9851
+ return this.adminGate(userId, adapterId) === "ok";
9852
+ }
9668
9853
  /** Whether this adapter has any fleet admin at all (an empty allowlist means the admin commands are off). */
9669
9854
  hasFleetAdmins(adapterId) {
9670
9855
  return (this.adminListOf(adapterId)?.length ?? 0) > 0;
@@ -12616,7 +12801,8 @@ export class FleetManager {
12616
12801
  // guest there) — most guests are not on the host's network. Its closing withdraws that audience (revokeAudience).
12617
12802
  const open = this.publicWebLink?.openSignin() ?? null;
12618
12803
  // 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] : [])],
12804
+ // M-3651: private — the account's DM, else this slash command's ephemeral answer, else withdrawn (below): verified at sign-in.
12805
+ const login = codes.issue({ epoch: tokenEpoch(token), audiences: ["local", ...(open ? [open.exposureId] : [])], private: true,
12620
12806
  recipient: { adapterId: owner.adapterId, userId: owner.userId, ...(ask.username ? { username: ask.username } : {}) } });
12621
12807
  if (!login) {
12622
12808
  await say(t("web.guest_busy"));
@@ -12785,7 +12971,7 @@ export class FleetManager {
12785
12971
  const current = () => !this.shuttingDown && this.webToken === token && this.adapters.get(account.adapterId) === adapter
12786
12972
  && this.guestRevokes === revokes && (this.guestAccountRevokes.get(key) ?? 0) === accountRevokes && this.guestSignInAllowed(account)
12787
12973
  && (!viaLink || linkOpen()) && this.returningDevices.current(device, tokenEpoch(token));
12788
- const issued = codes.issue({ epoch: tokenEpoch(token), recipient: account, audiences: [viaLink ? input.exposureId : "local"] });
12974
+ const issued = codes.issue({ epoch: tokenEpoch(token), recipient: account, audiences: [viaLink ? input.exposureId : "local"], private: true }); // M-3651: by DM only (withdrawn otherwise)
12789
12975
  if (!issued)
12790
12976
  return { kind: "limited", retryAfterMs: 60_000 }; // the guests' cap: never someone's evicted
12791
12977
  this.guestCodeInFlight.add(key);
@@ -15883,11 +16069,14 @@ export class FleetManager {
15883
16069
  }
15884
16070
  const channelName = msg.username || chatId;
15885
16071
  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);
16072
+ // The backend is only half of /start. The room waits for Restricted or Free.
16073
+ await this.beginClassicModeSelection({
16074
+ command: "start",
16075
+ channelId: chatId,
16076
+ channelName,
16077
+ userId: msg.userId,
16078
+ respond: async (reply) => (await msgAdapter?.sendText(chatId, reply))?.messageId,
16079
+ }, msgAdapter ?? undefined, requestedBackend, msg.adapterId);
15891
16080
  }
15892
16081
  else if (msgAdapter) {
15893
16082
  await this.beginClassicBackendSelection({
@@ -20945,6 +21134,8 @@ export class FleetManager {
20945
21134
  return true;
20946
21135
  if (await this.handleContactChangeCallback(data, adapterId, adapter))
20947
21136
  return true;
21137
+ if (await this.handleContactTicketCallback(data, adapterId, adapter))
21138
+ return true;
20948
21139
  if (await this.handleSettingsChangeCallback(data, adapterId, adapter))
20949
21140
  return true;
20950
21141
  if (await this.handleKiroMigrateCallback(data, adapterId, adapter))
@@ -20979,6 +21170,8 @@ export class FleetManager {
20979
21170
  return true;
20980
21171
  if (await this.handleClassicBackendSelection(data))
20981
21172
  return true;
21173
+ if (await this.handleClassicModeSelection(data))
21174
+ return true;
20982
21175
  if (await this.handleModelSelection(data, adapterId))
20983
21176
  return true;
20984
21177
  if (await this.handleEffortSelection(data, adapterId))
@@ -21020,16 +21213,27 @@ export class FleetManager {
21020
21213
  needsYouItems() {
21021
21214
  return this.needsYou?.webItems() ?? [];
21022
21215
  }
21023
- /** Enabled member composition supplies only a local attention reader, never an approval/execution callback. */
21024
- attachHubExecutionAttention(read, retry = null) {
21216
+ /** Enabled member composition supplies held-work readers and explicit owner retry/close operations. */
21217
+ attachHubExecutionAttention(read, retry = null, close = undefined) {
21025
21218
  this.hubExecutionAttention = read;
21026
21219
  this.hubHeldRetry = read ? retry : null;
21220
+ this.hubHeldClose = read ? close ?? null : null;
21027
21221
  this.needsYou?.poke();
21028
21222
  }
21029
21223
  /**
21030
21224
  * M-3632: Needs you → "Try again" on held Hub work (`hub:hold:<row>`). The question goes back through the member's whole
21031
21225
  * hand-off, including the Hub's begin lease; nothing is delivered without it.
21032
21226
  */
21227
+ async closeHubHeld(itemId, actor) {
21228
+ const item = this.hubExecutionAttention?.().find(i => `hub:${i.id}` === itemId && i.kind === "hold");
21229
+ if (!item || !this.hubHeldClose)
21230
+ return { status: 404, code: "not-found" };
21231
+ if (!this.contactAdminOf(item.agent, actor))
21232
+ return { status: 403, code: "forbidden" };
21233
+ const code = await this.hubHeldClose(item.id);
21234
+ this.needsYou?.poke();
21235
+ return { status: code === "closed" || code === "answered" ? 200 : code === "not-found" ? 404 : 503, code };
21236
+ }
21033
21237
  retryHubHeld(itemId) {
21034
21238
  const id = itemId.startsWith("hub:") ? itemId.slice(4) : itemId;
21035
21239
  if (!this.hubHeldRetry || !id.startsWith("hold:"))
@@ -21935,9 +22139,26 @@ export class FleetManager {
21935
22139
  * #1939 S1: the design's §3 for one web request (authority/web-authority.ts), with this fleet's admins, policy and
21936
22140
  * token; `instance` once the body has named it. Observe only: receipts record it, no agent acts on it yet.
21937
22141
  */
22142
+ /** A signed-in account is recognizable before verification; this supplies no action authority. */
22143
+ webSessionIdentity(session) {
22144
+ const owner = session.owner;
22145
+ if (owner) {
22146
+ const adapter = this.adapters.get(owner.adapterId) ?? this.worlds?.get(owner.adapterId)?.adapter;
22147
+ const channels = this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : []);
22148
+ const platform = adapter?.type ?? channels.find(channel => (channel.id ?? channel.type) === owner.adapterId)?.type;
22149
+ if (platform !== "discord" && platform !== "telegram")
22150
+ return;
22151
+ return Object.freeze({ platform, adapter_id: owner.adapterId, user_id: owner.userId, session_handle: session.handle });
22152
+ }
22153
+ if (session.tier === "admin" && (session.host === true || session.remote === "totp") && this.isWebOnlyFleet()) {
22154
+ return Object.freeze({ platform: "host", adapter_id: "host", user_id: "operator", session_handle: session.handle });
22155
+ }
22156
+ return;
22157
+ }
21938
22158
  webAuthority(input) {
21939
22159
  const state = this.webAuthorityState();
21940
- return evaluateWebAuthority({
22160
+ // M-3651: a guest's session is asked only whether it is its account, verified (`web-guest`, identity only).
22161
+ return (input.session?.tier === "guest" ? evaluateGuestIdentity : evaluateWebAuthority)({
21941
22162
  session: input.session, gateway: input.gateway, peer: input.peer,
21942
22163
  tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null,
21943
22164
  ...(input.instance !== undefined ? { target: { adapterId: this.getInstanceAdapterId(input.instance) } } : {}),
@@ -21975,6 +22196,42 @@ export class FleetManager {
21975
22196
  return { ok: false, refusal: check.refusal };
21976
22197
  const live = new Set(this.webSessions?.list(undefined, () => true).map(r => r.handle) ?? []);
21977
22198
  store.prune(a => a.epoch === state.epoch && now <= Math.min(a.until, a.authorizedAt + policy.maxSessionMs) && live.has(a.handle));
22199
+ const authorized = store.authorize(session.handle, session.owner, now, state.epoch, now + policy.maxSessionMs, peer);
22200
+ // M-3710: Needs you is projected per session — this one now sees the contact requests it may decide, not just their count.
22201
+ try {
22202
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
22203
+ }
22204
+ catch (err) {
22205
+ this.logger.warn({ err: err?.message }, "Needs you refresh after a web authorization failed");
22206
+ }
22207
+ return { ok: true, ...authorized };
22208
+ }
22209
+ /** M-3651 (auth-api's /auth/session): until when this guest session is verified as its account now; null when it is not. */
22210
+ guestVerifiedUntil(req, session) {
22211
+ if (session.tier !== "guest")
22212
+ return null;
22213
+ const v = this.webSessionAuthorization({ session, gateway: !!gatewayRequestContext(req), peer: webPeerOf(req) });
22214
+ return v.state === "verified" ? v.until : null;
22215
+ }
22216
+ /**
22217
+ * M-3651: a guest session that signed in with a code AgEnD delivered privately to its own account — recorded as that
22218
+ * account's authorization of it, judged by evaluateGuestIdentity (the switch, the links, "Only this computer", the token):
22219
+ * its messages then carry `web-guest`, who it is and never more. Only at sign-in: a guest is never sent a Confirm card.
22220
+ */
22221
+ authorizeGuestSession(session, peer, gateway) {
22222
+ const store = this.sessionAuthorizationStore();
22223
+ const state = this.webAuthorityState(), now = Date.now(), policy = webAuthorityPolicy(this.fleetConfig?.web);
22224
+ if (!store || !session.owner || session.tier !== "guest")
22225
+ return { ok: false, refusal: !store ? "disabled" : "no_account" };
22226
+ const check = evaluateGuestIdentity({
22227
+ session, gateway, peer, tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null, isAdmin: () => false,
22228
+ authorization: { handle: session.handle, owner: session.owner, authorizedAt: now, until: now + policy.maxSessionMs, epoch: state.epoch },
22229
+ policy: { ...policy, enabled: state.enabled, loopbackOnly: state.loopbackOnly, namedLink: state.namedLink, quickLink: state.quickLink }, epoch: state.epoch, now,
22230
+ });
22231
+ if (check.refusal)
22232
+ return { ok: false, refusal: check.refusal };
22233
+ const live = new Set(this.webSessions?.list(undefined, () => true).map(r => r.handle) ?? []);
22234
+ store.prune(a => a.epoch === state.epoch && now <= Math.min(a.until, a.authorizedAt + policy.maxSessionMs) && live.has(a.handle));
21978
22235
  return { ok: true, ...store.authorize(session.handle, session.owner, now, state.epoch, now + policy.maxSessionMs, peer) };
21979
22236
  }
21980
22237
  /**
@@ -21985,15 +22242,17 @@ export class FleetManager {
21985
22242
  * at once, with Not me (noteAuthorized). Re-verifying once that authorization has run out still takes the card.
21986
22243
  */
21987
22244
  authorizeSignedInSession(session, peer, gateway) {
21988
- if (session.tier !== "admin" || !session.owner || session.host)
22245
+ if ((session.tier !== "admin" && session.tier !== "guest") || !session.owner || session.host)
21989
22246
  return;
21990
- const r = this.authorizeWebSession(session, peer, gateway);
22247
+ // M-3651: a guest's private code verifies who it is (web-guest), never an admin's authority.
22248
+ const r = session.tier === "guest" ? this.authorizeGuestSession(session, peer, gateway) : this.authorizeWebSession(session, peer, gateway);
21991
22249
  if (!r.ok) {
21992
22250
  this.logger.info({ handle: session.handle, refusal: r.refusal }, "Web session signed in with a private code, not verified");
21993
22251
  return;
21994
22252
  }
21995
22253
  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) })
22254
+ void this.sessionAuthorizationRequests().noteAuthorized({ handle: session.handle, owner: session.owner, label: session.label, peer, until: Math.min(r.authorization.until, session.absoluteExpiry),
22255
+ ...(session.tier === "guest" ? { guest: true } : {}) })
21997
22256
  .catch(err => this.logger.warn({ err: err?.message }, "Web sign-in notice failed"));
21998
22257
  }
21999
22258
  /**
@@ -22638,7 +22897,10 @@ export class FleetManager {
22638
22897
  return this.authorizationRequests;
22639
22898
  const adapterOf = (adapterId) => this.adapters.get(adapterId) ?? this.worlds.get(adapterId)?.adapter;
22640
22899
  // 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" });
22900
+ // M-3730: zh-TW is a 24-hour clock (2026/11/25 00:19:00 [GMT+8]), never 上午12:19; English is unchanged.
22901
+ const when = (ms) => getLocale() === "zh-TW"
22902
+ ? 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" })
22903
+ : new Date(ms).toLocaleString(undefined, { timeZoneName: "short" });
22642
22904
  const quickHost = () => { try {
22643
22905
  const u = this.publicWebLink?.openSignin()?.url;
22644
22906
  return u ? new URL(u).host : "?";
@@ -22700,7 +22962,7 @@ export class FleetManager {
22700
22962
  text: {
22701
22963
  ask: (c) => t("web_auth.card_ask", c.label, where(c.peer), when(c.askedAt), when(c.until)),
22702
22964
  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)),
22965
+ signedIn: (c) => t(c.guest ? "web_auth.signed_in_guest" : "web_auth.signed_in", c.label, where(c.peer), when(c.until)),
22704
22966
  signedInHint: () => t("web_auth.signed_in_hint"),
22705
22967
  denied: (c) => t("web_auth.card_denied", c.label),
22706
22968
  expired: (c) => t("web_auth.card_expired", c.label),
@@ -22834,7 +23096,7 @@ export class FleetManager {
22834
23096
  // #1827: a /steer or /btw reaches the agent as the web person who wrote it.
22835
23097
  chatId: this.getGroupIdForInstance(instance) || "", messageId: newWebMessageId(),
22836
23098
  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),
23099
+ threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority, opts.identity),
22838
23100
  ...(opts.guest ? { webGuest: true } : {}), // #2855: a guest's /steer or /btw reaches the agent as a guest's
22839
23101
  };
22840
23102
  };
@@ -30133,11 +30395,30 @@ export class FleetManager {
30133
30395
  return undefined;
30134
30396
  return t("classic.backend_not_installed", backend, installation.binary, installation.install);
30135
30397
  }
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");
30398
+ /** Discord buttons when the interaction can draw them; otherwise the adapter's own chooser. Never the backend select. */
30399
+ classicModePoster(data, adapter) {
30400
+ if (data.respondButtons)
30401
+ return (text, choices) => data.respondButtons(text, choices);
30402
+ if (adapter?.promptUser)
30403
+ return (text, choices) => adapter.promptUser(data.channelId, text, choices);
30404
+ return undefined;
30405
+ }
30406
+ /** Where the finished start (and a hold notice) lands: the Discord interaction, or the Telegram menu message. */
30407
+ classicStartComplete(data, adapter) {
30408
+ if (data.retireButtons)
30409
+ return async (text) => { await data.retireButtons(text); };
30410
+ return async (text, messageId) => {
30411
+ if (messageId && adapter?.editMessageRemoveButtons) {
30412
+ try {
30413
+ await adapter.editMessageRemoveButtons(data.channelId, messageId, text);
30414
+ return;
30415
+ }
30416
+ catch { /* fall back to a new message */ }
30417
+ }
30418
+ await data.respond(text);
30419
+ };
30139
30420
  }
30140
- /** Handle Discord's required static slash choice, warning before a likely startup failure. */
30421
+ /** Handle Discord's required static slash choice. The room waits for the mode menu. */
30141
30422
  async handleClassicStartSlash(data, adapterId) {
30142
30423
  return withSpawnHoldReply(text => data.respond(text), () => this.handleClassicStartSlashCore(data, adapterId));
30143
30424
  }
@@ -30157,15 +30438,10 @@ export class FleetManager {
30157
30438
  await data.respond(blocker);
30158
30439
  return;
30159
30440
  }
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);
30441
+ // A missing binary is advisory and stays on the mode menu. The room is not created yet.
30442
+ await this.beginClassicModeSelection(data, undefined, requestedBackend, adapterId);
30167
30443
  }
30168
- /** Present platform-native backend choices, then start on selection or timeout. */
30444
+ /** Present platform-native backend choices. A choice opens the mode menu; a timeout or a failed menu creates nothing. */
30169
30445
  async beginClassicBackendSelection(data, adapter) {
30170
30446
  const adapterId = adapter.id;
30171
30447
  const blocker = this.validateClassicStart(data.channelId, data.userId, data.guildId, adapterId);
@@ -30178,18 +30454,7 @@ export class FleetManager {
30178
30454
  id: `${CLASSIC_BACKEND_CALLBACK_PREFIX}${nonce}:${choice.id}`,
30179
30455
  label: `${this.isBackendInstalled(choice.id) ? "✅" : "❌"} ${choice.label}`,
30180
30456
  }));
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
- };
30457
+ const complete = this.classicStartComplete(data, adapter);
30193
30458
  const timer = setTimeout(() => {
30194
30459
  // Timeout: cancel the selection — do NOT fall back to default.
30195
30460
  const p = this.pendingClassicStarts.get(nonce);
@@ -30201,27 +30466,38 @@ export class FleetManager {
30201
30466
  timer.unref?.();
30202
30467
  const pending = {
30203
30468
  channelId: data.channelId,
30204
- channelName: data.channelName,
30469
+ channelName: data.channelName || data.channelId,
30205
30470
  userId: data.userId,
30206
30471
  guildId: data.guildId,
30207
30472
  adapterId,
30208
30473
  timer,
30209
30474
  complete,
30475
+ phase: "backend",
30476
+ showMenu: this.classicModePoster(data, adapter),
30210
30477
  };
30211
30478
  this.pendingClassicStarts.set(nonce, pending);
30212
30479
  try {
30480
+ const prompt = t("classic.choose_backend");
30213
30481
  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);
30482
+ ? await data.respondChoices(prompt, choices)
30483
+ : await adapter.promptUser(data.channelId, prompt, choices);
30216
30484
  }
30217
30485
  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);
30486
+ // No silent default backend and no silent Restricted room.
30487
+ this.logger.warn({ err, channelId: data.channelId, adapterId }, "Classic backend menu failed; nothing created");
30488
+ await this.cancelClassicPending(nonce, t("classic.backend_menu_failed"));
30222
30489
  }
30223
30490
  }
30224
- /** Consume a selection callback. Returns true for all ClassicBot callback IDs, including stale ones. */
30491
+ /** Drop a pending /start without creating a room. */
30492
+ async cancelClassicPending(nonce, text) {
30493
+ const pending = this.pendingClassicStarts.get(nonce);
30494
+ if (!pending)
30495
+ return;
30496
+ this.pendingClassicStarts.delete(nonce);
30497
+ clearTimeout(pending.timer);
30498
+ await pending.complete(text, pending.messageId);
30499
+ }
30500
+ /** Consume a backend click. Returns true for every classic-backend id, including a stale one. */
30225
30501
  async handleClassicBackendSelection(data) {
30226
30502
  if (!data.callbackData.startsWith(CLASSIC_BACKEND_CALLBACK_PREFIX))
30227
30503
  return false;
@@ -30229,11 +30505,12 @@ export class FleetManager {
30229
30505
  if (!match)
30230
30506
  return true;
30231
30507
  const pending = this.pendingClassicStarts.get(match[1]);
30232
- if (!pending)
30508
+ if (!pending || pending.phase === "mode")
30233
30509
  return true;
30234
30510
  // 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)
30511
+ // issued /start may consume the pending selection. No user id fails closed:
30512
+ // choosing the backend is part of creating the room.
30513
+ if (!data.userId || data.userId !== pending.userId)
30237
30514
  return true;
30238
30515
  const callbackChannelId = data.threadId ?? data.chatId;
30239
30516
  if (callbackChannelId !== pending.channelId && data.chatId !== pending.channelId)
@@ -30241,25 +30518,125 @@ export class FleetManager {
30241
30518
  await this.finishClassicBackendSelection(match[1], match[2]);
30242
30519
  return true;
30243
30520
  }
30244
- /** Atomically claim one pending request so timeout/click races create at most one instance. */
30521
+ /** The backend is chosen. Retire that menu and ask for the mode. Nothing is registered here. */
30245
30522
  async finishClassicBackendSelection(nonce, backend) {
30246
30523
  const pending = this.pendingClassicStarts.get(nonce);
30247
- if (!pending)
30524
+ if (!pending || pending.phase === "mode")
30248
30525
  return;
30249
30526
  this.pendingClassicStarts.delete(nonce);
30250
30527
  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);
30528
+ if (!isSelectableClassicBackend(backend)) {
30529
+ await pending.complete(t("classic.backend_required"), pending.messageId);
30530
+ return;
30531
+ }
30532
+ // The grant can be revoked while the backend menu is up. Do not offer a mode, or create a room, after that.
30533
+ const blocker = this.validateClassicStart(pending.channelId, pending.userId, pending.guildId, pending.adapterId);
30534
+ if (blocker) {
30535
+ await pending.complete(blocker, pending.messageId);
30536
+ return;
30537
+ }
30538
+ await pending.complete(t("classic.backend_chosen", backend), pending.messageId);
30539
+ await this.openClassicModeMenu(pending, backend);
30540
+ }
30541
+ /** After a backend is known (slash, `/start BACKEND`, or a backend click). The room waits for a mode click. */
30542
+ async beginClassicModeSelection(data, adapter, backend, adapterId) {
30543
+ const ownerId = adapterId ?? adapter?.id;
30544
+ const blocker = this.validateClassicStart(data.channelId, data.userId, data.guildId, ownerId);
30545
+ if (blocker) {
30546
+ await data.respond(blocker);
30547
+ return;
30548
+ }
30549
+ await this.openClassicModeMenu({
30550
+ channelId: data.channelId,
30551
+ channelName: data.channelName || data.channelId,
30552
+ userId: data.userId,
30553
+ guildId: data.guildId,
30554
+ adapterId: ownerId,
30555
+ complete: this.classicStartComplete(data, adapter),
30556
+ showMenu: this.classicModePoster(data, adapter),
30557
+ }, backend);
30558
+ }
30559
+ /** For a fleet admin, Free is first and labeled recommended. Restricted stays a button.
30560
+ * Anyone else sees only Restricted. Either way the room waits for a tap. */
30561
+ async openClassicModeMenu(origin, backend) {
30562
+ const free = this.canChooseFreeMode(origin.userId, origin.adapterId);
30563
+ const missing = this.getMissingBackendWarning(backend);
30564
+ const prompt = [missing, t(free ? "classic.choose_mode" : "classic.choose_mode_fixed")].filter(Boolean).join("\n\n");
30565
+ if (!origin.showMenu) {
30566
+ await origin.complete(t("classic.mode_menu_failed"));
30567
+ return;
30568
+ }
30569
+ const nonce = randomBytes(6).toString("hex");
30570
+ const restrictedChoice = {
30571
+ id: `${CLASSIC_MODE_CALLBACK_PREFIX}${nonce}:restricted`,
30572
+ label: t("classic.mode_restricted"),
30573
+ };
30574
+ const choices = free
30575
+ ? [{ id: `${CLASSIC_MODE_CALLBACK_PREFIX}${nonce}:free`, label: t("classic.mode_free_recommended") }, restrictedChoice]
30576
+ : [restrictedChoice];
30577
+ const timer = setTimeout(() => {
30578
+ const pending = this.pendingClassicStarts.get(nonce);
30579
+ if (!pending)
30580
+ return;
30581
+ this.pendingClassicStarts.delete(nonce);
30582
+ pending.complete(t("classic.mode_selection_expired"), pending.messageId).catch(() => { });
30583
+ }, CLASSIC_BACKEND_SELECTION_TIMEOUT_MS);
30584
+ timer.unref?.();
30585
+ const pending = {
30586
+ channelId: origin.channelId,
30587
+ channelName: origin.channelName || origin.channelId,
30588
+ userId: origin.userId,
30589
+ guildId: origin.guildId,
30590
+ adapterId: origin.adapterId,
30591
+ timer,
30592
+ complete: origin.complete,
30593
+ phase: "mode",
30594
+ backend,
30595
+ showMenu: origin.showMenu,
30596
+ };
30597
+ this.pendingClassicStarts.set(nonce, pending);
30598
+ try {
30599
+ pending.messageId = await origin.showMenu(prompt, choices);
30600
+ }
30601
+ catch (err) {
30602
+ this.logger.warn({ err, channelId: origin.channelId, adapterId: origin.adapterId }, "Classic mode menu failed; nothing created");
30603
+ await this.cancelClassicPending(nonce, t("classic.mode_menu_failed"));
30604
+ }
30605
+ }
30606
+ /** Consume a mode click. A Free click from anyone else is ignored and the menu stays up. */
30607
+ async handleClassicModeSelection(data) {
30608
+ if (!data.callbackData.startsWith(CLASSIC_MODE_CALLBACK_PREFIX))
30609
+ return false;
30610
+ const match = data.callbackData.match(/^classic-mode:([0-9a-f]+):(restricted|free)$/);
30611
+ if (!match)
30612
+ return true;
30613
+ const pending = this.pendingClassicStarts.get(match[1]);
30614
+ if (!pending || pending.phase !== "mode")
30615
+ return true;
30616
+ // Same identity rule as the backend click. A missing user id must not settle
30617
+ // Restricted or Free, including Free opened by a fleet admin.
30618
+ if (!data.userId || data.userId !== pending.userId)
30619
+ return true;
30620
+ const callbackChannelId = data.threadId ?? data.chatId;
30621
+ if (callbackChannelId !== pending.channelId && data.chatId !== pending.channelId)
30622
+ return true;
30623
+ if (match[2] === "free" && !this.canChooseFreeMode(pending.userId, pending.adapterId)) {
30624
+ data.ack?.(t("classic.mode_free_admin_only"));
30625
+ return true;
30626
+ }
30627
+ await this.finishClassicModeSelection(match[1], match[2] === "restricted");
30628
+ return true;
30629
+ }
30630
+ /** Claim the mode choice and create the room. A second click or the timeout finds nothing. */
30631
+ async finishClassicModeSelection(nonce, restricted) {
30632
+ const pending = this.pendingClassicStarts.get(nonce);
30633
+ if (!pending || pending.phase !== "mode" || !pending.backend)
30634
+ return;
30635
+ this.pendingClassicStarts.delete(nonce);
30636
+ clearTimeout(pending.timer);
30637
+ const missing = this.getMissingBackendWarning(pending.backend);
30638
+ 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));
30639
+ await pending.complete(missing ? `${missing}\n\n${reply}` : reply, pending.messageId);
30263
30640
  }
30264
30641
  /** Start a classic channel instance with lightweight config */
30265
30642
  async startClassicInstance(instanceName, backend, preTaskCommand, model, autoPauseAfter, transition, execution) {
@@ -30309,7 +30686,7 @@ export class FleetManager {
30309
30686
  await this.startInstance(instanceName, config, topicMode, "classic", false, transition);
30310
30687
  }
30311
30688
  /** Handle /start slash command — register classic channel */
30312
- async handleClassicStart(channelId, channelName, userId, guildId, adapterId, backend) {
30689
+ async handleClassicStart(channelId, channelName, userId, guildId, adapterId, backend, restricted = true) {
30313
30690
  const blocker = this.validateClassicStart(channelId, userId, guildId, adapterId);
30314
30691
  if (blocker)
30315
30692
  return blocker;
@@ -30319,7 +30696,7 @@ export class FleetManager {
30319
30696
  const instanceName = classicChannels.deriveInstanceName(channelName || channelId, channelId, adapterId);
30320
30697
  clearPausedMarker(this.getInstanceDir(instanceName));
30321
30698
  const selectedBackend = isSelectableClassicBackend(backend) ? backend : undefined;
30322
- classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend);
30699
+ classicChannels.register(channelId, adapterId, instanceName, channelName || channelId, userId, selectedBackend, restricted);
30323
30700
  // Bind this classic instance to the bot that started it (authoritative), so
30324
30701
  // replies/cancel go out through that bot even though every same-guild bot
30325
30702
  // also sees the channel's messages.