@songsid/agend 2.4.0-beta.13 → 2.4.0-beta.15

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 (183) hide show
  1. package/dist/agent-endpoint.js +28 -6
  2. package/dist/agent-endpoint.js.map +1 -1
  3. package/dist/auth-api.js +1 -0
  4. package/dist/auth-api.js.map +1 -1
  5. package/dist/backend/claude-code.d.ts +9 -0
  6. package/dist/backend/claude-code.js +60 -4
  7. package/dist/backend/claude-code.js.map +1 -1
  8. package/dist/backend/grok.js +11 -0
  9. package/dist/backend/grok.js.map +1 -1
  10. package/dist/backend/types.d.ts +3 -0
  11. package/dist/backend/types.js.map +1 -1
  12. package/dist/backend-availability.d.ts +1 -16
  13. package/dist/backend-availability.js +2 -91
  14. package/dist/backend-availability.js.map +1 -1
  15. package/dist/backend-version-static.d.ts +15 -0
  16. package/dist/backend-version-static.js +95 -0
  17. package/dist/backend-version-static.js.map +1 -0
  18. package/dist/build-provenance.json +1 -1
  19. package/dist/channel/adapters/telegram.js +3 -1
  20. package/dist/channel/adapters/telegram.js.map +1 -1
  21. package/dist/channel/mcp-server.js +18 -1
  22. package/dist/channel/mcp-server.js.map +1 -1
  23. package/dist/channel/tool-router.d.ts +4 -0
  24. package/dist/channel/tool-router.js +43 -19
  25. package/dist/channel/tool-router.js.map +1 -1
  26. package/dist/classic-channel-manager.d.ts +3 -0
  27. package/dist/classic-channel-manager.js +18 -0
  28. package/dist/classic-channel-manager.js.map +1 -1
  29. package/dist/classic-cli-guard.d.ts +66 -0
  30. package/dist/classic-cli-guard.js +209 -0
  31. package/dist/classic-cli-guard.js.map +1 -0
  32. package/dist/cli-audited.js +7 -5
  33. package/dist/cli-audited.js.map +1 -1
  34. package/dist/config-validator.js +3 -0
  35. package/dist/config-validator.js.map +1 -1
  36. package/dist/contact-auth-api.d.ts +17 -0
  37. package/dist/contact-auth-api.js +88 -0
  38. package/dist/contact-auth-api.js.map +1 -0
  39. package/dist/contact-auth-files.d.ts +6 -0
  40. package/dist/contact-auth-files.js +29 -0
  41. package/dist/contact-auth-files.js.map +1 -0
  42. package/dist/contact-auth-policy.d.ts +80 -0
  43. package/dist/contact-auth-policy.js +25 -0
  44. package/dist/contact-auth-policy.js.map +1 -0
  45. package/dist/contact-auth-service.d.ts +32 -0
  46. package/dist/contact-auth-service.js +99 -0
  47. package/dist/contact-auth-service.js.map +1 -0
  48. package/dist/contact-auth-store.d.ts +86 -0
  49. package/dist/contact-auth-store.js +357 -0
  50. package/dist/contact-auth-store.js.map +1 -0
  51. package/dist/contact-auth-types.d.ts +196 -0
  52. package/dist/contact-auth-types.js +7 -0
  53. package/dist/contact-auth-types.js.map +1 -0
  54. package/dist/daemon.d.ts +8 -0
  55. package/dist/daemon.js +93 -4
  56. package/dist/daemon.js.map +1 -1
  57. package/dist/delivery-outbox.d.ts +6 -0
  58. package/dist/delivery-outbox.js +19 -0
  59. package/dist/delivery-outbox.js.map +1 -1
  60. package/dist/fleet-manager.d.ts +48 -0
  61. package/dist/fleet-manager.js +484 -22
  62. package/dist/fleet-manager.js.map +1 -1
  63. package/dist/general-knowledge/skills/concepts/SKILL.md +18 -0
  64. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +5 -0
  65. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +38 -0
  66. package/dist/general-knowledge/skills/hub/SKILL.md +6 -0
  67. package/dist/general-knowledge/skills/web-dashboard/SKILL.md +5 -0
  68. package/dist/hub/audit/index.d.ts +3 -1
  69. package/dist/hub/audit/index.js +35 -3
  70. package/dist/hub/audit/index.js.map +1 -1
  71. package/dist/hub/catalog.d.ts +8 -0
  72. package/dist/hub/catalog.js +39 -4
  73. package/dist/hub/catalog.js.map +1 -1
  74. package/dist/hub/compose/server.d.ts +2 -0
  75. package/dist/hub/compose/server.js +11 -1
  76. package/dist/hub/compose/server.js.map +1 -1
  77. package/dist/hub/directory/directory.js +5 -2
  78. package/dist/hub/directory/directory.js.map +1 -1
  79. package/dist/hub/directory/types.d.ts +5 -1
  80. package/dist/hub/directory/types.js.map +1 -1
  81. package/dist/hub/group-policy/resources.d.ts +1 -1
  82. package/dist/hub/http/compose.d.ts +2 -0
  83. package/dist/hub/http/compose.js +123 -6
  84. package/dist/hub/http/compose.js.map +1 -1
  85. package/dist/hub/http/deps.d.ts +2 -0
  86. package/dist/hub/http/schema.js +6 -1
  87. package/dist/hub/http/schema.js.map +1 -1
  88. package/dist/hub/invitations.js +15 -7
  89. package/dist/hub/invitations.js.map +1 -1
  90. package/dist/hub/roles/cutover-inventory.d.ts +3 -0
  91. package/dist/hub/roles/cutover-inventory.js +20 -4
  92. package/dist/hub/roles/cutover-inventory.js.map +1 -1
  93. package/dist/hub/roles/cutover-marker.d.ts +18 -2
  94. package/dist/hub/roles/cutover-marker.js +6 -2
  95. package/dist/hub/roles/cutover-marker.js.map +1 -1
  96. package/dist/hub/room-agent-discovery-model.d.ts +29 -0
  97. package/dist/hub/room-agent-discovery-model.js +33 -0
  98. package/dist/hub/room-agent-discovery-model.js.map +1 -0
  99. package/dist/hub/room-agent-discovery.d.ts +14 -0
  100. package/dist/hub/room-agent-discovery.js +65 -0
  101. package/dist/hub/room-agent-discovery.js.map +1 -0
  102. package/dist/hub/room-agent-requests.d.ts +71 -0
  103. package/dist/hub/room-agent-requests.js +377 -0
  104. package/dist/hub/room-agent-requests.js.map +1 -0
  105. package/dist/hub/rooms/directory.d.ts +13 -0
  106. package/dist/hub/rooms/directory.js +12 -3
  107. package/dist/hub/rooms/directory.js.map +1 -1
  108. package/dist/hub/rooms/schema.d.ts +5 -0
  109. package/dist/hub/rooms/schema.js +9 -0
  110. package/dist/hub/rooms/schema.js.map +1 -1
  111. package/dist/hub/rooms/service.d.ts +43 -19
  112. package/dist/hub/rooms/service.js +67 -11
  113. package/dist/hub/rooms/service.js.map +1 -1
  114. package/dist/hub/rooms/types.d.ts +1 -1
  115. package/dist/instance-lifecycle.d.ts +3 -1
  116. package/dist/instance-lifecycle.js +4 -1
  117. package/dist/instance-lifecycle.js.map +1 -1
  118. package/dist/locale.js +34 -4
  119. package/dist/locale.js.map +1 -1
  120. package/dist/needs-you-hub.d.ts +1 -0
  121. package/dist/needs-you-hub.js +9 -0
  122. package/dist/needs-you-hub.js.map +1 -1
  123. package/dist/needs-you.d.ts +12 -2
  124. package/dist/needs-you.js.map +1 -1
  125. package/dist/outbound-handlers.d.ts +9 -0
  126. package/dist/outbound-handlers.js +46 -10
  127. package/dist/outbound-handlers.js.map +1 -1
  128. package/dist/runtime-cli-install.js +7 -7
  129. package/dist/runtime-cli-install.js.map +1 -1
  130. package/dist/topic-commands.d.ts +1 -1
  131. package/dist/topic-commands.js +4 -6
  132. package/dist/topic-commands.js.map +1 -1
  133. package/dist/ui/agent-details-settings.js +7 -5
  134. package/dist/ui/contact-auth-client.js +50 -0
  135. package/dist/ui/contact-auth-strings.js +195 -0
  136. package/dist/ui/contact-authorizations.js +125 -0
  137. package/dist/ui/contact-needs.js +100 -0
  138. package/dist/ui/contact-permissions.js +238 -0
  139. package/dist/ui/contact-ticket-badge.js +54 -0
  140. package/dist/ui/contact-tool-groups.js +39 -0
  141. package/dist/ui/hub-client.js +30 -7
  142. package/dist/ui/hub-invitations.js +5 -1
  143. package/dist/ui/hub-room-new.js +10 -3
  144. package/dist/ui/hub-room-owner-requests-strings.js +114 -0
  145. package/dist/ui/hub-room-owner-requests.js +264 -0
  146. package/dist/ui/hub-room-pins.js +43 -0
  147. package/dist/ui/hub-room-settings.js +11 -2
  148. package/dist/ui/hub-room-strings.js +3 -0
  149. package/dist/ui/hub-room-thread.js +47 -5
  150. package/dist/ui/panel-chat.js +2 -0
  151. package/dist/ui/panel-details.js +2 -0
  152. package/dist/ui/panel-fleet.js +3 -2
  153. package/dist/ui/panel-hub.js +7 -1
  154. package/dist/ui/panel-needs.js +11 -4
  155. package/dist/ui/panel-settings.js +3 -0
  156. package/dist/ui/settings-appearance.js +6 -1
  157. package/dist/ui/settings-registry.js +1 -1
  158. package/dist/ui/shared/app-i18n.js +4 -0
  159. package/dist/ui/shared/app-route.js +1 -1
  160. package/dist/ui/shared/app-shell.js +18 -7
  161. package/dist/ui/shared/app-stream.js +3 -1
  162. package/dist/ui/shared/app.css +86 -0
  163. package/dist/ui/shared/chat-quote.js +26 -2
  164. package/dist/ui/shared/chat-thread.js +6 -2
  165. package/dist/ui/shared/hub-rooms-u2.css +22 -0
  166. package/dist/ui/shared/text-undo.js +17 -3
  167. package/dist/ui/shared/theme-picker.js +46 -0
  168. package/dist/ui/shared/theme.js +36 -3
  169. package/dist/ui/shared/tokens.css +273 -0
  170. package/dist/ui/shared/ui-confirm.js +5 -2
  171. package/dist/web-api.d.ts +10 -0
  172. package/dist/web-api.js +55 -3
  173. package/dist/web-api.js.map +1 -1
  174. package/dist/web-chat-history.d.ts +5 -0
  175. package/dist/web-chat-history.js +26 -0
  176. package/dist/web-chat-history.js.map +1 -1
  177. package/dist/web-reply-files.d.ts +1 -0
  178. package/dist/web-reply-files.js +2 -0
  179. package/dist/web-reply-files.js.map +1 -1
  180. package/dist/web-shell-routes.d.ts +1 -1
  181. package/dist/web-shell-routes.js +2 -1
  182. package/dist/web-shell-routes.js.map +1 -1
  183. package/package.json +1 -1
@@ -1,4 +1,8 @@
1
1
  import { withHubRoomReplyWarning } from "./hub-room-reply-warning.js";
2
+ import { ContactAuthService } from "./contact-auth-service.js";
3
+ import { stageContactFiles } from "./contact-auth-files.js";
4
+ import { ContactOriginClearSchema, ContactPermissionsSchema, sameContactPerson } from "./contact-auth-policy.js";
5
+ import { CLASSIC_RESTRICTED_TOOLS } from "./contact-auth-types.js";
2
6
  import { hubSharingNoticeText } from "./hub-sharing-notice.js";
3
7
  import { hubPageSharingSettings } from "./hub-page-sharing-settings.js";
4
8
  import { replyPreviews } from "./reply-preview-spec.js";
@@ -354,8 +358,8 @@ import { agyLegacyAgentsFile, danglingSymlink, migrateAgyAgentsFile } from "./ba
354
358
  import { claudeConfigDirFor, claudeProjectKey } from "./backend/claude-code.js";
355
359
  import { sharedRolloutIndex } from "./rollout-index.js";
356
360
  import { TASK_BOARD_ON_NOTICE, dashboardRefusalIn, taskBoardOffIn, taskBoardSwitchedOn } from "./dashboard-permissions.js";
357
- import { mayUseTool, resolveToolSet, scheduleOpRefusal, toolForIpcType, toolRefusedMessage, } from "./tool-permissions.js";
358
- import { authorizeSession, decideWebGate, loadOrCreateWebToken, readSessionCookies, readWebToken, sessionCookieUpgrade } from "./web-auth.js";
361
+ import { mayUseTool, toolsFor, resolveToolSet, scheduleOpRefusal, toolForIpcType, toolRefusedMessage, } from "./tool-permissions.js";
362
+ import { authorizeSession, decideWebGate, evaluateWebRequest, loadOrCreateWebToken, readSessionCookies, readWebToken, sessionCookieUpgrade } from "./web-auth.js";
359
363
  import { takeAssetVersion, warmAssetVersion } from "./web-asset-version.js";
360
364
  import { bypassesWebGate, handleAuthRequest, serveGuestRefusedPage, serveSigninPage } from "./auth-api.js";
361
365
  import { isWebPageNavigation } from "./web-shell-routes.js";
@@ -366,7 +370,7 @@ import { DeviceLoginRequests } from "./web-device-login.js";
366
370
  import { findSigninKnownEntry, addSigninKnownDevice } from "./web-signin-device.js";
367
371
  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";
368
372
  import { evaluateSettingsRole } from "./authority/settings-role.js";
369
- import { authorityNow, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
373
+ import { authorityNow, classifyWebPeer, evaluateWebAuthority, HOST_OPERATOR, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
370
374
  import { AuthorityStateStore, namedLinkLastTurnedOff } from "./authority/authority-state.js";
371
375
  import { SessionAuthorizations } from "./authority/session-authorizations.js";
372
376
  import { SessionAuthorizationRequests } from "./web-session-authorization.js";
@@ -1412,7 +1416,8 @@ export class FleetManager {
1412
1416
  if (this.paneManager)
1413
1417
  return this.paneManager;
1414
1418
  const store = windowsAgentsFor(this, this.runtimeWindowsExecutor());
1415
- const allowed = (name, tool) => nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
1419
+ const allowed = (name, tool) => (!this.classicContactRestricted(name) || CLASSIC_RESTRICTED_TOOLS.includes(tool))
1420
+ && nativePaneToolAvailable(tool) && mayUseTool(resolveToolSet(this.fleetConfig?.instances[name], name), tool)
1416
1421
  && !dashboardRefusalIn(this.fleetConfig, name, tool);
1417
1422
  return this.paneManager = new NativePaneManager({
1418
1423
  home: this.dataDir, store, config: name => this.fleetConfig?.instances[name],
@@ -5698,6 +5703,15 @@ export class FleetManager {
5698
5703
  if (row)
5699
5704
  for (const name of new Set([row.sourceInstance, row.targetInstance]))
5700
5705
  this.observeWorkingState(name, "obligations");
5706
+ const badge = row?.payload.contactTicket;
5707
+ const ticket = badge?.id ? outbox.contactAuthorizations.get(badge.id) : undefined;
5708
+ if (ticket && ticket.deliveryId === row?.deliveryId) {
5709
+ const state = event.state === "delivered" ? "delivered" : ["failed", "uncertain", "cancelled", "reconciliation_pending"].includes(event.state ?? "") ? "unknown" : "approved";
5710
+ for (const instance of new Set([ticket.source, ticket.target])) {
5711
+ this.webChatHistory?.updateContactTicket(instance, ticket.id, state);
5712
+ this.emitSseEvent("contact-auth", { instance, ticketId: ticket.id, revision: ticket.revision });
5713
+ }
5714
+ }
5701
5715
  }
5702
5716
  this.scheduleDeliveryOutboxPump();
5703
5717
  this.wakeCoordinator?.kick();
@@ -5737,6 +5751,7 @@ export class FleetManager {
5737
5751
  this.publishTraffic(row, "consumed");
5738
5752
  });
5739
5753
  outbox.on("generation_recovered", () => this.scheduleDeliveryOutboxPump());
5754
+ this.sweepContactAuthorizationOutcomes();
5740
5755
  this.replyObligationTimer = setInterval(() => measureSyncWork("fleet.replyObligationSweep", () => this.sweepReplyObligations()), REPLY_OBLIGATION_SWEEP_MS);
5741
5756
  this.replyObligationTimer.unref?.();
5742
5757
  // #856: the text the target daemon received differs from what was
@@ -5804,6 +5819,358 @@ export class FleetManager {
5804
5819
  this.trafficMemo = { atMs: nowMs, value: { now, items, delegations } };
5805
5820
  return this.trafficMemo.value;
5806
5821
  }
5822
+ contactRoom(name) { return this.classicChannels?.getAll?.().find(room => room.instanceName === name); }
5823
+ classicContactRestricted(instance) { return this.contactRoom(instance)?.restrictedMode === true; }
5824
+ inheritContactOrigin(source, target) {
5825
+ const service = this.contactService();
5826
+ if (service.host.legacyClassic?.(source))
5827
+ return;
5828
+ const origin = service.origin(source);
5829
+ if (origin)
5830
+ service.host.store.inheritOrigin(target, { ...origin, chain: [...origin.chain, target] });
5831
+ }
5832
+ contactAdapter(name) {
5833
+ const id = this.contactRoom(name)?.adapterId ?? this.getInstanceAdapterId(name);
5834
+ return id ? this.adapters.get(id) ?? this.worlds.get(id)?.adapter ?? null : null;
5835
+ }
5836
+ /** Called only with SDK input at the Classic ingress, never agent-supplied routing metadata. */
5837
+ recordClassicContactInput(instance, msg, adapter) {
5838
+ const room = this.contactRoom(instance);
5839
+ if (room?.restrictedMode !== true || msg.isBotMessage || msg.chatId !== room.channelId
5840
+ || (room.adapterId && room.adapterId !== adapter.id) || msg.adapterId !== adapter.id)
5841
+ return;
5842
+ const nativeThread = msg.transportThreadId ?? msg.threadId;
5843
+ const thread = nativeThread && nativeThread !== room.channelId && nativeThread.length <= 128
5844
+ && !/[\r\n\x00]/.test(nativeThread) ? nativeThread : undefined;
5845
+ const fileIds = (msg.attachments ?? []).map(file => file.fileId)
5846
+ .filter(id => typeof id === "string" && id.length > 0 && id.length <= 4096).slice(0, 20);
5847
+ this.contactService().host.store.recordRoomContext(instance, { ...(thread ? { threadId: thread } : {}), fileIds }, this.contactGeneration(instance));
5848
+ }
5849
+ restrictedClassicRouting(instance) {
5850
+ const room = this.contactRoom(instance);
5851
+ if (room?.restrictedMode !== true)
5852
+ return undefined;
5853
+ const adapter = this.contactAdapter(instance);
5854
+ if (!adapter)
5855
+ throw Error("Restricted room adapter is unavailable");
5856
+ const context = this.contactService().host.store.roomContext(instance, this.contactGeneration(instance));
5857
+ return { adapterId: adapter.id, chatId: room.channelId, ...(context.threadId ? { threadId: context.threadId } : {}) };
5858
+ }
5859
+ async prepareContactFiles(instance, paths) {
5860
+ if (this.contactRoom(instance)?.restrictedMode !== true || paths.length === 0)
5861
+ return undefined;
5862
+ const incarnation = this.contactGeneration(instance), home = realpathSync(getAgendHome());
5863
+ const inbox = join(home, "workspaces", instance, "inbox");
5864
+ const lease = await stageContactFiles(paths, home, inbox);
5865
+ if (this.contactGeneration(instance) !== incarnation) {
5866
+ await lease.dispose();
5867
+ throw Error("Room identity changed before attachment delivery");
5868
+ }
5869
+ return lease;
5870
+ }
5871
+ async downloadRoomAttachment(instance, fileId) {
5872
+ const route = this.restrictedClassicRouting(instance);
5873
+ if (!route)
5874
+ throw Error("This is not a restricted Classic room");
5875
+ const incarnation = this.contactGeneration(instance), store = this.contactService().host.store;
5876
+ if (!store.roomContext(instance, incarnation).fileIds.includes(fileId))
5877
+ throw Error("This attachment was not received in this room");
5878
+ const adapter = this.contactAdapter(instance);
5879
+ if (!adapter)
5880
+ throw Error("Restricted room adapter is unavailable");
5881
+ const file = await adapter.downloadAttachment(fileId);
5882
+ const home = realpathSync(getAgendHome()), scratch = join(home, "workspaces", instance, "inbox", "room-scratch");
5883
+ const copied = await snapshotReplyFile(file, scratch, randomBytes(16).toString("hex"), {
5884
+ stateDir: home, allowedRoots: [join(home, "inbox")], maxFileBytes: 20 * 1024 * 1024, maxDirBytes: 400 * 1024 * 1024,
5885
+ });
5886
+ if (!copied.ok)
5887
+ throw Error("The room attachment could not be copied safely");
5888
+ if (this.contactGeneration(instance) !== incarnation) {
5889
+ try {
5890
+ unlinkSync(copied.path);
5891
+ }
5892
+ catch { /* our snapshot only */ }
5893
+ throw Error("Room identity changed during attachment download");
5894
+ }
5895
+ return copied.path;
5896
+ }
5897
+ configureClassicRestriction(name, daemon) {
5898
+ const room = this.contactRoom(name);
5899
+ if (!room)
5900
+ return;
5901
+ const guarded = daemon;
5902
+ if (room.restrictedMode !== true) {
5903
+ guarded.setClassicRestriction?.({ mode: "legacy", roomTools: { publicRead: true, allowedMcpTools: [] } });
5904
+ return;
5905
+ }
5906
+ const policy = this.contactService().host.store.policy(name, this.contactGeneration(name));
5907
+ guarded.setClassicRestriction?.({ mode: room.restrictedMode === true ? "restricted" : "legacy",
5908
+ roomTools: policy.roomTools, policyRevision: policy.revision });
5909
+ }
5910
+ contactGeneration(name) {
5911
+ // Reuse the existing durable incarnation fence: replacement/retarget rotates it,
5912
+ // while an ordinary pause or daemon restart must not strand an approved request.
5913
+ const incarnation = this.hubAgentToken(name);
5914
+ if (!incarnation)
5915
+ throw Error("unavailable");
5916
+ return incarnation;
5917
+ }
5918
+ contactAdminOf(name, actor) {
5919
+ if (actor.platform === "host" && actor.adapterId === "host" && actor.userId === "operator")
5920
+ return true;
5921
+ const adapter = this.contactAdapter(name);
5922
+ if (!adapter || actor.adapterId !== adapter.id || actor.platform !== adapter.type)
5923
+ return false;
5924
+ return this.isFleetAdmin(actor.userId, adapter.id)
5925
+ || (!!this.contactRoom(name) && this.classicChannels?.isAdmin(actor.userId) === true);
5926
+ }
5927
+ contactService() {
5928
+ this.ensureDeliveryOutbox();
5929
+ return new ContactAuthService({ store: this.deliveryOutbox.contactAuthorizations,
5930
+ restricted: name => this.contactRoom(name)?.restrictedMode === true,
5931
+ legacyClassic: name => !!this.contactRoom(name) && this.contactRoom(name)?.restrictedMode !== true,
5932
+ adminOf: (name, actor) => this.contactAdminOf(name, actor),
5933
+ defaultApprovers: name => {
5934
+ const adapter = this.contactAdapter(name);
5935
+ if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
5936
+ return [];
5937
+ return (this.adminListOf(adapter.id) ?? []).map(userId => ({ platform: adapter.type, adapterId: adapter.id, userId, label: userId }));
5938
+ },
5939
+ generation: name => this.contactGeneration(name),
5940
+ hubRestricted: name => this.hubContactRestricted(name),
5941
+ delivered: ticket => !!ticket.deliveryId && this.deliveryOutbox.get(ticket.deliveryId)?.state === "delivered",
5942
+ deliveryState: ticket => ticket.deliveryId ? this.deliveryOutbox.get(ticket.deliveryId)?.state : undefined,
5943
+ admit: (request, ticketId) => {
5944
+ const payload = { ...request.payload, contactTicket: { id: ticketId, state: "delivered" } };
5945
+ const admitted = this.deliveryOutbox.admit({ operationId: request.operationId,
5946
+ sourceKey: `contact:${ticketId}`, sourceInstance: request.source,
5947
+ sourceDaemonBootId: this.getDaemonBootId(request.source) ?? request.sourceGeneration,
5948
+ targetInstance: request.target, targetSession: String(request.payload.targetSession ?? request.target),
5949
+ kind: String(request.payload.type ?? "fleet_inbound"), correlationId: request.correlationId,
5950
+ payload, forwards: request.forwards });
5951
+ this.scheduleDeliveryOutboxPump();
5952
+ return admitted.delivery.deliveryId;
5953
+ },
5954
+ changed: (instance, ticketId) => {
5955
+ this.sweepContactAuthorizationOutcomes();
5956
+ const revision = this.deliveryOutbox.contactAuthorizations.policy(instance).revision;
5957
+ const ticket = ticketId ? this.deliveryOutbox.contactAuthorizations.get(ticketId) : undefined;
5958
+ if (ticket) {
5959
+ this.emitSseEvent("message", { instance: ticket.source, role: "status", sender: "AgEnD", ts: new Date().toISOString(),
5960
+ text: t(ticket.state === "pending" ? "contact.held" : ticket.state === "approved" ? "contact.approved" : "contact.updated"),
5961
+ contactTicket: { id: ticket.id, state: ticket.state } });
5962
+ if (ticket.state === "approved")
5963
+ this.emitSseEvent("message", { instance: ticket.target, role: "user",
5964
+ sender: ticket.source, text: ticket.message, ts: new Date().toISOString(), contactTicket: { id: ticket.id, state: "approved" } });
5965
+ }
5966
+ this.emitSseEvent("contact-auth", { instance, ...(ticketId ? { ticketId } : {}), revision });
5967
+ this.needsYou?.poke();
5968
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
5969
+ },
5970
+ });
5971
+ }
5972
+ contactDeliveryCurrent(row) {
5973
+ const badge = row.payload.contactTicket;
5974
+ if (!badge)
5975
+ return true;
5976
+ if (typeof badge.id !== "string")
5977
+ return false;
5978
+ const service = this.contactService(), ticket = service.host.store.get(badge.id);
5979
+ return !!ticket && ticket.deliveryId === row.deliveryId && ticket.source === row.sourceInstance && ticket.target === row.targetInstance
5980
+ && !!ticket.decidedBy && service.canManage(ticket.target, ticket.decidedBy)
5981
+ && Date.parse(ticket.expiresAt) > Date.now()
5982
+ && ticket.sourceGeneration === this.contactGeneration(ticket.source)
5983
+ && ticket.targetGeneration === this.contactGeneration(ticket.target)
5984
+ && !this.hubContactRestricted(ticket.source);
5985
+ }
5986
+ contactPermissions(name, actor) {
5987
+ const service = this.contactService(), room = this.contactRoom(name);
5988
+ const canManage = service.canManage(name, actor), canSetMode = !!room && this.contactAdminOf(name, actor);
5989
+ if (!canManage && !canSetMode)
5990
+ throw Error("forbidden");
5991
+ if (!this.webChatOwner(name))
5992
+ throw Error("not-found");
5993
+ const store = service.host.store, generation = this.contactGeneration(name), policy = store.policy(name, generation);
5994
+ const origin = store.origin(name);
5995
+ const daemon = this.daemons.get(name);
5996
+ const backend = room ? this.classicChannels.getBackendByInstance(name, this.fleetConfig?.defaults?.backend) : this.fleetConfig?.instances[name]?.backend ?? "unknown";
5997
+ const nativeGuard = daemon?.classicNativeGuard?.() ?? { state: "not-covered", backend, reason: "Native guard is not loaded in this build", impactComplete: false };
5998
+ const removedTools = room ? [...toolsFor(resolveToolSet(this.fleetConfig?.instances[name], name))]
5999
+ .filter(tool => !CLASSIC_RESTRICTED_TOOLS.includes(tool)) : [];
6000
+ return { instance: name, revision: policy.revision,
6001
+ originState: { kind: origin?.kind ?? "none", people: origin?.people ?? [], chain: origin?.chain ?? [],
6002
+ receiptCount: origin?.receiptIds.length ?? 0, revision: store.originRevision(name), generation,
6003
+ canClear: canManage && !!origin, lastCleared: store.lastOriginClear(name, generation) },
6004
+ classicRoom: !!room,
6005
+ mode: room?.restrictedMode === true ? "restricted" : "legacy", approvers: service.approvers(name),
6006
+ eligibleApprovers: service.host.defaultApprovers(name),
6007
+ inheritedApprovers: policy.approvers === undefined,
6008
+ nativeGuard,
6009
+ canManage, canSetMode, suggestRestricted: !!room && room.restrictedMode !== true && !store.suggestionDismissed(name),
6010
+ roomTools: { ...policy.roomTools, wouldDisable: [...new Set([...removedTools, ...(nativeGuard.wouldDisable ?? [])])] }, grants: policy.grants, history: store.histories(name, this.contactGeneration(name)),
6011
+ ...(service.needsApplication(name) ? { originRestriction: { active: true,
6012
+ reason: !service.origin(name) || service.origin(name)?.kind === "unknown" ? "unknown-origin" : "earlier-non-admin", resetSupported: false } } : {}) };
6013
+ }
6014
+ contactActor(req, url) {
6015
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
6016
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
6017
+ return null;
6018
+ const result = this.webAuthority({ session: verdict.session, gateway: !!gatewayRequestContext(req),
6019
+ peer: gatewayRequestContext(req) ? (gatewayRequestContext(req)?.named ? "named_link" : "quick_link") : classifyWebPeer(req) });
6020
+ const actor = result.authority.kind === "web-verified" ? result.authority.actor : null;
6021
+ if (!actor)
6022
+ return null;
6023
+ if (actor.adapter_id === "host" && actor.user_id === "operator")
6024
+ return { platform: "host", adapterId: "host", userId: "operator", label: "Operator" };
6025
+ const adapter = this.adapters.get(actor.adapter_id);
6026
+ if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6027
+ return null;
6028
+ return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: actor.user_id };
6029
+ }
6030
+ writeContactPermissions(name, raw, actor) {
6031
+ const parsed = ContactPermissionsSchema.safeParse(raw);
6032
+ if (!parsed.success)
6033
+ throw Error("invalid-request");
6034
+ const input = parsed.data, before = this.contactPermissions(name, actor), store = this.contactService().host.store;
6035
+ if ((input.approvers || input.grants) && !before.canManage)
6036
+ throw Error("forbidden");
6037
+ if (input.approvers?.some(person => !before.eligibleApprovers.some(allowed => sameContactPerson(person, allowed))))
6038
+ throw Error("invalid-approver");
6039
+ if ((input.mode || input.roomTools) && !before.canSetMode)
6040
+ throw Error("forbidden");
6041
+ if (input.grants?.some(grant => grant.target !== name || !this.webChatOwner(grant.source)
6042
+ || Date.parse(grant.expiresAt) <= Date.now()))
6043
+ throw Error("invalid-grant");
6044
+ // Configuration does not prove an external MCP's account independence. Preserve a conservative warning.
6045
+ if (input.roomTools)
6046
+ input.roomTools.allowedMcpTools = input.roomTools.allowedMcpTools.map(tool => ({ ...tool,
6047
+ usesOwnerAccount: true, accountWarning: t("contact.mcpAccountWarning") }));
6048
+ if (input.revision !== before.revision)
6049
+ throw Error("conflict");
6050
+ // Mode persists in the existing Classic configuration; absent historical fields remain legacy.
6051
+ if (input.mode) {
6052
+ if (input.mode === "restricted" && before.mode !== "restricted")
6053
+ store.inheritOrigin(name, { kind: "unknown", people: [], receiptIds: [], chain: [name] });
6054
+ this.classicChannels.setRestrictedMode(name, input.mode === "restricted");
6055
+ }
6056
+ const policy = store.writePolicy(name, input, actor, instance => this.contactGeneration(instance));
6057
+ const daemon = this.daemons.get(name);
6058
+ daemon?.setClassicRestriction?.({ mode: this.contactRoom(name)?.restrictedMode === true ? "restricted" : "legacy",
6059
+ roomTools: policy.roomTools, policyRevision: policy.revision });
6060
+ this.emitSseEvent("contact-auth", { instance: name, revision: policy.revision });
6061
+ this.needsYou?.poke();
6062
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
6063
+ return this.contactPermissions(name, actor);
6064
+ }
6065
+ clearContactOrigin(name, raw, actor) {
6066
+ const parsed = ContactOriginClearSchema.safeParse(raw);
6067
+ if (!parsed.success)
6068
+ throw Error("invalid-request");
6069
+ const service = this.contactService();
6070
+ if (!service.canManage(name, actor))
6071
+ throw Error("forbidden");
6072
+ if (!this.webChatOwner(name))
6073
+ throw Error("not-found");
6074
+ service.host.store.clearOrigin(name, parsed.data, actor, () => {
6075
+ if (!service.canManage(name, actor))
6076
+ throw Error("forbidden");
6077
+ return this.contactGeneration(name);
6078
+ });
6079
+ this.emitSseEvent("contact-auth", { instance: name, revision: parsed.data.revision,
6080
+ originRevision: service.host.store.originRevision(name) });
6081
+ return this.contactPermissions(name, actor);
6082
+ }
6083
+ contactAuthorization(id, actor) {
6084
+ const service = this.contactService(), ticket = service.host.store.get(id);
6085
+ if (!ticket)
6086
+ throw Error("not-found");
6087
+ return service.view(ticket, actor);
6088
+ }
6089
+ contactAuthorizations(actor, filter) {
6090
+ const service = this.contactService(), page = service.host.store.list({ ...filter, status: undefined });
6091
+ return { ...page, items: page.items.flatMap(ticket => {
6092
+ try {
6093
+ const view = service.view(ticket, actor);
6094
+ if (filter.status && view.state !== filter.status)
6095
+ return [];
6096
+ if (filter.person && !view.origin.people.some(person => JSON.stringify([person.platform, person.adapterId, person.userId]) === filter.person))
6097
+ return [];
6098
+ return [view];
6099
+ }
6100
+ catch {
6101
+ return [];
6102
+ }
6103
+ }) };
6104
+ }
6105
+ decideContactAuthorization(id, decision, actor) {
6106
+ return this.contactService().decide(id, decision, actor);
6107
+ }
6108
+ /** Status only: no human receipt, approval capability or original correlation is attached. */
6109
+ sweepContactAuthorizationOutcomes() {
6110
+ const outbox = this.deliveryOutbox;
6111
+ if (!outbox?.isOpen || this.shuttingDown)
6112
+ return;
6113
+ try {
6114
+ outbox.contactAuthorizations.notifyOutcomes(ticket => {
6115
+ outbox.admitSystemNotice(ticket.source, `contact-outcome:${ticket.id}`, t(ticket.state === "declined" ? "contact.noticeDeclined" : "contact.noticeExpired", ticket.id, ticket.target));
6116
+ });
6117
+ }
6118
+ catch (err) {
6119
+ this.logger.error({ err }, "Contact outcome notice sweep failed; durable state will retry");
6120
+ }
6121
+ }
6122
+ contactNeeds(actor) {
6123
+ const service = this.contactService();
6124
+ const pending = service.host.store.pending()
6125
+ .filter(ticket => { try {
6126
+ return service.view(ticket, actor).canDecide;
6127
+ }
6128
+ catch {
6129
+ return false;
6130
+ } }).map(ticket => ({
6131
+ id: `contact:${ticket.id}`, type: "contact", reason: "contact_request", instance: ticket.target,
6132
+ since: Date.parse(ticket.createdAt), detail: "", contactTicket: { id: ticket.id, source: ticket.source, target: ticket.target },
6133
+ }));
6134
+ return [...pending, ...(this.classicChannels?.getAll() ?? []).filter(room => room.restrictedMode !== true
6135
+ && !service.host.store.suggestionDismissed(room.instanceName) && this.contactAdminOf(room.instanceName, actor))
6136
+ .map(room => ({ id: `contact-suggest:${room.instanceName}`, type: "contact",
6137
+ reason: "contact_restricted_suggestion", instance: room.instanceName,
6138
+ since: service.host.store.suggestionRaisedAt(room.instanceName), detail: "", contactSuggestion: { instance: room.instanceName } }))];
6139
+ }
6140
+ /**
6141
+ * The chat's contact items. M-3381 (the user, beta.14): the restricted-mode suggestions are ONE low-key line per world —
6142
+ * "N existing ClassicBot rooms can switch to restricted mode", saying where to act (the dashboard's Needs you, or a
6143
+ * room's Permissions) — not one line per room; each room's age counts from when its suggestion was raised.
6144
+ */
6145
+ contactSuggestions() {
6146
+ const rooms = this.classicChannels?.getAll().filter(room => room.restrictedMode !== true) ?? [];
6147
+ const store = this.contactService().host.store;
6148
+ const pending = store.pending().map(ticket => ({ id: `contact:${ticket.id}`, type: "contact",
6149
+ reason: "contact_request", instance: ticket.target, owner: this.getAdapterForInstance(ticket.target)?.id,
6150
+ since: Date.parse(ticket.createdAt), detail: "", contactTicket: { id: ticket.id, source: ticket.source, target: ticket.target } }));
6151
+ const byWorld = new Map();
6152
+ for (const room of rooms) {
6153
+ if (store.suggestionDismissed(room.instanceName))
6154
+ continue;
6155
+ const owner = this.getAdapterForInstance(room.instanceName)?.id;
6156
+ if (owner === undefined)
6157
+ continue;
6158
+ const raised = store.suggestionRaisedAt(room.instanceName), group = byWorld.get(owner);
6159
+ byWorld.set(owner, { count: (group?.count ?? 0) + 1, since: Math.min(group?.since ?? Infinity, raised) });
6160
+ }
6161
+ return [...pending, ...[...byWorld].map(([owner, group]) => ({
6162
+ id: `contact-suggest:rooms:${owner}`, type: "contact", reason: "contact_restricted_suggestion", instance: "", owner,
6163
+ // Low-key (#4228 review): listed in the chat's Needs you, but never a new-item notification or a DM.
6164
+ since: group.since, detail: "", contactSuggestionCount: group.count, quiet: true,
6165
+ }))];
6166
+ }
6167
+ acknowledgeContactSuggestion(instance, actor) {
6168
+ if (!this.contactAdminOf(instance, actor) || !this.contactRoom(instance))
6169
+ throw Error("forbidden");
6170
+ this.contactService().host.store.dismissSuggestion(instance);
6171
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
6172
+ this.needsYou?.poke();
6173
+ }
5807
6174
  /** Synchronous SQLite admission; the caller may acknowledge only after this returns. */
5808
6175
  admitDurableDelivery(input) {
5809
6176
  const bindingHold = this.generalLocationDeliveryHold(input.targetInstance);
@@ -5817,6 +6184,24 @@ export class FleetManager {
5817
6184
  if (!currentSourceBootId || !sourceDaemonBootId || currentSourceBootId !== sourceDaemonBootId) {
5818
6185
  throw new Error("Source daemon generation is no longer current; outcome is unknown");
5819
6186
  }
6187
+ const service = this.contactService();
6188
+ const metadata = input.payload.meta;
6189
+ const requestKind = metadata?.request_kind;
6190
+ const authorizationDeliveryId = service.requireApplication({ operationId: input.operationId, source: input.sourceInstance, target: input.targetInstance,
6191
+ verb: input.kind === "broadcast" ? "broadcast" : requestKind === "task" ? "delegate_task" : requestKind === "query" ? "request_information"
6192
+ : requestKind === "report" ? "report_result" : "send_to_instance",
6193
+ message: String(input.payload.content ?? ""), correlationId: input.correlationId,
6194
+ correlationExplicit: input.correlationExplicit ?? true,
6195
+ resultRecipient: input.sourceInstance, payload: input.payload, forwards: input.forwards });
6196
+ if (authorizationDeliveryId) {
6197
+ const delivery = outbox.get(authorizationDeliveryId);
6198
+ if (!delivery)
6199
+ throw Error("Authorized delivery is unavailable");
6200
+ return { deliveryId: delivery.deliveryId, state: delivery.state, duplicate: true, kind: delivery.kind };
6201
+ }
6202
+ const inheritedOrigin = service.origin(input.sourceInstance);
6203
+ if (inheritedOrigin && !service.host.legacyClassic?.(input.sourceInstance))
6204
+ service.host.store.inheritOrigin(input.targetInstance, { ...inheritedOrigin, chain: [...inheritedOrigin.chain, input.targetInstance] });
5820
6205
  const sourceKey = `mcp:${input.sourceInstance}:${input.operationId}:${input.targetInstance}:${input.targetSession ?? ""}:${input.kind}`;
5821
6206
  const admitted = outbox.admit({ ...input, sourceDaemonBootId, sourceKey });
5822
6207
  if (admitted.inserted)
@@ -5999,6 +6384,7 @@ export class FleetManager {
5999
6384
  * requesters are no longer told about overdue or expired asks (they can check delivery_status / describe_instance).
6000
6385
  */
6001
6386
  sweepReplyObligations(now = new Date()) {
6387
+ this.sweepContactAuthorizationOutcomes();
6002
6388
  const outbox = this.deliveryOutbox;
6003
6389
  if (!outbox || this.shuttingDown)
6004
6390
  return;
@@ -6354,11 +6740,15 @@ export class FleetManager {
6354
6740
  };
6355
6741
  sent = await this.deliverToInstance(target, payload, {
6356
6742
  isCrossInstance: true,
6743
+ stillCurrent: () => this.contactDeliveryCurrent(claimed),
6357
6744
  waitForIdle: claimed.kind !== "steer",
6358
6745
  noInlineWake: this.deliveryWorkerMode(target) !== "off",
6359
6746
  });
6360
6747
  }
6361
6748
  if (!sent) {
6749
+ if (payload.contactTicket && !this.contactDeliveryCurrent(claimed)) {
6750
+ outbox.cancelUnsubmittedContact(claimed.deliveryId, "Contact approval became stale before input");
6751
+ }
6362
6752
  const current = outbox.get(claimed.deliveryId);
6363
6753
  if (current?.state === "delivering") {
6364
6754
  outbox.retryBeforeBegin(claimed.deliveryId, claimed.targetDaemonBootId, claimed.attemptNo, "delivery was cancelled before target IPC handoff", Math.min(60_000, 1_000 * 2 ** Math.min(attempt - 1, 6)));
@@ -6396,8 +6786,8 @@ export class FleetManager {
6396
6786
  }
6397
6787
  const meta = claimed.payload.meta && typeof claimed.payload.meta === "object" ? claimed.payload.meta : {};
6398
6788
  const task = await this.nativeInstanceRuntime().execute(target, { ...claimed.payload, requestId: deliveryId, meta: { ...meta, from_instance: claimed.sourceInstance, correlation_id: claimed.correlationId } }, {
6399
- stillCurrent: () => !this.shuttingDown,
6400
- beforeStart: () => { if (outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
6789
+ stillCurrent: () => !this.shuttingDown && this.contactDeliveryCurrent(claimed),
6790
+ beforeStart: () => { if (!this.contactDeliveryCurrent(claimed) || outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
6401
6791
  throw new Error("Windows delivery attempt is no longer current"); begun = true; },
6402
6792
  });
6403
6793
  const outcome = task.outcomeConfirmed === false ? "uncertain" : task.status === "completed" ? "delivered" : "failed";
@@ -6415,6 +6805,8 @@ export class FleetManager {
6415
6805
  const reason = error instanceof Error ? error.message : String(error);
6416
6806
  if (begun)
6417
6807
  outbox.complete(deliveryId, targetDaemonBootId, attemptNo, "uncertain", reason);
6808
+ else if (claimed.payload.contactTicket && !this.contactDeliveryCurrent(claimed))
6809
+ outbox.cancelUnsubmittedContact(deliveryId, "Contact approval became stale before input");
6418
6810
  else
6419
6811
  outbox.retryBeforeBegin(deliveryId, targetDaemonBootId, attemptNo, reason, 5000);
6420
6812
  this.logger.warn({ target, deliveryId, err: reason }, "Windows durable delivery did not complete");
@@ -8511,6 +8903,26 @@ export class FleetManager {
8511
8903
  return payload;
8512
8904
  const row = this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
8513
8905
  origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
8906
+ const contactStore = this.deliveryOutbox.contactAuthorizations;
8907
+ if (this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
8908
+ throw Error("Contact origin storage unavailable");
8909
+ if (contactStore && (this.contactRoom(instanceName)?.restrictedMode === true || contactStore.origin(instanceName))) {
8910
+ const authority = origin.authority;
8911
+ const actor = origin.platform === "web" ? (authority?.kind === "web-verified" ? authority.actor : null)
8912
+ : { adapter_id: origin.adapter_id, user_id: origin.user_id };
8913
+ const adapter = actor?.adapter_id ? this.adapters.get(actor.adapter_id) : undefined;
8914
+ const platform = origin.platform === "web" ? adapter?.type : origin.platform;
8915
+ const person = actor?.adapter_id && actor.user_id
8916
+ && (platform === "discord" || platform === "telegram" || (actor.adapter_id === "host" && actor.user_id === "operator"))
8917
+ ? { platform: actor.adapter_id === "host" ? "host" : platform,
8918
+ adapterId: actor.adapter_id, userId: actor.user_id, label: origin.username ?? actor.user_id } : undefined;
8919
+ contactStore.inheritOrigin(instanceName, { kind: person ? "human" : "unknown", people: person ? [person] : [],
8920
+ receiptIds: [row.message_id], chain: [instanceName] });
8921
+ if (this.contactRoom(instanceName)?.restrictedMode === true && (!person || !this.contactAdminOf(instanceName, person))
8922
+ && typeof payload.content === "string" && (payload.type === "fleet_inbound" || payload.type === "steer")) {
8923
+ payload = { ...payload, content: `${t(person ? "contact.originNonAdmin" : "contact.originUnknown")}\n\n${payload.content}` };
8924
+ }
8925
+ }
8514
8926
  // #1939 §7: each ordinary verified web message, for the S1 beta to watch. No text, cookie or session id: the handle.
8515
8927
  const authority = origin.authority;
8516
8928
  if (authority?.kind === "web-verified" && authority.actor && authority.session) {
@@ -8955,8 +9367,7 @@ export class FleetManager {
8955
9367
  await this.handleTipsSlash(data, adapterId);
8956
9368
  }
8957
9369
  else if (data.command === "status") {
8958
- // Admin-gated (like the topic path): the merged table shows every
8959
- // instance's cost and IPC health.
9370
+ // Admin-gated, like the topic path: use the shared fleet instance table.
8960
9371
  if (!this.isFleetAdmin(data.userId, adapterId)) {
8961
9372
  await data.respond(t("cmd.admin_required", "/status"));
8962
9373
  return;
@@ -14879,6 +15290,8 @@ export class FleetManager {
14879
15290
  }
14880
15291
  const channelName = msg.username || chatId;
14881
15292
  if (requestedBackend) {
15293
+ // Advisory before the new-room policy is persisted, including direct /start BACKEND.
15294
+ await msgAdapter?.sendText(chatId, this.getClassicStartWarning(requestedBackend));
14882
15295
  // handleClassicStart binds the instance to this adapter authoritatively.
14883
15296
  const reply = await this.handleClassicStart(chatId, channelName, msg.userId, undefined, msg.adapterId, requestedBackend);
14884
15297
  await msgAdapter?.sendText(chatId, reply);
@@ -15387,6 +15800,9 @@ export class FleetManager {
15387
15800
  }
15388
15801
  }
15389
15802
  checkToolPermission(sink, instanceName, tool) {
15803
+ if (this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && !CLASSIC_RESTRICTED_TOOLS.includes(tool)) {
15804
+ return { allowed: false, message: "This Classic room is restricted. This tool is not in its room tool allowance." };
15805
+ }
15390
15806
  if (isCanvasWorkerTool(tool))
15391
15807
  return { allowed: false, message: CANVAS_WORKER_EXPERIMENTAL_MESSAGE }; // #2799: removed
15392
15808
  const profile = resolveToolSet(this.fleetConfig?.instances[instanceName], instanceName);
@@ -15482,7 +15898,7 @@ export class FleetManager {
15482
15898
  return;
15483
15899
  }
15484
15900
  // #2305: a reaction to a web chat message is the web chat's own (any fleet, web-only included): never an adapter's.
15485
- if (tool === "react" && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
15901
+ if (tool === "react" && !this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
15486
15902
  // The socket's own instance, never a session name the caller wrote itself (as checkToolPermission: it was not
15487
15903
  // identified) — a channel tool's call from a daemon carries none anyway (#2310 review).
15488
15904
  const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji);
@@ -15502,9 +15918,29 @@ export class FleetManager {
15502
15918
  : "Channel adapters are not ready — retry shortly");
15503
15919
  return;
15504
15920
  }
15921
+ const restrictedRoute = this.restrictedClassicRouting(instanceName);
15922
+ const restrictedIncarnation = restrictedRoute ? this.contactGeneration(instanceName) : undefined;
15923
+ const restrictedBoot = restrictedRoute ? this.getDaemonBootId(instanceName) : undefined;
15924
+ if (restrictedRoute && Array.isArray(args.previews) && args.previews.length) {
15925
+ respond(null, "File previews are not available in restricted rooms; use the room's own attachments");
15926
+ return;
15927
+ }
15928
+ let replyBookkeeping = Promise.resolve();
15929
+ const restrictedExtras = restrictedRoute ? {
15930
+ prepareFiles: (paths) => this.prepareContactFiles(instanceName, paths),
15931
+ replyFinished: () => replyBookkeeping,
15932
+ downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id),
15933
+ beforeSend: () => {
15934
+ const current = this.restrictedClassicRouting(instanceName);
15935
+ if (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
15936
+ || current.threadId !== restrictedRoute.threadId || this.contactGeneration(instanceName) !== restrictedIncarnation
15937
+ || this.getDaemonBootId(instanceName) !== restrictedBoot)
15938
+ throw Error("Restricted room route changed before delivery");
15939
+ },
15940
+ } : {};
15505
15941
  // Resolve threadId: use sender's topic_id if sender is a known fleet instance,
15506
15942
  // fall back to general topic if sender is unknown, or IPC owner if no sender.
15507
- const senderInstanceName = senderSessionName && this.fleetConfig?.instances[senderSessionName]
15943
+ const senderInstanceName = !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
15508
15944
  ? senderSessionName
15509
15945
  : null;
15510
15946
  const routingConfig = senderInstanceName
@@ -15516,9 +15952,9 @@ export class FleetManager {
15516
15952
  // ids are scoped to that bot/world; routing a secondary-world id through the
15517
15953
  // primary adapter produces a 404. Instance binding remains the compatibility
15518
15954
  // fallback for older daemons and calls without a live/persisted context.
15519
- const contextAdapterId = typeof msg.adapterId === "string" && msg.adapterId
15955
+ const contextAdapterId = restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId
15520
15956
  ? msg.adapterId
15521
- : undefined;
15957
+ : undefined);
15522
15958
  const contextWorld = contextAdapterId ? this.worlds.get(contextAdapterId) : undefined;
15523
15959
  if (contextAdapterId && !contextWorld) {
15524
15960
  respond(null, `Adapter world unavailable: ${contextAdapterId}`);
@@ -15552,6 +15988,14 @@ export class FleetManager {
15552
15988
  threadId = undefined;
15553
15989
  }
15554
15990
  }
15991
+ if (restrictedRoute) {
15992
+ args.chat_id = restrictedRoute.chatId;
15993
+ threadId = restrictedRoute.threadId;
15994
+ if (threadId)
15995
+ args.thread_id = threadId;
15996
+ else
15997
+ delete args.thread_id;
15998
+ }
15555
15999
  // Reply dedup: retries land here when the agent was told a send failed
15556
16000
  // (daemon budget elapsed, shell tool killed) while the adapter send was
15557
16001
  // still in flight and about to succeed. One real send, everyone gets its
@@ -15668,7 +16112,8 @@ export class FleetManager {
15668
16112
  && this.landedInOwnChannel(instanceName, replyAdapterId, result);
15669
16113
  }
15670
16114
  catch { /* not known: not the channel's (fail closed), and the bookkeeping below still runs */ }
15671
- void this.afterReplyRouted(instanceName, args, senderSessionName, buttonsView, inChannel, replyAdapterId ? { adapterId: replyAdapterId, result } : undefined, replyIdentity, result);
16115
+ replyBookkeeping = this.afterReplyRouted(instanceName, args, senderSessionName, buttonsView, inChannel, replyAdapterId ? { adapterId: replyAdapterId, result } : undefined, replyIdentity, result)
16116
+ .catch(err => { this.logger.warn({ err, instanceName }, "Reply bookkeeping failed after confirmed delivery"); });
15672
16117
  }
15673
16118
  catch (err) {
15674
16119
  this.logger.warn({ err, instanceName }, "Reply delivered but post-delivery bookkeeping failed");
@@ -15683,7 +16128,7 @@ export class FleetManager {
15683
16128
  });
15684
16129
  }
15685
16130
  };
15686
- if (routeToolCall(outAdapter, tool, args, threadId, respondAndRecord, replySet ? { replyButtons: replySet.callbacks, ...(replySet.poll ? { replyPoll: replySet.poll } : {}) } : {})) {
16131
+ if (routeToolCall(outAdapter, tool, args, threadId, respondAndRecord, { ...restrictedExtras, ...(replySet ? { replyButtons: replySet.callbacks, ...(replySet.poll ? { replyPoll: replySet.poll } : {}) } : {}) })) {
15687
16132
  return;
15688
16133
  }
15689
16134
  if (replySet)
@@ -15694,7 +16139,7 @@ export class FleetManager {
15694
16139
  return;
15695
16140
  }
15696
16141
  // Route standard channel tools (reply, react, edit_message, download_attachment)
15697
- if (routeToolCall(outAdapter, tool, args, threadId, respond)) {
16142
+ if (routeToolCall(outAdapter, tool, args, threadId, respond, restrictedExtras)) {
15698
16143
  return;
15699
16144
  }
15700
16145
  if (handler) {
@@ -16487,6 +16932,10 @@ export class FleetManager {
16487
16932
  if (op !== "list") {
16488
16933
  const profile = resolveToolSet(this.fleetConfig?.instances[caller], caller);
16489
16934
  const existing = op === "create" ? null : scheduler.get(args.id);
16935
+ const effectiveTarget = requestedTarget?.trim() || existing?.target || caller;
16936
+ if ((op === "create" || op === "update") && effectiveTarget !== caller && this.contactService().needsApplication(caller)) {
16937
+ throw new ToolNotPermittedError("Scheduled peer contact needs approval. Use a contact application instead; this conversation's origin remains restricted.");
16938
+ }
16490
16939
  const refusal = scheduleOpRefusal(profile, caller, op, { requestedTarget, existing });
16491
16940
  if (refusal) {
16492
16941
  this.logger.warn({ instance: caller, profile, op, target: requestedTarget ?? existing?.target, scheduleId: args.id }, "tool-permissions: schedule op refused");
@@ -20183,6 +20632,7 @@ export class FleetManager {
20183
20632
  return owner !== undefined && this.worlds.has(owner) ? owner : undefined;
20184
20633
  };
20185
20634
  this.needsYou = new NeedsYouHub({
20635
+ contactSuggestions: () => this.contactSuggestions(),
20186
20636
  dataDir: this.dataDir,
20187
20637
  now: () => Date.now(),
20188
20638
  mono: () => performance.now(),
@@ -24221,7 +24671,9 @@ export class FleetManager {
24221
24671
  const installable = new Set(Object.keys(BACKEND_INSTALLATION_INFO));
24222
24672
  const candidates = new Set([...installed, ...configured, ...installable]);
24223
24673
  const unsupported = [];
24674
+ const details = [];
24224
24675
  const choices = [...candidates].sort().flatMap(backend => {
24676
+ const label = backend === "claude-code" ? "Claude" : BACKEND_LABELS[backend] ?? backend;
24225
24677
  const flow = LOGIN_FLOWS[backend];
24226
24678
  const remoteLogin = !!flow && flow.remoteLogin !== "unsupported";
24227
24679
  const isInstalled = installed.has(backend);
@@ -24231,11 +24683,13 @@ export class FleetManager {
24231
24683
  status.push(t("login.status_configured"));
24232
24684
  if (!isInstalled && installable.has(backend)) {
24233
24685
  status.push(t(remoteLogin ? "login.status_install_then_auth" : "login.status_install"));
24234
- return [{ action: backend, label: `${backend} · ${status.join(" · ")}` }];
24686
+ details.push(`${label} · ${status.join(" · ")}`);
24687
+ return [{ action: backend, label }];
24235
24688
  }
24236
24689
  if (remoteLogin && isInstalled) {
24237
24690
  status.push(t("login.status_auth"));
24238
- return [{ action: backend, label: `${backend} · ${status.join(" · ")}` }];
24691
+ details.push(`${label} · ${status.join(" · ")}`);
24692
+ return [{ action: backend, label }];
24239
24693
  }
24240
24694
  status.push(t("login.status_unsupported"));
24241
24695
  unsupported.push({ backend, flow, status });
@@ -24269,7 +24723,7 @@ export class FleetManager {
24269
24723
  adapterId: chat.adapterId,
24270
24724
  chatId: chat.chatId,
24271
24725
  threadId: chat.threadId,
24272
- message: `${t("login.choose_backend")}\n${t("fleet.label_line", fleetLabel(this.fleetConfig))}`,
24726
+ message: `${t("login.choose_backend")}\n${t("fleet.label_line", fleetLabel(this.fleetConfig))}\n\n${details.join("\n")}`,
24273
24727
  choices,
24274
24728
  expiredText: t("buttons.stale"),
24275
24729
  });
@@ -25317,6 +25771,7 @@ export class FleetManager {
25317
25771
  cards: m.cards,
25318
25772
  posts: m.posts, // #2281: kept beside the row, never broadcast (not a row field)
25319
25773
  reserved: m.reserved, // #1774: an agent reply's place, taken when it was sent
25774
+ contactTicket: m.contactTicket,
25320
25775
  });
25321
25776
  // A sending page's own id for its pending bubble rides on the live copy only: never recorded, never replayed.
25322
25777
  const clientId = typeof data.clientId === "string" ? data.clientId : "";
@@ -26228,6 +26683,9 @@ export class FleetManager {
26228
26683
  // #1085: a Telegram forum ClassicBot is keyed by chat id (threadId), but the
26229
26684
  // reply context must carry the topic the message was really asked in.
26230
26685
  const replyThreadId = msg.transportThreadId ?? msg.threadId;
26686
+ const contactAdapter = this.worlds.get(msg.adapterId ?? "")?.adapter;
26687
+ if (contactAdapter)
26688
+ this.recordClassicContactInput(instanceName, msg, contactAdapter);
26231
26689
  // Resolve the channel/adapter from the instance itself so per-channel context
26232
26690
  // config is correct even for a same-channel second bot.
26233
26691
  const ctxAdapterId = this.classicChannels?.getAdapterIdByInstance(instanceName);
@@ -28596,6 +29054,10 @@ export class FleetManager {
28596
29054
  return undefined;
28597
29055
  return t("classic.backend_not_installed", backend, installation.binary, installation.install);
28598
29056
  }
29057
+ /** Coverage is not proven before launch; disclose the fallback without blocking an unsupported CLI. */
29058
+ getClassicStartWarning(backend) {
29059
+ return [t("classic.restricted_start_notice"), this.getMissingBackendWarning(backend)].filter(Boolean).join("\n\n");
29060
+ }
28599
29061
  /** Handle Discord's required static slash choice, warning before a likely startup failure. */
28600
29062
  async handleClassicStartSlash(data, adapterId) {
28601
29063
  return withSpawnHoldReply(text => data.respond(text), () => this.handleClassicStartSlashCore(data, adapterId));
@@ -28616,7 +29078,7 @@ export class FleetManager {
28616
29078
  await data.respond(blocker);
28617
29079
  return;
28618
29080
  }
28619
- const warning = this.getMissingBackendWarning(requestedBackend);
29081
+ const warning = this.getClassicStartWarning(requestedBackend);
28620
29082
  // Keep the deferred ephemeral response useful even if daemon startup later
28621
29083
  // fails because the executable is absent. This is advisory, not a gate.
28622
29084
  if (warning)
@@ -28670,8 +29132,8 @@ export class FleetManager {
28670
29132
  this.pendingClassicStarts.set(nonce, pending);
28671
29133
  try {
28672
29134
  pending.messageId = data.respondChoices
28673
- ? await data.respondChoices(t("classic.choose_backend"), choices)
28674
- : await adapter.promptUser(data.channelId, t("classic.choose_backend"), choices);
29135
+ ? await data.respondChoices(`${t("classic.choose_backend")}\n\n${t("classic.restricted_start_notice")}`, choices)
29136
+ : await adapter.promptUser(data.channelId, `${t("classic.choose_backend")}\n\n${t("classic.restricted_start_notice")}`, choices);
28675
29137
  }
28676
29138
  catch (err) {
28677
29139
  // A menu transport failure should not make /start unusable: consume the
@@ -28712,7 +29174,7 @@ export class FleetManager {
28712
29174
  ?? this.classicChannels?.getDefaults().backend
28713
29175
  ?? this.fleetConfig?.defaults?.backend
28714
29176
  ?? "claude-code";
28715
- const warning = this.getMissingBackendWarning(effectiveBackend);
29177
+ const warning = this.getClassicStartWarning(effectiveBackend);
28716
29178
  // Show the warning before starting so it survives a missing-binary startup
28717
29179
  // failure. The selected backend is still attempted as requested.
28718
29180
  if (warning)