@songsid/agend 2.4.0-beta.12 → 2.4.0-beta.14

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 (226) 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 +5 -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/codex.js +11 -0
  9. package/dist/backend/codex.js.map +1 -1
  10. package/dist/backend/grok.js +11 -0
  11. package/dist/backend/grok.js.map +1 -1
  12. package/dist/backend/types.d.ts +4 -1
  13. package/dist/backend/types.js.map +1 -1
  14. package/dist/backend-availability.d.ts +1 -16
  15. package/dist/backend-availability.js +2 -91
  16. package/dist/backend-availability.js.map +1 -1
  17. package/dist/backend-version-static.d.ts +15 -0
  18. package/dist/backend-version-static.js +95 -0
  19. package/dist/backend-version-static.js.map +1 -0
  20. package/dist/build-provenance.json +1 -1
  21. package/dist/channel/adapters/telegram.js +3 -1
  22. package/dist/channel/adapters/telegram.js.map +1 -1
  23. package/dist/channel/mcp-server.js +18 -1
  24. package/dist/channel/mcp-server.js.map +1 -1
  25. package/dist/channel/tool-router.d.ts +4 -0
  26. package/dist/channel/tool-router.js +43 -19
  27. package/dist/channel/tool-router.js.map +1 -1
  28. package/dist/classic-channel-manager.d.ts +3 -0
  29. package/dist/classic-channel-manager.js +18 -0
  30. package/dist/classic-channel-manager.js.map +1 -1
  31. package/dist/classic-cli-guard.d.ts +66 -0
  32. package/dist/classic-cli-guard.js +209 -0
  33. package/dist/classic-cli-guard.js.map +1 -0
  34. package/dist/cli-audited.js +7 -5
  35. package/dist/cli-audited.js.map +1 -1
  36. package/dist/config-validator.js +3 -0
  37. package/dist/config-validator.js.map +1 -1
  38. package/dist/contact-auth-api.d.ts +16 -0
  39. package/dist/contact-auth-api.js +78 -0
  40. package/dist/contact-auth-api.js.map +1 -0
  41. package/dist/contact-auth-files.d.ts +6 -0
  42. package/dist/contact-auth-files.js +29 -0
  43. package/dist/contact-auth-files.js.map +1 -0
  44. package/dist/contact-auth-policy.d.ts +75 -0
  45. package/dist/contact-auth-policy.js +23 -0
  46. package/dist/contact-auth-policy.js.map +1 -0
  47. package/dist/contact-auth-service.d.ts +32 -0
  48. package/dist/contact-auth-service.js +99 -0
  49. package/dist/contact-auth-service.js.map +1 -0
  50. package/dist/contact-auth-store.d.ts +75 -0
  51. package/dist/contact-auth-store.js +295 -0
  52. package/dist/contact-auth-store.js.map +1 -0
  53. package/dist/contact-auth-types.d.ts +170 -0
  54. package/dist/contact-auth-types.js +7 -0
  55. package/dist/contact-auth-types.js.map +1 -0
  56. package/dist/daemon.d.ts +16 -1
  57. package/dist/daemon.js +127 -11
  58. package/dist/daemon.js.map +1 -1
  59. package/dist/delivery-outbox.d.ts +6 -0
  60. package/dist/delivery-outbox.js +19 -0
  61. package/dist/delivery-outbox.js.map +1 -1
  62. package/dist/dispatcher-liveness.js +2 -2
  63. package/dist/dispatcher-liveness.js.map +1 -1
  64. package/dist/fleet-manager.d.ts +45 -0
  65. package/dist/fleet-manager.js +450 -23
  66. package/dist/fleet-manager.js.map +1 -1
  67. package/dist/general-knowledge/skills/concepts/SKILL.md +18 -0
  68. package/dist/general-knowledge/skills/credential-profiles/SKILL.md +12 -0
  69. package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +28 -0
  70. package/dist/general-knowledge/skills/hub/SKILL.md +6 -0
  71. package/dist/hub/audit/index.d.ts +3 -1
  72. package/dist/hub/audit/index.js +35 -3
  73. package/dist/hub/audit/index.js.map +1 -1
  74. package/dist/hub/catalog.d.ts +8 -0
  75. package/dist/hub/catalog.js +39 -4
  76. package/dist/hub/catalog.js.map +1 -1
  77. package/dist/hub/compose/server.d.ts +2 -0
  78. package/dist/hub/compose/server.js +11 -1
  79. package/dist/hub/compose/server.js.map +1 -1
  80. package/dist/hub/directory/directory.js +5 -2
  81. package/dist/hub/directory/directory.js.map +1 -1
  82. package/dist/hub/directory/types.d.ts +5 -1
  83. package/dist/hub/directory/types.js.map +1 -1
  84. package/dist/hub/group-policy/resources.d.ts +1 -1
  85. package/dist/hub/http/compose.d.ts +2 -0
  86. package/dist/hub/http/compose.js +123 -6
  87. package/dist/hub/http/compose.js.map +1 -1
  88. package/dist/hub/http/deps.d.ts +2 -0
  89. package/dist/hub/http/schema.js +6 -1
  90. package/dist/hub/http/schema.js.map +1 -1
  91. package/dist/hub/invitations.js +15 -7
  92. package/dist/hub/invitations.js.map +1 -1
  93. package/dist/hub/roles/cutover-inventory.d.ts +3 -0
  94. package/dist/hub/roles/cutover-inventory.js +20 -4
  95. package/dist/hub/roles/cutover-inventory.js.map +1 -1
  96. package/dist/hub/roles/cutover-marker.d.ts +18 -2
  97. package/dist/hub/roles/cutover-marker.js +6 -2
  98. package/dist/hub/roles/cutover-marker.js.map +1 -1
  99. package/dist/hub/room-agent-discovery-model.d.ts +29 -0
  100. package/dist/hub/room-agent-discovery-model.js +33 -0
  101. package/dist/hub/room-agent-discovery-model.js.map +1 -0
  102. package/dist/hub/room-agent-discovery.d.ts +14 -0
  103. package/dist/hub/room-agent-discovery.js +65 -0
  104. package/dist/hub/room-agent-discovery.js.map +1 -0
  105. package/dist/hub/room-agent-requests.d.ts +71 -0
  106. package/dist/hub/room-agent-requests.js +377 -0
  107. package/dist/hub/room-agent-requests.js.map +1 -0
  108. package/dist/hub/rooms/directory.d.ts +13 -0
  109. package/dist/hub/rooms/directory.js +12 -3
  110. package/dist/hub/rooms/directory.js.map +1 -1
  111. package/dist/hub/rooms/schema.d.ts +5 -0
  112. package/dist/hub/rooms/schema.js +9 -0
  113. package/dist/hub/rooms/schema.js.map +1 -1
  114. package/dist/hub/rooms/service.d.ts +43 -19
  115. package/dist/hub/rooms/service.js +67 -11
  116. package/dist/hub/rooms/service.js.map +1 -1
  117. package/dist/hub/rooms/types.d.ts +1 -1
  118. package/dist/instance-lifecycle.d.ts +6 -1
  119. package/dist/instance-lifecycle.js +11 -4
  120. package/dist/instance-lifecycle.js.map +1 -1
  121. package/dist/locale.js +34 -4
  122. package/dist/locale.js.map +1 -1
  123. package/dist/needs-you-hub.d.ts +1 -0
  124. package/dist/needs-you-hub.js +6 -0
  125. package/dist/needs-you-hub.js.map +1 -1
  126. package/dist/needs-you.d.ts +14 -2
  127. package/dist/needs-you.js +4 -0
  128. package/dist/needs-you.js.map +1 -1
  129. package/dist/office-share-page.js +1 -1
  130. package/dist/office-share-page.js.map +1 -1
  131. package/dist/outbound-handlers.d.ts +9 -0
  132. package/dist/outbound-handlers.js +48 -10
  133. package/dist/outbound-handlers.js.map +1 -1
  134. package/dist/pause-marker.d.ts +1 -1
  135. package/dist/pause-marker.js +1 -1
  136. package/dist/pause-marker.js.map +1 -1
  137. package/dist/public-web-gateway.d.ts +20 -0
  138. package/dist/public-web-gateway.js +61 -4
  139. package/dist/public-web-gateway.js.map +1 -1
  140. package/dist/runtime-cli-install.js +7 -7
  141. package/dist/runtime-cli-install.js.map +1 -1
  142. package/dist/topic-commands.d.ts +1 -1
  143. package/dist/topic-commands.js +4 -6
  144. package/dist/topic-commands.js.map +1 -1
  145. package/dist/ui/accounts-keepalive.js +2 -1
  146. package/dist/ui/accounts-view.js +2 -1
  147. package/dist/ui/agent-details-settings.js +7 -5
  148. package/dist/ui/contact-auth-client.js +48 -0
  149. package/dist/ui/contact-auth-strings.js +164 -0
  150. package/dist/ui/contact-authorizations.js +125 -0
  151. package/dist/ui/contact-needs.js +84 -0
  152. package/dist/ui/contact-permissions.js +193 -0
  153. package/dist/ui/contact-ticket-badge.js +54 -0
  154. package/dist/ui/fleet-canvas.js +3 -1
  155. package/dist/ui/fleet-office-skin.js +4 -3
  156. package/dist/ui/fleet-route.js +44 -6
  157. package/dist/ui/fleet-task-view.js +2 -1
  158. package/dist/ui/host-install.js +5 -2
  159. package/dist/ui/hub-ai-apps.js +2 -1
  160. package/dist/ui/hub-chat-strings.js +2 -1
  161. package/dist/ui/hub-client.js +30 -7
  162. package/dist/ui/hub-grant-picker.js +2 -1
  163. package/dist/ui/hub-group-strings.js +2 -1
  164. package/dist/ui/hub-invitations.js +5 -1
  165. package/dist/ui/hub-my-agents.js +2 -1
  166. package/dist/ui/hub-owner-strings.js +2 -1
  167. package/dist/ui/hub-personal-agent.js +2 -1
  168. package/dist/ui/hub-quota.js +2 -1
  169. package/dist/ui/hub-roles-strings.js +2 -1
  170. package/dist/ui/hub-room-new-strings.js +2 -1
  171. package/dist/ui/hub-room-new.js +10 -3
  172. package/dist/ui/hub-room-owner-requests-strings.js +114 -0
  173. package/dist/ui/hub-room-owner-requests.js +264 -0
  174. package/dist/ui/hub-room-pins.js +43 -0
  175. package/dist/ui/hub-room-settings.js +11 -2
  176. package/dist/ui/hub-room-source.js +2 -1
  177. package/dist/ui/hub-room-strings.js +3 -0
  178. package/dist/ui/hub-room-thread.js +47 -5
  179. package/dist/ui/hub-strings.js +2 -1
  180. package/dist/ui/hub-teams.js +2 -1
  181. package/dist/ui/model-picker.js +3 -2
  182. package/dist/ui/panel-chat.js +8 -2
  183. package/dist/ui/panel-details.js +2 -0
  184. package/dist/ui/panel-fleet.js +3 -2
  185. package/dist/ui/panel-hub.js +14 -4
  186. package/dist/ui/panel-needs.js +8 -3
  187. package/dist/ui/panel-runtimes.js +2 -1
  188. package/dist/ui/panel-settings.js +3 -0
  189. package/dist/ui/reply-file-preview.js +2 -1
  190. package/dist/ui/settings-access-overview.js +2 -1
  191. package/dist/ui/settings-connector.js +2 -1
  192. package/dist/ui/shared/agent-sheet.js +2 -1
  193. package/dist/ui/shared/app-i18n.js +2 -2
  194. package/dist/ui/shared/app-route.js +1 -1
  195. package/dist/ui/shared/app-shell.js +35 -9
  196. package/dist/ui/shared/app-stream.js +3 -1
  197. package/dist/ui/shared/app.css +42 -0
  198. package/dist/ui/shared/asset-url.d.ts +2 -0
  199. package/dist/ui/shared/asset-url.js +20 -0
  200. package/dist/ui/shared/chat-quote.js +26 -2
  201. package/dist/ui/shared/chat-table-select.js +175 -0
  202. package/dist/ui/shared/chat-thread.js +6 -2
  203. package/dist/ui/shared/hub-rooms-u2.css +22 -0
  204. package/dist/ui/shared/image-annotate.js +2 -1
  205. package/dist/ui/shared/text-undo.js +17 -3
  206. package/dist/ui/shared/ui-states.js +3 -2
  207. package/dist/ui/shared/view-history.js +2 -1
  208. package/dist/ui/subagent-row.js +3 -2
  209. package/dist/ui/usage-pool.js +2 -1
  210. package/dist/ui/workspace-panel.js +2 -1
  211. package/dist/wake-coordinator.js +3 -2
  212. package/dist/wake-coordinator.js.map +1 -1
  213. package/dist/web-api.d.ts +9 -0
  214. package/dist/web-api.js +56 -4
  215. package/dist/web-api.js.map +1 -1
  216. package/dist/web-chat-history.d.ts +5 -0
  217. package/dist/web-chat-history.js +26 -0
  218. package/dist/web-chat-history.js.map +1 -1
  219. package/dist/web-host-install.d.ts +1 -1
  220. package/dist/web-reply-files.d.ts +1 -0
  221. package/dist/web-reply-files.js +2 -0
  222. package/dist/web-reply-files.js.map +1 -1
  223. package/dist/web-shell-routes.d.ts +1 -1
  224. package/dist/web-shell-routes.js +2 -1
  225. package/dist/web-shell-routes.js.map +1 -1
  226. 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 { 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],
@@ -2626,8 +2631,9 @@ export class FleetManager {
2626
2631
  locale: getLocale(),
2627
2632
  readState: agent => {
2628
2633
  const process = this.getInstanceStatus(agent), interaction = this.getInstanceInteraction(agent);
2634
+ const reason = process === "paused" ? readPauseReason(this.getInstanceDir(agent)) : null;
2629
2635
  return { process, execution: this.getInstanceExecutionState(agent),
2630
- pauseReason: process === "paused" ? readPauseReason(this.getInstanceDir(agent)) : null,
2636
+ pauseReason: reason === "stale_auth" ? "error" : reason,
2631
2637
  waitingForApproval: interaction?.phase === "waiting" && !interaction.stale && !interaction.suspected
2632
2638
  && (interaction.kind === "permission" || interaction.kind === "dangerous_command") };
2633
2639
  },
@@ -5697,6 +5703,15 @@ export class FleetManager {
5697
5703
  if (row)
5698
5704
  for (const name of new Set([row.sourceInstance, row.targetInstance]))
5699
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
+ }
5700
5715
  }
5701
5716
  this.scheduleDeliveryOutboxPump();
5702
5717
  this.wakeCoordinator?.kick();
@@ -5803,6 +5818,305 @@ export class FleetManager {
5803
5818
  this.trafficMemo = { atMs: nowMs, value: { now, items, delegations } };
5804
5819
  return this.trafficMemo.value;
5805
5820
  }
5821
+ contactRoom(name) { return this.classicChannels?.getAll?.().find(room => room.instanceName === name); }
5822
+ classicContactRestricted(instance) { return this.contactRoom(instance)?.restrictedMode === true; }
5823
+ inheritContactOrigin(source, target) {
5824
+ const service = this.contactService();
5825
+ if (service.host.legacyClassic?.(source))
5826
+ return;
5827
+ const origin = service.origin(source);
5828
+ if (origin)
5829
+ service.host.store.inheritOrigin(target, { ...origin, chain: [...origin.chain, target] });
5830
+ }
5831
+ contactAdapter(name) {
5832
+ const id = this.contactRoom(name)?.adapterId ?? this.getInstanceAdapterId(name);
5833
+ return id ? this.adapters.get(id) ?? this.worlds.get(id)?.adapter ?? null : null;
5834
+ }
5835
+ /** Called only with SDK input at the Classic ingress, never agent-supplied routing metadata. */
5836
+ recordClassicContactInput(instance, msg, adapter) {
5837
+ const room = this.contactRoom(instance);
5838
+ if (room?.restrictedMode !== true || msg.isBotMessage || msg.chatId !== room.channelId
5839
+ || (room.adapterId && room.adapterId !== adapter.id) || msg.adapterId !== adapter.id)
5840
+ return;
5841
+ const nativeThread = msg.transportThreadId ?? msg.threadId;
5842
+ const thread = nativeThread && nativeThread !== room.channelId && nativeThread.length <= 128
5843
+ && !/[\r\n\x00]/.test(nativeThread) ? nativeThread : undefined;
5844
+ const fileIds = (msg.attachments ?? []).map(file => file.fileId)
5845
+ .filter(id => typeof id === "string" && id.length > 0 && id.length <= 4096).slice(0, 20);
5846
+ this.contactService().host.store.recordRoomContext(instance, { ...(thread ? { threadId: thread } : {}), fileIds }, this.contactGeneration(instance));
5847
+ }
5848
+ restrictedClassicRouting(instance) {
5849
+ const room = this.contactRoom(instance);
5850
+ if (room?.restrictedMode !== true)
5851
+ return undefined;
5852
+ const adapter = this.contactAdapter(instance);
5853
+ if (!adapter)
5854
+ throw Error("Restricted room adapter is unavailable");
5855
+ const context = this.contactService().host.store.roomContext(instance, this.contactGeneration(instance));
5856
+ return { adapterId: adapter.id, chatId: room.channelId, ...(context.threadId ? { threadId: context.threadId } : {}) };
5857
+ }
5858
+ async prepareContactFiles(instance, paths) {
5859
+ if (this.contactRoom(instance)?.restrictedMode !== true || paths.length === 0)
5860
+ return undefined;
5861
+ const incarnation = this.contactGeneration(instance), home = realpathSync(getAgendHome());
5862
+ const inbox = join(home, "workspaces", instance, "inbox");
5863
+ const lease = await stageContactFiles(paths, home, inbox);
5864
+ if (this.contactGeneration(instance) !== incarnation) {
5865
+ await lease.dispose();
5866
+ throw Error("Room identity changed before attachment delivery");
5867
+ }
5868
+ return lease;
5869
+ }
5870
+ async downloadRoomAttachment(instance, fileId) {
5871
+ const route = this.restrictedClassicRouting(instance);
5872
+ if (!route)
5873
+ throw Error("This is not a restricted Classic room");
5874
+ const incarnation = this.contactGeneration(instance), store = this.contactService().host.store;
5875
+ if (!store.roomContext(instance, incarnation).fileIds.includes(fileId))
5876
+ throw Error("This attachment was not received in this room");
5877
+ const adapter = this.contactAdapter(instance);
5878
+ if (!adapter)
5879
+ throw Error("Restricted room adapter is unavailable");
5880
+ const file = await adapter.downloadAttachment(fileId);
5881
+ const home = realpathSync(getAgendHome()), scratch = join(home, "workspaces", instance, "inbox", "room-scratch");
5882
+ const copied = await snapshotReplyFile(file, scratch, randomBytes(16).toString("hex"), {
5883
+ stateDir: home, allowedRoots: [join(home, "inbox")], maxFileBytes: 20 * 1024 * 1024, maxDirBytes: 400 * 1024 * 1024,
5884
+ });
5885
+ if (!copied.ok)
5886
+ throw Error("The room attachment could not be copied safely");
5887
+ if (this.contactGeneration(instance) !== incarnation) {
5888
+ try {
5889
+ unlinkSync(copied.path);
5890
+ }
5891
+ catch { /* our snapshot only */ }
5892
+ throw Error("Room identity changed during attachment download");
5893
+ }
5894
+ return copied.path;
5895
+ }
5896
+ configureClassicRestriction(name, daemon) {
5897
+ const room = this.contactRoom(name);
5898
+ if (!room)
5899
+ return;
5900
+ const guarded = daemon;
5901
+ if (room.restrictedMode !== true) {
5902
+ guarded.setClassicRestriction?.({ mode: "legacy", roomTools: { publicRead: true, allowedMcpTools: [] } });
5903
+ return;
5904
+ }
5905
+ const policy = this.contactService().host.store.policy(name, this.contactGeneration(name));
5906
+ guarded.setClassicRestriction?.({ mode: room.restrictedMode === true ? "restricted" : "legacy",
5907
+ roomTools: policy.roomTools, policyRevision: policy.revision });
5908
+ }
5909
+ contactGeneration(name) {
5910
+ // Reuse the existing durable incarnation fence: replacement/retarget rotates it,
5911
+ // while an ordinary pause or daemon restart must not strand an approved request.
5912
+ const incarnation = this.hubAgentToken(name);
5913
+ if (!incarnation)
5914
+ throw Error("unavailable");
5915
+ return incarnation;
5916
+ }
5917
+ contactAdminOf(name, actor) {
5918
+ if (actor.platform === "host" && actor.adapterId === "host" && actor.userId === "operator")
5919
+ return true;
5920
+ const adapter = this.contactAdapter(name);
5921
+ if (!adapter || actor.adapterId !== adapter.id || actor.platform !== adapter.type)
5922
+ return false;
5923
+ return this.isFleetAdmin(actor.userId, adapter.id)
5924
+ || (!!this.contactRoom(name) && this.classicChannels?.isAdmin(actor.userId) === true);
5925
+ }
5926
+ contactService() {
5927
+ this.ensureDeliveryOutbox();
5928
+ return new ContactAuthService({ store: this.deliveryOutbox.contactAuthorizations,
5929
+ restricted: name => this.contactRoom(name)?.restrictedMode === true,
5930
+ legacyClassic: name => !!this.contactRoom(name) && this.contactRoom(name)?.restrictedMode !== true,
5931
+ adminOf: (name, actor) => this.contactAdminOf(name, actor),
5932
+ defaultApprovers: name => {
5933
+ const adapter = this.contactAdapter(name);
5934
+ if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
5935
+ return [];
5936
+ return (this.adminListOf(adapter.id) ?? []).map(userId => ({ platform: adapter.type, adapterId: adapter.id, userId, label: userId }));
5937
+ },
5938
+ generation: name => this.contactGeneration(name),
5939
+ hubRestricted: name => this.hubContactRestricted(name),
5940
+ delivered: ticket => !!ticket.deliveryId && this.deliveryOutbox.get(ticket.deliveryId)?.state === "delivered",
5941
+ deliveryState: ticket => ticket.deliveryId ? this.deliveryOutbox.get(ticket.deliveryId)?.state : undefined,
5942
+ admit: (request, ticketId) => {
5943
+ const payload = { ...request.payload, contactTicket: { id: ticketId, state: "delivered" } };
5944
+ const admitted = this.deliveryOutbox.admit({ operationId: request.operationId,
5945
+ sourceKey: `contact:${ticketId}`, sourceInstance: request.source,
5946
+ sourceDaemonBootId: this.getDaemonBootId(request.source) ?? request.sourceGeneration,
5947
+ targetInstance: request.target, targetSession: String(request.payload.targetSession ?? request.target),
5948
+ kind: String(request.payload.type ?? "fleet_inbound"), correlationId: request.correlationId,
5949
+ payload, forwards: request.forwards });
5950
+ this.scheduleDeliveryOutboxPump();
5951
+ return admitted.delivery.deliveryId;
5952
+ },
5953
+ changed: (instance, ticketId) => {
5954
+ const revision = this.deliveryOutbox.contactAuthorizations.policy(instance).revision;
5955
+ const ticket = ticketId ? this.deliveryOutbox.contactAuthorizations.get(ticketId) : undefined;
5956
+ if (ticket) {
5957
+ this.emitSseEvent("message", { instance: ticket.source, role: "status", sender: "AgEnD", ts: new Date().toISOString(),
5958
+ text: t(ticket.state === "pending" ? "contact.held" : ticket.state === "approved" ? "contact.approved" : "contact.updated"),
5959
+ contactTicket: { id: ticket.id, state: ticket.state } });
5960
+ if (ticket.state === "approved")
5961
+ this.emitSseEvent("message", { instance: ticket.target, role: "user",
5962
+ sender: ticket.source, text: ticket.message, ts: new Date().toISOString(), contactTicket: { id: ticket.id, state: "approved" } });
5963
+ }
5964
+ this.emitSseEvent("contact-auth", { instance, ...(ticketId ? { ticketId } : {}), revision });
5965
+ this.needsYou?.poke();
5966
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
5967
+ },
5968
+ });
5969
+ }
5970
+ contactDeliveryCurrent(row) {
5971
+ const badge = row.payload.contactTicket;
5972
+ if (!badge)
5973
+ return true;
5974
+ if (typeof badge.id !== "string")
5975
+ return false;
5976
+ const service = this.contactService(), ticket = service.host.store.get(badge.id);
5977
+ return !!ticket && ticket.deliveryId === row.deliveryId && ticket.source === row.sourceInstance && ticket.target === row.targetInstance
5978
+ && !!ticket.decidedBy && service.canManage(ticket.target, ticket.decidedBy)
5979
+ && Date.parse(ticket.expiresAt) > Date.now()
5980
+ && ticket.sourceGeneration === this.contactGeneration(ticket.source)
5981
+ && ticket.targetGeneration === this.contactGeneration(ticket.target)
5982
+ && !this.hubContactRestricted(ticket.source);
5983
+ }
5984
+ contactPermissions(name, actor) {
5985
+ const service = this.contactService(), room = this.contactRoom(name);
5986
+ const canManage = service.canManage(name, actor), canSetMode = !!room && this.contactAdminOf(name, actor);
5987
+ if (!canManage && !canSetMode)
5988
+ throw Error("forbidden");
5989
+ if (!this.webChatOwner(name))
5990
+ throw Error("not-found");
5991
+ const store = service.host.store, policy = store.policy(name, this.contactGeneration(name));
5992
+ const daemon = this.daemons.get(name);
5993
+ const backend = room ? this.classicChannels.getBackendByInstance(name, this.fleetConfig?.defaults?.backend) : this.fleetConfig?.instances[name]?.backend ?? "unknown";
5994
+ const nativeGuard = daemon?.classicNativeGuard?.() ?? { state: "not-covered", backend, reason: "Native guard is not loaded in this build", impactComplete: false };
5995
+ const removedTools = room ? [...toolsFor(resolveToolSet(this.fleetConfig?.instances[name], name))]
5996
+ .filter(tool => !CLASSIC_RESTRICTED_TOOLS.includes(tool)) : [];
5997
+ return { instance: name, revision: policy.revision, classicRoom: !!room,
5998
+ mode: room?.restrictedMode === true ? "restricted" : "legacy", approvers: service.approvers(name),
5999
+ eligibleApprovers: service.host.defaultApprovers(name),
6000
+ inheritedApprovers: policy.approvers === undefined,
6001
+ nativeGuard,
6002
+ canManage, canSetMode, suggestRestricted: !!room && room.restrictedMode !== true && !store.suggestionDismissed(name),
6003
+ roomTools: { ...policy.roomTools, wouldDisable: [...new Set([...removedTools, ...(nativeGuard.wouldDisable ?? [])])] }, grants: policy.grants, history: store.histories(name, this.contactGeneration(name)),
6004
+ ...(service.needsApplication(name) ? { originRestriction: { active: true,
6005
+ reason: !service.origin(name) || service.origin(name)?.kind === "unknown" ? "unknown-origin" : "earlier-non-admin", resetSupported: false } } : {}) };
6006
+ }
6007
+ contactActor(req, url) {
6008
+ const verdict = evaluateWebRequest(req, url, this.webToken, this.webSessions, { touch: false });
6009
+ if (verdict.kind !== "allow" || verdict.via !== "session" || verdict.session.tier !== "admin")
6010
+ return null;
6011
+ const result = this.webAuthority({ session: verdict.session, gateway: !!gatewayRequestContext(req),
6012
+ peer: gatewayRequestContext(req) ? (gatewayRequestContext(req)?.named ? "named_link" : "quick_link") : classifyWebPeer(req) });
6013
+ const actor = result.authority.kind === "web-verified" ? result.authority.actor : null;
6014
+ if (!actor)
6015
+ return null;
6016
+ if (actor.adapter_id === "host" && actor.user_id === "operator")
6017
+ return { platform: "host", adapterId: "host", userId: "operator", label: "Operator" };
6018
+ const adapter = this.adapters.get(actor.adapter_id);
6019
+ if (!adapter || (adapter.type !== "discord" && adapter.type !== "telegram"))
6020
+ return null;
6021
+ return { platform: adapter.type, adapterId: actor.adapter_id, userId: actor.user_id, label: actor.user_id };
6022
+ }
6023
+ writeContactPermissions(name, raw, actor) {
6024
+ const parsed = ContactPermissionsSchema.safeParse(raw);
6025
+ if (!parsed.success)
6026
+ throw Error("invalid-request");
6027
+ const input = parsed.data, before = this.contactPermissions(name, actor), store = this.contactService().host.store;
6028
+ if ((input.approvers || input.grants) && !before.canManage)
6029
+ throw Error("forbidden");
6030
+ if (input.approvers?.some(person => !before.eligibleApprovers.some(allowed => sameContactPerson(person, allowed))))
6031
+ throw Error("invalid-approver");
6032
+ if ((input.mode || input.roomTools) && !before.canSetMode)
6033
+ throw Error("forbidden");
6034
+ if (input.grants?.some(grant => grant.target !== name || !this.webChatOwner(grant.source)
6035
+ || Date.parse(grant.expiresAt) <= Date.now()))
6036
+ throw Error("invalid-grant");
6037
+ // Configuration does not prove an external MCP's account independence. Preserve a conservative warning.
6038
+ if (input.roomTools)
6039
+ input.roomTools.allowedMcpTools = input.roomTools.allowedMcpTools.map(tool => ({ ...tool,
6040
+ usesOwnerAccount: true, accountWarning: t("contact.mcpAccountWarning") }));
6041
+ if (input.revision !== before.revision)
6042
+ throw Error("conflict");
6043
+ // Mode persists in the existing Classic configuration; absent historical fields remain legacy.
6044
+ if (input.mode) {
6045
+ if (input.mode === "restricted" && before.mode !== "restricted")
6046
+ store.inheritOrigin(name, { kind: "unknown", people: [], receiptIds: [], chain: [name] });
6047
+ this.classicChannels.setRestrictedMode(name, input.mode === "restricted");
6048
+ }
6049
+ const policy = store.writePolicy(name, input, actor, instance => this.contactGeneration(instance));
6050
+ const daemon = this.daemons.get(name);
6051
+ daemon?.setClassicRestriction?.({ mode: this.contactRoom(name)?.restrictedMode === true ? "restricted" : "legacy",
6052
+ roomTools: policy.roomTools, policyRevision: policy.revision });
6053
+ this.emitSseEvent("contact-auth", { instance: name, revision: policy.revision });
6054
+ this.needsYou?.poke();
6055
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
6056
+ return this.contactPermissions(name, actor);
6057
+ }
6058
+ contactAuthorization(id, actor) {
6059
+ const service = this.contactService(), ticket = service.host.store.get(id);
6060
+ if (!ticket)
6061
+ throw Error("not-found");
6062
+ return service.view(ticket, actor);
6063
+ }
6064
+ contactAuthorizations(actor, filter) {
6065
+ const service = this.contactService(), page = service.host.store.list({ ...filter, status: undefined });
6066
+ return { ...page, items: page.items.flatMap(ticket => {
6067
+ try {
6068
+ const view = service.view(ticket, actor);
6069
+ if (filter.status && view.state !== filter.status)
6070
+ return [];
6071
+ if (filter.person && !view.origin.people.some(person => JSON.stringify([person.platform, person.adapterId, person.userId]) === filter.person))
6072
+ return [];
6073
+ return [view];
6074
+ }
6075
+ catch {
6076
+ return [];
6077
+ }
6078
+ }) };
6079
+ }
6080
+ decideContactAuthorization(id, decision, actor) {
6081
+ return this.contactService().decide(id, decision, actor);
6082
+ }
6083
+ contactNeeds(actor) {
6084
+ const service = this.contactService();
6085
+ const pending = service.host.store.pending()
6086
+ .filter(ticket => { try {
6087
+ return service.view(ticket, actor).canDecide;
6088
+ }
6089
+ catch {
6090
+ return false;
6091
+ } }).map(ticket => ({
6092
+ id: `contact:${ticket.id}`, type: "contact", reason: "contact_request", instance: ticket.target,
6093
+ since: Date.parse(ticket.createdAt), detail: "", contactTicket: { id: ticket.id, source: ticket.source, target: ticket.target },
6094
+ }));
6095
+ return [...pending, ...(this.classicChannels?.getAll() ?? []).filter(room => room.restrictedMode !== true
6096
+ && !service.host.store.suggestionDismissed(room.instanceName) && this.contactAdminOf(room.instanceName, actor))
6097
+ .map(room => ({ id: `contact-suggest:${room.instanceName}`, type: "contact",
6098
+ reason: "contact_restricted_suggestion", instance: room.instanceName,
6099
+ since: Date.parse(room.createdAt) || 0, detail: "", contactSuggestion: { instance: room.instanceName } }))];
6100
+ }
6101
+ contactSuggestions() {
6102
+ const rooms = this.classicChannels?.getAll().filter(room => room.restrictedMode !== true) ?? [];
6103
+ const store = this.contactService().host.store;
6104
+ const pending = store.pending().map(ticket => ({ id: `contact:${ticket.id}`, type: "contact",
6105
+ reason: "contact_request", instance: ticket.target, owner: this.getAdapterForInstance(ticket.target)?.id,
6106
+ since: Date.parse(ticket.createdAt), detail: "", contactTicket: { id: ticket.id, source: ticket.source, target: ticket.target } }));
6107
+ return [...pending, ...rooms.filter(room => !store.suggestionDismissed(room.instanceName)).map(room => ({
6108
+ id: `contact-suggest:${room.instanceName}`, type: "contact", reason: "contact_restricted_suggestion",
6109
+ instance: room.instanceName, owner: this.getAdapterForInstance(room.instanceName)?.id,
6110
+ since: Date.parse(room.createdAt) || 0, detail: t("contact.suggest"), contactSuggestion: { instance: room.instanceName },
6111
+ }))];
6112
+ }
6113
+ acknowledgeContactSuggestion(instance, actor) {
6114
+ if (!this.contactAdminOf(instance, actor) || !this.contactRoom(instance))
6115
+ throw Error("forbidden");
6116
+ this.contactService().host.store.dismissSuggestion(instance);
6117
+ this.emitSseEvent("needs", { items: this.needsYouItems() });
6118
+ this.needsYou?.poke();
6119
+ }
5806
6120
  /** Synchronous SQLite admission; the caller may acknowledge only after this returns. */
5807
6121
  admitDurableDelivery(input) {
5808
6122
  const bindingHold = this.generalLocationDeliveryHold(input.targetInstance);
@@ -5816,6 +6130,24 @@ export class FleetManager {
5816
6130
  if (!currentSourceBootId || !sourceDaemonBootId || currentSourceBootId !== sourceDaemonBootId) {
5817
6131
  throw new Error("Source daemon generation is no longer current; outcome is unknown");
5818
6132
  }
6133
+ const service = this.contactService();
6134
+ const metadata = input.payload.meta;
6135
+ const requestKind = metadata?.request_kind;
6136
+ const authorizationDeliveryId = service.requireApplication({ operationId: input.operationId, source: input.sourceInstance, target: input.targetInstance,
6137
+ verb: input.kind === "broadcast" ? "broadcast" : requestKind === "task" ? "delegate_task" : requestKind === "query" ? "request_information"
6138
+ : requestKind === "report" ? "report_result" : "send_to_instance",
6139
+ message: String(input.payload.content ?? ""), correlationId: input.correlationId,
6140
+ correlationExplicit: input.correlationExplicit ?? true,
6141
+ resultRecipient: input.sourceInstance, payload: input.payload, forwards: input.forwards });
6142
+ if (authorizationDeliveryId) {
6143
+ const delivery = outbox.get(authorizationDeliveryId);
6144
+ if (!delivery)
6145
+ throw Error("Authorized delivery is unavailable");
6146
+ return { deliveryId: delivery.deliveryId, state: delivery.state, duplicate: true, kind: delivery.kind };
6147
+ }
6148
+ const inheritedOrigin = service.origin(input.sourceInstance);
6149
+ if (inheritedOrigin && !service.host.legacyClassic?.(input.sourceInstance))
6150
+ service.host.store.inheritOrigin(input.targetInstance, { ...inheritedOrigin, chain: [...inheritedOrigin.chain, input.targetInstance] });
5819
6151
  const sourceKey = `mcp:${input.sourceInstance}:${input.operationId}:${input.targetInstance}:${input.targetSession ?? ""}:${input.kind}`;
5820
6152
  const admitted = outbox.admit({ ...input, sourceDaemonBootId, sourceKey });
5821
6153
  if (admitted.inserted)
@@ -6353,11 +6685,15 @@ export class FleetManager {
6353
6685
  };
6354
6686
  sent = await this.deliverToInstance(target, payload, {
6355
6687
  isCrossInstance: true,
6688
+ stillCurrent: () => this.contactDeliveryCurrent(claimed),
6356
6689
  waitForIdle: claimed.kind !== "steer",
6357
6690
  noInlineWake: this.deliveryWorkerMode(target) !== "off",
6358
6691
  });
6359
6692
  }
6360
6693
  if (!sent) {
6694
+ if (payload.contactTicket && !this.contactDeliveryCurrent(claimed)) {
6695
+ outbox.cancelUnsubmittedContact(claimed.deliveryId, "Contact approval became stale before input");
6696
+ }
6361
6697
  const current = outbox.get(claimed.deliveryId);
6362
6698
  if (current?.state === "delivering") {
6363
6699
  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)));
@@ -6395,8 +6731,8 @@ export class FleetManager {
6395
6731
  }
6396
6732
  const meta = claimed.payload.meta && typeof claimed.payload.meta === "object" ? claimed.payload.meta : {};
6397
6733
  const task = await this.nativeInstanceRuntime().execute(target, { ...claimed.payload, requestId: deliveryId, meta: { ...meta, from_instance: claimed.sourceInstance, correlation_id: claimed.correlationId } }, {
6398
- stillCurrent: () => !this.shuttingDown,
6399
- beforeStart: () => { if (outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
6734
+ stillCurrent: () => !this.shuttingDown && this.contactDeliveryCurrent(claimed),
6735
+ beforeStart: () => { if (!this.contactDeliveryCurrent(claimed) || outbox.begin(deliveryId, targetDaemonBootId, attemptNo) !== "begun")
6400
6736
  throw new Error("Windows delivery attempt is no longer current"); begun = true; },
6401
6737
  });
6402
6738
  const outcome = task.outcomeConfirmed === false ? "uncertain" : task.status === "completed" ? "delivered" : "failed";
@@ -6414,6 +6750,8 @@ export class FleetManager {
6414
6750
  const reason = error instanceof Error ? error.message : String(error);
6415
6751
  if (begun)
6416
6752
  outbox.complete(deliveryId, targetDaemonBootId, attemptNo, "uncertain", reason);
6753
+ else if (claimed.payload.contactTicket && !this.contactDeliveryCurrent(claimed))
6754
+ outbox.cancelUnsubmittedContact(deliveryId, "Contact approval became stale before input");
6417
6755
  else
6418
6756
  outbox.retryBeforeBegin(deliveryId, targetDaemonBootId, attemptNo, reason, 5000);
6419
6757
  this.logger.warn({ target, deliveryId, err: reason }, "Windows durable delivery did not complete");
@@ -8510,6 +8848,26 @@ export class FleetManager {
8510
8848
  return payload;
8511
8849
  const row = this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
8512
8850
  origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
8851
+ const contactStore = this.deliveryOutbox.contactAuthorizations;
8852
+ if (this.contactRoom(instanceName)?.restrictedMode === true && !contactStore)
8853
+ throw Error("Contact origin storage unavailable");
8854
+ if (contactStore && (this.contactRoom(instanceName)?.restrictedMode === true || contactStore.origin(instanceName))) {
8855
+ const authority = origin.authority;
8856
+ const actor = origin.platform === "web" ? (authority?.kind === "web-verified" ? authority.actor : null)
8857
+ : { adapter_id: origin.adapter_id, user_id: origin.user_id };
8858
+ const adapter = actor?.adapter_id ? this.adapters.get(actor.adapter_id) : undefined;
8859
+ const platform = origin.platform === "web" ? adapter?.type : origin.platform;
8860
+ const person = actor?.adapter_id && actor.user_id
8861
+ && (platform === "discord" || platform === "telegram" || (actor.adapter_id === "host" && actor.user_id === "operator"))
8862
+ ? { platform: actor.adapter_id === "host" ? "host" : platform,
8863
+ adapterId: actor.adapter_id, userId: actor.user_id, label: origin.username ?? actor.user_id } : undefined;
8864
+ contactStore.inheritOrigin(instanceName, { kind: person ? "human" : "unknown", people: person ? [person] : [],
8865
+ receiptIds: [row.message_id], chain: [instanceName] });
8866
+ if (this.contactRoom(instanceName)?.restrictedMode === true && (!person || !this.contactAdminOf(instanceName, person))
8867
+ && typeof payload.content === "string" && (payload.type === "fleet_inbound" || payload.type === "steer")) {
8868
+ payload = { ...payload, content: `${t(person ? "contact.originNonAdmin" : "contact.originUnknown")}\n\n${payload.content}` };
8869
+ }
8870
+ }
8513
8871
  // #1939 §7: each ordinary verified web message, for the S1 beta to watch. No text, cookie or session id: the handle.
8514
8872
  const authority = origin.authority;
8515
8873
  if (authority?.kind === "web-verified" && authority.actor && authority.session) {
@@ -8954,8 +9312,7 @@ export class FleetManager {
8954
9312
  await this.handleTipsSlash(data, adapterId);
8955
9313
  }
8956
9314
  else if (data.command === "status") {
8957
- // Admin-gated (like the topic path): the merged table shows every
8958
- // instance's cost and IPC health.
9315
+ // Admin-gated, like the topic path: use the shared fleet instance table.
8959
9316
  if (!this.isFleetAdmin(data.userId, adapterId)) {
8960
9317
  await data.respond(t("cmd.admin_required", "/status"));
8961
9318
  return;
@@ -14878,6 +15235,8 @@ export class FleetManager {
14878
15235
  }
14879
15236
  const channelName = msg.username || chatId;
14880
15237
  if (requestedBackend) {
15238
+ // Advisory before the new-room policy is persisted, including direct /start BACKEND.
15239
+ await msgAdapter?.sendText(chatId, this.getClassicStartWarning(requestedBackend));
14881
15240
  // handleClassicStart binds the instance to this adapter authoritatively.
14882
15241
  const reply = await this.handleClassicStart(chatId, channelName, msg.userId, undefined, msg.adapterId, requestedBackend);
14883
15242
  await msgAdapter?.sendText(chatId, reply);
@@ -15386,6 +15745,9 @@ export class FleetManager {
15386
15745
  }
15387
15746
  }
15388
15747
  checkToolPermission(sink, instanceName, tool) {
15748
+ if (this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && !CLASSIC_RESTRICTED_TOOLS.includes(tool)) {
15749
+ return { allowed: false, message: "This Classic room is restricted. This tool is not in its room tool allowance." };
15750
+ }
15389
15751
  if (isCanvasWorkerTool(tool))
15390
15752
  return { allowed: false, message: CANVAS_WORKER_EXPERIMENTAL_MESSAGE }; // #2799: removed
15391
15753
  const profile = resolveToolSet(this.fleetConfig?.instances[instanceName], instanceName);
@@ -15481,7 +15843,7 @@ export class FleetManager {
15481
15843
  return;
15482
15844
  }
15483
15845
  // #2305: a reaction to a web chat message is the web chat's own (any fleet, web-only included): never an adapter's.
15484
- if (tool === "react" && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
15846
+ if (tool === "react" && !this.classicChannels?.getAll?.().some(room => room.instanceName === instanceName && room.restrictedMode === true) && typeof args.message_id === "string" && isWebMessageId(args.message_id)) {
15485
15847
  // The socket's own instance, never a session name the caller wrote itself (as checkToolPermission: it was not
15486
15848
  // identified) — a channel tool's call from a daemon carries none anyway (#2310 review).
15487
15849
  const r = await this.reactToWebMessage(instanceName, args.message_id, args.emoji);
@@ -15501,9 +15863,29 @@ export class FleetManager {
15501
15863
  : "Channel adapters are not ready — retry shortly");
15502
15864
  return;
15503
15865
  }
15866
+ const restrictedRoute = this.restrictedClassicRouting(instanceName);
15867
+ const restrictedIncarnation = restrictedRoute ? this.contactGeneration(instanceName) : undefined;
15868
+ const restrictedBoot = restrictedRoute ? this.getDaemonBootId(instanceName) : undefined;
15869
+ if (restrictedRoute && Array.isArray(args.previews) && args.previews.length) {
15870
+ respond(null, "File previews are not available in restricted rooms; use the room's own attachments");
15871
+ return;
15872
+ }
15873
+ let replyBookkeeping = Promise.resolve();
15874
+ const restrictedExtras = restrictedRoute ? {
15875
+ prepareFiles: (paths) => this.prepareContactFiles(instanceName, paths),
15876
+ replyFinished: () => replyBookkeeping,
15877
+ downloadAttachment: (id) => this.downloadRoomAttachment(instanceName, id),
15878
+ beforeSend: () => {
15879
+ const current = this.restrictedClassicRouting(instanceName);
15880
+ if (!current || current.adapterId !== restrictedRoute.adapterId || current.chatId !== restrictedRoute.chatId
15881
+ || current.threadId !== restrictedRoute.threadId || this.contactGeneration(instanceName) !== restrictedIncarnation
15882
+ || this.getDaemonBootId(instanceName) !== restrictedBoot)
15883
+ throw Error("Restricted room route changed before delivery");
15884
+ },
15885
+ } : {};
15504
15886
  // Resolve threadId: use sender's topic_id if sender is a known fleet instance,
15505
15887
  // fall back to general topic if sender is unknown, or IPC owner if no sender.
15506
- const senderInstanceName = senderSessionName && this.fleetConfig?.instances[senderSessionName]
15888
+ const senderInstanceName = !restrictedRoute && senderSessionName && this.fleetConfig?.instances[senderSessionName]
15507
15889
  ? senderSessionName
15508
15890
  : null;
15509
15891
  const routingConfig = senderInstanceName
@@ -15515,9 +15897,9 @@ export class FleetManager {
15515
15897
  // ids are scoped to that bot/world; routing a secondary-world id through the
15516
15898
  // primary adapter produces a 404. Instance binding remains the compatibility
15517
15899
  // fallback for older daemons and calls without a live/persisted context.
15518
- const contextAdapterId = typeof msg.adapterId === "string" && msg.adapterId
15900
+ const contextAdapterId = restrictedRoute?.adapterId ?? (typeof msg.adapterId === "string" && msg.adapterId
15519
15901
  ? msg.adapterId
15520
- : undefined;
15902
+ : undefined);
15521
15903
  const contextWorld = contextAdapterId ? this.worlds.get(contextAdapterId) : undefined;
15522
15904
  if (contextAdapterId && !contextWorld) {
15523
15905
  respond(null, `Adapter world unavailable: ${contextAdapterId}`);
@@ -15551,6 +15933,14 @@ export class FleetManager {
15551
15933
  threadId = undefined;
15552
15934
  }
15553
15935
  }
15936
+ if (restrictedRoute) {
15937
+ args.chat_id = restrictedRoute.chatId;
15938
+ threadId = restrictedRoute.threadId;
15939
+ if (threadId)
15940
+ args.thread_id = threadId;
15941
+ else
15942
+ delete args.thread_id;
15943
+ }
15554
15944
  // Reply dedup: retries land here when the agent was told a send failed
15555
15945
  // (daemon budget elapsed, shell tool killed) while the adapter send was
15556
15946
  // still in flight and about to succeed. One real send, everyone gets its
@@ -15667,7 +16057,8 @@ export class FleetManager {
15667
16057
  && this.landedInOwnChannel(instanceName, replyAdapterId, result);
15668
16058
  }
15669
16059
  catch { /* not known: not the channel's (fail closed), and the bookkeeping below still runs */ }
15670
- void this.afterReplyRouted(instanceName, args, senderSessionName, buttonsView, inChannel, replyAdapterId ? { adapterId: replyAdapterId, result } : undefined, replyIdentity, result);
16060
+ replyBookkeeping = this.afterReplyRouted(instanceName, args, senderSessionName, buttonsView, inChannel, replyAdapterId ? { adapterId: replyAdapterId, result } : undefined, replyIdentity, result)
16061
+ .catch(err => { this.logger.warn({ err, instanceName }, "Reply bookkeeping failed after confirmed delivery"); });
15671
16062
  }
15672
16063
  catch (err) {
15673
16064
  this.logger.warn({ err, instanceName }, "Reply delivered but post-delivery bookkeeping failed");
@@ -15682,7 +16073,7 @@ export class FleetManager {
15682
16073
  });
15683
16074
  }
15684
16075
  };
15685
- if (routeToolCall(outAdapter, tool, args, threadId, respondAndRecord, replySet ? { replyButtons: replySet.callbacks, ...(replySet.poll ? { replyPoll: replySet.poll } : {}) } : {})) {
16076
+ if (routeToolCall(outAdapter, tool, args, threadId, respondAndRecord, { ...restrictedExtras, ...(replySet ? { replyButtons: replySet.callbacks, ...(replySet.poll ? { replyPoll: replySet.poll } : {}) } : {}) })) {
15686
16077
  return;
15687
16078
  }
15688
16079
  if (replySet)
@@ -15693,7 +16084,7 @@ export class FleetManager {
15693
16084
  return;
15694
16085
  }
15695
16086
  // Route standard channel tools (reply, react, edit_message, download_attachment)
15696
- if (routeToolCall(outAdapter, tool, args, threadId, respond)) {
16087
+ if (routeToolCall(outAdapter, tool, args, threadId, respond, restrictedExtras)) {
15697
16088
  return;
15698
16089
  }
15699
16090
  if (handler) {
@@ -16486,6 +16877,10 @@ export class FleetManager {
16486
16877
  if (op !== "list") {
16487
16878
  const profile = resolveToolSet(this.fleetConfig?.instances[caller], caller);
16488
16879
  const existing = op === "create" ? null : scheduler.get(args.id);
16880
+ const effectiveTarget = requestedTarget?.trim() || existing?.target || caller;
16881
+ if ((op === "create" || op === "update") && effectiveTarget !== caller && this.contactService().needsApplication(caller)) {
16882
+ throw new ToolNotPermittedError("Scheduled peer contact needs approval. Use a contact application instead; this conversation's origin remains restricted.");
16883
+ }
16489
16884
  const refusal = scheduleOpRefusal(profile, caller, op, { requestedTarget, existing });
16490
16885
  if (refusal) {
16491
16886
  this.logger.warn({ instance: caller, profile, op, target: requestedTarget ?? existing?.target, scheduleId: args.id }, "tool-permissions: schedule op refused");
@@ -20125,6 +20520,7 @@ export class FleetManager {
20125
20520
  kiroCompatibility: this.kiroCompatibilityHolds?.get(name),
20126
20521
  backendMissing: this.missingBinaryHold(name),
20127
20522
  pauseReason, pausedAt,
20523
+ staleAuth: this.daemons.get(name)?.staleAuthIssue?.() ?? null,
20128
20524
  crashedAt: crashed ? (this.needsCrashedAt.get(name) ?? null) : null,
20129
20525
  signIn: pauseReason === "auth" ? this.signInFor(name) : null,
20130
20526
  modelSwitch: this.modelObservationForInstance(name)?.active ?? null,
@@ -20181,6 +20577,7 @@ export class FleetManager {
20181
20577
  return owner !== undefined && this.worlds.has(owner) ? owner : undefined;
20182
20578
  };
20183
20579
  this.needsYou = new NeedsYouHub({
20580
+ contactSuggestions: () => this.contactSuggestions(),
20184
20581
  dataDir: this.dataDir,
20185
20582
  now: () => Date.now(),
20186
20583
  mono: () => performance.now(),
@@ -24219,7 +24616,9 @@ export class FleetManager {
24219
24616
  const installable = new Set(Object.keys(BACKEND_INSTALLATION_INFO));
24220
24617
  const candidates = new Set([...installed, ...configured, ...installable]);
24221
24618
  const unsupported = [];
24619
+ const details = [];
24222
24620
  const choices = [...candidates].sort().flatMap(backend => {
24621
+ const label = backend === "claude-code" ? "Claude" : BACKEND_LABELS[backend] ?? backend;
24223
24622
  const flow = LOGIN_FLOWS[backend];
24224
24623
  const remoteLogin = !!flow && flow.remoteLogin !== "unsupported";
24225
24624
  const isInstalled = installed.has(backend);
@@ -24229,11 +24628,13 @@ export class FleetManager {
24229
24628
  status.push(t("login.status_configured"));
24230
24629
  if (!isInstalled && installable.has(backend)) {
24231
24630
  status.push(t(remoteLogin ? "login.status_install_then_auth" : "login.status_install"));
24232
- return [{ action: backend, label: `${backend} · ${status.join(" · ")}` }];
24631
+ details.push(`${label} · ${status.join(" · ")}`);
24632
+ return [{ action: backend, label }];
24233
24633
  }
24234
24634
  if (remoteLogin && isInstalled) {
24235
24635
  status.push(t("login.status_auth"));
24236
- return [{ action: backend, label: `${backend} · ${status.join(" · ")}` }];
24636
+ details.push(`${label} · ${status.join(" · ")}`);
24637
+ return [{ action: backend, label }];
24237
24638
  }
24238
24639
  status.push(t("login.status_unsupported"));
24239
24640
  unsupported.push({ backend, flow, status });
@@ -24267,7 +24668,7 @@ export class FleetManager {
24267
24668
  adapterId: chat.adapterId,
24268
24669
  chatId: chat.chatId,
24269
24670
  threadId: chat.threadId,
24270
- message: `${t("login.choose_backend")}\n${t("fleet.label_line", fleetLabel(this.fleetConfig))}`,
24671
+ message: `${t("login.choose_backend")}\n${t("fleet.label_line", fleetLabel(this.fleetConfig))}\n\n${details.join("\n")}`,
24271
24672
  choices,
24272
24673
  expiredText: t("buttons.stale"),
24273
24674
  });
@@ -24925,6 +25326,13 @@ export class FleetManager {
24925
25326
  const npmCopy = mode === "remove-npm" ? await this.findClaudeNpmCopy().catch(() => null) : null;
24926
25327
  if (mode === "remove-npm" && (!npmCopy || !existsSync(npmCopy)))
24927
25328
  return { refused: "no_npm_copy" };
25329
+ // M-3318 (#4146's shape): never run npm's uninstall while another npm is changing packages on this computer — e.g. an agent's Claude Code updating itself with
25330
+ // `npm install -g` in that same prefix. The same judgement as the AgEnD installer's wait (#4148, launcher/agend-install.cjs); here it is refused with what runs, never queued.
25331
+ if (mode === "remove-npm") {
25332
+ const busy = await this.otherNpmChanging().catch(() => null);
25333
+ if (busy && busy.length)
25334
+ return { refused: "npm_busy", message: busy.map(row => `pid ${row.pid}: npm ${row.command}`).join("; ") };
25335
+ }
24928
25336
  const info = plan ? { install: plan.command } : npmCopy ? { install: npmUninstallCommand(npmCopy) } : base;
24929
25337
  // The fleet-wide window, claimed before the first await (shared with /login, chat's install and sign-in).
24930
25338
  const claim = this.loginWindow.tryClaim("install", backend);
@@ -25053,6 +25461,17 @@ export class FleetManager {
25053
25461
  }
25054
25462
  /** M-3307: the npm copy of Claude Code the last switch found (its package directory), the one `remove-npm` removes. */
25055
25463
  claudeNpmCopy = null;
25464
+ /**
25465
+ * M-3318: the other npm processes on this computer that may be changing packages (pid and npm's command word only — never the argv, which can carry
25466
+ * a registry credential), judged as the AgEnD installer judges them (#4148). Null when the process list cannot be read.
25467
+ */
25468
+ async otherNpmChanging() {
25469
+ const [{ createRequire }, { promisify }, { execFile }] = await Promise.all([import("node:module"), import("node:util"), import("./child-process.js")]);
25470
+ const judge = createRequire(import.meta.url)("../launcher/agend-install.cjs");
25471
+ const { stdout } = await promisify(execFile)("ps", ["-A", "-o", "pid=,ppid=,args="], { timeout: 5_000, maxBuffer: 4 * 1024 * 1024 });
25472
+ const rows = judge.npmChangingFromProcessList(String(stdout), process.pid);
25473
+ return rows ? rows.map(row => ({ pid: row.pid, command: (judge.npmCommands(row.args) ?? ["?"])[0] ?? "?" })) : null;
25474
+ }
25056
25475
  /** M-3307: Claude's native install is there: `~/.local/bin/claude` leads into its versions folder. */
25057
25476
  async nativeClaudePresent() {
25058
25477
  const real = await realpath(join(homedir(), ".local", "bin", "claude")).catch(() => null);
@@ -25297,6 +25716,7 @@ export class FleetManager {
25297
25716
  cards: m.cards,
25298
25717
  posts: m.posts, // #2281: kept beside the row, never broadcast (not a row field)
25299
25718
  reserved: m.reserved, // #1774: an agent reply's place, taken when it was sent
25719
+ contactTicket: m.contactTicket,
25300
25720
  });
25301
25721
  // A sending page's own id for its pending bubble rides on the live copy only: never recorded, never replayed.
25302
25722
  const clientId = typeof data.clientId === "string" ? data.clientId : "";
@@ -26208,6 +26628,9 @@ export class FleetManager {
26208
26628
  // #1085: a Telegram forum ClassicBot is keyed by chat id (threadId), but the
26209
26629
  // reply context must carry the topic the message was really asked in.
26210
26630
  const replyThreadId = msg.transportThreadId ?? msg.threadId;
26631
+ const contactAdapter = this.worlds.get(msg.adapterId ?? "")?.adapter;
26632
+ if (contactAdapter)
26633
+ this.recordClassicContactInput(instanceName, msg, contactAdapter);
26211
26634
  // Resolve the channel/adapter from the instance itself so per-channel context
26212
26635
  // config is correct even for a same-channel second bot.
26213
26636
  const ctxAdapterId = this.classicChannels?.getAdapterIdByInstance(instanceName);
@@ -28576,6 +28999,10 @@ export class FleetManager {
28576
28999
  return undefined;
28577
29000
  return t("classic.backend_not_installed", backend, installation.binary, installation.install);
28578
29001
  }
29002
+ /** Coverage is not proven before launch; disclose the fallback without blocking an unsupported CLI. */
29003
+ getClassicStartWarning(backend) {
29004
+ return [t("classic.restricted_start_notice"), this.getMissingBackendWarning(backend)].filter(Boolean).join("\n\n");
29005
+ }
28579
29006
  /** Handle Discord's required static slash choice, warning before a likely startup failure. */
28580
29007
  async handleClassicStartSlash(data, adapterId) {
28581
29008
  return withSpawnHoldReply(text => data.respond(text), () => this.handleClassicStartSlashCore(data, adapterId));
@@ -28596,7 +29023,7 @@ export class FleetManager {
28596
29023
  await data.respond(blocker);
28597
29024
  return;
28598
29025
  }
28599
- const warning = this.getMissingBackendWarning(requestedBackend);
29026
+ const warning = this.getClassicStartWarning(requestedBackend);
28600
29027
  // Keep the deferred ephemeral response useful even if daemon startup later
28601
29028
  // fails because the executable is absent. This is advisory, not a gate.
28602
29029
  if (warning)
@@ -28650,8 +29077,8 @@ export class FleetManager {
28650
29077
  this.pendingClassicStarts.set(nonce, pending);
28651
29078
  try {
28652
29079
  pending.messageId = data.respondChoices
28653
- ? await data.respondChoices(t("classic.choose_backend"), choices)
28654
- : await adapter.promptUser(data.channelId, t("classic.choose_backend"), choices);
29080
+ ? await data.respondChoices(`${t("classic.choose_backend")}\n\n${t("classic.restricted_start_notice")}`, choices)
29081
+ : await adapter.promptUser(data.channelId, `${t("classic.choose_backend")}\n\n${t("classic.restricted_start_notice")}`, choices);
28655
29082
  }
28656
29083
  catch (err) {
28657
29084
  // A menu transport failure should not make /start unusable: consume the
@@ -28692,7 +29119,7 @@ export class FleetManager {
28692
29119
  ?? this.classicChannels?.getDefaults().backend
28693
29120
  ?? this.fleetConfig?.defaults?.backend
28694
29121
  ?? "claude-code";
28695
- const warning = this.getMissingBackendWarning(effectiveBackend);
29122
+ const warning = this.getClassicStartWarning(effectiveBackend);
28696
29123
  // Show the warning before starting so it survives a missing-binary startup
28697
29124
  // failure. The selected backend is still attempted as requested.
28698
29125
  if (warning)