@songsid/agend 2.2.1 → 2.3.0-beta.10
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.
- package/dist/agent-cli-instructions.md +5 -2
- package/dist/agent-cli.js +284 -2
- package/dist/agent-cli.js.map +1 -1
- package/dist/agent-endpoint.d.ts +2 -0
- package/dist/agent-endpoint.js +29 -0
- package/dist/agent-endpoint.js.map +1 -1
- package/dist/agent-file-read.d.ts +38 -0
- package/dist/agent-file-read.js +317 -0
- package/dist/agent-file-read.js.map +1 -0
- package/dist/agent-whats-new.d.ts +11 -0
- package/dist/agent-whats-new.js +29 -2
- package/dist/agent-whats-new.js.map +1 -1
- package/dist/atomic-write.js +9 -1
- package/dist/atomic-write.js.map +1 -1
- package/dist/auth-api.d.ts +30 -1
- package/dist/auth-api.js +61 -12
- package/dist/auth-api.js.map +1 -1
- package/dist/authority/authority-state.d.ts +38 -0
- package/dist/authority/authority-state.js +114 -0
- package/dist/authority/authority-state.js.map +1 -0
- package/dist/authority/session-authorizations.d.ts +43 -0
- package/dist/authority/session-authorizations.js +102 -0
- package/dist/authority/session-authorizations.js.map +1 -0
- package/dist/authority/web-authority.d.ts +120 -0
- package/dist/authority/web-authority.js +157 -0
- package/dist/authority/web-authority.js.map +1 -0
- package/dist/backend/antigravity.js +3 -3
- package/dist/backend/antigravity.js.map +1 -1
- package/dist/backend/claude-code.d.ts +2 -2
- package/dist/backend/claude-code.js +10 -5
- package/dist/backend/claude-code.js.map +1 -1
- package/dist/backend/launch-effort.js +1 -1
- package/dist/backend/launch-effort.js.map +1 -1
- package/dist/backend/muse.js +10 -2
- package/dist/backend/muse.js.map +1 -1
- package/dist/backend/types.d.ts +14 -0
- package/dist/backend/types.js +25 -0
- package/dist/backend/types.js.map +1 -1
- package/dist/backend-availability.d.ts +120 -0
- package/dist/backend-availability.js +396 -0
- package/dist/backend-availability.js.map +1 -0
- package/dist/backend-command.d.ts +21 -3
- package/dist/backend-command.js +23 -4
- package/dist/backend-command.js.map +1 -1
- package/dist/bundled-skills.d.ts +14 -0
- package/dist/bundled-skills.js +29 -0
- package/dist/bundled-skills.js.map +1 -0
- package/dist/cache-analysis.d.ts +47 -1
- package/dist/cache-analysis.js +68 -8
- package/dist/cache-analysis.js.map +1 -1
- package/dist/cache-ledger.d.ts +16 -3
- package/dist/cache-ledger.js +33 -13
- package/dist/cache-ledger.js.map +1 -1
- package/dist/cache-report-tool.d.ts +17 -0
- package/dist/cache-report-tool.js +40 -0
- package/dist/cache-report-tool.js.map +1 -0
- package/dist/cache-service.d.ts +70 -3
- package/dist/cache-service.js +178 -17
- package/dist/cache-service.js.map +1 -1
- package/dist/channel/adapters/discord.d.ts +9 -0
- package/dist/channel/adapters/discord.js +52 -2
- package/dist/channel/adapters/discord.js.map +1 -1
- package/dist/channel/adapters/telegram.d.ts +8 -1
- package/dist/channel/adapters/telegram.js +74 -4
- package/dist/channel/adapters/telegram.js.map +1 -1
- package/dist/channel/mcp-tools.js +48 -2
- package/dist/channel/mcp-tools.js.map +1 -1
- package/dist/channel/types.d.ts +21 -0
- package/dist/classic-channel-manager.d.ts +10 -5
- package/dist/classic-channel-manager.js +12 -9
- package/dist/classic-channel-manager.js.map +1 -1
- package/dist/cli.js +130 -31
- package/dist/cli.js.map +1 -1
- package/dist/config-validator.js +119 -4
- package/dist/config-validator.js.map +1 -1
- package/dist/daemon.d.ts +5 -0
- package/dist/daemon.js +273 -22
- package/dist/daemon.js.map +1 -1
- package/dist/decision-list.d.ts +25 -0
- package/dist/decision-list.js +30 -0
- package/dist/decision-list.js.map +1 -0
- package/dist/delivery-outbox.d.ts +10 -0
- package/dist/delivery-outbox.js +12 -1
- package/dist/delivery-outbox.js.map +1 -1
- package/dist/fleet-context.d.ts +15 -0
- package/dist/fleet-manager.d.ts +506 -11
- package/dist/fleet-manager.js +1784 -130
- package/dist/fleet-manager.js.map +1 -1
- package/dist/fleet-traffic.d.ts +74 -0
- package/dist/fleet-traffic.js +196 -0
- package/dist/fleet-traffic.js.map +1 -0
- package/dist/general-knowledge/skills/credential-profiles/SKILL.md +20 -5
- package/dist/general-knowledge/skills/cross-instance-messaging/SKILL.md +6 -1
- package/dist/general-knowledge/skills/multi-channel/SKILL.md +3 -2
- package/dist/general-knowledge/skills/persona-emoji/SKILL.md +1 -1
- package/dist/general-knowledge/skills/web-appearance/SKILL.md +492 -0
- package/dist/general-knowledge/skills/web-dashboard/SKILL.md +476 -0
- package/dist/general-knowledge/skills/worker-collaboration/SKILL.md +1 -1
- package/dist/human-delivery-receipts.d.ts +24 -1
- package/dist/human-delivery-receipts.js +64 -11
- package/dist/human-delivery-receipts.js.map +1 -1
- package/dist/instance-avatar.js +3 -0
- package/dist/instance-avatar.js.map +1 -1
- package/dist/instance-config-impact.js +6 -1
- package/dist/instance-config-impact.js.map +1 -1
- package/dist/instance-lifecycle.js +9 -4
- package/dist/instance-lifecycle.js.map +1 -1
- package/dist/instance-names.d.ts +4 -0
- package/dist/instance-names.js +12 -0
- package/dist/instance-names.js.map +1 -0
- package/dist/instructions.d.ts +12 -1
- package/dist/instructions.js +13 -2
- package/dist/instructions.js.map +1 -1
- package/dist/locale.js +100 -8
- package/dist/locale.js.map +1 -1
- package/dist/ls-attach-resolve.d.ts +95 -0
- package/dist/ls-attach-resolve.js +174 -0
- package/dist/ls-attach-resolve.js.map +1 -0
- package/dist/memory-hogs.d.ts +27 -0
- package/dist/memory-hogs.js +124 -0
- package/dist/memory-hogs.js.map +1 -0
- package/dist/needs-you-hub.d.ts +4 -0
- package/dist/needs-you-hub.js +31 -6
- package/dist/needs-you-hub.js.map +1 -1
- package/dist/needs-you.d.ts +1 -13
- package/dist/needs-you.js +3 -37
- package/dist/needs-you.js.map +1 -1
- package/dist/outbound-handlers.d.ts +15 -0
- package/dist/outbound-handlers.js +152 -11
- package/dist/outbound-handlers.js.map +1 -1
- package/dist/outbound-schemas.d.ts +228 -4
- package/dist/outbound-schemas.js +147 -1
- package/dist/outbound-schemas.js.map +1 -1
- package/dist/public-web-gateway.js +21 -1
- package/dist/public-web-gateway.js.map +1 -1
- package/dist/public-web-link.d.ts +9 -0
- package/dist/public-web-link.js +8 -0
- package/dist/public-web-link.js.map +1 -1
- package/dist/quickstart-api.d.ts +10 -1
- package/dist/quickstart-api.js +12 -4
- package/dist/quickstart-api.js.map +1 -1
- package/dist/reply-buttons-controller.d.ts +4 -0
- package/dist/reply-buttons-controller.js +2 -2
- package/dist/reply-buttons-controller.js.map +1 -1
- package/dist/repo-worktree-guard.d.ts +36 -0
- package/dist/repo-worktree-guard.js +143 -0
- package/dist/repo-worktree-guard.js.map +1 -0
- package/dist/restart-progress.d.ts +65 -1
- package/dist/restart-progress.js +236 -10
- package/dist/restart-progress.js.map +1 -1
- package/dist/rollout-index.d.ts +5 -0
- package/dist/rollout-index.js +26 -5
- package/dist/rollout-index.js.map +1 -1
- package/dist/scheduler/scheduler.d.ts +70 -1
- package/dist/scheduler/scheduler.js +256 -17
- package/dist/scheduler/scheduler.js.map +1 -1
- package/dist/service-installer.d.ts +2 -1
- package/dist/service-installer.js +18 -3
- package/dist/service-installer.js.map +1 -1
- package/dist/settings-api.d.ts +19 -0
- package/dist/settings-api.js +210 -2
- package/dist/settings-api.js.map +1 -1
- package/dist/settings-change.js +112 -0
- package/dist/settings-change.js.map +1 -1
- package/dist/settings-effect.js +32 -2
- package/dist/settings-effect.js.map +1 -1
- package/dist/settings-http-confirmation.js +5 -0
- package/dist/settings-http-confirmation.js.map +1 -1
- package/dist/tmux-manager.d.ts +5 -0
- package/dist/tmux-manager.js +16 -0
- package/dist/tmux-manager.js.map +1 -1
- package/dist/tool-permissions.d.ts +4 -6
- package/dist/tool-permissions.js +100 -2
- package/dist/tool-permissions.js.map +1 -1
- package/dist/topic-commands.d.ts +17 -7
- package/dist/topic-commands.js +39 -21
- package/dist/topic-commands.js.map +1 -1
- package/dist/topic-link.d.ts +128 -0
- package/dist/topic-link.js +269 -0
- package/dist/topic-link.js.map +1 -0
- package/dist/types.d.ts +61 -1
- package/dist/ui/app-effects.js +233 -0
- package/dist/ui/chat-ambient.js +307 -0
- package/dist/ui/chat-effect-posters.js +42 -0
- package/dist/ui/chat-effects.js +160 -0
- package/dist/ui/chat-live-replies.js +58 -0
- package/dist/ui/chat-render.js +9 -6
- package/dist/ui/chat-store.js +9 -3
- package/dist/ui/chat-strings.js +70 -2
- package/dist/ui/chat-thread.js +191 -37
- package/dist/ui/chat-tour.js +1 -1
- package/dist/ui/effect-trial-controller.js +124 -0
- package/dist/ui/effect-trial-offer.js +31 -0
- package/dist/ui/effect-trial-panel.js +40 -0
- package/dist/ui/fleet-cache.js +23 -1
- package/dist/ui/fleet-canvas-layout.js +111 -0
- package/dist/ui/fleet-canvas.js +525 -0
- package/dist/ui/fleet-org.js +27 -12
- package/dist/ui/fleet-traffic.js +343 -0
- package/dist/ui/fleet-usage.js +401 -0
- package/dist/ui/image-lightbox.js +1 -1
- package/dist/ui/panel-chat.js +203 -57
- package/dist/ui/panel-details.js +20 -6
- package/dist/ui/panel-fleet.js +43 -18
- package/dist/ui/panel-log.js +6 -6
- package/dist/ui/panel-needs.js +3 -3
- package/dist/ui/panel-settings.js +34 -13
- package/dist/ui/preview-panel.js +25 -9
- package/dist/ui/preview.js +3 -2
- package/dist/ui/settings-appearance.js +349 -0
- package/dist/ui/settings-catalog.js +92 -0
- package/dist/ui/settings-dialogs.js +40 -12
- package/dist/ui/settings-effects.js +202 -0
- package/dist/ui/settings-guests.js +117 -0
- package/dist/ui/settings-learn.js +25 -0
- package/dist/ui/settings-model.js +15 -6
- package/dist/ui/settings-mods.js +271 -0
- package/dist/ui/settings-owner-effects.js +80 -0
- package/dist/ui/settings-strings.js +333 -10
- package/dist/ui/settings-web-authority.js +91 -0
- package/dist/ui/shared/agend-auth.js +28 -4
- package/dist/ui/shared/agent-widget.js +248 -0
- package/dist/ui/shared/app-i18n.js +6 -2
- package/dist/ui/shared/app-prefs.js +34 -13
- package/dist/ui/shared/app-route.js +24 -2
- package/dist/ui/shared/app-session.js +3 -1
- package/dist/ui/shared/app-shell.js +102 -23
- package/dist/ui/shared/app-store.js +28 -1
- package/dist/ui/shared/app-stream.js +14 -7
- package/dist/ui/shared/app-themes.js +206 -0
- package/dist/ui/shared/app.css +565 -4
- package/dist/ui/shared/app.js +23 -10
- package/dist/ui/shared/card-strings.js +32 -0
- package/dist/ui/shared/effect-app-runtime.js +297 -0
- package/dist/ui/shared/effect-baseline.js +64 -0
- package/dist/ui/shared/effect-chat-runtime.js +167 -0
- package/dist/ui/shared/effect-cursor.js +125 -0
- package/dist/ui/shared/effect-frame.js +146 -0
- package/dist/ui/shared/effect-geometry.js +137 -0
- package/dist/ui/shared/effect-host-style.js +10 -0
- package/dist/ui/shared/effect-owner-regions.js +74 -0
- package/dist/ui/shared/effect-owner-source.js +115 -0
- package/dist/ui/shared/effect-policy.js +151 -0
- package/dist/ui/shared/effect-poster-reader.js +98 -0
- package/dist/ui/shared/effect-posters.js +117 -0
- package/dist/ui/shared/effect-profiler.js +184 -0
- package/dist/ui/shared/effect-profiles.js +65 -0
- package/dist/ui/shared/effect-registry.js +535 -0
- package/dist/ui/shared/effect-runtime-loader.js +234 -0
- package/dist/ui/shared/effect-safety.js +153 -0
- package/dist/ui/shared/effect-stock-snapshot.js +43 -0
- package/dist/ui/shared/effect-stock-trust.js +217 -0
- package/dist/ui/shared/effect-trial-shadow.js +62 -0
- package/dist/ui/shared/effect-trial-source.js +103 -0
- package/dist/ui/shared/effect-trial-stage.js +170 -0
- package/dist/ui/shared/effect-trial.css +40 -0
- package/dist/ui/shared/fx-motion.js +67 -0
- package/dist/ui/shared/header-tools.js +1 -1
- package/dist/ui/shared/identity-card.js +273 -0
- package/dist/ui/shared/identity-color.js +261 -0
- package/dist/ui/shared/instance-nav.js +215 -41
- package/dist/ui/shared/owner-css.js +221 -0
- package/dist/ui/shared/owner-effect-prefs.js +117 -0
- package/dist/ui/shared/panel-view.js +103 -10
- package/dist/ui/shared/signin.js +2 -0
- package/dist/ui/shared/tokens.css +9 -3
- package/dist/ui/shared/ui-dialog.js +1 -1
- package/dist/ui/shared/ui-icons.js +3 -0
- package/dist/ui/shared/ui-menu.js +1 -1
- package/dist/ui/shared/ui-toast.js +1 -1
- package/dist/ui/shared/usage-dialog.js +22 -2
- package/dist/ui/shared/view-strings.js +98 -2
- package/dist/ui/shared/web-authorize.js +151 -0
- package/dist/ui/signin.html +1 -0
- package/dist/ui/web-terminal/terminal.css +4 -4
- package/dist/usage/providers.d.ts +28 -0
- package/dist/usage/providers.js +126 -36
- package/dist/usage/providers.js.map +1 -1
- package/dist/usage-report.d.ts +158 -0
- package/dist/usage-report.js +226 -0
- package/dist/usage-report.js.map +1 -0
- package/dist/usage-rollup.d.ts +51 -0
- package/dist/usage-rollup.js +168 -0
- package/dist/usage-rollup.js.map +1 -0
- package/dist/view-api.d.ts +68 -0
- package/dist/view-api.js +249 -8
- package/dist/view-api.js.map +1 -1
- package/dist/web-ambient.d.ts +72 -0
- package/dist/web-ambient.js +161 -0
- package/dist/web-ambient.js.map +1 -0
- package/dist/web-api.d.ts +111 -5
- package/dist/web-api.js +1235 -58
- package/dist/web-api.js.map +1 -1
- package/dist/web-appearance-limits.d.ts +82 -0
- package/dist/web-appearance-limits.js +83 -0
- package/dist/web-appearance-limits.js.map +1 -0
- package/dist/web-appearance-policy.d.ts +64 -0
- package/dist/web-appearance-policy.js +87 -0
- package/dist/web-appearance-policy.js.map +1 -0
- package/dist/web-appearance-tools.d.ts +53 -0
- package/dist/web-appearance-tools.js +124 -0
- package/dist/web-appearance-tools.js.map +1 -0
- package/dist/web-appearance-view.d.ts +124 -0
- package/dist/web-appearance-view.js +278 -0
- package/dist/web-appearance-view.js.map +1 -0
- package/dist/web-appearance.d.ts +93 -0
- package/dist/web-appearance.js +373 -0
- package/dist/web-appearance.js.map +1 -0
- package/dist/web-asset-parts.d.ts +93 -0
- package/dist/web-asset-parts.js +133 -0
- package/dist/web-asset-parts.js.map +1 -0
- package/dist/web-auth.js +20 -2
- package/dist/web-auth.js.map +1 -1
- package/dist/web-card.d.ts +110 -0
- package/dist/web-card.js +266 -0
- package/dist/web-card.js.map +1 -0
- package/dist/web-channel-echo.d.ts +7 -1
- package/dist/web-channel-echo.js +6 -2
- package/dist/web-channel-echo.js.map +1 -1
- package/dist/web-chat-history.d.ts +59 -0
- package/dist/web-chat-history.js +102 -4
- package/dist/web-chat-history.js.map +1 -1
- package/dist/web-commands.d.ts +1 -0
- package/dist/web-effect-bootstrap.d.ts +12 -0
- package/dist/web-effect-bootstrap.js +49 -0
- package/dist/web-effect-bootstrap.js.map +1 -0
- package/dist/web-effect-bundle.d.ts +28 -0
- package/dist/web-effect-bundle.js +171 -0
- package/dist/web-effect-bundle.js.map +1 -0
- package/dist/web-effect-canonical.d.ts +8 -0
- package/dist/web-effect-canonical.js +27 -0
- package/dist/web-effect-canonical.js.map +1 -0
- package/dist/web-effect-library.d.ts +114 -0
- package/dist/web-effect-library.js +530 -0
- package/dist/web-effect-library.js.map +1 -0
- package/dist/web-effect-playback.d.ts +30 -0
- package/dist/web-effect-playback.js +71 -0
- package/dist/web-effect-playback.js.map +1 -0
- package/dist/web-effect-poster.d.ts +8 -0
- package/dist/web-effect-poster.js +52 -0
- package/dist/web-effect-poster.js.map +1 -0
- package/dist/web-effect-profiles.d.ts +118 -0
- package/dist/web-effect-profiles.js +180 -0
- package/dist/web-effect-profiles.js.map +1 -0
- package/dist/web-effect-service.d.ts +93 -0
- package/dist/web-effect-service.js +335 -0
- package/dist/web-effect-service.js.map +1 -0
- package/dist/web-effect-tools.d.ts +48 -0
- package/dist/web-effect-tools.js +129 -0
- package/dist/web-effect-tools.js.map +1 -0
- package/dist/web-effect-trials.d.ts +86 -0
- package/dist/web-effect-trials.js +204 -0
- package/dist/web-effect-trials.js.map +1 -0
- package/dist/web-effect-upload.d.ts +27 -0
- package/dist/web-effect-upload.js +185 -0
- package/dist/web-effect-upload.js.map +1 -0
- package/dist/web-effect-worker.d.ts +8 -0
- package/dist/web-effect-worker.js +170 -0
- package/dist/web-effect-worker.js.map +1 -0
- package/dist/web-effect.d.ts +103 -0
- package/dist/web-effect.js +153 -0
- package/dist/web-effect.js.map +1 -0
- package/dist/web-guest-access.d.ts +125 -0
- package/dist/web-guest-access.js +234 -0
- package/dist/web-guest-access.js.map +1 -0
- package/dist/web-guest-rooms.d.ts +82 -0
- package/dist/web-guest-rooms.js +135 -0
- package/dist/web-guest-rooms.js.map +1 -0
- package/dist/web-identity-color.d.ts +87 -0
- package/dist/web-identity-color.js +209 -0
- package/dist/web-identity-color.js.map +1 -0
- package/dist/web-identity-palette.d.ts +113 -0
- package/dist/web-identity-palette.js +84 -0
- package/dist/web-identity-palette.js.map +1 -0
- package/dist/web-image-meta.d.ts +25 -0
- package/dist/web-image-meta.js +200 -0
- package/dist/web-image-meta.js.map +1 -0
- package/dist/web-login.d.ts +47 -0
- package/dist/web-login.js +115 -0
- package/dist/web-login.js.map +1 -1
- package/dist/web-mod-agent.d.ts +50 -0
- package/dist/web-mod-agent.js +207 -0
- package/dist/web-mod-agent.js.map +1 -0
- package/dist/web-mod-bundle.d.ts +157 -0
- package/dist/web-mod-bundle.js +529 -0
- package/dist/web-mod-bundle.js.map +1 -0
- package/dist/web-mod-export.d.ts +68 -0
- package/dist/web-mod-export.js +100 -0
- package/dist/web-mod-export.js.map +1 -0
- package/dist/web-mod-store.d.ts +289 -0
- package/dist/web-mod-store.js +638 -0
- package/dist/web-mod-store.js.map +1 -0
- package/dist/web-org.d.ts +3 -3
- package/dist/web-org.js +11 -17
- package/dist/web-org.js.map +1 -1
- package/dist/web-owner-css-store.d.ts +180 -0
- package/dist/web-owner-css-store.js +384 -0
- package/dist/web-owner-css-store.js.map +1 -0
- package/dist/web-owner-css.d.ts +58 -0
- package/dist/web-owner-css.js +552 -0
- package/dist/web-owner-css.js.map +1 -0
- package/dist/web-prefs.d.ts +62 -0
- package/dist/web-prefs.js +232 -36
- package/dist/web-prefs.js.map +1 -1
- package/dist/web-preview.d.ts +15 -3
- package/dist/web-preview.js +28 -9
- package/dist/web-preview.js.map +1 -1
- package/dist/web-returning-device.d.ts +41 -0
- package/dist/web-returning-device.js +57 -5
- package/dist/web-returning-device.js.map +1 -1
- package/dist/web-session-authorization.d.ts +132 -0
- package/dist/web-session-authorization.js +193 -0
- package/dist/web-session-authorization.js.map +1 -0
- package/dist/web-session.d.ts +70 -10
- package/dist/web-session.js +137 -22
- package/dist/web-session.js.map +1 -1
- package/dist/web-settings-patch.d.ts +67 -2
- package/dist/web-settings-patch.js +196 -1
- package/dist/web-settings-patch.js.map +1 -1
- package/dist/web-settings-tools.d.ts +89 -0
- package/dist/web-settings-tools.js +270 -0
- package/dist/web-settings-tools.js.map +1 -0
- package/dist/web-shell-routes.d.ts +2 -2
- package/dist/web-shell-routes.js +2 -2
- package/dist/web-shell-routes.js.map +1 -1
- package/dist/web-theme-store.d.ts +257 -0
- package/dist/web-theme-store.js +627 -0
- package/dist/web-theme-store.js.map +1 -0
- package/dist/web-theme.d.ts +123 -0
- package/dist/web-theme.js +416 -0
- package/dist/web-theme.js.map +1 -0
- package/dist/web-widget.d.ts +72 -0
- package/dist/web-widget.js +245 -0
- package/dist/web-widget.js.map +1 -0
- package/dist/workflow-templates/default.md +1 -1
- package/package.json +1 -1
- package/templates/systemd.service.ejs +8 -0
package/dist/fleet-manager.js
CHANGED
|
@@ -20,14 +20,14 @@ import { withinBudget } from "./monotonic-budget.js";
|
|
|
20
20
|
import { measureSyncWork } from "./sync-work-attribution.js";
|
|
21
21
|
import { RuntimeCpuProfiler, ProfileBusyError, profileDuration } from "./runtime-cpu-profile.js";
|
|
22
22
|
import { ProfileControlServer } from "./profile-control.js";
|
|
23
|
-
import { existsSync, readFileSync, mkdirSync, writeFileSync, unlinkSync, rmSync, readdirSync, renameSync, copyFileSync, chmodSync, statSync, accessSync, realpathSync, constants as fsConstants, closeSync } from "node:fs";
|
|
23
|
+
import { existsSync, readFileSync, mkdirSync, writeFileSync, unlinkSync, rmSync, readdirSync, renameSync, copyFileSync, chmodSync, statSync, accessSync, realpathSync, lstatSync, constants as fsConstants, closeSync } from "node:fs";
|
|
24
24
|
import { atomicWriteFileSync } from "./atomic-write.js";
|
|
25
25
|
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
26
26
|
import { freemem, totalmem, cpus, homedir } from "node:os";
|
|
27
27
|
import { createServer } from "node:http";
|
|
28
28
|
import { Worker } from "node:worker_threads";
|
|
29
29
|
import { ProbeWorkerPool } from "./probe-worker-pool.js";
|
|
30
|
-
import { join, dirname, basename, delimiter, isAbsolute, resolve as resolvePath } from "node:path";
|
|
30
|
+
import { join, dirname, basename, delimiter, isAbsolute, relative, resolve as resolvePath } from "node:path";
|
|
31
31
|
import { fileURLToPath } from "node:url";
|
|
32
32
|
import { getAgendHome, ensureWorkspaceGit } from "./paths.js";
|
|
33
33
|
import { fleetLabel } from "./fleet-label.js";
|
|
@@ -48,6 +48,7 @@ import { isProbeableRouteTarget } from "./fleet-context.js";
|
|
|
48
48
|
import { getEffectiveInstanceDefaults, loadFleetConfig, loadRawFleetConfig, DEFAULT_COST_GUARD, DEFAULT_DAILY_SUMMARY, DEFAULT_INSTANCE_CONFIG } from "./config.js";
|
|
49
49
|
import { EventLog } from "./event-log.js";
|
|
50
50
|
import { binaryProbe } from "./binary-probe.js";
|
|
51
|
+
import { AVAILABILITY_STALE_MS, BackendAvailabilityStore, hostAvailabilityProbes } from "./backend-availability.js";
|
|
51
52
|
import { classifySqliteOpenError } from "./sqlite-open-errors.js";
|
|
52
53
|
import { OutboxOpenError } from "./outbox-open-error.js";
|
|
53
54
|
import { AdapterWorld } from "./adapter-world.js";
|
|
@@ -65,7 +66,7 @@ import { createBackend } from "./backend/factory.js";
|
|
|
65
66
|
import { readEffortMetadata } from "./backend/effort-metadata.js";
|
|
66
67
|
import { codexEffort, flagEffort } from "./backend/launch-effort.js";
|
|
67
68
|
import { codexMetadataHomes, readCodexModelEffortLevels, resolveCodexLaunchModel } from "./backend/codex-metadata.js";
|
|
68
|
-
import { CLI_ENV_TTL_MS, isModelCompatible, resolveBinary, SYSINFO_BACKEND_IDS, UnsupportedCliError } from "./backend/types.js";
|
|
69
|
+
import { CLI_ENV_TTL_MS, isModelCompatible, noteResolvedBinary, resolveBinary, SYSINFO_BACKEND_IDS, UnsupportedCliError } from "./backend/types.js";
|
|
69
70
|
import { createLogger, rotateLogIfNeeded } from "./logger.js";
|
|
70
71
|
import { processAttachments } from "./channel/attachment-handler.js";
|
|
71
72
|
import { routeToolCall } from "./channel/tool-router.js";
|
|
@@ -134,19 +135,36 @@ export function applyTaskListCap(tasks, filterAssignee, filterStatus) {
|
|
|
134
135
|
}
|
|
135
136
|
return tasks;
|
|
136
137
|
}
|
|
137
|
-
import { handleWebRequest, broadcastSseEvent, SSE_HEARTBEAT_MS } from "./web-api.js";
|
|
138
|
+
import { handleWebRequest, broadcastSseEvent, broadcastToGuests, SSE_HEARTBEAT_MS } from "./web-api.js";
|
|
138
139
|
import { LogService } from "./log-service.js";
|
|
139
|
-
import { WebChatHistory, WEB_CHAT_TEXT_MAX, isWebMessageId, newWebMessageId } from "./web-chat-history.js";
|
|
140
|
+
import { WebChatHistory, WEB_CHAT_TEXT_MAX, isWebMessageId, newWebMessageId, webChatFrom } from "./web-chat-history.js";
|
|
140
141
|
import { WebChatDiskStore } from "./web-chat-store.js";
|
|
141
142
|
import { SeenUsers, resolveMentions } from "./web-mentions.js";
|
|
142
|
-
import { WebPrefsStore } from "./web-prefs.js";
|
|
143
|
+
import { OPERATOR, WebPrefsStore } from "./web-prefs.js";
|
|
144
|
+
import { agendVersion } from "./agent-whats-new.js";
|
|
145
|
+
import { OwnerCssStore } from "./web-owner-css-store.js";
|
|
146
|
+
import { ThemeStore } from "./web-theme-store.js";
|
|
147
|
+
import { WebAppearance } from "./web-appearance.js";
|
|
148
|
+
import { WebEffectLibrary } from "./web-effect-library.js";
|
|
149
|
+
import { WebEffectTrials } from "./web-effect-trials.js";
|
|
150
|
+
import { WebEffectService } from "./web-effect-service.js";
|
|
151
|
+
import { WebEffectProfiles } from "./web-effect-profiles.js";
|
|
152
|
+
import { WebEffectTools, WEB_EFFECT_TOOLS } from "./web-effect-tools.js";
|
|
153
|
+
import { resolveEffectParams } from "./web-effect.js";
|
|
154
|
+
import { cw1EffectChecker } from "./web-mod-bundle.js";
|
|
155
|
+
import { effectiveAppearanceLimits } from "./web-appearance-limits.js";
|
|
143
156
|
import { WEB_NAME_FALLBACK, safeWebName, validateWebName, webNameInUse, webPersonKey } from "./web-profile.js";
|
|
144
157
|
import { ReplyButtonStore, parseReplyButtons, replyButtonClickText, replyButtonsFallbackText, REPLY_BUTTON_PREFIX } from "./reply-buttons.js";
|
|
145
158
|
import { ReplyButtonsController } from "./reply-buttons-controller.js";
|
|
146
159
|
import { parsePoll } from "./reply-polls.js";
|
|
147
160
|
import { isUploadRequest, limitRequestReceive, publicAttachment, sweepOrphanedUploads, UPLOAD_REQUEST_TIMEOUT_MS, uploadLimits, WebFileLedger } from "./web-upload.js";
|
|
148
161
|
import { REPLY_FILES_MAX_BYTES, snapshotReplyFile, sweepReplySnapshots, webFilesDir } from "./web-reply-files.js";
|
|
149
|
-
import { handleViewRequest, isViewPath, profileIdentities, resolveInstanceIdentity } from "./view-api.js";
|
|
162
|
+
import { cardPicture, handleViewRequest, humanCards, identityColors, instanceTeams, isViewPath, personBannerFocus, personIdentityColour, profileIdentities, resolveInstanceIdentity, setPersonBannerFocus, setPersonIdentityColour } from "./view-api.js";
|
|
163
|
+
import { autoIdentityColor } from "./web-identity-color.js";
|
|
164
|
+
import { AppearanceTools } from "./web-appearance-tools.js";
|
|
165
|
+
import { cardVersion, resolveCard } from "./web-card.js";
|
|
166
|
+
import { ModStore } from "./web-mod-store.js";
|
|
167
|
+
import { AgentMods } from "./web-mod-agent.js";
|
|
150
168
|
import { downloadStickerImage } from "./channel/sticker-download.js";
|
|
151
169
|
import { WebImageCache, imageMimeForFile, WEB_IMAGE_MAX_AGE_MS, WEB_IMAGE_MAX_BYTES, WEB_IMAGE_RETRY_MS } from "./web-images.js";
|
|
152
170
|
import { accentColor, avatarFor, ownBotConnections } from "./instance-avatar.js";
|
|
@@ -161,7 +179,11 @@ import { runOnLoginShell } from "./login-shell.js";
|
|
|
161
179
|
import { tightenInstanceDirs } from "./private-dir.js";
|
|
162
180
|
import { decideSlash } from "./slash-authz.js";
|
|
163
181
|
import { canonicalCommand, commandSpec, decideCommand, ruleFor } from "./command-table.js";
|
|
164
|
-
import { runVisibilityCommand } from "./cross-instance-notice.js";
|
|
182
|
+
import { crossInstanceVisibility, runVisibilityCommand } from "./cross-instance-notice.js";
|
|
183
|
+
import { WebSettingsTools } from "./web-settings-tools.js";
|
|
184
|
+
import { bindGuestRequest, guestRouteDecision } from "./web-guest-access.js";
|
|
185
|
+
import { GUEST_ROOM_TICK_MS, GuestRoomMembership, guestGroupRooms } from "./web-guest-rooms.js";
|
|
186
|
+
import { Delegations, TrafficLog, trafficItem } from "./fleet-traffic.js";
|
|
165
187
|
import { installedChannel, updateNoticeKey } from "./update-check.js";
|
|
166
188
|
import { resolveInstalledAgend } from "./update-dispatch.js";
|
|
167
189
|
import { resolveUpdateLaunch, openUpdateLog, updateLogPath, watchUpdateLaunch } from "./update-launch.js";
|
|
@@ -173,7 +195,7 @@ import { setLocale, detectLocale, getLocale, t } from "./locale.js";
|
|
|
173
195
|
import { recentChatContext } from "./log-tail.js";
|
|
174
196
|
import { describeSignalSource, recordInternalRequest, withOrigin } from "./fleet-control-audit.js";
|
|
175
197
|
import { handleAgentRequest, ToolNotPermittedError } from "./agent-endpoint.js";
|
|
176
|
-
import { ClassicChannelManager, getClassicBackendChoices, isSelectableClassicBackend, readClassicLastActivityAt } from "./classic-channel-manager.js";
|
|
198
|
+
import { ClassicChannelManager, classicWebEchoOn, getClassicBackendChoices, inferClassicChannelType, isSelectableClassicBackend, readClassicLastActivityAt } from "./classic-channel-manager.js";
|
|
177
199
|
import { assertExplicitInstanceRemoval } from "./instance-removal.js";
|
|
178
200
|
import { KNOWN_BACKENDS, validateFleetConfig } from "./config-validator.js";
|
|
179
201
|
import { isRemovedBackend, removedBackendMessage } from "./backend/removed.js";
|
|
@@ -192,7 +214,9 @@ import { NeedsYouHub } from "./needs-you-hub.js";
|
|
|
192
214
|
import { WEB_CHAT_NOTICE, claimNotice, hasWebChat, releaseNotice, upgradeNoticesPath } from "./upgrade-notices.js";
|
|
193
215
|
import { GENERAL_PAUSE_ERROR, isGeneralInstance } from "./general-instance.js";
|
|
194
216
|
import { buildOrgChart } from "./web-org.js";
|
|
195
|
-
import {
|
|
217
|
+
import { topMemoryHogs } from "./memory-hogs.js";
|
|
218
|
+
import { GENERAL_POINTING_REFUSALS, SNOWFLAKE, hasPlaceRefs, placeRef, webRoute, webTextLinks, placeSuffix, renderPlaceRefs, stripPlaceRefs, topicUrl, worldPlaceOf } from "./topic-link.js";
|
|
219
|
+
import { CacheService, cacheWindow } from "./cache-service.js";
|
|
196
220
|
import { runWebCommand } from "./web-commands.js";
|
|
197
221
|
import { CompactWatch, launchIdentity } from "./compact-watch.js";
|
|
198
222
|
import { agyLegacyAgentsFile, danglingSymlink, migrateAgyAgentsFile } from "./backend/antigravity.js";
|
|
@@ -202,11 +226,17 @@ import { mayUseTool, resolveToolSet, scheduleOpRefusal, toolForIpcType, toolRefu
|
|
|
202
226
|
import { authorizeSession, decideWebGate, loadOrCreateWebToken, readWebToken } from "./web-auth.js";
|
|
203
227
|
import { bypassesWebGate, handleAuthRequest, serveSigninPage } from "./auth-api.js";
|
|
204
228
|
import { isWebPageNavigation } from "./web-shell-routes.js";
|
|
205
|
-
import { localSessionPolicy, tokenEpoch, WebSessionStore } from "./web-session.js";
|
|
206
|
-
import {
|
|
229
|
+
import { guestSessionPolicy, localSessionPolicy, tokenEpoch, WebSessionStore } from "./web-session.js";
|
|
230
|
+
import { authorityNow, evaluateWebAuthority, VERIFIED_SESSION_HOURS, webAuthorityPolicy } from "./authority/web-authority.js";
|
|
231
|
+
import { AuthorityStateStore } from "./authority/authority-state.js";
|
|
232
|
+
import { SessionAuthorizations } from "./authority/session-authorizations.js";
|
|
233
|
+
import { SessionAuthorizationRequests } from "./web-session-authorization.js";
|
|
234
|
+
import { GuestLoginCodes, WebLoginCodes, LOGIN_CODE_TTL_MS } from "./web-login.js";
|
|
235
|
+
import { decisionListAnswer } from "./decision-list.js";
|
|
207
236
|
import { CodeRequestLimiter, ReturningDevices } from "./web-returning-device.js";
|
|
208
|
-
import { allowedHostNames, applyWebSecurityHeaders, hostnameOf, isHostAllowed, WEB_HOST_REJECTED_MESSAGE } from "./web-host-guard.js";
|
|
237
|
+
import { allowedHostNames, applyWebSecurityHeaders, hostnameOf, isHostAllowed, LOOPBACK_HOST_NAMES, WEB_HOST_REJECTED_MESSAGE } from "./web-host-guard.js";
|
|
209
238
|
import { createPreviewListener, normalizeOrigin, previewAvailability, previewSettings } from "./web-preview.js";
|
|
239
|
+
import { createEffectBootstrap } from "./web-effect-bootstrap.js";
|
|
210
240
|
import { fleetLevelDifferences, fleetLevelSignature, appendedConnections } from "./fleet-level-config.js";
|
|
211
241
|
import { checkSelfRestartAllowance, recordSelfRestartAttempt } from "./self-restart-limit.js";
|
|
212
242
|
import { SecretStore } from "./secret-store.js";
|
|
@@ -216,7 +246,7 @@ import { PROVIDER_SECRET_SPECS, providerSecretSpec, providerRegistryEnvKeys, isR
|
|
|
216
246
|
/** A self-restart is a whole service restart; 120s is the apply budget, not this. */
|
|
217
247
|
const SELF_RESTART_DEADLINE_MS = 300_000;
|
|
218
248
|
import { APPLY_FLEET_TARGET, ApplyJobStore, viewOf, } from "./apply-job.js";
|
|
219
|
-
import { CHAT_PROFILE_LOGIN_BACKENDS, credentialHomeSpec, credentialProfileHome, credentialSwitchCarriesConversation, credentialSwitchStartsFresh, instanceCredentialProfile } from "./backend/credential-profile.js";
|
|
249
|
+
import { CHAT_PROFILE_LOGIN_BACKENDS, credentialHomeSpec, credentialProfileHome, credentialProfileLogin, credentialProfileStoreHome, credentialSwitchCarriesConversation, credentialSwitchStartsFresh, instanceCredentialProfile } from "./backend/credential-profile.js";
|
|
220
250
|
import { carryClaudeConversation } from "./backend/claude-carry.js";
|
|
221
251
|
import { mergeBackendOptions, profileKey, profileName, profileOf } from "./classic-bindings.js";
|
|
222
252
|
import { classifyInstanceChange, CLASSIC_HOT_CONFIG_KEYS, HOT_INSTANCE_CONFIG_KEYS, hotConfigUpdate, } from "./instance-config-impact.js";
|
|
@@ -265,6 +295,41 @@ export function selectLruEvictions(warm, cap, opts) {
|
|
|
265
295
|
* fleet.yaml. Keep in sync with `uniqueInstanceName` — every name it emits
|
|
266
296
|
* must match here, or a deleted instance's CLI is left running (#1305 P2-3).
|
|
267
297
|
*/
|
|
298
|
+
/**
|
|
299
|
+
* #2163: where `p` really is — symlinks resolved. A path that does not exist yet is resolved through its deepest
|
|
300
|
+
* existing ancestor (a missing child of a link elsewhere is elsewhere too).
|
|
301
|
+
*/
|
|
302
|
+
function realPathThroughAncestors(p) {
|
|
303
|
+
const missing = [];
|
|
304
|
+
let at = resolvePath(p);
|
|
305
|
+
for (;;) {
|
|
306
|
+
try {
|
|
307
|
+
return join(realpathSync(at), ...missing.reverse());
|
|
308
|
+
}
|
|
309
|
+
catch { /* not there yet: try its parent */ }
|
|
310
|
+
try {
|
|
311
|
+
lstatSync(at);
|
|
312
|
+
return null;
|
|
313
|
+
}
|
|
314
|
+
catch { /* truly absent — not a broken link whose target is unknown */ }
|
|
315
|
+
const up = dirname(at);
|
|
316
|
+
if (up === at)
|
|
317
|
+
return resolvePath(p);
|
|
318
|
+
missing.push(basename(at));
|
|
319
|
+
at = up;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
/**
|
|
323
|
+
* #2163: whether `dir` is inside AgEnD's own workspaces (<AGEND_HOME>/workspaces/<name>/…), compared after resolving
|
|
324
|
+
* symlinks on both sides — including a missing folder's existing ancestors — so a link elsewhere is not inside, nor is a broken link.
|
|
325
|
+
*/
|
|
326
|
+
export function insideManagedWorkspaces(dir, agendHome = getAgendHome()) {
|
|
327
|
+
const root = realPathThroughAncestors(join(agendHome, "workspaces")), real = realPathThroughAncestors(dir);
|
|
328
|
+
if (root === null || real === null)
|
|
329
|
+
return false;
|
|
330
|
+
const rel = relative(root, real);
|
|
331
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
|
|
332
|
+
}
|
|
268
333
|
export function isOrphanInstanceWindowName(name) {
|
|
269
334
|
return /-t\d+$/.test(name) || /^classic-/.test(name);
|
|
270
335
|
}
|
|
@@ -486,6 +551,8 @@ function emojiListFilter(opts) {
|
|
|
486
551
|
withImageUrls: flag(opts.with_image_urls),
|
|
487
552
|
};
|
|
488
553
|
}
|
|
554
|
+
/** #1920: a guest's scope until phase 2 derives one: nothing. */
|
|
555
|
+
const NO_GUEST_SCOPE = new Set();
|
|
489
556
|
export class FleetManager {
|
|
490
557
|
dataDir;
|
|
491
558
|
static signalTarget = null;
|
|
@@ -714,6 +781,8 @@ export class FleetManager {
|
|
|
714
781
|
// Adapter restart: prevents re-entrant restart attempts
|
|
715
782
|
adapterRestarting = new Set();
|
|
716
783
|
// Adapter isolation: track state per adapter for retry + visibility
|
|
784
|
+
/** #2175: this boot's progress message, whose completion may still be owed by its background retry. */
|
|
785
|
+
startupProgress = null;
|
|
717
786
|
adapterState = new Map();
|
|
718
787
|
/** Web Settings secret rotation is deliberately separate from reconnect
|
|
719
788
|
* recovery: a rotation must build a fresh provider client with the new token,
|
|
@@ -752,10 +821,16 @@ export class FleetManager {
|
|
|
752
821
|
collabInstances = new Set();
|
|
753
822
|
// Health endpoint
|
|
754
823
|
healthServer = null;
|
|
824
|
+
/** #2118: independent of HTML preview availability/port; fixed bootstrap only, no effect resources. */
|
|
825
|
+
effectBootstrap = createEffectBootstrap();
|
|
826
|
+
/** Fixed trusted document coherence, independent of the HTML preview listener; never a resource grant. */
|
|
827
|
+
get effectBoot() { return this.effectBootstrap.boot; }
|
|
755
828
|
healthServerDrain = null;
|
|
756
829
|
/** #1306: the preview listener (health_port + 1 by default), and whether it is listening. */
|
|
757
830
|
previewListener = null;
|
|
758
831
|
previewListening = false;
|
|
832
|
+
/** The preview listener could not open its port: "<port>: <error code>", for the page (#2061 follow-up); null otherwise. */
|
|
833
|
+
previewListenError = null;
|
|
759
834
|
/** The ports the preview listener was started for, and the inputs it was built from (a reload compares them). */
|
|
760
835
|
previewPorts = null;
|
|
761
836
|
previewInputs = "";
|
|
@@ -774,6 +849,9 @@ export class FleetManager {
|
|
|
774
849
|
/** Injectable only to keep the chat→CLI reload hand-off deterministic in tests. */
|
|
775
850
|
fullRestartLauncher = launchFullRestartHelper;
|
|
776
851
|
eventLogPruneTimer = null;
|
|
852
|
+
/** #1920 §3.2: the background reads of guests' ClassicBot room membership (a minute's tick; reads only what is due). */
|
|
853
|
+
guestRoomsTimer = null;
|
|
854
|
+
guestRoomMembership = null;
|
|
777
855
|
outboxPruneTimer = null;
|
|
778
856
|
logRotateTimer = null;
|
|
779
857
|
discordPresenceTimer = null;
|
|
@@ -788,6 +866,17 @@ export class FleetManager {
|
|
|
788
866
|
startedAt = 0;
|
|
789
867
|
stormOpenNotifyTimer = null;
|
|
790
868
|
memoryLogAt = null;
|
|
869
|
+
/**
|
|
870
|
+
* #2015: while host memory is elevated or critical, the processes holding the most in the fleet's service and whose
|
|
871
|
+
* they are (an instance, the fleet, tmux), for the pressure log, /health and the dashboard — never chat (#1712).
|
|
872
|
+
* Rescanned at most once a minute (async, one at a time); cleared when pressure ends.
|
|
873
|
+
*/
|
|
874
|
+
memoryTop = null;
|
|
875
|
+
memoryTopScan = { at: null, inFlight: false, loggedAt: null };
|
|
876
|
+
/** The scan (a seam for tests: they give it a fake /proc). */
|
|
877
|
+
memoryHogScan = topMemoryHogs;
|
|
878
|
+
/** The fleet's own tmux session exists (only then are its panes read: a fleet that never started has none). */
|
|
879
|
+
tmuxSessionEnsured = false;
|
|
791
880
|
memoryDebugAt = null;
|
|
792
881
|
memoryLogLevel = null;
|
|
793
882
|
/** #1685: the host_memory value the last status frame carried, so a change re-sends the frame. */
|
|
@@ -884,6 +973,214 @@ export class FleetManager {
|
|
|
884
973
|
return true;
|
|
885
974
|
return false;
|
|
886
975
|
}
|
|
976
|
+
themeStoreInstance;
|
|
977
|
+
webAppearanceService;
|
|
978
|
+
/** #1629: every instance's theme, placements, assets and lock (web-themes.json). */
|
|
979
|
+
get themeStore() {
|
|
980
|
+
// r4.1 Q3 (b): the card's limits are read from fleet.yaml at each upload (a change applies without a restart).
|
|
981
|
+
return (this.themeStoreInstance ??= new ThemeStore(this.dataDir, { limits: () => effectiveAppearanceLimits(this.fleetConfig?.web?.appearance).limits, effectsDropped: ids => this.effectLibrary.collectUnreferenced(ids) }));
|
|
982
|
+
}
|
|
983
|
+
/** #1629: the theme tools, a person's reset and lock, and the one appearance rate limiter (shared with effects). */
|
|
984
|
+
get webAppearance() {
|
|
985
|
+
return (this.webAppearanceService ??= new WebAppearance(this.themeStore, () => this.fleetConfig?.web ?? null, () => { try {
|
|
986
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
987
|
+
}
|
|
988
|
+
catch { /* the next frame carries the rev */ } }));
|
|
989
|
+
}
|
|
990
|
+
effectLibraryInstance;
|
|
991
|
+
effectTrialsInstance;
|
|
992
|
+
/** Lazy, single-owner storage. Register every host reference source before any operation can collect. */
|
|
993
|
+
get effectLibrary() {
|
|
994
|
+
if (!this.effectLibraryInstance) {
|
|
995
|
+
const library = new WebEffectLibrary(this.dataDir);
|
|
996
|
+
// Providers are lazy; publish only after every registration succeeds.
|
|
997
|
+
library.registerReferenceSource("themes", () => {
|
|
998
|
+
if (!this.themeStore.readable())
|
|
999
|
+
throw new Error("themes_unreadable");
|
|
1000
|
+
return this.themeStore.placedEffects().flatMap(row => row.ids.map(id => ({ id, holder: `instance:${row.name}` })));
|
|
1001
|
+
});
|
|
1002
|
+
library.registerReferenceSource("prefs", () => this.webPrefs.ownerEffectReferences());
|
|
1003
|
+
library.registerReferenceSource("mods", () => {
|
|
1004
|
+
const mods = this.mods.list();
|
|
1005
|
+
if (mods.unreadable)
|
|
1006
|
+
throw new Error("mods_unreadable");
|
|
1007
|
+
return mods.mods.flatMap(mod => mod.effects.map(effect => ({ id: effect.id, holder: `mod:${mod.id}` })));
|
|
1008
|
+
});
|
|
1009
|
+
this.effectTrialsInstance = new WebEffectTrials({ library, known: name => this.isKnownInstance(name) });
|
|
1010
|
+
this.effectLibraryInstance = library;
|
|
1011
|
+
}
|
|
1012
|
+
return this.effectLibraryInstance;
|
|
1013
|
+
}
|
|
1014
|
+
/** Volatile Try offers and session-bound runs share this library. */
|
|
1015
|
+
get effectTrials() { if (!this.effectTrialsInstance)
|
|
1016
|
+
void this.effectLibrary; return this.effectTrialsInstance; }
|
|
1017
|
+
effectProfilesInstance;
|
|
1018
|
+
get effectProfiles() { return (this.effectProfilesInstance ??= new WebEffectProfiles(this.dataDir)); }
|
|
1019
|
+
effectServiceInstance;
|
|
1020
|
+
get effectService() {
|
|
1021
|
+
return (this.effectServiceInstance ??= new WebEffectService({ library: this.effectLibrary, themes: this.themeStore, profiles: this.effectProfiles, prefs: this.webPrefs, trials: this.effectTrials,
|
|
1022
|
+
known: name => this.isKnownInstance(name), changed: () => { try {
|
|
1023
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
1024
|
+
}
|
|
1025
|
+
catch { /* next status carries revision */ } } }));
|
|
1026
|
+
}
|
|
1027
|
+
effectToolsService;
|
|
1028
|
+
/** Caller identity is supplied only by the owned IPC connection / verified agent endpoint token. */
|
|
1029
|
+
get effectTools() {
|
|
1030
|
+
return (this.effectToolsService ??= new WebEffectTools({
|
|
1031
|
+
library: this.effectLibrary, limiter: this.webAppearance.limiter,
|
|
1032
|
+
authorize: (name, buckets) => !this.isKnownInstance(name) ? { error: "unknown_instance" } : this.webAppearance.authorizeEffect(name, buckets),
|
|
1033
|
+
placed: name => this.themeStore.get(name).placements.effects,
|
|
1034
|
+
place: (name, effects) => {
|
|
1035
|
+
const before = this.themeStore.get(name).placements.effects;
|
|
1036
|
+
const explicit = new Set(effects.filter(e => typeof e !== "string").map(e => e.id));
|
|
1037
|
+
const w = this.themeStore.setPlacements(name, { effects }, "agent", what => {
|
|
1038
|
+
// An unchanged human/private placement may be retained, never exposed or newly acquired by an agent.
|
|
1039
|
+
const r = explicit.has(what.id) ? this.effectLibrary.read(what.id, { kind: "agent", id: name })
|
|
1040
|
+
: this.effectLibrary.readReferenced(what.id, `instance:${name}`);
|
|
1041
|
+
if (!r.ok)
|
|
1042
|
+
return r.error;
|
|
1043
|
+
const params = explicit.has(what.id) ? what.params : before.find(e => e.id === what.id)?.params;
|
|
1044
|
+
return resolveEffectParams(r.entry.manifest, params ?? {}).ok ? null : "effect_params";
|
|
1045
|
+
});
|
|
1046
|
+
return w.ok ? { ok: true, rev: w.rev } : { ok: false, error: w.error };
|
|
1047
|
+
},
|
|
1048
|
+
changed: () => { try {
|
|
1049
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
1050
|
+
}
|
|
1051
|
+
catch { /* later status carries placements */ } },
|
|
1052
|
+
// A nonmutating own/shared offer is not an appearance write. Only an explicit non-public admin-session click may start it.
|
|
1053
|
+
preview: async (instance, id) => {
|
|
1054
|
+
const result = this.effectTrials.offer(instance, id);
|
|
1055
|
+
if (!result.ok)
|
|
1056
|
+
return { error: "not_found" };
|
|
1057
|
+
const present = this.webChatHistory.list(instance).some(row => row.effectTrial?.offer === result.offer.offer);
|
|
1058
|
+
if (!present && !this.publishEffectTrial(instance, result.offer))
|
|
1059
|
+
return { error: "trial_unavailable" };
|
|
1060
|
+
return { id, status: "offered", expiresAt: result.offer.expiresAt, message: "A trial card is in your web chat. A signed-in admin outside the public link can start it; nothing was applied." };
|
|
1061
|
+
},
|
|
1062
|
+
profiles: id => this.effectProfiles.read(id),
|
|
1063
|
+
profileSummary: id => this.effectService.profileSummary(id),
|
|
1064
|
+
profileSummaries: ids => this.effectService.profileSummaries(ids),
|
|
1065
|
+
playbackSummary: (name, id) => this.effectService.playbackSummary(name, id),
|
|
1066
|
+
}));
|
|
1067
|
+
}
|
|
1068
|
+
appearanceToolsService;
|
|
1069
|
+
/** #1629 r4 §1: get_web_appearance / preview_web_appearance — the caller's own look, resolved as the page resolves it. */
|
|
1070
|
+
get appearanceTools() {
|
|
1071
|
+
return (this.appearanceToolsService ??= new AppearanceTools({
|
|
1072
|
+
frame: (name) => (this.getUiStatus().instances.find(i => i.name === name) ?? { name }),
|
|
1073
|
+
theme: (name) => {
|
|
1074
|
+
const r = this.themeStore.get(name);
|
|
1075
|
+
return { theme: r.theme, locked: r.locked, widgets: r.placements.widgets, ambient: r.placements.ambient,
|
|
1076
|
+
glyphAsset: (id) => this.themeStore.asset(name, id) };
|
|
1077
|
+
},
|
|
1078
|
+
effects: name => this.themeStore.readable() ? this.themeStore.get(name).placements.effects.map(p => ({ id: p.id, by: p.by, ...(p.params ? { params: p.params } : {}), playback: this.effectService.playbackSummary(name, p.id) })) : [],
|
|
1079
|
+
card: (name) => resolveCard(name, humanCards(this.dataDir).get(name), this.themeStore.get(name).theme.card),
|
|
1080
|
+
// #1958: the host's identity-colour settings, as the page reads them (an unreadable prefs file: the defaults).
|
|
1081
|
+
colorPrefs: () => { try {
|
|
1082
|
+
const v = this.webPrefs.read(OPERATOR).values;
|
|
1083
|
+
return { show: v["color.show"], off: v["color.off"] === true };
|
|
1084
|
+
}
|
|
1085
|
+
catch {
|
|
1086
|
+
return {};
|
|
1087
|
+
} },
|
|
1088
|
+
cardPicture: (name, slot) => cardPicture(this, name, slot),
|
|
1089
|
+
themeAsset: (name, id) => this.themeStore.asset(name, id),
|
|
1090
|
+
profileAvatar: (name) => this.webImage("avatar", name),
|
|
1091
|
+
botAvatar: (_name, key) => this.webImage("bot", key),
|
|
1092
|
+
themeAnswer: (name) => this.webAppearance.getTheme(name),
|
|
1093
|
+
}));
|
|
1094
|
+
}
|
|
1095
|
+
/** #1958: a profile, card or colour write (view-api.ts) landed: every open page gets a fresh status frame. */
|
|
1096
|
+
identityChanged() {
|
|
1097
|
+
try {
|
|
1098
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
1099
|
+
}
|
|
1100
|
+
catch { /* the next frame carries it */ }
|
|
1101
|
+
}
|
|
1102
|
+
/** A fleet.yaml instance (own key) or a ClassicBot room, now (#1629: a person's reset/lock names one). */
|
|
1103
|
+
isKnownInstance(name) {
|
|
1104
|
+
return Object.hasOwn(this.fleetConfig?.instances ?? {}, name) || (this.classicChannels?.getAll() ?? []).some((ch) => ch.instanceName === name);
|
|
1105
|
+
}
|
|
1106
|
+
modStore;
|
|
1107
|
+
/**
|
|
1108
|
+
* #1629 r4-5 / B2: installed mods use the same validated library and scoped holder claims as direct uploads.
|
|
1109
|
+
*/
|
|
1110
|
+
get mods() {
|
|
1111
|
+
return (this.modStore ??= new ModStore(this.dataDir, {
|
|
1112
|
+
themes: this.themeStore,
|
|
1113
|
+
prefs: this.webPrefs,
|
|
1114
|
+
ownerCss: this.ownerCss,
|
|
1115
|
+
effects: this.effectLibrary,
|
|
1116
|
+
context: () => ({ agendVersion: agendVersion(), limits: this.themeStore.limits(), effects: cw1EffectChecker() }),
|
|
1117
|
+
isKnownInstance: (name) => this.isKnownInstance(name),
|
|
1118
|
+
prefsIdentity: OPERATOR,
|
|
1119
|
+
}));
|
|
1120
|
+
}
|
|
1121
|
+
agentModsService;
|
|
1122
|
+
/** #1629 r4-5b: export_web_mod / propose_web_mod — the caller's own look as a file, and a proposal for a person. */
|
|
1123
|
+
get agentMods() {
|
|
1124
|
+
return (this.agentModsService ??= new AgentMods({
|
|
1125
|
+
themes: this.themeStore, mods: this.mods, limiter: this.webAppearance.limiter,
|
|
1126
|
+
webConfig: () => this.fleetConfig?.web ?? null,
|
|
1127
|
+
// The mod store's own: a proposal is checked exactly as the person's import of it will be.
|
|
1128
|
+
context: () => this.mods.checkContext(),
|
|
1129
|
+
readOwnEffect: (instance, id) => { const r = this.effectLibrary.read(id, { kind: "agent", id: instance }); return r.ok ? { name: r.entry.manifest.name, files: r.entry.files } : null; },
|
|
1130
|
+
notice: (instance, text) => { try {
|
|
1131
|
+
this.emitSseEvent("message", { instance, sender: instance, role: "status", text, ts: new Date().toISOString() });
|
|
1132
|
+
}
|
|
1133
|
+
catch { /* the page reads it from Settings too */ } },
|
|
1134
|
+
changed: () => { try {
|
|
1135
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
1136
|
+
}
|
|
1137
|
+
catch { /* the next frame */ } },
|
|
1138
|
+
}));
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* #1629 r4-5c: an effect as this person may carry it away in an export — their own claim, or one a person shared —
|
|
1142
|
+
* read with their principal (Sol's ACL). Being able to view or run a placed effect never grants packaging someone
|
|
1143
|
+
* else's private claim: the library's reference read is runtime access, not an export path. Null: not theirs.
|
|
1144
|
+
*/
|
|
1145
|
+
modPlacedEffect(person, id) {
|
|
1146
|
+
const r = this.effectLibrary.read(id, { kind: "human", id: person });
|
|
1147
|
+
return r.ok ? { name: r.entry.manifest.name, files: r.entry.files } : null;
|
|
1148
|
+
}
|
|
1149
|
+
/** #1629 r4-5: an instance's card text as every viewer sees it (a person's fields over the agent's). */
|
|
1150
|
+
modCardText(name) {
|
|
1151
|
+
const card = resolveCard(name, humanCards(this.dataDir).get(name), this.themeStore.get(name).theme.card);
|
|
1152
|
+
return { ...(card.tagline ? { tagline: card.tagline.text } : {}), ...(card.bio ? { bio: card.bio.text } : {}) };
|
|
1153
|
+
}
|
|
1154
|
+
ownerCssStore;
|
|
1155
|
+
/** #1629 r4 §3: each person's own CSS; which version is in force is their `css.active` in the web preferences. */
|
|
1156
|
+
get ownerCss() {
|
|
1157
|
+
return (this.ownerCssStore ??= new OwnerCssStore(this.dataDir, this.webPrefs));
|
|
1158
|
+
}
|
|
1159
|
+
webSettingsToolsService;
|
|
1160
|
+
/**
|
|
1161
|
+
* #2056: Settings → Web appearance for a tool (General, a coordinator, full) — the page's own stores and checks, and the
|
|
1162
|
+
* page's announcement after a change (web-settings-tools.ts).
|
|
1163
|
+
*/
|
|
1164
|
+
get webSettings() {
|
|
1165
|
+
return (this.webSettingsToolsService ??= new WebSettingsTools({
|
|
1166
|
+
prefs: this.webPrefs, ownerCss: this.ownerCss, mods: this.mods, effects: this.effectService,
|
|
1167
|
+
instances: () => [...Object.keys(this.fleetConfig?.instances ?? {}),
|
|
1168
|
+
...(this.classicChannels?.getAll() ?? []).map((ch) => ch.instanceName).filter((n) => !Object.hasOwn(this.fleetConfig?.instances ?? {}, n))],
|
|
1169
|
+
colour: (name) => personIdentityColour(this.dataDir, name),
|
|
1170
|
+
setColour: (name, patch) => { const w = setPersonIdentityColour(this.dataDir, name, patch); if (w.ok)
|
|
1171
|
+
this.identityChanged(); return w; },
|
|
1172
|
+
bannerFocus: (name) => personBannerFocus(this.dataDir, name),
|
|
1173
|
+
setBannerFocus: (name, focus) => { const w = setPersonBannerFocus(this.dataDir, name, focus); if (w.ok)
|
|
1174
|
+
this.identityChanged(); return w; },
|
|
1175
|
+
placements: (name) => this.themeStore.get(name).placements.effects.map((e) => (typeof e === "string" ? { id: e } : e)),
|
|
1176
|
+
ambient: (name) => Object.fromEntries(Object.entries(this.themeStore.get(name).placements.ambient).flatMap(([k, a]) => a ? [[k, { spec: a.spec, by: a.by }]] : [])),
|
|
1177
|
+
setAmbient: (name, spec, which) => this.webAppearance.humanSetAmbient(name, spec, which),
|
|
1178
|
+
announce: () => { try {
|
|
1179
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
1180
|
+
}
|
|
1181
|
+
catch { /* the next status frame carries it */ } },
|
|
1182
|
+
}));
|
|
1183
|
+
}
|
|
887
1184
|
get webPrefs() {
|
|
888
1185
|
// #1664: a favorite must be an instance of this fleet now — fleet.yaml's (own keys) or a ClassicBot room's.
|
|
889
1186
|
return (this.webPrefsStore ??= new WebPrefsStore(this.dataDir, {
|
|
@@ -1154,9 +1451,26 @@ export class FleetManager {
|
|
|
1154
1451
|
sseHeartbeatMs = SSE_HEARTBEAT_MS;
|
|
1155
1452
|
/** The dashboard's login codes. Memory only: a code that outlives the process is a code nobody can prove was not copied. */
|
|
1156
1453
|
webLoginCodes = null;
|
|
1454
|
+
/**
|
|
1455
|
+
* #1920 step 4: guests' codes, apart from the admins' — one per account, so no guest's `/web` withdraws another's or
|
|
1456
|
+
* an admin's code (#2093 review), at most 32 at once. Local sign-in only for now (audience "local").
|
|
1457
|
+
*/
|
|
1458
|
+
webGuestLoginCodes = null;
|
|
1459
|
+
/** #1920 step 4: when each account last got a guest code (monotonic) — one a minute, so `/web` is no DM flood. */
|
|
1460
|
+
guestCodeAskedAt = new Map();
|
|
1461
|
+
/** #2093 review: an account's guest /web in progress — one at a time, so two at once cannot both pass the minute. */
|
|
1462
|
+
guestCodeInFlight = new Set();
|
|
1463
|
+
/**
|
|
1464
|
+
* #2093 review: revokes a guest /web in progress must see — every web session's (`/web revoke` from an admin) bumps
|
|
1465
|
+
* the global count, an account's own bumps its entry — checked before the code is issued and while it is delivered.
|
|
1466
|
+
*/
|
|
1467
|
+
guestRevokes = 0;
|
|
1468
|
+
guestAccountRevokes = new Map();
|
|
1157
1469
|
/** #1570: browsers that may ask the sign-in page for a fresh code, and how often they may. */
|
|
1158
1470
|
returningDevices = null;
|
|
1159
1471
|
codeRequestLimiter = new CodeRequestLimiter();
|
|
1472
|
+
/** #1920 step 4b: guests' device code requests, limited apart — guests never use up the admins' fleet-wide budget. */
|
|
1473
|
+
guestCodeRequestLimiter = new CodeRequestLimiter();
|
|
1160
1474
|
/**
|
|
1161
1475
|
* Set while a Settings apply job is driving the reconcile. The reconcile
|
|
1162
1476
|
* stays the single doer; it just says out loud what it is doing to whom, so
|
|
@@ -1304,6 +1618,7 @@ export class FleetManager {
|
|
|
1304
1618
|
meta: {
|
|
1305
1619
|
chat_id: set.chatId, message_id: messageId, user: by.username, user_id: by.userId, ts,
|
|
1306
1620
|
thread_id: set.threadId, adapter_id: inbound.adapterId, source: inbound.source,
|
|
1621
|
+
...(web && by.guest ? { web_guest: "1" } : {}), // #1920: "[user:… via web (guest), id:…]", as /ui/send
|
|
1307
1622
|
...reactions.meta,
|
|
1308
1623
|
},
|
|
1309
1624
|
}, by.humanOrigin, button.label)) !== false;
|
|
@@ -1324,6 +1639,9 @@ export class FleetManager {
|
|
|
1324
1639
|
this.emitSseEvent("message", {
|
|
1325
1640
|
instance: set.instance, sender: by.username, role: "user", text: content, ts, ...(web ? { messageId } : {}),
|
|
1326
1641
|
click: { label: button.label, of: set.id },
|
|
1642
|
+
// #1920: a platform click is its clicker's; it is the instance's channel's only when its buttons are there (the
|
|
1643
|
+
// same rule as a reply's: a set sent to another topic or a DM is not). A web click is the web's.
|
|
1644
|
+
...(web ? {} : { from: webChatFrom(set.adapterId, by.userId), ...(this.clickInOwnChannel(set) ? { channel: true } : {}) }),
|
|
1327
1645
|
});
|
|
1328
1646
|
return true;
|
|
1329
1647
|
}
|
|
@@ -1378,6 +1696,18 @@ export class FleetManager {
|
|
|
1378
1696
|
}
|
|
1379
1697
|
}
|
|
1380
1698
|
});
|
|
1699
|
+
// #1918: the org canvas's traffic — from the row this listener's events already name, never a probe of its own.
|
|
1700
|
+
// The row as it is now (it has already changed when the event comes): its state, not the event's, is the truth.
|
|
1701
|
+
outbox.on("state", (event) => {
|
|
1702
|
+
const row = event.deliveryId ? outbox.get(event.deliveryId) : undefined;
|
|
1703
|
+
if (row)
|
|
1704
|
+
this.publishTraffic(row);
|
|
1705
|
+
});
|
|
1706
|
+
outbox.on("consumed", (event) => {
|
|
1707
|
+
const row = event.deliveryId ? outbox.get(event.deliveryId) : undefined;
|
|
1708
|
+
if (row)
|
|
1709
|
+
this.publishTraffic(row, "consumed");
|
|
1710
|
+
});
|
|
1381
1711
|
outbox.on("generation_recovered", () => this.scheduleDeliveryOutboxPump());
|
|
1382
1712
|
this.replyObligationTimer = setInterval(() => measureSyncWork("fleet.replyObligationSweep", () => this.sweepReplyObligations()), REPLY_OBLIGATION_SWEEP_MS);
|
|
1383
1713
|
this.replyObligationTimer.unref?.();
|
|
@@ -1399,6 +1729,52 @@ export class FleetManager {
|
|
|
1399
1729
|
});
|
|
1400
1730
|
this.scheduleDeliveryOutboxPump();
|
|
1401
1731
|
}
|
|
1732
|
+
/** #1918: cross-instance traffic, as the org canvas draws it (fleet-traffic.ts). */
|
|
1733
|
+
trafficLog = new TrafficLog();
|
|
1734
|
+
delegations = new Delegations();
|
|
1735
|
+
trafficMemo = null;
|
|
1736
|
+
/**
|
|
1737
|
+
* One delivery row's traffic item, kept for the snapshot and sent to the open pages when it is news; and the
|
|
1738
|
+
* delegation it opens or closes (a task and its report), sent as "delegation".
|
|
1739
|
+
*/
|
|
1740
|
+
publishTraffic(row, state) {
|
|
1741
|
+
try {
|
|
1742
|
+
const item = trafficItem(row, this.fleetConfig, new Date().toISOString(), state);
|
|
1743
|
+
const news = item ? this.trafficLog.note(item) : null;
|
|
1744
|
+
const work = news ? this.delegations.note(row, news) : [];
|
|
1745
|
+
if (news || work.length)
|
|
1746
|
+
this.trafficMemo = null;
|
|
1747
|
+
if (news)
|
|
1748
|
+
this.emitSseEvent("traffic", news);
|
|
1749
|
+
// Each delegation as its two instances are seen now: one that expires or is pushed out may be older than a change
|
|
1750
|
+
// to their visibility (the incoming row's own item was checked; these can be anyone's).
|
|
1751
|
+
const visible = (name) => crossInstanceVisibility(this.fleetConfig, name) !== "hidden";
|
|
1752
|
+
for (const d of work)
|
|
1753
|
+
if (visible(d.from) && visible(d.to))
|
|
1754
|
+
this.emitSseEvent("delegation", d);
|
|
1755
|
+
}
|
|
1756
|
+
catch (err) {
|
|
1757
|
+
this.logger.debug({ err }, "traffic: an item was not published");
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
/**
|
|
1761
|
+
* GET /ui/traffic: what is in flight now (the outbox's pending rows) and what finished in the last two minutes, at
|
|
1762
|
+
* most TRAFFIC_SNAPSHOT_MAX items. Worked out at most once every two seconds, so the public link's polling (or any
|
|
1763
|
+
* number of pages) costs one indexed read per two seconds. Visibility is applied as of now.
|
|
1764
|
+
*/
|
|
1765
|
+
trafficSnapshot() {
|
|
1766
|
+
const nowMs = performance.now();
|
|
1767
|
+
if (this.trafficMemo && nowMs - this.trafficMemo.atMs < 2_000)
|
|
1768
|
+
return this.trafficMemo.value;
|
|
1769
|
+
const now = new Date().toISOString();
|
|
1770
|
+
const pending = (this.deliveryOutbox?.listPending() ?? [])
|
|
1771
|
+
.map((r) => trafficItem(r, this.fleetConfig, r.createdAt ?? now)).filter((i) => i !== null);
|
|
1772
|
+
const visible = (name) => crossInstanceVisibility(this.fleetConfig, name) !== "hidden";
|
|
1773
|
+
const items = this.trafficLog.snapshot(pending).filter((i) => visible(i.from) && visible(i.to));
|
|
1774
|
+
const delegations = this.delegations.snapshot().filter((d) => visible(d.from) && visible(d.to));
|
|
1775
|
+
this.trafficMemo = { atMs: nowMs, value: { now, items, delegations } };
|
|
1776
|
+
return this.trafficMemo.value;
|
|
1777
|
+
}
|
|
1402
1778
|
/** Synchronous SQLite admission; the caller may acknowledge only after this returns. */
|
|
1403
1779
|
admitDurableDelivery(input) {
|
|
1404
1780
|
const outbox = this.deliveryOutbox;
|
|
@@ -1411,6 +1787,8 @@ export class FleetManager {
|
|
|
1411
1787
|
}
|
|
1412
1788
|
const sourceKey = `mcp:${input.sourceInstance}:${input.operationId}:${input.targetInstance}:${input.targetSession ?? ""}:${input.kind}`;
|
|
1413
1789
|
const admitted = outbox.admit({ ...input, sourceDaemonBootId, sourceKey });
|
|
1790
|
+
if (admitted.inserted)
|
|
1791
|
+
this.publishTraffic(admitted.delivery);
|
|
1414
1792
|
if (admitted.inserted)
|
|
1415
1793
|
this.logger.info({
|
|
1416
1794
|
deliveryId: admitted.delivery.deliveryId,
|
|
@@ -1433,10 +1811,18 @@ export class FleetManager {
|
|
|
1433
1811
|
queryDurableDeliveryStatus(callerInstance, selector) {
|
|
1434
1812
|
this.ensureDeliveryOutbox();
|
|
1435
1813
|
const page = this.deliveryOutbox.queryStatusForInstance(callerInstance, selector);
|
|
1814
|
+
// #1939 §10: a human receipt's authority as it reads now (switch, epoch, loopback_only).
|
|
1815
|
+
const state = page.items.some(item => item.authority) ? this.webAuthorityState() : null;
|
|
1816
|
+
const human = (item) => {
|
|
1817
|
+
if (!item.authority || !state)
|
|
1818
|
+
return item;
|
|
1819
|
+
const authority = authorityNow(item.authority, state);
|
|
1820
|
+
return { ...item, authority, ...(authority.downgraded ? { source_instance: "human:web:unknown" } : {}) };
|
|
1821
|
+
};
|
|
1436
1822
|
// #1641: a sender that sees only `queued` cannot tell "next in line" from "the target is stuck": say which.
|
|
1437
1823
|
return {
|
|
1438
1824
|
...page,
|
|
1439
|
-
items: page.items.map(item => (item.state === "queued" || item.state === "retry_wait")
|
|
1825
|
+
items: page.items.map(human).map(item => (item.state === "queued" || item.state === "retry_wait")
|
|
1440
1826
|
? { ...item, waiting_reason: this.deliveryWaitingReason(item.target_instance) }
|
|
1441
1827
|
: item),
|
|
1442
1828
|
};
|
|
@@ -1784,17 +2170,58 @@ export class FleetManager {
|
|
|
1784
2170
|
this.logger.info({ hostMemory: snapshot }, "Host memory recovered");
|
|
1785
2171
|
}
|
|
1786
2172
|
this.memoryLogLevel = snapshot.level;
|
|
2173
|
+
if (this.memoryTop) {
|
|
2174
|
+
this.memoryTop = null;
|
|
2175
|
+
this.memoryTopScan.loggedAt = null;
|
|
2176
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
2177
|
+
}
|
|
1787
2178
|
return;
|
|
1788
2179
|
}
|
|
2180
|
+
if (snapshot.level === "elevated" || snapshot.level === "critical")
|
|
2181
|
+
this.refreshMemoryTop(snapshot);
|
|
1789
2182
|
if (changed || this.memoryLogAt === null || now - this.memoryLogAt >= 10 * 60_000) {
|
|
1790
2183
|
this.memoryLogAt = now;
|
|
1791
|
-
this.logger.warn({ hostMemory: snapshot }, snapshot.level === "critical"
|
|
2184
|
+
this.logger.warn({ hostMemory: snapshot, ...(this.memoryTop ? { topProcesses: this.memoryTop.processes } : {}) }, snapshot.level === "critical"
|
|
1792
2185
|
? "Host memory critical — deferring new CLI spawns"
|
|
1793
2186
|
: snapshot.level === "elevated" ? "Host memory pressure — slowing new CLI spawns"
|
|
1794
2187
|
: "Host memory sample unavailable — slowing new CLI spawns");
|
|
1795
2188
|
}
|
|
1796
2189
|
this.memoryLogLevel = snapshot.level;
|
|
1797
2190
|
}
|
|
2191
|
+
/**
|
|
2192
|
+
* #2015: rescan the largest processes (at most once a minute, one at a time). The first result of an episode, and
|
|
2193
|
+
* then at most every 10 minutes, is logged with the pressure; /health and the dashboard read the latest. Never chat.
|
|
2194
|
+
*/
|
|
2195
|
+
refreshMemoryTop(snapshot) {
|
|
2196
|
+
const scan = this.memoryTopScan;
|
|
2197
|
+
const now = performance.now();
|
|
2198
|
+
if (scan.inFlight || (scan.at !== null && now - scan.at < 60_000))
|
|
2199
|
+
return;
|
|
2200
|
+
scan.inFlight = true;
|
|
2201
|
+
scan.at = now;
|
|
2202
|
+
void (async () => {
|
|
2203
|
+
const session = getTmuxSession();
|
|
2204
|
+
const [tmuxServerPid, panes] = this.tmuxSessionEnsured
|
|
2205
|
+
? await Promise.all([TmuxManager.getServerPid(session), TmuxManager.listPanePids(session)])
|
|
2206
|
+
: [null, []];
|
|
2207
|
+
const processes = await this.memoryHogScan({
|
|
2208
|
+
fleetPid: process.pid, tmuxServerPid, panes,
|
|
2209
|
+
isInstance: name => this.daemons.has(name) || Object.hasOwn(this.fleetConfig?.instances ?? {}, name),
|
|
2210
|
+
}, 3);
|
|
2211
|
+
// Pressure may have ended while the scan ran: nothing is kept then.
|
|
2212
|
+
if (this.shuttingDown || processes.length === 0 || this.hostMemoryIndicator() === null)
|
|
2213
|
+
return;
|
|
2214
|
+
const before = JSON.stringify(this.memoryTop?.processes ?? null);
|
|
2215
|
+
this.memoryTop = { at: new Date().toISOString(), processes };
|
|
2216
|
+
if (scan.loggedAt === null || performance.now() - scan.loggedAt >= 10 * 60_000) {
|
|
2217
|
+
scan.loggedAt = performance.now();
|
|
2218
|
+
this.logger.warn({ hostMemory: snapshot, topProcesses: processes }, "Host memory pressure — largest processes in the fleet");
|
|
2219
|
+
}
|
|
2220
|
+
if (JSON.stringify(processes) !== before)
|
|
2221
|
+
this.emitSseEvent("status", this.getUiStatus());
|
|
2222
|
+
})().catch(err => this.logger.debug({ err }, "Largest-process scan failed"))
|
|
2223
|
+
.finally(() => { scan.inFlight = false; });
|
|
2224
|
+
}
|
|
1798
2225
|
/** Wire the one fleet-wide storm into notification and recovery surfaces. */
|
|
1799
2226
|
bindStormWindowEvents() {
|
|
1800
2227
|
this.stormWindow.on("opened", (snapshot) => {
|
|
@@ -2116,6 +2543,7 @@ export class FleetManager {
|
|
|
2116
2543
|
this.fleetConfig = loaded;
|
|
2117
2544
|
this.savedFleetConfigSnapshot = structuredClone(this.fleetConfig);
|
|
2118
2545
|
this.warnAboutRemovedLoginMode(loaded);
|
|
2546
|
+
this.enforceGuestSwitch();
|
|
2119
2547
|
return this.fleetConfig;
|
|
2120
2548
|
}
|
|
2121
2549
|
relayLoginModeWarned = false;
|
|
@@ -3241,7 +3669,8 @@ export class FleetManager {
|
|
|
3241
3669
|
* for `instance` (#1320 part B). Per entry: the channel's own adapter, no
|
|
3242
3670
|
* thread, mention suppression on. Returns the number of channels posted
|
|
3243
3671
|
* to. Failures are per-entry warn-and-continue — a failed echo never fails
|
|
3244
|
-
* the web send.
|
|
3672
|
+
* the web send. Only entries classicWebEchoOn admits are touched (#2054: unset follows web.echo_to_channel; an explicit
|
|
3673
|
+
* `web_echo: false` never echoes).
|
|
3245
3674
|
*
|
|
3246
3675
|
* Every copy is fenced at start time: an entry whose explicit world is
|
|
3247
3676
|
* gone is skipped (only legacy adapterId-less entries fall back to the
|
|
@@ -3252,6 +3681,15 @@ export class FleetManager {
|
|
|
3252
3681
|
* already in flight may still land late — the contract permits that.
|
|
3253
3682
|
*/
|
|
3254
3683
|
/** `sender` (#1827): the web person's name, as the room log records them ("web-user" when none). */
|
|
3684
|
+
/**
|
|
3685
|
+
* #1920 §5.2: a web message's channel copy was sent — it is now what the channel saw. Kept so (and on disk), and sent
|
|
3686
|
+
* to the guests' streams only: an admin's page already has it, and nothing about it changed for them.
|
|
3687
|
+
*/
|
|
3688
|
+
webMessageInChannel(instance, messageId) {
|
|
3689
|
+
const m = this.webChatHistory.markChannel(instance, messageId);
|
|
3690
|
+
if (m)
|
|
3691
|
+
broadcastToGuests(this.sseClients, "message", m, (err) => this.logger.debug({ err }, "SSE client write failed; evicting"));
|
|
3692
|
+
}
|
|
3255
3693
|
async sendClassicWebEcho(instance, text, sender = WEB_NAME_FALLBACK) {
|
|
3256
3694
|
const guard = this.webChannelEchoGuards.get(instance);
|
|
3257
3695
|
const handled = new Set();
|
|
@@ -3268,7 +3706,7 @@ export class FleetManager {
|
|
|
3268
3706
|
}
|
|
3269
3707
|
}
|
|
3270
3708
|
const entry = (this.classicChannels?.getAll() ?? [])
|
|
3271
|
-
.find(candidate => candidate.instanceName === instance && candidate.webEcho
|
|
3709
|
+
.find(candidate => candidate.instanceName === instance && classicWebEchoOn(candidate.webEcho, this.fleetConfig?.web?.echo_to_channel)
|
|
3272
3710
|
&& !handled.has(`${candidate.channelId}#${candidate.adapterId ?? ""}`));
|
|
3273
3711
|
if (!entry)
|
|
3274
3712
|
break;
|
|
@@ -3468,12 +3906,31 @@ export class FleetManager {
|
|
|
3468
3906
|
}
|
|
3469
3907
|
/** Evidence-only admission. Bots/system/agent payloads have no trusted origin. */
|
|
3470
3908
|
humanReceiptPayload(instanceName, payload, origin, originalBody) {
|
|
3909
|
+
// #1939 S3: "via web (verified)" comes only from the receipt written here — never from a caller's meta.
|
|
3910
|
+
const given = payload.meta;
|
|
3911
|
+
if (given && "web_verified" in given) {
|
|
3912
|
+
const { web_verified: _claimed, ...rest } = given;
|
|
3913
|
+
payload = { ...payload, meta: rest };
|
|
3914
|
+
}
|
|
3471
3915
|
if (!origin || !this.deliveryOutbox)
|
|
3472
3916
|
return payload;
|
|
3473
3917
|
const row = this.deliveryOutbox.createHumanReceipt({ targetInstance: instanceName, originalBody,
|
|
3474
3918
|
origin: { ...origin }, inputKind: String(payload.type), managerBootId: this.managerBootId });
|
|
3919
|
+
// #1939 §7: each ordinary verified web message, for the S1 beta to watch. No text, cookie or session id: the handle.
|
|
3920
|
+
const authority = origin.authority;
|
|
3921
|
+
if (authority?.kind === "web-verified" && authority.actor && authority.session) {
|
|
3922
|
+
try {
|
|
3923
|
+
this.eventLog?.insert(instanceName, "web_authority", { receipt_id: row.receipt_id, session: authority.session.handle,
|
|
3924
|
+
peer: authority.session.peer, surface: "local", actor: `${authority.actor.adapter_id}:${authority.actor.user_id}`,
|
|
3925
|
+
input_kind: String(payload.type), outcome: "web-verified", authority_epoch: authority.authority_epoch });
|
|
3926
|
+
}
|
|
3927
|
+
catch (err) {
|
|
3928
|
+
this.logger.warn({ err, instanceName }, "Could not record web authority");
|
|
3929
|
+
}
|
|
3930
|
+
}
|
|
3931
|
+
const verified = origin.platform === "web" && authority?.kind === "web-verified";
|
|
3475
3932
|
return { ...payload, meta: { ...(payload.meta ?? {}),
|
|
3476
|
-
human_receipt_id: row.receipt_id, verification_id: row.message_id } };
|
|
3933
|
+
human_receipt_id: row.receipt_id, verification_id: row.message_id, ...(verified ? { web_verified: "1" } : {}) } };
|
|
3477
3934
|
}
|
|
3478
3935
|
/** Bind at the actual IPC send, after all wake/reconnect waits. No human retry lane. */
|
|
3479
3936
|
bindHumanReceiptPayload(instanceName, payload) {
|
|
@@ -3687,6 +4144,14 @@ export class FleetManager {
|
|
|
3687
4144
|
return;
|
|
3688
4145
|
}
|
|
3689
4146
|
const scope = door.scope;
|
|
4147
|
+
// #1920 step 4: a non-admin's /web while guest sign-in is on is theirs to sign in as a guest (or revoke their own)
|
|
4148
|
+
// — before the table, which keeps /web for fleet admins. Per account: it touches no instance binding.
|
|
4149
|
+
// Decided synchronously, so an admin's /web still reaches the table with no await after the door (#1399).
|
|
4150
|
+
if (data.command === "dashboard" && this.isGuestWebAsk(adapterId, data.userId)) {
|
|
4151
|
+
await this.guestWebCommand({ adapterId, userId: data.userId, username: data.username,
|
|
4152
|
+
arg: String(data.options?.action ?? "").trim().toLowerCase(), replyHere: text => data.respond(text), replyPrivately: text => data.respond(text) });
|
|
4153
|
+
return;
|
|
4154
|
+
}
|
|
3690
4155
|
const spec = commandSpec(data.command);
|
|
3691
4156
|
if (!spec) {
|
|
3692
4157
|
this.logger.info({ command: data.command, adapterId }, "Slash command is not in the command table");
|
|
@@ -3704,7 +4169,11 @@ export class FleetManager {
|
|
|
3704
4169
|
// A command off for want of fleet admins names where they go (`{0}` in its disabled reply).
|
|
3705
4170
|
if (decision.reply === spec.disabled)
|
|
3706
4171
|
args.push(this.adminListKey(adapterId));
|
|
3707
|
-
|
|
4172
|
+
// #1990: a refusal that sends the person to General links to it — not in a ClassicBot room, whose readers need
|
|
4173
|
+
// not be in the fleet's guild.
|
|
4174
|
+
const toGeneral = GENERAL_POINTING_REFUSALS.has(key) && scope !== "classic" && scope !== "none";
|
|
4175
|
+
const reply = toGeneral ? this.renderPlaces(adapterId, t(key, ...args) + placeSuffix({ kind: "general" }, "General")).text : t(key, ...args);
|
|
4176
|
+
await data.respond(reply).catch(() => { });
|
|
3708
4177
|
return;
|
|
3709
4178
|
}
|
|
3710
4179
|
if (data.command === "start") {
|
|
@@ -4317,6 +4786,22 @@ export class FleetManager {
|
|
|
4317
4786
|
this.logger.warn({ err, name, backend }, "Failed to sync worker skills — continuing startup");
|
|
4318
4787
|
}
|
|
4319
4788
|
}
|
|
4789
|
+
else if (kind === "classic") {
|
|
4790
|
+
// #2163: a Classic bot gets only the skills marked `classic` (its own look, the dashboard) — never the fleet's
|
|
4791
|
+
// coordination playbooks (#557 kept those out of end-user bots) — and only into a workspace AgEnD manages: the
|
|
4792
|
+
// room's own folder under <AGEND_HOME>/workspaces/. Anywhere else, nothing is written; `agend-agent skill <name>`
|
|
4793
|
+
// reads any bundled skill on demand.
|
|
4794
|
+
try {
|
|
4795
|
+
const skillsWorkDir = this.resolveKnowledgeWorkDir(config.working_directory, backend, name);
|
|
4796
|
+
if (insideManagedWorkspaces(skillsWorkDir))
|
|
4797
|
+
measureSyncWork("fleet.classicSkills", () => this.syncRoleSkills(skillsWorkDir, backend, "classic"));
|
|
4798
|
+
else
|
|
4799
|
+
this.logger.debug({ name, skillsWorkDir }, "Classic workspace is not AgEnD-managed — no skills published");
|
|
4800
|
+
}
|
|
4801
|
+
catch (err) {
|
|
4802
|
+
this.logger.warn({ err, name, backend }, "Failed to sync classic skills — continuing startup");
|
|
4803
|
+
}
|
|
4804
|
+
}
|
|
4320
4805
|
const receipt = execution ? this.classicSettingsOwners.get(execution) : undefined;
|
|
4321
4806
|
const identity = { kind, backend, model: this.resolveInstanceModel(name).display };
|
|
4322
4807
|
if (receipt) {
|
|
@@ -5127,10 +5612,14 @@ export class FleetManager {
|
|
|
5127
5612
|
// #1620: fleet.yaml's web.session.local, read at every check — a Settings save or a reload applies at once
|
|
5128
5613
|
// (shortening ends the sessions it now outlives). The public link's policy stays fixed.
|
|
5129
5614
|
localPolicy: () => localSessionPolicy(this.fleetConfig?.web?.session?.local),
|
|
5615
|
+
// #1920 §5.4: a guest's, from web.guests.session (never longer than the surface's own).
|
|
5616
|
+
guestPolicy: () => guestSessionPolicy(this.fleetConfig?.web?.guests?.session),
|
|
5130
5617
|
});
|
|
5618
|
+
this.enforceGuestSwitch(); // #1920: guests off while the fleet was down
|
|
5131
5619
|
}
|
|
5132
5620
|
if (!this.returningDevices) {
|
|
5133
5621
|
this.returningDevices = new ReturningDevices({ dataDir: this.dataDir, onWarn: message => this.logger.warn(message) });
|
|
5622
|
+
this.enforceGuestSwitch(); // #1920: guests' devices too, if guests went off while down
|
|
5134
5623
|
}
|
|
5135
5624
|
if (!this.webLoginCodes) {
|
|
5136
5625
|
this.webLoginCodes = new WebLoginCodes({
|
|
@@ -5142,6 +5631,16 @@ export class FleetManager {
|
|
|
5142
5631
|
},
|
|
5143
5632
|
});
|
|
5144
5633
|
}
|
|
5634
|
+
if (!this.webGuestLoginCodes) {
|
|
5635
|
+
this.webGuestLoginCodes = new GuestLoginCodes({
|
|
5636
|
+
onEvent: event => {
|
|
5637
|
+
if (event === "burned")
|
|
5638
|
+
this.logger.warn("A guest web login code was used up by wrong attempts");
|
|
5639
|
+
else if (event === "breaker-open")
|
|
5640
|
+
this.logger.warn("Guest web sign-in paused: too many wrong login codes");
|
|
5641
|
+
},
|
|
5642
|
+
});
|
|
5643
|
+
}
|
|
5145
5644
|
}
|
|
5146
5645
|
/**
|
|
5147
5646
|
* A single-use login code for the dashboard, for a channel only the operator
|
|
@@ -5265,6 +5764,7 @@ export class FleetManager {
|
|
|
5265
5764
|
dispatch: (req, res) => this.dispatchWebHttp(req, res, this.fleetConfig?.health_port ?? 19280) }),
|
|
5266
5765
|
revoke: id => {
|
|
5267
5766
|
this.webLoginCodes?.revokeAudience(id);
|
|
5767
|
+
this.webGuestLoginCodes?.revokeAudience(id);
|
|
5268
5768
|
const result = this.webSessions?.revokeExposure(id);
|
|
5269
5769
|
if (result && !result.durable)
|
|
5270
5770
|
this.logger.warn("Public session revocation could not be saved; exposure remains closed");
|
|
@@ -5296,13 +5796,32 @@ export class FleetManager {
|
|
|
5296
5796
|
if (!current() || !this.publicOwnerCurrent(info.owner))
|
|
5297
5797
|
throw new Error("public owner changed");
|
|
5298
5798
|
}
|
|
5799
|
+
/**
|
|
5800
|
+
* #1920 §5.5 (step 4b): a guest signing in through the public link — said in the General of the admin who opened it
|
|
5801
|
+
* (who, how many agents), awaited as an admin's public sign-in is, while that link is the open one, its opener still
|
|
5802
|
+
* current, and the account still an admitted guest. A failure refuses the sign-in.
|
|
5803
|
+
*/
|
|
5804
|
+
async confirmGuestPublicWebLogin(info, current) {
|
|
5805
|
+
const admitted = () => {
|
|
5806
|
+
const open = this.publicWebLink?.openSignin();
|
|
5807
|
+
return current() && open && open.exposureId === info.exposureId && this.publicOwnerCurrent(open.owner) && this.guestSignInAllowed(info.account) ? open : null;
|
|
5808
|
+
};
|
|
5809
|
+
const open = admitted();
|
|
5810
|
+
if (!open)
|
|
5811
|
+
throw new Error("guest public sign-in unavailable");
|
|
5812
|
+
const adapter = open.owner.binding;
|
|
5813
|
+
await adapter.sendText(open.owner.chatId, t("web.guest_public_login_notice", this.webPerson(info.account).name, info.label, this.guestScope(info.account).size, info.handle.slice(0, 8)), { threadId: open.owner.threadId, allowedMentions: { parse: [] } });
|
|
5814
|
+
if (!admitted())
|
|
5815
|
+
throw new Error("guest public sign-in changed");
|
|
5816
|
+
}
|
|
5299
5817
|
/** Telegram's typed command enters through the same strict owner and nonce path as Discord. */
|
|
5300
5818
|
async dashboardMenu(msg) {
|
|
5301
5819
|
const id = msg.adapterId;
|
|
5302
5820
|
const owner = id ? this.dashboardOwner(msg.userId, id, msg.chatId, msg.threadId, msg.username) : null;
|
|
5303
5821
|
if (!owner) {
|
|
5304
5822
|
const adapter = id ? this.adapters.get(id) : undefined;
|
|
5305
|
-
|
|
5823
|
+
const out = this.renderPlaces(id, t("dashboard.public_general") + placeSuffix({ kind: "general" }, "General"), { threadId: msg.threadId });
|
|
5824
|
+
await adapter?.sendText(msg.chatId, out.text, out.opts);
|
|
5306
5825
|
return;
|
|
5307
5826
|
}
|
|
5308
5827
|
if (!await this.showDashboardMenu(owner)) {
|
|
@@ -5618,16 +6137,197 @@ export class FleetManager {
|
|
|
5618
6137
|
this.initializeWebSessions();
|
|
5619
6138
|
void this.publicWebLink?.close("dashboard revoke");
|
|
5620
6139
|
this.webLoginCodes.revoke();
|
|
6140
|
+
this.webGuestLoginCodes.revokeAll();
|
|
6141
|
+
this.guestRevokes++; // and every guest /web still on its way
|
|
5621
6142
|
// #1570: no browser may ask the sign-in page for a code any more.
|
|
5622
6143
|
const devices = this.returningDevices.revokeAll();
|
|
5623
6144
|
const sessions = this.webSessions.revokeAll();
|
|
5624
|
-
|
|
6145
|
+
// #1939 §10: and every web authority given so far (its receipts read as none).
|
|
6146
|
+
const authority = this.revokeWebAuthority();
|
|
6147
|
+
const result = { count: sessions.count, durable: sessions.durable && devices.durable && authority.durable };
|
|
5625
6148
|
if (result.durable)
|
|
5626
6149
|
this.logger.info({ count: result.count, devices: devices.count }, "Web sessions revoked (all)");
|
|
5627
6150
|
else
|
|
5628
6151
|
this.logger.warn({ count: result.count }, "Web sessions revoked in memory only — the session file could not be updated or removed");
|
|
5629
6152
|
return result;
|
|
5630
6153
|
}
|
|
6154
|
+
/**
|
|
6155
|
+
* #1920 phase 3: Settings → Web sign-ins → Guests — the switches, each connection's access mode and the agents named for
|
|
6156
|
+
* an open one, and every guest account (signed in, with a returning device, or narrowed): who, its platform, what it
|
|
6157
|
+
* reaches now, its sessions and devices, and its narrowing. Ids are the accounts' own (an admin's page).
|
|
6158
|
+
*/
|
|
6159
|
+
guestOverview() {
|
|
6160
|
+
this.initializeWebSessions();
|
|
6161
|
+
const cfg = this.fleetConfig?.web?.guests;
|
|
6162
|
+
const own = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : undefined);
|
|
6163
|
+
const connections = [...this.worlds.entries()].map(([id, w]) => ({ id, type: w.adapter.type, mode: (w.accessManager.getMode() === "open" ? "open" : "allowlist"),
|
|
6164
|
+
named: [...(own(cfg?.open_instances, id) ?? [])] }));
|
|
6165
|
+
const accounts = new Map();
|
|
6166
|
+
for (const a of this.webSessions.guestActivity())
|
|
6167
|
+
accounts.set(`${a.adapterId}\u0000${a.userId}`, a);
|
|
6168
|
+
const devices = this.returningDevices.guestCounts();
|
|
6169
|
+
for (const k of devices.keys())
|
|
6170
|
+
if (!accounts.has(k)) {
|
|
6171
|
+
const [adapterId, userId] = k.split("\u0000");
|
|
6172
|
+
accounts.set(k, { adapterId, userId, sessions: 0, lastSeen: null });
|
|
6173
|
+
}
|
|
6174
|
+
for (const key of Object.keys(cfg?.narrow ?? {})) {
|
|
6175
|
+
const at = key.indexOf(":"), adapterId = key.slice(0, at), userId = key.slice(at + 1), k = `${adapterId}\u0000${userId}`;
|
|
6176
|
+
if (at > 0 && !accounts.has(k))
|
|
6177
|
+
accounts.set(k, { adapterId, userId, sessions: 0, lastSeen: null });
|
|
6178
|
+
}
|
|
6179
|
+
const guests = [...accounts.entries()].map(([k, a]) => {
|
|
6180
|
+
const owner = { adapterId: a.adapterId, userId: a.userId };
|
|
6181
|
+
const badge = this.guestBadge(owner);
|
|
6182
|
+
// `reach`: before narrowing — what Settings offers to narrow to (#2104 review: never an agent it cannot reach).
|
|
6183
|
+
return { ...a, name: badge.name, platform: badge.platform, scope: [...this.guestScope(owner)].sort(), reach: [...this.guestReach(owner)].sort(),
|
|
6184
|
+
devices: devices.get(k) ?? 0, narrow: own(cfg?.narrow, `${a.adapterId}:${a.userId}`) ?? null };
|
|
6185
|
+
}).sort((x, y) => (y.lastSeen ?? -1) - (x.lastSeen ?? -1));
|
|
6186
|
+
return { enabled: cfg?.enabled === true, chat: cfg?.chat !== false, instances: Object.keys(this.fleetConfig?.instances ?? {}).sort(), connections, guests };
|
|
6187
|
+
}
|
|
6188
|
+
/** #1920 phase 3 (the app shell): a guest's chip — its web name, and its connection's platform (discord, telegram). */
|
|
6189
|
+
guestBadge(owner) {
|
|
6190
|
+
return { name: this.webPerson(owner).name, platform: this.worlds.get(owner.adapterId)?.adapter.type ?? owner.adapterId };
|
|
6191
|
+
}
|
|
6192
|
+
/** #1920 step 4: whether a `/web` is a guest's — guest sign-in on, and not from a fleet admin (theirs runs as before). */
|
|
6193
|
+
isGuestWebAsk(adapterId, userId) {
|
|
6194
|
+
return !!adapterId && this.fleetConfig?.web?.guests?.enabled === true && !this.isFleetAdmin(userId, adapterId);
|
|
6195
|
+
}
|
|
6196
|
+
/** #1920 step 4 (auth-api): a guest code's account may still sign in — guests on, and something in its scope now. */
|
|
6197
|
+
guestSignInAllowed(account) {
|
|
6198
|
+
return this.fleetConfig?.web?.guests?.enabled === true && !this.isFleetAdmin(account.userId, account.adapterId) && this.guestScope(account).size > 0;
|
|
6199
|
+
}
|
|
6200
|
+
/**
|
|
6201
|
+
* #1920 §5.4: a guest's own `/web revoke` — its sessions and its outstanding code; nobody else's (an admin's revokes
|
|
6202
|
+
* everyone's, as before).
|
|
6203
|
+
*/
|
|
6204
|
+
revokeGuestWebSessions(owner) {
|
|
6205
|
+
this.initializeWebSessions();
|
|
6206
|
+
const key = `${owner.adapterId}\u0000${owner.userId}`;
|
|
6207
|
+
this.guestAccountRevokes.set(key, (this.guestAccountRevokes.get(key) ?? 0) + 1); // its /web on its way, too
|
|
6208
|
+
while (this.guestAccountRevokes.size > 4096)
|
|
6209
|
+
this.guestAccountRevokes.delete(this.guestAccountRevokes.keys().next().value);
|
|
6210
|
+
this.webGuestLoginCodes.revokeRecipient(owner);
|
|
6211
|
+
// §5.4: its sessions and its returning devices (no browser of theirs may ask for a code any more).
|
|
6212
|
+
const devices = this.returningDevices.revokeGuest(owner);
|
|
6213
|
+
const ended = this.webSessions.revokeAll(r => r.tier === "guest" && r.owner?.adapterId === owner.adapterId && r.owner.userId === owner.userId);
|
|
6214
|
+
this.logger.info({ adapterId: owner.adapterId, count: ended.count, devices: devices.count, durable: ended.durable && devices.durable }, "Guest web sessions revoked by their account");
|
|
6215
|
+
return { count: ended.count, durable: ended.durable && devices.durable };
|
|
6216
|
+
}
|
|
6217
|
+
/**
|
|
6218
|
+
* #1920 §2.3 (step 4): `/web` from someone who is not a fleet admin, while guest sign-in is on. `revoke` ends their
|
|
6219
|
+
* own guest sessions. Otherwise a guest code (tier guest, bound to this account) goes privately — a DM, else the
|
|
6220
|
+
* slash command's ephemeral answer (`replyPrivately`) — once a minute at most, and only when their scope (from what
|
|
6221
|
+
* they may already use in chat, rooms read at sign-in) holds something. The code itself is never posted where asked.
|
|
6222
|
+
* Callers ask isGuestWebAsk first (synchronously); false here too when it is not a guest's.
|
|
6223
|
+
*/
|
|
6224
|
+
async guestWebCommand(ask) {
|
|
6225
|
+
if (!this.isGuestWebAsk(ask.adapterId, ask.userId))
|
|
6226
|
+
return false;
|
|
6227
|
+
const owner = { adapterId: ask.adapterId, userId: ask.userId };
|
|
6228
|
+
const say = (text) => ask.replyHere(text).catch(() => undefined);
|
|
6229
|
+
if (ask.arg === "revoke") {
|
|
6230
|
+
const ended = this.revokeGuestWebSessions(owner);
|
|
6231
|
+
await say(t(ended.durable ? "web.guest_revoked" : "web.guest_revoked_not_durable", ended.count));
|
|
6232
|
+
return true;
|
|
6233
|
+
}
|
|
6234
|
+
const token = this.webToken;
|
|
6235
|
+
const adapter = this.adapters.get(ask.adapterId);
|
|
6236
|
+
if (this.shuttingDown || !token || !adapter) {
|
|
6237
|
+
await say(t("dashboard.starting"));
|
|
6238
|
+
return true;
|
|
6239
|
+
}
|
|
6240
|
+
const key = `${owner.adapterId}\u0000${owner.userId}`, asked = this.guestCodeAskedAt.get(key);
|
|
6241
|
+
if (this.guestCodeInFlight.has(key) || (asked !== undefined && performance.now() - asked < 60_000)) {
|
|
6242
|
+
await say(t("web.guest_wait"));
|
|
6243
|
+
return true;
|
|
6244
|
+
}
|
|
6245
|
+
this.guestCodeInFlight.add(key);
|
|
6246
|
+
try {
|
|
6247
|
+
await this.issueGuestCode(ask, owner, key, adapter, token);
|
|
6248
|
+
}
|
|
6249
|
+
finally {
|
|
6250
|
+
this.guestCodeInFlight.delete(key);
|
|
6251
|
+
}
|
|
6252
|
+
return true;
|
|
6253
|
+
}
|
|
6254
|
+
/** guestWebCommand's issuance, one per account at a time; a revoke made meanwhile (either kind) ends it unissued. */
|
|
6255
|
+
async issueGuestCode(ask, owner, key, adapter, token) {
|
|
6256
|
+
const say = (text) => ask.replyHere(text).catch(() => undefined);
|
|
6257
|
+
const revokes = this.guestRevokes, accountRevokes = this.guestAccountRevokes.get(key) ?? 0;
|
|
6258
|
+
const unrevoked = () => this.guestRevokes === revokes && (this.guestAccountRevokes.get(key) ?? 0) === accountRevokes;
|
|
6259
|
+
// §3.2: its rooms are read at sign-in (bounded; never longer than the reads' own deadline).
|
|
6260
|
+
await withinBudget(this.refreshGuestRooms(owner, { mode: "force" }), performance.now() + 6_000).catch(() => undefined);
|
|
6261
|
+
if (!unrevoked())
|
|
6262
|
+
return; // revoked while its rooms were read: no code
|
|
6263
|
+
const scope = this.guestScope(owner);
|
|
6264
|
+
if (!scope.size) {
|
|
6265
|
+
const open = this.worlds.get(owner.adapterId)?.accessManager.getMode() === "open";
|
|
6266
|
+
await say(t(open ? "web.guest_not_set_up" : "web.guest_nothing"));
|
|
6267
|
+
return;
|
|
6268
|
+
}
|
|
6269
|
+
this.initializeWebSessions();
|
|
6270
|
+
const codes = this.webGuestLoginCodes;
|
|
6271
|
+
if (codes.pausedForMs() > 0) {
|
|
6272
|
+
await say(t("web.guest_paused"));
|
|
6273
|
+
return;
|
|
6274
|
+
}
|
|
6275
|
+
// §5.5 (step 4b): with the public link open, the code works through it too (an admin opened it; a guest is still a
|
|
6276
|
+
// guest there) — most guests are not on the host's network. Its closing withdraws that audience (revokeAudience).
|
|
6277
|
+
const open = this.publicWebLink?.openSignin() ?? null;
|
|
6278
|
+
// One code per account (a new one replaces only its own); at the cap, refused — never another guest's evicted.
|
|
6279
|
+
const login = codes.issue({ epoch: tokenEpoch(token), audiences: ["local", ...(open ? [open.exposureId] : [])],
|
|
6280
|
+
recipient: { adapterId: owner.adapterId, userId: owner.userId, ...(ask.username ? { username: ask.username } : {}) } });
|
|
6281
|
+
if (!login) {
|
|
6282
|
+
await say(t("web.guest_busy"));
|
|
6283
|
+
return;
|
|
6284
|
+
}
|
|
6285
|
+
this.guestCodeAskedAt.delete(key);
|
|
6286
|
+
this.guestCodeAskedAt.set(key, performance.now());
|
|
6287
|
+
while (this.guestCodeAskedAt.size > 256)
|
|
6288
|
+
this.guestCodeAskedAt.delete(this.guestCodeAskedAt.keys().next().value);
|
|
6289
|
+
const current = () => !this.shuttingDown && this.webToken === token && this.adapters.get(owner.adapterId) === adapter
|
|
6290
|
+
&& unrevoked() && this.guestSignInAllowed(owner);
|
|
6291
|
+
const privateText = `${t("web.guest_intro", scope.size)}\n${this.topicCommands.getDashboardText()}${open ? `\n${t("web.guest_public", open.url)}` : ""}\n${t("dashboard.code", login.display, Math.round(LOGIN_CODE_TTL_MS / 60_000))}`;
|
|
6292
|
+
const deadline = performance.now() + 10_000;
|
|
6293
|
+
try {
|
|
6294
|
+
let byDm = false;
|
|
6295
|
+
try {
|
|
6296
|
+
if (!adapter.sendDirect)
|
|
6297
|
+
throw new Error("DM unavailable");
|
|
6298
|
+
await withinBudget(adapter.sendDirect(owner.userId, `${privateText}\n${t("dashboard.code_next")}`, { disablePreview: true }), Math.min(deadline, performance.now() + 5_000));
|
|
6299
|
+
byDm = true;
|
|
6300
|
+
}
|
|
6301
|
+
catch (err) {
|
|
6302
|
+
this.logDashboardDmFailure(err);
|
|
6303
|
+
if (!ask.replyPrivately || !current())
|
|
6304
|
+
throw err;
|
|
6305
|
+
const id = await withinBudget(ask.replyPrivately(privateText), deadline); // a slash command's answer: ephemeral
|
|
6306
|
+
if (!id)
|
|
6307
|
+
throw new Error("private delivery unconfirmed");
|
|
6308
|
+
}
|
|
6309
|
+
if (!current())
|
|
6310
|
+
throw new Error("guest no longer admitted");
|
|
6311
|
+
if (byDm) {
|
|
6312
|
+
await this.sendCodeAlone((body, opts) => adapter.sendDirect(owner.userId, body, opts), adapter.type, login.display);
|
|
6313
|
+
if (!current())
|
|
6314
|
+
throw new Error("guest no longer admitted");
|
|
6315
|
+
await say(t("web.guest_sent"));
|
|
6316
|
+
}
|
|
6317
|
+
}
|
|
6318
|
+
catch (err) {
|
|
6319
|
+
codes.revokeIfCurrent(login.issuanceId); // this flow's code only, never a later one's
|
|
6320
|
+
this.logger.info({ err: err?.message, adapterId: owner.adapterId }, "Guest sign-in code was not delivered privately");
|
|
6321
|
+
if (!unrevoked())
|
|
6322
|
+
return; // revoked meanwhile: the revoke's own answer said so
|
|
6323
|
+
const start = adapter.type === "telegram" ? this.tgStartWebUrl(owner.adapterId) : null;
|
|
6324
|
+
// #1742 for guests (step 4b-3): its START button (a bare /start, or the link's /start web) then asks again, from
|
|
6325
|
+
// the DM — once, within the window.
|
|
6326
|
+
if (adapter.type === "telegram")
|
|
6327
|
+
this.openTgWebStartWindow(owner.adapterId, owner.userId);
|
|
6328
|
+
await say(start ? t("web.guest_dm_failed_link", start) : t("web.guest_dm_failed"));
|
|
6329
|
+
}
|
|
6330
|
+
}
|
|
5631
6331
|
/** #1570 (auth-api): this browser becomes a returning device of the code's owner. The cookie value, or null. */
|
|
5632
6332
|
rememberReturningDevice(owner, input) {
|
|
5633
6333
|
const token = this.webToken;
|
|
@@ -5655,6 +6355,12 @@ export class FleetManager {
|
|
|
5655
6355
|
if (!token || this.shuttingDown)
|
|
5656
6356
|
return { kind: "refused" };
|
|
5657
6357
|
this.initializeWebSessions();
|
|
6358
|
+
// #2095 review: verified before the request's body was read — a revoke (its own, or an admin's) made meanwhile
|
|
6359
|
+
// removed it, and nothing it asks for may then go out.
|
|
6360
|
+
if (!this.returningDevices.current(device, tokenEpoch(token)))
|
|
6361
|
+
return { kind: "refused" };
|
|
6362
|
+
if (device.tier === "guest")
|
|
6363
|
+
return this.requestGuestDeviceCode(device, input, token);
|
|
5658
6364
|
const paused = this.webLoginCodes.pausedForMs();
|
|
5659
6365
|
if (paused > 0)
|
|
5660
6366
|
return { kind: "limited", retryAfterMs: paused };
|
|
@@ -5686,7 +6392,7 @@ export class FleetManager {
|
|
|
5686
6392
|
this.logger.info({ err: err?.message, adapterId }, "Sign-in code request: the private message could not be sent");
|
|
5687
6393
|
return { kind: "refused" };
|
|
5688
6394
|
}
|
|
5689
|
-
if (this.webToken !== token || !this.publicOwnerCurrent(owner)) {
|
|
6395
|
+
if (this.webToken !== token || !this.publicOwnerCurrent(owner) || !this.returningDevices.current(device, tokenEpoch(token))) {
|
|
5690
6396
|
this.webLoginCodes.revokeIfCurrent(issued.issuanceId);
|
|
5691
6397
|
return { kind: "refused" };
|
|
5692
6398
|
}
|
|
@@ -5694,15 +6400,94 @@ export class FleetManager {
|
|
|
5694
6400
|
// Asked again after the follow-up's wait: the owner, the token, shutdown, and a public request's exposure.
|
|
5695
6401
|
const exposureGone = input.surface === "gateway"
|
|
5696
6402
|
&& (this.publicWebLink?.exposureId !== input.exposureId || this.publicWebLink?.status().state !== "open");
|
|
5697
|
-
if (this.shuttingDown || this.webToken !== token || !this.publicOwnerCurrent(owner) || exposureGone) {
|
|
6403
|
+
if (this.shuttingDown || this.webToken !== token || !this.publicOwnerCurrent(owner) || exposureGone || !this.returningDevices.current(device, tokenEpoch(token))) {
|
|
5698
6404
|
this.webLoginCodes.revokeIfCurrent(issued.issuanceId);
|
|
5699
6405
|
return { kind: "refused" };
|
|
5700
6406
|
}
|
|
5701
6407
|
this.logger.info({ adapterId, surface: input.surface }, "Web sign-in code sent privately to a returning device's owner");
|
|
5702
6408
|
return { kind: "sent" };
|
|
5703
6409
|
}
|
|
6410
|
+
/**
|
|
6411
|
+
* #1920 step 4b: a guest's returning device asks for a code — a guest code for that account, by DM only, under the
|
|
6412
|
+
* same rules as its /web (guests on, not an admin, something in scope now; one per account and the cap; one flow per
|
|
6413
|
+
* account at a time; a revoke meanwhile ends it), its own limiter, and the guests' breaker. Asked through the public
|
|
6414
|
+
* link: only while that exposure is the open one (its code then works through it alone), as an admin's device.
|
|
6415
|
+
*/
|
|
6416
|
+
async requestGuestDeviceCode(device, input, token) {
|
|
6417
|
+
const codes = this.webGuestLoginCodes;
|
|
6418
|
+
const account = { adapterId: device.owner.adapterId, userId: device.owner.userId };
|
|
6419
|
+
const key = `${account.adapterId}\u0000${account.userId}`;
|
|
6420
|
+
const adapter = this.adapters.get(account.adapterId);
|
|
6421
|
+
const viaLink = input.surface === "gateway";
|
|
6422
|
+
const linkOpen = () => !!input.exposureId && this.publicWebLink?.openSignin()?.exposureId === input.exposureId;
|
|
6423
|
+
if ((viaLink ? !linkOpen() : input.exposureId !== undefined) || !adapter?.sendDirect || !this.guestSignInAllowed(account)) {
|
|
6424
|
+
this.logger.info({ adapterId: account.adapterId, surface: input.surface }, "Guest sign-in code request refused");
|
|
6425
|
+
return { kind: "refused" };
|
|
6426
|
+
}
|
|
6427
|
+
const paused = codes.pausedForMs();
|
|
6428
|
+
if (paused > 0)
|
|
6429
|
+
return { kind: "limited", retryAfterMs: paused };
|
|
6430
|
+
const asked = this.guestCodeAskedAt.get(key);
|
|
6431
|
+
if (this.guestCodeInFlight.has(key))
|
|
6432
|
+
return { kind: "limited", retryAfterMs: 5_000 };
|
|
6433
|
+
if (asked !== undefined && performance.now() - asked < 60_000)
|
|
6434
|
+
return { kind: "limited", retryAfterMs: 60_000 - (performance.now() - asked) };
|
|
6435
|
+
const admitted = this.guestCodeRequestLimiter.admit(device.idHash);
|
|
6436
|
+
if (!admitted.ok)
|
|
6437
|
+
return { kind: "limited", retryAfterMs: admitted.retryAfterMs };
|
|
6438
|
+
const revokes = this.guestRevokes, accountRevokes = this.guestAccountRevokes.get(key) ?? 0;
|
|
6439
|
+
const current = () => !this.shuttingDown && this.webToken === token && this.adapters.get(account.adapterId) === adapter
|
|
6440
|
+
&& this.guestRevokes === revokes && (this.guestAccountRevokes.get(key) ?? 0) === accountRevokes && this.guestSignInAllowed(account)
|
|
6441
|
+
&& (!viaLink || linkOpen()) && this.returningDevices.current(device, tokenEpoch(token));
|
|
6442
|
+
const issued = codes.issue({ epoch: tokenEpoch(token), recipient: account, audiences: [viaLink ? input.exposureId : "local"] });
|
|
6443
|
+
if (!issued)
|
|
6444
|
+
return { kind: "limited", retryAfterMs: 60_000 }; // the guests' cap: never someone's evicted
|
|
6445
|
+
this.guestCodeInFlight.add(key);
|
|
6446
|
+
this.guestCodeAskedAt.delete(key);
|
|
6447
|
+
this.guestCodeAskedAt.set(key, performance.now());
|
|
6448
|
+
try {
|
|
6449
|
+
const text = t("web.resend_code", issued.display, Math.round(LOGIN_CODE_TTL_MS / 60_000), input.label || t("web.resend_unknown_browser"), t(viaLink ? "web.resend_public" : "web.resend_local"))
|
|
6450
|
+
+ "\n" + t("dashboard.code_next");
|
|
6451
|
+
try {
|
|
6452
|
+
await withinBudget(adapter.sendDirect(account.userId, text, { disablePreview: true }), performance.now() + 5_000);
|
|
6453
|
+
}
|
|
6454
|
+
catch (err) {
|
|
6455
|
+
codes.revokeIfCurrent(issued.issuanceId);
|
|
6456
|
+
this.logger.info({ err: err?.message, adapterId: account.adapterId }, "Guest sign-in code request: the private message could not be sent");
|
|
6457
|
+
return { kind: "refused" };
|
|
6458
|
+
}
|
|
6459
|
+
if (!current()) {
|
|
6460
|
+
codes.revokeIfCurrent(issued.issuanceId);
|
|
6461
|
+
return { kind: "refused" };
|
|
6462
|
+
}
|
|
6463
|
+
await this.sendCodeAlone((body, opts) => adapter.sendDirect(account.userId, body, opts), adapter.type, issued.display);
|
|
6464
|
+
if (!current()) {
|
|
6465
|
+
codes.revokeIfCurrent(issued.issuanceId);
|
|
6466
|
+
return { kind: "refused" };
|
|
6467
|
+
}
|
|
6468
|
+
this.logger.info({ adapterId: account.adapterId }, "Guest sign-in code sent privately to a returning device's account");
|
|
6469
|
+
return { kind: "sent" };
|
|
6470
|
+
}
|
|
6471
|
+
finally {
|
|
6472
|
+
this.guestCodeInFlight.delete(key);
|
|
6473
|
+
}
|
|
6474
|
+
}
|
|
6475
|
+
/** #1920 step 4b (auth-api): this browser becomes a guest's returning device. The cookie value, or null. */
|
|
6476
|
+
rememberGuestDevice(account, input) {
|
|
6477
|
+
const token = this.webToken;
|
|
6478
|
+
if (!token)
|
|
6479
|
+
return null;
|
|
6480
|
+
this.initializeWebSessions();
|
|
6481
|
+
return this.returningDevices.rememberGuest(account, { ...input, tokenEpoch: tokenEpoch(token), webToken: token });
|
|
6482
|
+
}
|
|
5704
6483
|
/** Called by the sign-in endpoint: a login the operator did not make should be visible to them. */
|
|
5705
6484
|
onWebLogin(info) {
|
|
6485
|
+
// #1920 §2.3: a guest's sign-in is always said in General (web.notify_login is the operator's own sign-ins): who,
|
|
6486
|
+
// and how many agents they now reach — admins stay aware of everyone who is not one of them.
|
|
6487
|
+
if (info.tier === "guest" && info.owner) {
|
|
6488
|
+
this.notifyFleetError(t("web.guest_login_notice", this.webPerson(info.owner).name, info.label, this.guestScope(info.owner).size, info.handle.slice(0, 8)));
|
|
6489
|
+
return;
|
|
6490
|
+
}
|
|
5706
6491
|
if (this.fleetConfig?.web?.notify_login === false)
|
|
5707
6492
|
return;
|
|
5708
6493
|
// The session handle makes each notice distinct: notifyFleetError throttles by text, and a second
|
|
@@ -5901,11 +6686,17 @@ export class FleetManager {
|
|
|
5901
6686
|
* landed mid-edit) must not be cleared or disturbed (Prism b).
|
|
5902
6687
|
*/
|
|
5903
6688
|
async appendCleanupWarning(target, watch, warning, cleanupCommand) {
|
|
5904
|
-
|
|
5905
|
-
|
|
5906
|
-
|
|
5907
|
-
|
|
5908
|
-
|
|
6689
|
+
// #2175: one text per outcome, frozen at its first tick. The completion carries elapsed seconds, so a text made
|
|
6690
|
+
// anew each tick would never equal the one already handed over and landed (terminalLanded compares exactly).
|
|
6691
|
+
const key = JSON.stringify([warning, cleanupCommand ?? null]);
|
|
6692
|
+
if (watch.frozen?.key !== key) {
|
|
6693
|
+
watch.frozen = { key, text: formatRestartProgressCompletion("update", {
|
|
6694
|
+
...watch.summary,
|
|
6695
|
+
warningText: warning,
|
|
6696
|
+
warningCommand: cleanupCommand,
|
|
6697
|
+
}, watch.receipt.startedAt) };
|
|
6698
|
+
}
|
|
6699
|
+
const text = watch.frozen.text;
|
|
5909
6700
|
const stopWatching = () => {
|
|
5910
6701
|
this.updateCleanupWatch = null;
|
|
5911
6702
|
if (this.updateProgressTimer)
|
|
@@ -5913,10 +6704,22 @@ export class FleetManager {
|
|
|
5913
6704
|
this.updateProgressTimer = null;
|
|
5914
6705
|
};
|
|
5915
6706
|
if (text !== this.lastUpdateProgressText) {
|
|
5916
|
-
|
|
5917
|
-
|
|
5918
|
-
|
|
5919
|
-
|
|
6707
|
+
// #2175: while the completion is still owed by the background retry, that retry is the message's only
|
|
6708
|
+
// writer — this text (the completion plus the warning) goes to it rather than racing it. Handing it over is not
|
|
6709
|
+
// delivery: the receipt and this watch stay until the retry reports this exact text landed (a later tick).
|
|
6710
|
+
const progress = this.startupProgress;
|
|
6711
|
+
if (progress?.terminalLanded(text)) {
|
|
6712
|
+
// landed through the retry
|
|
6713
|
+
}
|
|
6714
|
+
else if (progress?.replaceTerminalText(text)) {
|
|
6715
|
+
return;
|
|
6716
|
+
}
|
|
6717
|
+
else {
|
|
6718
|
+
const adapter = this.adapters.get(target.adapterId);
|
|
6719
|
+
if (!adapter)
|
|
6720
|
+
return; // retry on a later tick
|
|
6721
|
+
await adapter.editMessage(target.chatId, target.messageId, text, target.threadId);
|
|
6722
|
+
}
|
|
5920
6723
|
this.lastUpdateProgressText = text;
|
|
5921
6724
|
}
|
|
5922
6725
|
const verdict = cleanupWatchVerdict(readUpdateProgress(this.dataDir), watch.receipt);
|
|
@@ -6066,6 +6869,9 @@ export class FleetManager {
|
|
|
6066
6869
|
const { getTmuxSocketName: getSocket } = await import("./paths.js");
|
|
6067
6870
|
TmuxManager.setSocketName(getSocket());
|
|
6068
6871
|
await TmuxManager.ensureSession(getTmuxSession());
|
|
6872
|
+
this.tmuxSessionEnsured = true;
|
|
6873
|
+
// #2072: what this host can run — probed in the background, published for every picker.
|
|
6874
|
+
this.startAvailabilityRefresh();
|
|
6069
6875
|
// Pre-flight (advisory, fire-and-forget): warm the per-backend auth cache
|
|
6070
6876
|
// before instances spawn, so a CLI that comes up on its sign-in screen gets
|
|
6071
6877
|
// an instant 🔑 verdict instead of decaying into crash/MCP-died noise.
|
|
@@ -6273,7 +7079,7 @@ export class FleetManager {
|
|
|
6273
7079
|
...DEFAULT_SCHEDULER_CONFIG,
|
|
6274
7080
|
...this.fleetConfig?.defaults.scheduler,
|
|
6275
7081
|
};
|
|
6276
|
-
this.scheduler = new Scheduler(join(this.dataDir, "scheduler.db"), (schedule, runId, retry) => this.handleScheduleTrigger(schedule, runId, retry), schedulerConfig, (name) => this.fleetConfig?.instances?.[name] != null || !!this.classicChannels?.getAll().some(ch => ch.instanceName === name), (schedule, retry, reason) => this.scheduleRetryDropped(schedule, retry, reason));
|
|
7082
|
+
this.scheduler = new Scheduler(join(this.dataDir, "scheduler.db"), (schedule, runId, retry) => this.handleScheduleTrigger(schedule, runId, retry), schedulerConfig, (name) => this.fleetConfig?.instances?.[name] != null || !!this.classicChannels?.getAll().some(ch => ch.instanceName === name), (schedule, retry, reason) => this.scheduleRetryDropped(schedule, retry, reason), this.logger);
|
|
6277
7083
|
this.scheduler.init();
|
|
6278
7084
|
this.logger.info("Scheduler initialized");
|
|
6279
7085
|
// Tips share the daily-report clock but remain an independent internal
|
|
@@ -6303,6 +7109,7 @@ export class FleetManager {
|
|
|
6303
7109
|
const generals = allEntries.filter(([_, cfg]) => cfg.general_topic);
|
|
6304
7110
|
const others = allEntries.filter(([_, cfg]) => !cfg.general_topic);
|
|
6305
7111
|
const startupProgress = new RestartProgress(this.runnableStartupCount(fleet, topicMode), pendingUpdateProgress?.startedAt ?? startupStartedAt, this.logger, { mode: pendingProgressOperation === "full-restart" ? "reload" : pendingUpdateProgress ? "update" : "restart" });
|
|
7112
|
+
this.startupProgress = startupProgress;
|
|
6306
7113
|
if (generals.length > 0) {
|
|
6307
7114
|
for (const [name, cfg] of generals) {
|
|
6308
7115
|
try {
|
|
@@ -6389,6 +7196,18 @@ export class FleetManager {
|
|
|
6389
7196
|
this.pruneEventLog();
|
|
6390
7197
|
this.eventLogPruneTimer = setInterval(() => this.pruneEventLog(), 24 * 60 * 60_000);
|
|
6391
7198
|
this.eventLogPruneTimer.unref?.();
|
|
7199
|
+
// #2122 §5.5: usage is collected from the start, not from the first time someone opens a report — the same bounded
|
|
7200
|
+
// background passes the cache report uses (16 MB a pass, then every 10 minutes).
|
|
7201
|
+
{
|
|
7202
|
+
const cache = this.cacheServiceFor();
|
|
7203
|
+
cache.start();
|
|
7204
|
+
void cache.kick();
|
|
7205
|
+
}
|
|
7206
|
+
// #1920 §3.2: guests' ClassicBot room membership, read in the background — now, then each key ten minutes after
|
|
7207
|
+
// its answer (a minute after a failed read; the tick only finds what is due). A request only reads the answers.
|
|
7208
|
+
void this.refreshAllGuestRooms();
|
|
7209
|
+
this.guestRoomsTimer = setInterval(() => { void this.refreshAllGuestRooms(); }, GUEST_ROOM_TICK_MS);
|
|
7210
|
+
this.guestRoomsTimer.unref?.();
|
|
6392
7211
|
// #1335: delivery-outbox.db and Task Board retention. Same once-at-startup
|
|
6393
7212
|
// + daily-timer pattern; chunked DELETEs so one run cannot hold the loop.
|
|
6394
7213
|
void this.pruneOutboxAndTasks();
|
|
@@ -6889,7 +7708,8 @@ export class FleetManager {
|
|
|
6889
7708
|
adapters: { total: this.adapterState.size, connected, states, details },
|
|
6890
7709
|
startupComplete: this.startupComplete,
|
|
6891
7710
|
memory: readFleetMemory(),
|
|
6892
|
-
hostMemory
|
|
7711
|
+
hostMemory: this.memoryTop && (hostMemory.level === "elevated" || hostMemory.level === "critical")
|
|
7712
|
+
? { ...hostMemory, topProcesses: this.memoryTop.processes, topProcessesAt: this.memoryTop.at } : hostMemory,
|
|
6893
7713
|
problems,
|
|
6894
7714
|
};
|
|
6895
7715
|
}
|
|
@@ -7505,6 +8325,48 @@ export class FleetManager {
|
|
|
7505
8325
|
this.adapterRestarting.delete(id);
|
|
7506
8326
|
}
|
|
7507
8327
|
}
|
|
8328
|
+
/**
|
|
8329
|
+
* #1990: how a reader in world `worldId`'s group reaches a place token's target — undefined (plain text) for another
|
|
8330
|
+
* world's instance, an instance without a fleet topic (a ClassicBot room may be anywhere), or an id no link is built
|
|
8331
|
+
* from. Discord: the channel mention; Telegram: the topic URL (General's topic included).
|
|
8332
|
+
*/
|
|
8333
|
+
placeLink(worldId, target) {
|
|
8334
|
+
const world = this.worlds.get(worldId ?? "");
|
|
8335
|
+
if (!world)
|
|
8336
|
+
return undefined;
|
|
8337
|
+
let topic;
|
|
8338
|
+
if (target.kind === "general") {
|
|
8339
|
+
const notice = this.fleetNoticeTarget(world.id);
|
|
8340
|
+
if (!notice || notice.chatId !== world.groupId || notice.opts.threadId === undefined)
|
|
8341
|
+
return undefined;
|
|
8342
|
+
topic = String(notice.opts.threadId);
|
|
8343
|
+
}
|
|
8344
|
+
else {
|
|
8345
|
+
if (this.getInstanceAdapterId(target.name) !== world.id)
|
|
8346
|
+
return undefined;
|
|
8347
|
+
const topicId = this.fleetConfig?.instances[target.name]?.topic_id;
|
|
8348
|
+
if (topicId == null)
|
|
8349
|
+
return undefined;
|
|
8350
|
+
topic = String(topicId);
|
|
8351
|
+
}
|
|
8352
|
+
if (world.type === "discord")
|
|
8353
|
+
return SNOWFLAKE.test(topic) && SNOWFLAKE.test(world.groupId) ? { mention: `<#${topic}>` } : undefined;
|
|
8354
|
+
const url = topicUrl(worldPlaceOf(world), topic, { general: target.kind === "general" });
|
|
8355
|
+
return url ? { url } : undefined;
|
|
8356
|
+
}
|
|
8357
|
+
/** #1990: a message for world `worldId`'s group with its place tokens rendered (links as text or Telegram entities). */
|
|
8358
|
+
renderPlaces(worldId, text, opts) {
|
|
8359
|
+
if (!hasPlaceRefs(text))
|
|
8360
|
+
return { text, opts };
|
|
8361
|
+
const type = this.worlds.get(worldId ?? "")?.type;
|
|
8362
|
+
const surface = type === "discord" ? "discord" : type === "telegram" ? "telegram" : "plain";
|
|
8363
|
+
const out = renderPlaceRefs(text, surface, target => this.placeLink(worldId, target));
|
|
8364
|
+
return { text: out.text, opts: out.textLinks.length ? { ...opts, textLinks: out.textLinks } : opts };
|
|
8365
|
+
}
|
|
8366
|
+
/** #1990: renderPlaces for the world that owns `instanceName`'s topic. */
|
|
8367
|
+
renderPlacesFor(instanceName, text, opts) {
|
|
8368
|
+
return this.renderPlaces(this.getInstanceAdapterId(instanceName), text, opts);
|
|
8369
|
+
}
|
|
7508
8370
|
/** Handle inbound message — transcribe voice if present, then route */
|
|
7509
8371
|
findGeneralInstance(adapterId) {
|
|
7510
8372
|
if (!this.fleetConfig)
|
|
@@ -7998,6 +8860,13 @@ export class FleetManager {
|
|
|
7998
8860
|
if (!isPrivateChat && !cmdMatch && rawText.startsWith("/")) {
|
|
7999
8861
|
return; // bare slash in group — ignore silently
|
|
8000
8862
|
}
|
|
8863
|
+
// #1920 step 4b-3: /web typed in a ClassicBot room (a group: `/web@ThisBot`) by someone who is not a fleet admin,
|
|
8864
|
+
// while guest sign-in is on: their guest code, privately — as anywhere else. An admin's goes on as before.
|
|
8865
|
+
if (/^\/(?:web|dashboard)(?:\s|$)/i.test(text) && msgAdapter && this.isGuestWebAsk(msg.adapterId, msg.userId)) {
|
|
8866
|
+
await this.guestWebCommand({ adapterId: msg.adapterId, userId: msg.userId, username: msg.username,
|
|
8867
|
+
arg: text.replace(/^\/(?:web|dashboard)/i, "").trim().toLowerCase(), replyHere: body => msgAdapter.sendText(chatId, body) });
|
|
8868
|
+
return;
|
|
8869
|
+
}
|
|
8001
8870
|
// Handle /start command
|
|
8002
8871
|
if (text === "/start" || text.startsWith("/start ")) {
|
|
8003
8872
|
// #1686: intercept /start web before the ClassicBot admission flow runs.
|
|
@@ -8006,15 +8875,21 @@ export class FleetManager {
|
|
|
8006
8875
|
// #1742: a bare /start from a fleet admin whose /web just failed to reach them privately is that /start web
|
|
8007
8876
|
// (Telegram's START button sends it bare) — once, within the window; any other bare /start is ClassicBot's.
|
|
8008
8877
|
const admin = isPrivateChat && this.isFleetAdmin(msg.userId, msg.adapterId ?? "");
|
|
8878
|
+
// #1920 step 4b-3: a guest's too (guest sign-in on, not an admin) — its /web reached it no other way.
|
|
8879
|
+
const guest = isPrivateChat && !admin && this.isGuestWebAsk(msg.adapterId, msg.userId);
|
|
8009
8880
|
const webStart = isPrivateChat && (requestedBackend === "web"
|
|
8010
|
-
|| (text === "/start" && admin && this.takeTgWebStartWindow(msg.adapterId ?? "", msg.userId)));
|
|
8881
|
+
|| (text === "/start" && (admin || guest) && this.takeTgWebStartWindow(msg.adapterId ?? "", msg.userId)));
|
|
8011
8882
|
if (webStart) {
|
|
8012
8883
|
if (requestedBackend === "web")
|
|
8013
8884
|
this.takeTgWebStartWindow(msg.adapterId ?? "", msg.userId);
|
|
8014
8885
|
// #1742: the /web menu right here; the code comes to this DM.
|
|
8015
8886
|
if (admin)
|
|
8016
8887
|
await this.startWebInDm(msg, msgAdapter ?? undefined);
|
|
8017
|
-
//
|
|
8888
|
+
// A guest: its guest code, here (this DM is where it goes).
|
|
8889
|
+
else if (guest && msgAdapter)
|
|
8890
|
+
await this.guestWebCommand({ adapterId: msg.adapterId, userId: msg.userId, username: msg.username, arg: "",
|
|
8891
|
+
replyHere: body => msgAdapter.sendText(chatId, body) });
|
|
8892
|
+
// Anyone else: /start alone is enough to open the DM channel; no further action.
|
|
8018
8893
|
return;
|
|
8019
8894
|
}
|
|
8020
8895
|
// All new starts, including explicit backend and later chooser callbacks,
|
|
@@ -8318,10 +9193,7 @@ export class FleetManager {
|
|
|
8318
9193
|
this.afterUserInboundDelivered(generalInstance, msg);
|
|
8319
9194
|
this.logger.info(`${msg.username} → ${generalInstance}: ${(text ?? "").slice(0, 100)}`);
|
|
8320
9195
|
this.eventLog?.logActivity("message", msg.username, (text ?? "").slice(0, 200), generalInstance);
|
|
8321
|
-
this.
|
|
8322
|
-
instance: generalInstance, sender: msg.username, role: "user",
|
|
8323
|
-
text: (text ?? "").slice(0, WEB_CHAT_TEXT_MAX), ts: new Date().toISOString(),
|
|
8324
|
-
});
|
|
9196
|
+
this.emitPlatformInbound(generalInstance, msg, text ?? "");
|
|
8325
9197
|
}
|
|
8326
9198
|
catch (err) {
|
|
8327
9199
|
this.logger.warn({ err: err.message, instanceName: generalInstance }, "General wake/delivery failed");
|
|
@@ -8430,9 +9302,16 @@ export class FleetManager {
|
|
|
8430
9302
|
this.afterUserInboundDelivered(instanceName, msg);
|
|
8431
9303
|
this.logger.info(`${msg.username} → ${instanceName}: ${(text ?? "").slice(0, 100)}`);
|
|
8432
9304
|
this.eventLog?.logActivity("message", msg.username, (text ?? "").slice(0, 200), instanceName);
|
|
9305
|
+
this.emitPlatformInbound(instanceName, msg, text ?? "");
|
|
9306
|
+
}
|
|
9307
|
+
/**
|
|
9308
|
+
* A person's platform message as the web chat shows it — the user's own words, as a user (#1306), in the instance's
|
|
9309
|
+
* history (#1565). #1920 §5.2: said in the instance's topic, General or room, so it is that channel's, by that account.
|
|
9310
|
+
*/
|
|
9311
|
+
emitPlatformInbound(instance, msg, text) {
|
|
8433
9312
|
this.emitSseEvent("message", {
|
|
8434
|
-
instance
|
|
8435
|
-
|
|
9313
|
+
instance, sender: msg.username, role: "user", text: text.slice(0, WEB_CHAT_TEXT_MAX), ts: new Date().toISOString(),
|
|
9314
|
+
channel: true, from: webChatFrom(msg.adapterId, msg.userId),
|
|
8436
9315
|
});
|
|
8437
9316
|
}
|
|
8438
9317
|
/** Handle outbound tool calls from a daemon instance */
|
|
@@ -8734,7 +9613,14 @@ export class FleetManager {
|
|
|
8734
9613
|
// an agent cannot invent it to suppress the normal completion marker.
|
|
8735
9614
|
if (!error && result != null && msg.statusOnly !== true) {
|
|
8736
9615
|
try {
|
|
8737
|
-
|
|
9616
|
+
// #1920 §5.2: shown to the instance's guests only when it landed in the instance's own topic or room.
|
|
9617
|
+
let inChannel = false;
|
|
9618
|
+
try {
|
|
9619
|
+
inChannel = outAdapter !== WEB_ONLY_REPLY_SINK
|
|
9620
|
+
&& this.landedInOwnChannel(instanceName, contextAdapterId ?? this.getInstanceAdapterId(instanceName), result);
|
|
9621
|
+
}
|
|
9622
|
+
catch { /* not known: not the channel's (fail closed), and the bookkeeping below still runs */ }
|
|
9623
|
+
void this.afterReplyRouted(instanceName, args, senderSessionName, buttonsView, inChannel);
|
|
8738
9624
|
}
|
|
8739
9625
|
catch (err) {
|
|
8740
9626
|
this.logger.warn({ err, instanceName }, "Reply delivered but post-delivery bookkeeping failed");
|
|
@@ -8788,7 +9674,35 @@ export class FleetManager {
|
|
|
8788
9674
|
return this.worlds.size === 0 && this.isWebOnlyFleet() ? { adapter: WEB_ONLY_PROMPT_SINK, adapterId: "web", chatId: "web" } : null;
|
|
8789
9675
|
}
|
|
8790
9676
|
/** Resolves when the reply is in the web chat (#1770: after its files are copied); the caller need not wait. */
|
|
8791
|
-
|
|
9677
|
+
/**
|
|
9678
|
+
* #1920 §5.2: whether a platform send landed in the instance's own place — its ClassicBot room, or its topic in its
|
|
9679
|
+
* connection's group — so its channel's members saw it. Anything else (another chat, a DM, a context left from General,
|
|
9680
|
+
* an answer without the chat it went to) is not the channel's.
|
|
9681
|
+
*/
|
|
9682
|
+
landedInOwnChannel(instance, adapterId, sent) {
|
|
9683
|
+
const s = sent && typeof sent === "object" ? sent : {};
|
|
9684
|
+
if (!adapterId || typeof s.chatId !== "string" || !s.chatId)
|
|
9685
|
+
return false;
|
|
9686
|
+
const roomId = this.classicChannels?.getChannelIdByInstance(instance);
|
|
9687
|
+
if (roomId !== undefined)
|
|
9688
|
+
return (this.classicChannels?.getAdapterIdByInstance(instance) ?? this.getPrimaryAdapterId()) === adapterId && roomId === s.chatId;
|
|
9689
|
+
const cfg = this.fleetConfig?.instances && Object.hasOwn(this.fleetConfig.instances, instance) ? this.fleetConfig.instances[instance] : undefined;
|
|
9690
|
+
const world = this.worlds.get(adapterId);
|
|
9691
|
+
if (!cfg || this.getInstanceAdapterId(instance) !== adapterId || !world?.groupId || s.chatId !== world.groupId)
|
|
9692
|
+
return false;
|
|
9693
|
+
const thread = typeof s.threadId === "string" && s.threadId ? s.threadId : null;
|
|
9694
|
+
return cfg.topic_id == null ? thread === null : thread === String(cfg.topic_id);
|
|
9695
|
+
}
|
|
9696
|
+
/** #1920 §5.2 (#2085 review): a platform click's buttons are in the instance's own place — else not its channel's. */
|
|
9697
|
+
clickInOwnChannel(set) {
|
|
9698
|
+
try {
|
|
9699
|
+
return this.landedInOwnChannel(set.instance, set.adapterId, { chatId: set.chatId, threadId: set.threadId || undefined });
|
|
9700
|
+
}
|
|
9701
|
+
catch {
|
|
9702
|
+
return false;
|
|
9703
|
+
}
|
|
9704
|
+
}
|
|
9705
|
+
afterReplyRouted(instanceName, args, senderSessionName, buttons = null, inChannel = false) {
|
|
8792
9706
|
// A reply is NOT proof the turn is over (#410) — but it is not proof of
|
|
8793
9707
|
// more work either. Split the difference: an instance that is clearly
|
|
8794
9708
|
// idle loses the button now; one that looks busy keeps it (re-posted
|
|
@@ -8824,6 +9738,7 @@ export class FleetManager {
|
|
|
8824
9738
|
ts,
|
|
8825
9739
|
...(attachments.length ? { attachments } : {}),
|
|
8826
9740
|
...(buttons ? { buttons } : {}), // #1266
|
|
9741
|
+
...(inChannel ? { channel: true } : {}), // #1920 §5.2
|
|
8827
9742
|
});
|
|
8828
9743
|
};
|
|
8829
9744
|
const before = this.webReplyOrder.get(instanceName);
|
|
@@ -9177,6 +10092,19 @@ export class FleetManager {
|
|
|
9177
10092
|
}
|
|
9178
10093
|
dispatchTypedIpc(name, msg) {
|
|
9179
10094
|
const type = String(msg.type);
|
|
10095
|
+
if (type.startsWith("fleet_") && WEB_EFFECT_TOOLS.has(type.slice(6))) {
|
|
10096
|
+
const ipc = this.instanceIpcClients.get(name), fleetRequestId = msg.fleetRequestId;
|
|
10097
|
+
if (!ipc || typeof fleetRequestId !== "string")
|
|
10098
|
+
return;
|
|
10099
|
+
void this.handleWebThemeHttp(name, type.slice(6), (msg.payload ?? {})).then(result => {
|
|
10100
|
+
if (this.instanceIpcClients.get(name) === ipc)
|
|
10101
|
+
ipc.send({ type: "fleet_web_theme_response", fleetRequestId, result });
|
|
10102
|
+
}, err => {
|
|
10103
|
+
if (this.instanceIpcClients.get(name) === ipc)
|
|
10104
|
+
ipc.send({ type: "fleet_web_theme_response", fleetRequestId, error: err instanceof Error ? err.message : "Effect operation failed" });
|
|
10105
|
+
}).catch(err => this.logger.debug({ err }, "Effect tool response could not be written"));
|
|
10106
|
+
return;
|
|
10107
|
+
}
|
|
9180
10108
|
if (type.startsWith("fleet_schedule_")) {
|
|
9181
10109
|
this.handleScheduleCrud(name, msg);
|
|
9182
10110
|
return;
|
|
@@ -9202,6 +10130,37 @@ export class FleetManager {
|
|
|
9202
10130
|
this.handlePersonaEmoji(name, msg);
|
|
9203
10131
|
return;
|
|
9204
10132
|
}
|
|
10133
|
+
if (type === "fleet_get_web_theme" || type === "fleet_set_web_theme" || type === "fleet_set_web_theme_asset" || type === "fleet_reset_web_theme"
|
|
10134
|
+
|| type === "fleet_get_web_appearance" || type === "fleet_preview_web_appearance"
|
|
10135
|
+
|| type === "fleet_set_web_widget" || type === "fleet_remove_web_widget"
|
|
10136
|
+
|| type === "fleet_set_web_ambient" || type === "fleet_clear_web_ambient"
|
|
10137
|
+
|| type === "fleet_export_web_mod" || type === "fleet_propose_web_mod") {
|
|
10138
|
+
this.handleWebTheme(name, msg);
|
|
10139
|
+
return;
|
|
10140
|
+
}
|
|
10141
|
+
}
|
|
10142
|
+
/**
|
|
10143
|
+
* #1629: the caller's own web theme over IPC (the agent endpoint calls the same service). `name` is the instance this
|
|
10144
|
+
* IPC connection belongs to — never anything the message says. A refusal is a result the agent reads (its `error`
|
|
10145
|
+
* and what to do), not a transport error.
|
|
10146
|
+
*/
|
|
10147
|
+
handleWebTheme(instanceName, msg) {
|
|
10148
|
+
const fleetRequestId = msg.fleetRequestId;
|
|
10149
|
+
const ipc = this.instanceIpcClients.get(instanceName);
|
|
10150
|
+
if (!ipc)
|
|
10151
|
+
return;
|
|
10152
|
+
const tool = String(msg.type).replace(/^fleet_/, "");
|
|
10153
|
+
try {
|
|
10154
|
+
const args = (msg.payload ?? {});
|
|
10155
|
+
const result = tool === "get_web_appearance" || tool === "preview_web_appearance"
|
|
10156
|
+
? this.appearanceTools.handle(instanceName, tool, args)
|
|
10157
|
+
: tool === "export_web_mod" || tool === "propose_web_mod" ? this.agentMods.handle(instanceName, tool, args)
|
|
10158
|
+
: this.webAppearance.handleTool(instanceName, tool, args);
|
|
10159
|
+
ipc.send({ type: "fleet_web_theme_response", fleetRequestId, result });
|
|
10160
|
+
}
|
|
10161
|
+
catch (err) {
|
|
10162
|
+
ipc.send({ type: "fleet_web_theme_response", fleetRequestId, error: err.message });
|
|
10163
|
+
}
|
|
9205
10164
|
}
|
|
9206
10165
|
/** `list_emojis` / `set_persona_emoji` / `preview_emojis` / `list_stickers` / `preview_stickers` over IPC; the agent endpoint calls the same methods. */
|
|
9207
10166
|
handlePersonaEmoji(instanceName, msg) {
|
|
@@ -9289,10 +10248,11 @@ export class FleetManager {
|
|
|
9289
10248
|
}
|
|
9290
10249
|
case "fleet_decision_list":
|
|
9291
10250
|
db.pruneExpiredDecisions();
|
|
9292
|
-
|
|
10251
|
+
// #2152: titles by default; the full text by id, or all of it with full: true.
|
|
10252
|
+
result = decisionListAnswer(db.listDecisions(projectRoot, {
|
|
9293
10253
|
includeArchived: payload.include_archived,
|
|
9294
10254
|
tags: payload.tags,
|
|
9295
|
-
});
|
|
10255
|
+
}), { id: payload.id, full: payload.full });
|
|
9296
10256
|
break;
|
|
9297
10257
|
case "fleet_decision_update": {
|
|
9298
10258
|
const id = payload.id;
|
|
@@ -9485,10 +10445,16 @@ export class FleetManager {
|
|
|
9485
10445
|
created_by: instance,
|
|
9486
10446
|
});
|
|
9487
10447
|
}
|
|
9488
|
-
|
|
9489
|
-
|
|
9490
|
-
|
|
9491
|
-
|
|
10448
|
+
// #2152: titles by default (agend-agent decision-list); one decision's full text by id (decision-get <id>).
|
|
10449
|
+
// The CLI sends include_archived (snake case, as the MCP tool): both spellings are read.
|
|
10450
|
+
case "list":
|
|
10451
|
+
case "get":
|
|
10452
|
+
if (op === "get" && !asStr(args.id)?.trim())
|
|
10453
|
+
return { error: "id is required" };
|
|
10454
|
+
return decisionListAnswer(db.listDecisions(projectRoot, {
|
|
10455
|
+
includeArchived: args.includeArchived === true || args.include_archived === true,
|
|
10456
|
+
tags: asStrArr(args.tags),
|
|
10457
|
+
}), { id: op === "get" ? asStr(args.id) ?? "" : args.id, full: args.full });
|
|
9492
10458
|
case "update": {
|
|
9493
10459
|
const id = asStr(args.id);
|
|
9494
10460
|
if (!id)
|
|
@@ -9606,6 +10572,19 @@ export class FleetManager {
|
|
|
9606
10572
|
async handleSetPersonaEmojiHttp(instance, args) {
|
|
9607
10573
|
return this.setPersonaEmoji(instance, args);
|
|
9608
10574
|
}
|
|
10575
|
+
/** #1629: `agend-agent theme …` — the same service as the tools; `instance` is the token's. */
|
|
10576
|
+
async handleWebThemeHttp(instance, tool, args) {
|
|
10577
|
+
if (WEB_EFFECT_TOOLS.has(tool)) {
|
|
10578
|
+
if (!this.isKnownInstance(instance))
|
|
10579
|
+
return { error: "unknown_instance" };
|
|
10580
|
+
return this.effectTools.handle(instance, tool, args);
|
|
10581
|
+
}
|
|
10582
|
+
if (tool === "get_web_appearance" || tool === "preview_web_appearance")
|
|
10583
|
+
return this.appearanceTools.handle(instance, tool, args);
|
|
10584
|
+
if (tool === "export_web_mod" || tool === "propose_web_mod")
|
|
10585
|
+
return this.agentMods.handle(instance, tool, args);
|
|
10586
|
+
return this.webAppearance.handleTool(instance, tool, args);
|
|
10587
|
+
}
|
|
9609
10588
|
async handlePreviewEmojisHttp(instance, args) {
|
|
9610
10589
|
return this.previewEmojis(instance, args);
|
|
9611
10590
|
}
|
|
@@ -10021,6 +11000,7 @@ export class FleetManager {
|
|
|
10021
11000
|
*/
|
|
10022
11001
|
saveFleetConfig(explicitPatches = []) {
|
|
10023
11002
|
this.publicWebLink?.refresh();
|
|
11003
|
+
this.enforceGuestSwitch(); // #1920: a Settings save turning guests off ends their sessions
|
|
10024
11004
|
if (!this.fleetConfig || !this.configPath)
|
|
10025
11005
|
return;
|
|
10026
11006
|
if (!this.savedFleetConfigSnapshot)
|
|
@@ -10308,6 +11288,17 @@ export class FleetManager {
|
|
|
10308
11288
|
catch (err) {
|
|
10309
11289
|
this.logger.warn({ err: err.message, name }, "Dropping a removed instance from web favorites failed");
|
|
10310
11290
|
}
|
|
11291
|
+
try {
|
|
11292
|
+
this.themeStore.forget(name);
|
|
11293
|
+
this.webAppearance.forget(name);
|
|
11294
|
+
this.appearanceTools.forget(name);
|
|
11295
|
+
this.effectToolsService?.forget(name);
|
|
11296
|
+
this.mods.forgetInstance(name);
|
|
11297
|
+
this.agentMods.forget(name);
|
|
11298
|
+
}
|
|
11299
|
+
catch (err) {
|
|
11300
|
+
this.logger.warn({ err: err.message, name }, "Dropping a removed instance's web theme failed");
|
|
11301
|
+
}
|
|
10311
11302
|
// Clean up statusline watcher + instance directory
|
|
10312
11303
|
this.statuslineWatcher.unwatch(name);
|
|
10313
11304
|
// instanceDirToClean and effectiveBackend are captured before lifecycle.remove
|
|
@@ -10499,11 +11490,23 @@ export class FleetManager {
|
|
|
10499
11490
|
guildEmojiFetches = new Map();
|
|
10500
11491
|
// ── #1630: what stands for an instance in the web app, and Discord server emoji in web chat ──
|
|
10501
11492
|
webImageCaches = null;
|
|
11493
|
+
/** Server emoji whose picture fetch failure was already logged at warn (once each; bounded). */
|
|
11494
|
+
webEmojiFailures = new Set();
|
|
10502
11495
|
webImageCache(kind) {
|
|
10503
11496
|
const onError = (key, err) => this.logger.debug({ err: err?.message, key }, "web image fetch failed (kept what was cached)");
|
|
11497
|
+
// A server emoji's picture that cannot be fetched reads `:name:` in web chat (it used to be an empty box, the user's
|
|
11498
|
+
// "tofu"): say why once per emoji, where it can be seen, not on every render (its key is quiet for an hour anyway).
|
|
11499
|
+
const emojiError = (key, err) => {
|
|
11500
|
+
if (this.webEmojiFailures.has(key))
|
|
11501
|
+
return onError(key, err);
|
|
11502
|
+
this.webEmojiFailures.add(key);
|
|
11503
|
+
while (this.webEmojiFailures.size > 512)
|
|
11504
|
+
this.webEmojiFailures.delete(this.webEmojiFailures.values().next().value);
|
|
11505
|
+
this.logger.warn({ err: err?.message, key }, "Discord server emoji picture could not be fetched (web chat shows its :name:)");
|
|
11506
|
+
};
|
|
10504
11507
|
this.webImageCaches ??= {
|
|
10505
11508
|
avatars: new WebImageCache({ dir: join(this.dataDir, "cache", "avatars"), onError }),
|
|
10506
|
-
emoji: new WebImageCache({ dir: join(this.dataDir, "cache", "emoji"), onError }),
|
|
11509
|
+
emoji: new WebImageCache({ dir: join(this.dataDir, "cache", "emoji"), onError: emojiError }),
|
|
10507
11510
|
};
|
|
10508
11511
|
return this.webImageCaches[kind];
|
|
10509
11512
|
}
|
|
@@ -10596,10 +11599,25 @@ export class FleetManager {
|
|
|
10596
11599
|
const avatar = avatarFor({ name, displayName, profileVersion, bot: bot && connection ? { connection, version: bot.version } : null,
|
|
10597
11600
|
personaEmoji: cfg?.status_emojis?.delivered });
|
|
10598
11601
|
// The ring belongs to an own bot's face: only when that is what is shown (a shared bot's would ring everyone alike).
|
|
10599
|
-
|
|
11602
|
+
// #1958: the own bot's colour is also the identity colour's role tier — whatever face is shown (never a shared bot's).
|
|
11603
|
+
const roleColor = ownConnection && owner
|
|
10600
11604
|
? this.webAccent(ownConnection, owner, cfg ? (cfg.topic_id == null ? undefined : String(cfg.topic_id)) : this.classicChannels?.getChannelIdByInstance(name))
|
|
10601
11605
|
: null;
|
|
10602
|
-
|
|
11606
|
+
const accent = !profileVersion && bot && ownConnection && owner ? roleColor : null;
|
|
11607
|
+
// #1629 (first design §5, r2 (d)): the agent's theme may name its own picture and ring colour. Both come below a
|
|
11608
|
+
// person's upload (never when there is one) and ride beside the theme-free face: a viewer who turned agents'
|
|
11609
|
+
// themes off (fx.show), or a safe-mode load, shows `avatar` and `accent` as before.
|
|
11610
|
+
let theme = { v: 1 };
|
|
11611
|
+
try {
|
|
11612
|
+
theme = this.themeStore.get(name).theme;
|
|
11613
|
+
}
|
|
11614
|
+
catch { /* unreadable themes: none */ }
|
|
11615
|
+
const themeAvatar = !profileVersion && theme.avatar ? { kind: "image", src: `/ui/img/theme/${encodeURIComponent(name)}/${theme.avatar}` } : undefined;
|
|
11616
|
+
const themeAccent = !profileVersion && theme.accent ? theme.accent : undefined;
|
|
11617
|
+
return { avatar, ...(accent ? { accent } : {}), ...(themeAvatar ? { themeAvatar } : {}), ...(themeAccent ? { themeAccent } : {}),
|
|
11618
|
+
// #1958: the agent's own identity colour (theme.identity.color, else its accent) and where it would show it.
|
|
11619
|
+
...(roleColor ? { roleColor } : {}), ...(theme.identity?.color ?? theme.accent ? { agentColor: theme.identity?.color ?? theme.accent } : {}),
|
|
11620
|
+
...(theme.identity?.show ? { agentShow: theme.identity.show } : {}) };
|
|
10603
11621
|
}
|
|
10604
11622
|
/**
|
|
10605
11623
|
* GET /ui/img/bot|avatar/<key>: what is cached, never a fetch. Only a connection some instance or room speaks
|
|
@@ -11686,7 +12704,8 @@ export class FleetManager {
|
|
|
11686
12704
|
// Discord, so every such fallback failed inside the catch handler.
|
|
11687
12705
|
const target = this.fleetNoticeTarget();
|
|
11688
12706
|
if (this.adapter && target) {
|
|
11689
|
-
this.
|
|
12707
|
+
const out = this.renderPlaces(this.getPrimaryAdapterId(), body, target.opts);
|
|
12708
|
+
this.adapter.sendText(target.chatId, out.text, out.opts)
|
|
11690
12709
|
.catch(err => this.logger.warn({ err }, "Failed to send fleet error notification"));
|
|
11691
12710
|
dispatched = true;
|
|
11692
12711
|
}
|
|
@@ -11698,7 +12717,7 @@ export class FleetManager {
|
|
|
11698
12717
|
// also suppressed the next ten minutes of identical ones. Leaving the key
|
|
11699
12718
|
// unspent lets the next caller, once an adapter is up, actually get
|
|
11700
12719
|
// through. The counter is not reset either: nothing was shown.
|
|
11701
|
-
this.logger.warn({ text: body }, "Fleet error could not be delivered (no adapter or no target yet) — not consuming the throttle window");
|
|
12720
|
+
this.logger.warn({ text: stripPlaceRefs(body) }, "Fleet error could not be delivered (no adapter or no target yet) — not consuming the throttle window");
|
|
11702
12721
|
return false;
|
|
11703
12722
|
}
|
|
11704
12723
|
if (!throttled)
|
|
@@ -11736,24 +12755,28 @@ export class FleetManager {
|
|
|
11736
12755
|
const groupId = channelCfg?.group_id;
|
|
11737
12756
|
// Fleet topic instance
|
|
11738
12757
|
const threadId = this.fleetConfig?.instances[instanceName]?.topic_id;
|
|
12758
|
+
const worldId = this.getInstanceAdapterId(instanceName);
|
|
11739
12759
|
if (threadId != null && groupId) {
|
|
11740
|
-
|
|
12760
|
+
const out = this.renderPlaces(worldId, text, { threadId: String(threadId), ...extraOpts });
|
|
12761
|
+
adapter.sendText(String(groupId), out.text, out.opts)
|
|
11741
12762
|
.catch(e => this.logger.warn({ err: e, instanceName }, "Failed to send instance topic notification"));
|
|
11742
12763
|
return true;
|
|
11743
12764
|
}
|
|
11744
12765
|
// Classic instance: find its channelId from the classic manager
|
|
11745
12766
|
const classicChatId = this.classicChannels?.getChannelIdByInstance(instanceName);
|
|
11746
12767
|
if (classicChatId) {
|
|
11747
|
-
|
|
12768
|
+
// #1990: a ClassicBot room's readers need not be in the fleet's group, so its notices name places as plain text.
|
|
12769
|
+
adapter.sendText(classicChatId, stripPlaceRefs(text), extraOpts)
|
|
11748
12770
|
.catch(e => this.logger.warn({ err: e, instanceName }, "Failed to send classic notification"));
|
|
11749
12771
|
return true;
|
|
11750
12772
|
}
|
|
11751
12773
|
// Fallback: the instance has neither a topic nor a classic channel, so post
|
|
11752
12774
|
// where fleet-wide notices go. Not the bare group id: on Discord that is a
|
|
11753
12775
|
// guild, and the send fails inside the catch handler.
|
|
11754
|
-
const target = this.fleetNoticeTarget(
|
|
12776
|
+
const target = this.fleetNoticeTarget(worldId);
|
|
11755
12777
|
if (target) {
|
|
11756
|
-
|
|
12778
|
+
const out = this.renderPlaces(worldId, text, { ...target.opts, ...extraOpts });
|
|
12779
|
+
adapter.sendText(target.chatId, out.text, out.opts)
|
|
11757
12780
|
.catch(e => this.logger.warn({ err: e, instanceName }, "Failed to send notification (no topic)"));
|
|
11758
12781
|
return true;
|
|
11759
12782
|
}
|
|
@@ -11824,12 +12847,14 @@ export class FleetManager {
|
|
|
11824
12847
|
this.pendingNonceButtons.set(nonce, entry);
|
|
11825
12848
|
try {
|
|
11826
12849
|
const choices = opts.choices.map(c => ({ id: `${opts.prefix}${nonce}:${c.action}`, label: c.label }));
|
|
12850
|
+
// #1990: place names link for the group the prompt is posted in; the dashboard's copy is plain (for now).
|
|
12851
|
+
const posted = this.renderPlaces(opts.adapterId, opts.message, opts.threadId ? { threadId: opts.threadId } : undefined);
|
|
11827
12852
|
const sent = opts.deliver ? await opts.deliver(choices) : await opts.adapter.notifyAlert(opts.chatId, {
|
|
11828
12853
|
type: opts.alertType,
|
|
11829
12854
|
instanceName: opts.instanceName,
|
|
11830
|
-
message:
|
|
12855
|
+
message: posted.text,
|
|
11831
12856
|
choices,
|
|
11832
|
-
},
|
|
12857
|
+
}, posted.opts);
|
|
11833
12858
|
// Bind the nonce to the provider's canonical delivery address, not the
|
|
11834
12859
|
// logical routing input. Telegram, for example, represents General as
|
|
11835
12860
|
// AgEnD topic "1" on input but omits message_thread_id on the wire and in
|
|
@@ -11847,8 +12872,15 @@ export class FleetManager {
|
|
|
11847
12872
|
// Offered on the dashboard only once it is live on the platform (a failed post is disarmed above),
|
|
11848
12873
|
// and only if nothing claimed or expired it meanwhile.
|
|
11849
12874
|
if (WEB_MIRRORED_PROMPT_PREFIXES.has(opts.prefix) && this.pendingNonceButtons.get(nonce) === entry) {
|
|
12875
|
+
// #1990: on the dashboard an instance's name opens its terminal View (where the prompt is answered by hand).
|
|
12876
|
+
const web = renderPlaceRefs(opts.message, "web", target => {
|
|
12877
|
+
const route = target.kind === "instance" && Object.hasOwn(this.fleetConfig?.instances ?? {}, target.name) ? webRoute("view", target.name) : undefined;
|
|
12878
|
+
return route ? { url: route } : undefined;
|
|
12879
|
+
});
|
|
12880
|
+
const links = webTextLinks(web.textLinks, web.text);
|
|
11850
12881
|
entry.web = {
|
|
11851
|
-
text:
|
|
12882
|
+
text: web.text,
|
|
12883
|
+
...(links ? { links } : {}),
|
|
11852
12884
|
actions: opts.choices.map(c => ({ id: c.action, label: c.label })),
|
|
11853
12885
|
expiresAt: Date.now() + (opts.timeoutMs ?? NONCE_BUTTON_TIMEOUT_MS),
|
|
11854
12886
|
};
|
|
@@ -12004,6 +13036,8 @@ export class FleetManager {
|
|
|
12004
13036
|
}
|
|
12005
13037
|
/** Routes a click to the handler that owns its prefix; false when none does. */
|
|
12006
13038
|
async dispatchAdapterCallback(data, adapterId, adapter) {
|
|
13039
|
+
if (await this.sessionAuthorizationRequests().handleCallback(data, adapterId))
|
|
13040
|
+
return true; // #1939 S2b
|
|
12007
13041
|
if (data.callbackData.startsWith(REPLY_BUTTON_PREFIX)) { // #1266
|
|
12008
13042
|
const buttons = this.replyButtons();
|
|
12009
13043
|
if (!buttons) {
|
|
@@ -12100,7 +13134,7 @@ export class FleetManager {
|
|
|
12100
13134
|
isClassic: name => classic.has(name),
|
|
12101
13135
|
place: name => {
|
|
12102
13136
|
const world = this.worlds.get(this.getInstanceAdapterId(name) ?? "");
|
|
12103
|
-
return world ?
|
|
13137
|
+
return world ? worldPlaceOf(world) : undefined;
|
|
12104
13138
|
},
|
|
12105
13139
|
// fleet.yaml's topic only. A ClassicBot room has none here, so no link: its channel may sit in any allowed
|
|
12106
13140
|
// guild, not necessarily its world's group.
|
|
@@ -12141,7 +13175,7 @@ export class FleetManager {
|
|
|
12141
13175
|
cacheInstances() {
|
|
12142
13176
|
const fleet = Object.entries(this.fleetConfig?.instances ?? {}).map(([name, cfg]) => ({
|
|
12143
13177
|
name, backend: this.backendNameOf(name), workingDirectory: cfg.working_directory, ledgerPath: join(this.getInstanceDir(name), "cache-ledger.json"),
|
|
12144
|
-
claudeConfigDir: this.claudeConfigDirOf(name),
|
|
13178
|
+
claudeConfigDir: this.claudeConfigDirOf(name), profile: this.usageProfileOf(name, this.backendNameOf(name)),
|
|
12145
13179
|
}));
|
|
12146
13180
|
const taken = new Set(fleet.map(i => i.name));
|
|
12147
13181
|
const classic = (this.classicChannels?.getAll() ?? []).filter(ch => !taken.has(ch.instanceName)).map(ch => ({
|
|
@@ -12150,6 +13184,7 @@ export class FleetManager {
|
|
|
12150
13184
|
workingDirectory: join(getAgendHome(), "workspaces", ch.instanceName),
|
|
12151
13185
|
ledgerPath: join(this.getInstanceDir(ch.instanceName), "cache-ledger.json"),
|
|
12152
13186
|
claudeConfigDir: this.claudeConfigDirOf(ch.instanceName),
|
|
13187
|
+
profile: this.usageProfileOf(ch.instanceName, this.classicChannels?.getBackendByInstance(ch.instanceName, this.fleetConfig?.defaults?.backend) ?? this.fleetConfig?.defaults?.backend ?? "claude-code"),
|
|
12153
13188
|
}));
|
|
12154
13189
|
return [...fleet, ...new Map(classic.map(c => [c.name, c])).values()];
|
|
12155
13190
|
}
|
|
@@ -12159,17 +13194,63 @@ export class FleetManager {
|
|
|
12159
13194
|
* (cache-service.ts) — never a vendor call, never a synchronous transcript read.
|
|
12160
13195
|
*/
|
|
12161
13196
|
cacheReport(window) {
|
|
12162
|
-
|
|
12163
|
-
|
|
13197
|
+
return this.cacheServiceFor().report(cacheWindow(window));
|
|
13198
|
+
}
|
|
13199
|
+
/**
|
|
13200
|
+
* #2122 §5.1: the profile the usage read now is tagged with — the claude profile whose config dir is read ("default"
|
|
13201
|
+
* without one); codex "unrecorded" (its rollouts don't say which login wrote them).
|
|
13202
|
+
*/
|
|
13203
|
+
usageProfileOf(name, backend) {
|
|
13204
|
+
if (backend === "claude-code")
|
|
13205
|
+
return this.credentialProfileOf(name, "claude-code") ?? "default";
|
|
13206
|
+
if (backend === "codex")
|
|
13207
|
+
return "unrecorded";
|
|
13208
|
+
return undefined;
|
|
13209
|
+
}
|
|
13210
|
+
/** #2122: the fleet's day boundary zone — defaults.scheduler.default_timezone, else this host's. */
|
|
13211
|
+
usageZone() {
|
|
13212
|
+
return this.fleetConfig?.defaults?.scheduler?.default_timezone?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
|
|
13213
|
+
}
|
|
13214
|
+
/**
|
|
13215
|
+
* #2122: the usage report (usage-report.ts) — from the ledgers and rollups as they are now and the delivered-message
|
|
13216
|
+
* counts; never a transcript read. `only`: just that instance (an ordinary agent's own row).
|
|
13217
|
+
*/
|
|
13218
|
+
async usageReport(params) {
|
|
13219
|
+
const { buildUsageReport } = await import("./usage-report.js");
|
|
13220
|
+
const data = await this.cacheServiceFor().usageData();
|
|
13221
|
+
const team = new Map();
|
|
13222
|
+
for (const [t, cfg] of Object.entries(this.fleetConfig?.teams ?? {}))
|
|
13223
|
+
for (const m of cfg?.members ?? [])
|
|
13224
|
+
if (!team.has(m))
|
|
13225
|
+
team.set(m, t);
|
|
13226
|
+
const now = Date.now();
|
|
13227
|
+
this.ensureDeliveryOutbox?.();
|
|
13228
|
+
// Every hour of the kept history: the report places each on a local date and keeps the range's own.
|
|
13229
|
+
const messages = this.deliveryOutbox?.deliveredMessageHours(now - 401 * 86_400_000, now + 3_600_000) ?? [];
|
|
13230
|
+
const keep = (name) => params.only === undefined || name === params.only;
|
|
13231
|
+
return buildUsageReport({
|
|
13232
|
+
now, zone: this.usageZone(), range: params.range, group: params.group, scanning: data.scanning,
|
|
13233
|
+
instances: data.instances.filter(i => keep(i.inst.name)).map(i => ({ name: i.inst.name, backend: i.inst.backend, team: team.get(i.inst.name) ?? null,
|
|
13234
|
+
status: i.status, ...(i.with ? { with: i.with } : {}), ledger: i.ledger, days: i.days })),
|
|
13235
|
+
messages: messages.filter(m => keep(m.instance)),
|
|
13236
|
+
});
|
|
13237
|
+
}
|
|
13238
|
+
/** #2001: get_cache_report's — the same report, as last worked out (reused for a minute, until the next pass). */
|
|
13239
|
+
cacheReportPublished(window) {
|
|
13240
|
+
return this.cacheServiceFor().published(cacheWindow(window));
|
|
13241
|
+
}
|
|
13242
|
+
cacheServiceFor() {
|
|
13243
|
+
return this.cacheService ??= new CacheService({
|
|
12164
13244
|
instances: () => this.cacheInstances(),
|
|
12165
13245
|
claudeProjectsDir: () => join(process.env.CLAUDE_CONFIG_DIR?.trim() || join(homedir(), ".claude"), "projects"),
|
|
12166
13246
|
claudeKey: claudeProjectKey,
|
|
12167
13247
|
codexSessionsDir: () => join(process.env.CODEX_HOME?.trim() || join(homedir(), ".codex"), "sessions"),
|
|
12168
13248
|
listRollouts: root => sharedRolloutIndex(root).list(),
|
|
13249
|
+
rolloutsUnreadable: root => sharedRolloutIndex(root).unreadable,
|
|
12169
13250
|
metaPath: join(this.dataDir, "cache-codex-rollouts.json"),
|
|
13251
|
+
zone: () => this.usageZone(),
|
|
12170
13252
|
log: (level, msg, extra) => this.logger[level](extra ?? {}, msg),
|
|
12171
13253
|
});
|
|
12172
|
-
return this.cacheService.report(w);
|
|
12173
13254
|
}
|
|
12174
13255
|
/** The web's Acknowledge (any item; a signed-in session is fleet-admin level). */
|
|
12175
13256
|
acknowledgeNeedsItem(id, principal) {
|
|
@@ -12265,9 +13346,7 @@ export class FleetManager {
|
|
|
12265
13346
|
finishedAt: Date.parse(d.finishedAt) || 0,
|
|
12266
13347
|
})),
|
|
12267
13348
|
ownerOf,
|
|
12268
|
-
worlds: () => [...this.worlds.values()].map((w) => ({
|
|
12269
|
-
id: w.id, adapter: w.adapter, place: { type: w.type, ...(w.groupId ? { groupId: w.groupId } : {}) },
|
|
12270
|
-
})),
|
|
13349
|
+
worlds: () => [...this.worlds.values()].map((w) => ({ id: w.id, adapter: w.adapter, place: worldPlaceOf(w) })),
|
|
12271
13350
|
noticeTarget: world => {
|
|
12272
13351
|
const target = this.fleetNoticeTarget(world);
|
|
12273
13352
|
return target ? { chatId: target.chatId, ...(target.opts.threadId !== undefined ? { threadId: String(target.opts.threadId) } : {}) } : null;
|
|
@@ -12681,6 +13760,198 @@ export class FleetManager {
|
|
|
12681
13760
|
webBackendTokens = new Map();
|
|
12682
13761
|
/** #1269: the web's /clear confirmations — one token per question, used once, for the instance as it was asked about. */
|
|
12683
13762
|
webClearTokens = new Map();
|
|
13763
|
+
/**
|
|
13764
|
+
* #1939 S1: the design's §3 for one web request (authority/web-authority.ts), with this fleet's admins, policy and
|
|
13765
|
+
* token; `instance` once the body has named it. Observe only: receipts record it, no agent acts on it yet.
|
|
13766
|
+
*/
|
|
13767
|
+
webAuthority(input) {
|
|
13768
|
+
const state = this.webAuthorityState();
|
|
13769
|
+
return evaluateWebAuthority({
|
|
13770
|
+
session: input.session, gateway: input.gateway, peer: input.peer,
|
|
13771
|
+
tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null,
|
|
13772
|
+
...(input.instance !== undefined ? { target: { adapterId: this.getInstanceAdapterId(input.instance) } } : {}),
|
|
13773
|
+
isAdmin: (userId, adapterId) => this.adminGate(userId, adapterId) === "ok",
|
|
13774
|
+
authorization: input.session ? this.sessionAuthorizationStore()?.get(input.session.handle) ?? null : null,
|
|
13775
|
+
policy: { ...webAuthorityPolicy(this.fleetConfig?.web), enabled: state.enabled, loopbackOnly: state.loopbackOnly }, epoch: state.epoch, now: Date.now(),
|
|
13776
|
+
});
|
|
13777
|
+
}
|
|
13778
|
+
sessionAuthorizations = null;
|
|
13779
|
+
sessionAuthorizationStore() {
|
|
13780
|
+
if (!this.dataDir)
|
|
13781
|
+
return null;
|
|
13782
|
+
this.sessionAuthorizations ??= new SessionAuthorizations(join(this.dataDir, "web-authorizations.json"), this.logger);
|
|
13783
|
+
return this.sessionAuthorizations;
|
|
13784
|
+
}
|
|
13785
|
+
/**
|
|
13786
|
+
* #1939 §0: record that a session's account has authorized it — called only once that account has confirmed on Discord
|
|
13787
|
+
* or Telegram (S2b). The session must qualify now (§3, as a message from it would be judged); then every message,
|
|
13788
|
+
* click, /steer and /btw from it is web-verified until max_session_hours after now, the session ends, or a revocation.
|
|
13789
|
+
* Ones no longer worth keeping (their session gone, an old epoch, run out) are dropped on the way.
|
|
13790
|
+
*/
|
|
13791
|
+
authorizeWebSession(session, peer, gateway) {
|
|
13792
|
+
const store = this.sessionAuthorizationStore();
|
|
13793
|
+
const state = this.webAuthorityState(), now = Date.now(), policy = webAuthorityPolicy(this.fleetConfig?.web);
|
|
13794
|
+
if (!store || !session.owner)
|
|
13795
|
+
return { ok: false, refusal: !store ? "disabled" : "no_account" };
|
|
13796
|
+
const check = evaluateWebAuthority({
|
|
13797
|
+
session, gateway, peer, tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null,
|
|
13798
|
+
isAdmin: (userId, adapterId) => this.adminGate(userId, adapterId) === "ok",
|
|
13799
|
+
authorization: { handle: session.handle, owner: session.owner, authorizedAt: now, until: now + policy.maxSessionMs, epoch: state.epoch },
|
|
13800
|
+
policy: { ...policy, enabled: state.enabled, loopbackOnly: state.loopbackOnly }, epoch: state.epoch, now,
|
|
13801
|
+
});
|
|
13802
|
+
if (check.refusal)
|
|
13803
|
+
return { ok: false, refusal: check.refusal };
|
|
13804
|
+
const live = new Set(this.webSessions?.list(undefined, () => true).map(r => r.handle) ?? []);
|
|
13805
|
+
store.prune(a => a.epoch === state.epoch && now <= Math.min(a.until, a.authorizedAt + policy.maxSessionMs) && live.has(a.handle));
|
|
13806
|
+
return { ok: true, ...store.authorize(session.handle, session.owner, now, state.epoch, now + policy.maxSessionMs) };
|
|
13807
|
+
}
|
|
13808
|
+
authorityStateStore = null;
|
|
13809
|
+
/**
|
|
13810
|
+
* #1939 §10: the switch, "Only this computer can authorize" and the revocation epoch in force for the configuration as
|
|
13811
|
+
* it is now (a change since last seen moves the epoch first; authority-state.ts). No data directory: off.
|
|
13812
|
+
*/
|
|
13813
|
+
webAuthorityState() {
|
|
13814
|
+
if (!this.dataDir)
|
|
13815
|
+
return { enabled: false, loopbackOnly: true, epoch: 0 };
|
|
13816
|
+
this.authorityStateStore ??= new AuthorityStateStore(join(this.dataDir, "web-authority.json"), this.logger, undefined, undefined, () => { this.ensureDeliveryOutbox?.(); return this.deliveryOutbox?.maxWebAuthorityEpoch() ?? 0; });
|
|
13817
|
+
return this.authorityStateStore.current(this.fleetConfig?.web?.verified_authority);
|
|
13818
|
+
}
|
|
13819
|
+
/**
|
|
13820
|
+
* #1939 S2a: Settings → Web → Web authority — the state in force (the switch counts as off while its state cannot be
|
|
13821
|
+
* written), what fleet.yaml says, the hosts that make the dashboard reachable from elsewhere (the warning while
|
|
13822
|
+
* loopback_only is off), and the sessions authorized now (§0): each one's device, account, and when it runs out.
|
|
13823
|
+
*/
|
|
13824
|
+
webAuthorityOverview() {
|
|
13825
|
+
const configured = this.fleetConfig?.web?.verified_authority ?? {};
|
|
13826
|
+
const lanHosts = (this.fleetConfig?.web?.allowed_hosts ?? []).filter(h => { const name = hostnameOf(String(h)); return name !== null && !LOOPBACK_HOST_NAMES.includes(name); });
|
|
13827
|
+
const state = this.webAuthorityState(), maxMs = webAuthorityPolicy(this.fleetConfig?.web).maxSessionMs, now = Date.now();
|
|
13828
|
+
const sessions = new Map((this.webSessions?.list(undefined, () => true) ?? []).map(r => [r.handle, r]));
|
|
13829
|
+
const authorized = state.enabled ? (this.sessionAuthorizationStore()?.list() ?? [])
|
|
13830
|
+
.filter(a => a.epoch === state.epoch && sessions.has(a.handle) && now <= Math.min(a.until, a.authorizedAt + maxMs))
|
|
13831
|
+
.map(a => ({ handle: a.handle, label: sessions.get(a.handle).label, account: `${a.owner.adapterId}:${a.owner.userId}`, authorizedAt: a.authorizedAt,
|
|
13832
|
+
until: Math.min(a.until, a.authorizedAt + maxMs, sessions.get(a.handle).absoluteExpiry) })) : [];
|
|
13833
|
+
return { state, configured, hours: VERIFIED_SESSION_HOURS, lanHosts, authorized };
|
|
13834
|
+
}
|
|
13835
|
+
authorizationRequests = null;
|
|
13836
|
+
/**
|
|
13837
|
+
* #1939 S2b (§0.1): "Authorize this browser" — the Confirm card in the account's DM. Confirm runs §3 again at the tap
|
|
13838
|
+
* (authorizeWebSession on the session read again by its handle); Not me signs the session out.
|
|
13839
|
+
*/
|
|
13840
|
+
sessionAuthorizationRequests() {
|
|
13841
|
+
if (this.authorizationRequests)
|
|
13842
|
+
return this.authorizationRequests;
|
|
13843
|
+
const adapterOf = (adapterId) => this.adapters.get(adapterId) ?? this.worlds.get(adapterId)?.adapter;
|
|
13844
|
+
// The host's clock, with its zone: the person may read the DM on a phone in another one.
|
|
13845
|
+
const when = (ms) => new Date(ms).toLocaleString(undefined, { timeZoneName: "short" });
|
|
13846
|
+
const where = (peer) => t(peer === "loopback" ? "web_auth.peer_loopback" : "web_auth.peer_lan");
|
|
13847
|
+
return this.authorizationRequests = new SessionAuthorizationRequests({
|
|
13848
|
+
now: () => performance.now(), wallNow: () => Date.now(),
|
|
13849
|
+
maxSessionMs: () => webAuthorityPolicy(this.fleetConfig?.web).maxSessionMs,
|
|
13850
|
+
sendDirect: async (owner, text, choices) => {
|
|
13851
|
+
const adapter = adapterOf(owner.adapterId);
|
|
13852
|
+
if (!adapter?.sendDirect)
|
|
13853
|
+
return null;
|
|
13854
|
+
const sent = await adapter.sendDirect(owner.userId, text, { choices, allowedMentions: { parse: [] } });
|
|
13855
|
+
return sent?.messageId ? { chatId: sent.chatId, messageId: sent.messageId } : null;
|
|
13856
|
+
},
|
|
13857
|
+
sendGeneralHint: async (owner, text) => {
|
|
13858
|
+
const adapter = adapterOf(owner.adapterId), general = this.findGeneralInstance(owner.adapterId);
|
|
13859
|
+
const topic = general ? this.fleetConfig?.instances[general]?.topic_id : undefined;
|
|
13860
|
+
const group = general ? this.getGroupIdForInstance(general) : undefined;
|
|
13861
|
+
if (adapter && group)
|
|
13862
|
+
await adapter.sendText(String(group), text, { ...(topic != null ? { threadId: String(topic) } : {}), allowedMentions: { parse: [] } });
|
|
13863
|
+
},
|
|
13864
|
+
editCard: async (owner, at, text, choices) => {
|
|
13865
|
+
const adapter = adapterOf(owner.adapterId);
|
|
13866
|
+
if (!adapter)
|
|
13867
|
+
return;
|
|
13868
|
+
if (!choices.length && adapter.editMessageRemoveButtons) {
|
|
13869
|
+
await adapter.editMessageRemoveButtons(at.chatId, at.messageId, text);
|
|
13870
|
+
return;
|
|
13871
|
+
}
|
|
13872
|
+
await adapter.editMessage(at.chatId, at.messageId, text);
|
|
13873
|
+
if (adapter.replaceMessageButtons)
|
|
13874
|
+
await adapter.replaceMessageButtons(at.chatId, at.messageId, choices);
|
|
13875
|
+
},
|
|
13876
|
+
authorize: (handle, peer) => {
|
|
13877
|
+
const record = this.webSessions?.findByHandle(handle);
|
|
13878
|
+
if (!record)
|
|
13879
|
+
return { ok: false, refusal: "session_gone" };
|
|
13880
|
+
const r = this.authorizeWebSession(record, peer, false);
|
|
13881
|
+
// What the card says: the end of the authorization, or the session's own end when that comes first.
|
|
13882
|
+
return r.ok ? { ok: true, until: Math.min(r.authorization.until, record.absoluteExpiry) } : { ok: false, refusal: r.refusal };
|
|
13883
|
+
},
|
|
13884
|
+
signOut: (handle) => {
|
|
13885
|
+
this.webSessions?.revokeByHandle(handle);
|
|
13886
|
+
this.sessionAuthorizationStore()?.prune(a => a.handle !== handle);
|
|
13887
|
+
},
|
|
13888
|
+
event: (type, payload) => { try {
|
|
13889
|
+
this.eventLog?.insert("web", type, payload);
|
|
13890
|
+
}
|
|
13891
|
+
catch { /* the event log is best effort */ } },
|
|
13892
|
+
text: {
|
|
13893
|
+
ask: (c) => t("web_auth.card_ask", c.label, where(c.peer), when(c.askedAt), when(c.until)),
|
|
13894
|
+
confirmed: (c) => t("web_auth.card_confirmed", c.label, where(c.peer), when(c.until)),
|
|
13895
|
+
denied: (c) => t("web_auth.card_denied", c.label),
|
|
13896
|
+
expired: (c) => t("web_auth.card_expired", c.label),
|
|
13897
|
+
refused: (c) => t("web_auth.card_refused", c.label, t(`web_auth.refusal_${c.refusal}`)),
|
|
13898
|
+
revoked: (c) => t("web_auth.card_revoked", c.label),
|
|
13899
|
+
ended: (c) => t("web_auth.card_ended", c.label),
|
|
13900
|
+
generalHint: () => t("web_auth.general_hint"),
|
|
13901
|
+
confirmLabel: () => t("web_auth.confirm"),
|
|
13902
|
+
notMeLabel: () => t("web_auth.not_me"),
|
|
13903
|
+
notYours: () => t("web_auth.not_yours"),
|
|
13904
|
+
},
|
|
13905
|
+
log: this.logger,
|
|
13906
|
+
});
|
|
13907
|
+
}
|
|
13908
|
+
/** #1939 S2b: the web session asks to be authorized (the request judged by §3 first — as it will be again at the tap). */
|
|
13909
|
+
async requestSessionAuthorization(input) {
|
|
13910
|
+
const s = input.session;
|
|
13911
|
+
const gate = this.webAuthorityQualifies(input);
|
|
13912
|
+
if (gate)
|
|
13913
|
+
return { ok: false, refusal: gate };
|
|
13914
|
+
return this.sessionAuthorizationRequests().ask({ handle: s.handle, owner: s.owner, label: s.label, peer: input.peer, sessionEnd: s.absoluteExpiry });
|
|
13915
|
+
}
|
|
13916
|
+
/**
|
|
13917
|
+
* #1939 §3 without the authorization: would this request's session qualify to be authorized? null: yes; otherwise the
|
|
13918
|
+
* first check it fails (for the app to say why it can't be authorized here).
|
|
13919
|
+
*/
|
|
13920
|
+
webAuthorityQualifies(input) {
|
|
13921
|
+
const s = input.session, state = this.webAuthorityState(), now = Date.now(), policy = webAuthorityPolicy(this.fleetConfig?.web);
|
|
13922
|
+
const r = evaluateWebAuthority({
|
|
13923
|
+
session: s, gateway: input.gateway, peer: input.peer, tokenEpoch: this.webToken ? tokenEpoch(this.webToken) : null,
|
|
13924
|
+
isAdmin: (userId, adapterId) => this.adminGate(userId, adapterId) === "ok",
|
|
13925
|
+
authorization: s?.owner ? { handle: s.handle, owner: s.owner, authorizedAt: now, until: now + policy.maxSessionMs, epoch: state.epoch } : null,
|
|
13926
|
+
policy: { ...policy, enabled: state.enabled, loopbackOnly: state.loopbackOnly }, epoch: state.epoch, now,
|
|
13927
|
+
});
|
|
13928
|
+
return r.refusal;
|
|
13929
|
+
}
|
|
13930
|
+
/** #1939 S2b: what the app shows for this browser — verified (until when), a card pending, or why not. */
|
|
13931
|
+
webSessionAuthorization(input) {
|
|
13932
|
+
const s = input.session;
|
|
13933
|
+
const verdict = this.webAuthority(input);
|
|
13934
|
+
if (!verdict.refusal && verdict.authority.session) {
|
|
13935
|
+
const a = this.sessionAuthorizationStore()?.get(s.handle);
|
|
13936
|
+
const max = webAuthorityPolicy(this.fleetConfig?.web).maxSessionMs;
|
|
13937
|
+
if (a)
|
|
13938
|
+
return { state: "verified", until: Math.min(a.until, a.authorizedAt + max, s.absoluteExpiry) };
|
|
13939
|
+
}
|
|
13940
|
+
const pending = s ? this.sessionAuthorizationRequests().pending(s.handle) : null;
|
|
13941
|
+
if (pending)
|
|
13942
|
+
return { state: "pending", expiresInMs: pending.expiresInMs };
|
|
13943
|
+
return { state: "none", reason: this.webAuthorityQualifies(input) ?? (verdict.refusal ?? "not_authorized") };
|
|
13944
|
+
}
|
|
13945
|
+
/** #1939 §10: revoke every web authority given so far (receipts read as none), without signing anyone out. */
|
|
13946
|
+
revokeWebAuthority() {
|
|
13947
|
+
this.webAuthorityState(); // any switch change first, then this revocation
|
|
13948
|
+
const result = this.authorityStateStore?.revoke() ?? { epoch: 0, durable: false };
|
|
13949
|
+
if (result.durable)
|
|
13950
|
+
this.logger.info({ epoch: result.epoch }, "Web authority revoked");
|
|
13951
|
+
else
|
|
13952
|
+
this.logger.warn({ epoch: result.epoch }, "Web authority revoked in memory only — web authority stays off until its state can be written; a restart before then undoes this revocation");
|
|
13953
|
+
return result;
|
|
13954
|
+
}
|
|
12684
13955
|
/** #1269: an instance's chat command from the web chat (web-commands.ts); `publicLink`: a gateway request. */
|
|
12685
13956
|
webCommand(input, opts) {
|
|
12686
13957
|
const webMeta = (instance) => {
|
|
@@ -12689,15 +13960,16 @@ export class FleetManager {
|
|
|
12689
13960
|
// #1827: a /steer or /btw reaches the agent as the web person who wrote it.
|
|
12690
13961
|
chatId: this.getGroupIdForInstance(instance) || "", messageId: newWebMessageId(),
|
|
12691
13962
|
username: opts.person?.name ?? WEB_NAME_FALLBACK, userId: opts.person?.userId ?? WEB_NAME_FALLBACK,
|
|
12692
|
-
threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true),
|
|
13963
|
+
threadId: topicId != null ? String(topicId) : undefined, adapterId: this.getAdapterForInstance(instance)?.id ?? "", source: "web", humanOrigin: webHumanOrigin(true, opts.authority),
|
|
12693
13964
|
};
|
|
12694
13965
|
};
|
|
12695
13966
|
const choicesFromCache = (instance) => {
|
|
12696
|
-
const
|
|
13967
|
+
const backend = this.backendNameForInstance(instance);
|
|
13968
|
+
const cached = this.readCliEnv(backend, this.catalogProfile(backend, instance)); // the cached catalog only: never a probe here
|
|
12697
13969
|
if (!cached?.models.length)
|
|
12698
13970
|
return null;
|
|
12699
13971
|
const current = this.resolveInstanceModel(instance).model;
|
|
12700
|
-
return { current, options: cached.models.map(o => ({ id: o.id, label: this.modelChoiceLabel(o, current) })) };
|
|
13972
|
+
return { current, options: this.withCurrentModel(cached.models, current).map(o => ({ id: o.id, label: this.modelChoiceLabel(o, current) })) };
|
|
12701
13973
|
};
|
|
12702
13974
|
return runWebCommand({
|
|
12703
13975
|
// Own entries only: a name like "__proto__" or "constructor" must not be found on the prototype (#1476 review).
|
|
@@ -12744,7 +14016,7 @@ export class FleetManager {
|
|
|
12744
14016
|
return step.noop ? { text: step.text } : { error: step.text };
|
|
12745
14017
|
if (step.kind === "choose") {
|
|
12746
14018
|
const id = (token) => joinBackendArgs([...step.args, token]);
|
|
12747
|
-
return { choices: { prompt: step.text, current: step.current === null ? null : id(step.current), options: step.choices.map(c => ({ id: id(c.token), label: c.label })) } };
|
|
14019
|
+
return { choices: { prompt: step.text, current: step.current === null ? null : id(step.current), options: step.choices.map(c => ({ id: id(c.token), label: c.label, ...(c.disabled ? { disabled: c.disabled } : {}) })) } };
|
|
12748
14020
|
}
|
|
12749
14021
|
const now = performance.now();
|
|
12750
14022
|
for (const [k, v] of this.webBackendTokens)
|
|
@@ -12919,12 +14191,12 @@ export class FleetManager {
|
|
|
12919
14191
|
* the operator's. Keep the instance notice passive and put the action in the
|
|
12920
14192
|
* same-world General topic where an administrator can make the choice. */
|
|
12921
14193
|
async notifyNormalExit(instanceName) {
|
|
12922
|
-
this.notifyInstanceTopic(instanceName, t("exit.instance_notice", instanceName));
|
|
14194
|
+
this.notifyInstanceTopic(instanceName, t("exit.instance_notice", instanceName) + placeSuffix({ kind: "general" }, "General"));
|
|
12923
14195
|
const web = this.webOnlyPromptPlace();
|
|
12924
14196
|
if (web) {
|
|
12925
14197
|
await this.postNonceButtonPrompt({
|
|
12926
14198
|
prefix: EXIT_RESTART_CALLBACK_PREFIX, alertType: "exit_restart", instanceName, ...web,
|
|
12927
|
-
message: t("exit.general_notice", instanceName),
|
|
14199
|
+
message: t("exit.general_notice", placeRef({ kind: "instance", name: instanceName }, instanceName)),
|
|
12928
14200
|
choices: [{ action: "restart", label: t("exit.restart") }, { action: "ignore", label: t("exit.ignore") }],
|
|
12929
14201
|
expiredText: t("exit.expired", instanceName),
|
|
12930
14202
|
});
|
|
@@ -12953,7 +14225,7 @@ export class FleetManager {
|
|
|
12953
14225
|
adapterId,
|
|
12954
14226
|
chatId,
|
|
12955
14227
|
threadId,
|
|
12956
|
-
message: t("exit.general_notice", instanceName),
|
|
14228
|
+
message: t("exit.general_notice", placeRef({ kind: "instance", name: instanceName }, instanceName)),
|
|
12957
14229
|
choices: [
|
|
12958
14230
|
{ action: "restart", label: t("exit.restart") },
|
|
12959
14231
|
{ action: "ignore", label: t("exit.ignore") },
|
|
@@ -13000,7 +14272,7 @@ export class FleetManager {
|
|
|
13000
14272
|
* contain usernames or secret-adjacent text and stays in daemon.log.
|
|
13001
14273
|
*/
|
|
13002
14274
|
async notifyInteractivePrompt(instanceName, kind) {
|
|
13003
|
-
this.notifyInstanceTopic(instanceName, t("interactive.instance_notice", instanceName));
|
|
14275
|
+
this.notifyInstanceTopic(instanceName, t("interactive.instance_notice", instanceName) + placeSuffix({ kind: "general" }, "General"));
|
|
13004
14276
|
// Multi-world fleets can have one General per bot/platform. Route the assist
|
|
13005
14277
|
// request to the General bound to the same adapter as the blocked instance.
|
|
13006
14278
|
const generalName = this.findGeneralInstance(this.getInstanceAdapterId(instanceName));
|
|
@@ -13011,7 +14283,7 @@ export class FleetManager {
|
|
|
13011
14283
|
const label = this.interactivePromptLabel(kind);
|
|
13012
14284
|
const prompt = {
|
|
13013
14285
|
prefix: INTERACTIVE_ASSIST_CALLBACK_PREFIX, alertType: "interactive_prompt", instanceName,
|
|
13014
|
-
message: t("interactive.general_notice", instanceName, label),
|
|
14286
|
+
message: t("interactive.general_notice", placeRef({ kind: "instance", name: instanceName }, instanceName), label),
|
|
13015
14287
|
choices: [{ action: "confirm", label: t("interactive.confirm") }, { action: "cancel", label: t("interactive.cancel") }],
|
|
13016
14288
|
expiredText: t("interactive.expired", instanceName),
|
|
13017
14289
|
extra: { generalName, promptKind: kind, assistFor: this.interactionWaitKey(instanceName) },
|
|
@@ -13882,7 +15154,12 @@ export class FleetManager {
|
|
|
13882
15154
|
fleetConfig: () => this.fleetConfig,
|
|
13883
15155
|
isFleetAdmin: (userId, adapterId) => this.isFleetAdmin(userId, adapterId),
|
|
13884
15156
|
eventLog: () => this.eventLog,
|
|
13885
|
-
recoverBackendInstances: (backend, profile) =>
|
|
15157
|
+
recoverBackendInstances: (backend, profile) => {
|
|
15158
|
+
// #2072: a sign-in just finished — the pickers learn it now, not at the next pass.
|
|
15159
|
+
if (!profile)
|
|
15160
|
+
void this.backendAvailability.refresh([backend], { force: true });
|
|
15161
|
+
return this.recoverBackendInstances(backend, undefined, profile ?? null);
|
|
15162
|
+
},
|
|
13886
15163
|
claimWindow: backend => this.loginWindow.tryClaim("web", backend),
|
|
13887
15164
|
releaseWindow: claim => { this.loginWindow.release(claim); },
|
|
13888
15165
|
isClaimCurrent: claim => this.loginWindow.isCurrent(claim),
|
|
@@ -14401,6 +15678,8 @@ export class FleetManager {
|
|
|
14401
15678
|
// binary the same way, so a binary only a login shell could see was
|
|
14402
15679
|
// installed, reported as verified, and then offered nowhere.
|
|
14403
15680
|
this.adoptBinaryDirectory(installedAt, backend);
|
|
15681
|
+
// #2072: an install just finished — the pickers learn it now, not at the next pass.
|
|
15682
|
+
void this.backendAvailability.refresh([backend], { force: true });
|
|
14404
15683
|
if (!LOGIN_FLOWS[backend]) {
|
|
14405
15684
|
this.installHandoff = null;
|
|
14406
15685
|
await chat.adapter.sendText(chat.chatId, t("install.success_no_login", backend), { threadId: chat.threadId }).catch(() => { });
|
|
@@ -14610,6 +15889,14 @@ export class FleetManager {
|
|
|
14610
15889
|
const room = this.classicChannels?.getAll().find(c => c.instanceName === name);
|
|
14611
15890
|
return room ? `room:${room.channelId}:${room.adapterId ?? ""}` : null;
|
|
14612
15891
|
}
|
|
15892
|
+
/** The only Try-card publisher: no arbitrary SSE sender/role can manufacture this metadata. */
|
|
15893
|
+
publishEffectTrial(instance, offer) {
|
|
15894
|
+
const row = this.webChatHistory.recordEffectTrial(instance, offer, new Date().toISOString());
|
|
15895
|
+
if (!row)
|
|
15896
|
+
return false;
|
|
15897
|
+
broadcastSseEvent(this.sseClients, "message", row, err => this.logger.debug({ err }, "SSE client write failed; evicting"), this.webChatHistory.cursorOf(row));
|
|
15898
|
+
return true;
|
|
15899
|
+
}
|
|
14613
15900
|
/** Push an SSE event to all connected Web UI clients. */
|
|
14614
15901
|
emitSseEvent(event, data) {
|
|
14615
15902
|
// #1386: a prompt opened or closed, or an instance's state moved — "Needs you" may have changed.
|
|
@@ -14626,8 +15913,14 @@ export class FleetManager {
|
|
|
14626
15913
|
role: typeof m.role === "string" ? m.role : undefined,
|
|
14627
15914
|
buttons: m.buttons,
|
|
14628
15915
|
click: m.click,
|
|
15916
|
+
links: m.links,
|
|
15917
|
+
channel: m.channel,
|
|
15918
|
+
from: m.from,
|
|
14629
15919
|
});
|
|
14630
15920
|
broadcastSseEvent(this.sseClients, event, recorded, onError, this.webChatHistory.cursorOf(recorded));
|
|
15921
|
+
// #1629: live-only receipt after the recorded agent reply. Never persist/replay it or give it an SSE cursor.
|
|
15922
|
+
if (recorded.role === "agent")
|
|
15923
|
+
broadcastSseEvent(this.sseClients, "agent_reply_live", { v: 1, boot: recorded.boot, id: recorded.id, instance: recorded.instance }, onError);
|
|
14631
15924
|
return;
|
|
14632
15925
|
}
|
|
14633
15926
|
// #1266: a reply's buttons ended — the history shows it too (a later load, the public link's poll).
|
|
@@ -14852,7 +16145,10 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
14852
16145
|
// can keep those copies current; other backends never had unmanaged
|
|
14853
16146
|
// AgEnD-published skills and must retain the normal user-ownership guard.
|
|
14854
16147
|
const adoptLegacyUnmanaged = backend === "kiro-cli" && role === "general";
|
|
14855
|
-
this.syncManagedSkills(join(workDir, ...skillSegments), join(root, "skills"), role, adoptLegacyUnmanaged
|
|
16148
|
+
this.syncManagedSkills(join(workDir, ...skillSegments), join(root, "skills"), role, adoptLegacyUnmanaged,
|
|
16149
|
+
// #2163: a Classic bot's skills folder (or a skill in it) may be a link out of its workspace; every path is
|
|
16150
|
+
// checked where it really lands, just before it is written.
|
|
16151
|
+
role === "classic" ? (path) => insideManagedWorkspaces(path) : undefined);
|
|
14856
16152
|
this.logger.debug({ workDir, backend, role }, "Synced role-based bundled skills");
|
|
14857
16153
|
}
|
|
14858
16154
|
/**
|
|
@@ -14938,11 +16234,22 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
14938
16234
|
* migration exception is the pre-manifest Kiro General layout explicitly
|
|
14939
16235
|
* selected by adoptLegacyUnmanaged.
|
|
14940
16236
|
*/
|
|
14941
|
-
syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false) {
|
|
16237
|
+
syncManagedSkills(destSkills, srcSkills, role, adoptLegacyUnmanaged = false, confined) {
|
|
14942
16238
|
if (!existsSync(srcSkills))
|
|
14943
16239
|
return;
|
|
16240
|
+
const refuse = (path) => {
|
|
16241
|
+
if (!confined || confined(path))
|
|
16242
|
+
return false;
|
|
16243
|
+
this.logger.warn({ path, destSkills }, "Not publishing skills — the path leads out of the managed workspace");
|
|
16244
|
+
return true;
|
|
16245
|
+
};
|
|
16246
|
+
if (refuse(destSkills))
|
|
16247
|
+
return;
|
|
14944
16248
|
mkdirSync(destSkills, { recursive: true });
|
|
14945
16249
|
const manifestPath = join(destSkills, ".agend-managed-skills.json");
|
|
16250
|
+
// Its ownership claims decide what is replaced or removed below: one that lives elsewhere is never believed.
|
|
16251
|
+
if (refuse(manifestPath))
|
|
16252
|
+
return;
|
|
14946
16253
|
const hadManifest = existsSync(manifestPath);
|
|
14947
16254
|
let previouslyManaged = [];
|
|
14948
16255
|
try {
|
|
@@ -14971,9 +16278,9 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
14971
16278
|
}
|
|
14972
16279
|
const eligible = bundled.filter(name => {
|
|
14973
16280
|
const roles = this.readManagedSkillRoles(join(srcSkills, name, "SKILL.md"));
|
|
14974
|
-
// General is the coordinator and receives
|
|
14975
|
-
//
|
|
14976
|
-
return role === "general" || roles.includes(
|
|
16281
|
+
// General is the coordinator and receives every playbook. Workers and Classic bots receive only skills
|
|
16282
|
+
// explicitly marked for their role (#2163).
|
|
16283
|
+
return role === "general" || roles.includes(role);
|
|
14977
16284
|
});
|
|
14978
16285
|
const managed = [];
|
|
14979
16286
|
for (const name of eligible) {
|
|
@@ -14990,6 +16297,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
14990
16297
|
}
|
|
14991
16298
|
managed.push(name);
|
|
14992
16299
|
const newContent = readFileSync(join(srcSkills, name, "SKILL.md"), "utf-8");
|
|
16300
|
+
if (refuse(dest))
|
|
16301
|
+
continue;
|
|
14993
16302
|
try {
|
|
14994
16303
|
if (existsSync(dest) && readFileSync(dest, "utf-8") === newContent)
|
|
14995
16304
|
continue;
|
|
@@ -15036,9 +16345,9 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15036
16345
|
if (!Array.isArray(frontmatter.roles))
|
|
15037
16346
|
throw new Error("roles must be an array");
|
|
15038
16347
|
const roles = [...new Set(frontmatter.roles)]
|
|
15039
|
-
.filter((value) => value === "general" || value === "worker");
|
|
16348
|
+
.filter((value) => value === "general" || value === "worker" || value === "classic");
|
|
15040
16349
|
if (roles.length !== frontmatter.roles.length || roles.length === 0) {
|
|
15041
|
-
throw new Error("roles must contain only general and/or
|
|
16350
|
+
throw new Error("roles must contain only general, worker and/or classic");
|
|
15042
16351
|
}
|
|
15043
16352
|
return roles;
|
|
15044
16353
|
}
|
|
@@ -15423,10 +16732,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15423
16732
|
this.logger.info(`${msg.username} → ${instanceName} (classic): ${text.slice(0, 100)}`);
|
|
15424
16733
|
// #1592: the web chat shows what was asked, as for every other inbound — the user's own words (no chat-log
|
|
15425
16734
|
// context), as a user (#1306: never a role read from text), in the room's history (#1565).
|
|
15426
|
-
this.
|
|
15427
|
-
instance: instanceName, sender: msg.username, role: "user",
|
|
15428
|
-
text: text.slice(0, WEB_CHAT_TEXT_MAX), ts: new Date().toISOString(),
|
|
15429
|
-
});
|
|
16735
|
+
this.emitPlatformInbound(instanceName, msg, text);
|
|
15430
16736
|
}
|
|
15431
16737
|
/** Paste raw text directly to a classic instance's CLI (no [user:] wrapping) */
|
|
15432
16738
|
/** #1690: our own runtime switches awaiting the daemon's outcome, by id. */
|
|
@@ -15464,7 +16770,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15464
16770
|
/** #1806: null on a switch INTO claude-code — the configured model then belongs to the backend being left. */
|
|
15465
16771
|
configured = this.fleetConfig?.instances[instanceName]?.model ?? this.fleetConfig?.defaults?.model) {
|
|
15466
16772
|
const aliases = ["default", "sonnet", "opus", "haiku", "opusplan", "Fable"];
|
|
15467
|
-
const api = (this.readCliEnv("claude-code")?.apiModels ?? []).map(m => m.id);
|
|
16773
|
+
const api = (this.readCliEnv("claude-code", this.catalogProfile("claude-code", instanceName))?.apiModels ?? []).map(m => m.id);
|
|
15468
16774
|
const lower = model.trim().toLowerCase();
|
|
15469
16775
|
const bare = lower.replace(/\[1m\]$/, "");
|
|
15470
16776
|
const known = aliases.some(a => a.toLowerCase() === bare)
|
|
@@ -15492,13 +16798,22 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15492
16798
|
: undefined;
|
|
15493
16799
|
return classic ?? this.fleetConfig?.defaults?.backend ?? "claude-code";
|
|
15494
16800
|
}
|
|
15495
|
-
|
|
15496
|
-
|
|
16801
|
+
/**
|
|
16802
|
+
* #2072: a catalog is the account's, so a credential profile has its own. Only claude-code's probe reads an account
|
|
16803
|
+
* catalog through a profile's login (its `GET /v1/models` with the profile's token); other backends' probes read the
|
|
16804
|
+
* process environment, so their catalog stays the backend's own.
|
|
16805
|
+
*/
|
|
16806
|
+
catalogProfile(backend, instanceName) {
|
|
16807
|
+
return backend === "claude-code" && instanceName ? this.credentialProfileOf(instanceName, backend) : null;
|
|
16808
|
+
}
|
|
16809
|
+
cliEnvPath(backend, profile = null) {
|
|
16810
|
+
const safe = (s) => s.replace(/[^A-Za-z0-9._-]/g, "_");
|
|
16811
|
+
return join(getAgendHome(), "cli-env", profile ? `${safe(backend)}@${safe(profile)}.json` : `${safe(backend)}.json`);
|
|
15497
16812
|
}
|
|
15498
|
-
/** Read the cached CLI env for a backend, or null if missing/stale/unparseable. */
|
|
15499
|
-
readCliEnv(backend) {
|
|
16813
|
+
/** Read the cached CLI env for a backend (a credential profile's own, when given), or null if missing/stale/unparseable. */
|
|
16814
|
+
readCliEnv(backend, profile = null) {
|
|
15500
16815
|
try {
|
|
15501
|
-
const env = JSON.parse(readFileSync(this.cliEnvPath(backend), "utf-8"));
|
|
16816
|
+
const env = JSON.parse(readFileSync(this.cliEnvPath(backend, profile), "utf-8"));
|
|
15502
16817
|
if (typeof env?.probedAt === "number" && Date.now() - env.probedAt < CLI_ENV_TTL_MS)
|
|
15503
16818
|
return env;
|
|
15504
16819
|
}
|
|
@@ -15541,10 +16856,12 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15541
16856
|
* previous list, never stall the command that asked for it.
|
|
15542
16857
|
*/
|
|
15543
16858
|
async probeBackendBounded(backend, opts = {}) {
|
|
15544
|
-
// #725: single-flight per backend. Explicit vendor refreshes remain a
|
|
16859
|
+
// #725: single-flight per backend (#2072: per backend and credential profile). Explicit vendor refreshes remain a
|
|
15545
16860
|
// separate flight from an ordinary probe, while sysinfo can join either.
|
|
15546
|
-
const
|
|
15547
|
-
const
|
|
16861
|
+
const profile = opts.profile ?? null;
|
|
16862
|
+
const key = profile ? `${backend}@${profile}` : backend;
|
|
16863
|
+
const regularFlight = this.pendingCliEnvProbes.get(key);
|
|
16864
|
+
const vendorFlight = this.pendingVendorCliEnvProbes.get(key);
|
|
15548
16865
|
if (opts.refreshVendorCatalog && vendorFlight)
|
|
15549
16866
|
return vendorFlight;
|
|
15550
16867
|
if (!opts.refreshVendorCatalog && (vendorFlight || regularFlight))
|
|
@@ -15555,25 +16872,26 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15555
16872
|
const epoch = this.cliEnvProbeEpoch;
|
|
15556
16873
|
const input = {
|
|
15557
16874
|
mode: "env", backend, instanceDir,
|
|
15558
|
-
config: { workingDirectory: "", instanceDir, instanceName: `probe-${backend}`, mcpServers: {}
|
|
16875
|
+
config: { workingDirectory: "", instanceDir, instanceName: `probe-${backend}`, mcpServers: {},
|
|
16876
|
+
...(profile ? { credentialStoreHome: credentialProfileStoreHome(getAgendHome(), backend, profile) } : {}) },
|
|
15559
16877
|
refreshVendorCatalog: opts.refreshVendorCatalog === true,
|
|
15560
16878
|
};
|
|
15561
|
-
const bounded = this.runBackendProbeWorker(`global:${
|
|
16879
|
+
const bounded = this.runBackendProbeWorker(`global:${key}`, input).then(probed => {
|
|
15562
16880
|
if (!probed || Array.isArray(probed) || this.shuttingDown || epoch !== this.cliEnvProbeEpoch)
|
|
15563
16881
|
return null;
|
|
15564
16882
|
try {
|
|
15565
|
-
return this.persistCliEnvProbeResult(backend, probed);
|
|
16883
|
+
return this.persistCliEnvProbeResult(backend, probed, profile);
|
|
15566
16884
|
}
|
|
15567
16885
|
catch (err) {
|
|
15568
|
-
this.logger.warn({ backend, err }, "CLI env cache write failed");
|
|
16886
|
+
this.logger.warn({ backend, profile, err }, "CLI env cache write failed");
|
|
15569
16887
|
return null;
|
|
15570
16888
|
}
|
|
15571
16889
|
}).finally(() => {
|
|
15572
16890
|
const flights = opts.refreshVendorCatalog ? this.pendingVendorCliEnvProbes : this.pendingCliEnvProbes;
|
|
15573
|
-
if (flights.get(
|
|
15574
|
-
flights.delete(
|
|
16891
|
+
if (flights.get(key) === bounded)
|
|
16892
|
+
flights.delete(key);
|
|
15575
16893
|
});
|
|
15576
|
-
(opts.refreshVendorCatalog ? this.pendingVendorCliEnvProbes : this.pendingCliEnvProbes).set(
|
|
16894
|
+
(opts.refreshVendorCatalog ? this.pendingVendorCliEnvProbes : this.pendingCliEnvProbes).set(key, bounded);
|
|
15577
16895
|
return bounded;
|
|
15578
16896
|
}
|
|
15579
16897
|
stopCliEnvProbes() {
|
|
@@ -15688,12 +17006,21 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15688
17006
|
modelDisplayForInstance(instanceName) {
|
|
15689
17007
|
return this.resolveInstanceModel(instanceName).display;
|
|
15690
17008
|
}
|
|
17009
|
+
/**
|
|
17010
|
+
* #2072: the model an instance runs is always among its choices — one its CLI's catalog does not list (an older
|
|
17011
|
+
* name, a custom provider's, a typed one) is shown first, marked, so the menu never hides what is running.
|
|
17012
|
+
*/
|
|
17013
|
+
withCurrentModel(options, currentModel) {
|
|
17014
|
+
if (!currentModel || currentModel === "default" || options.some(o => o.id === currentModel))
|
|
17015
|
+
return options;
|
|
17016
|
+
return [{ id: currentModel, label: currentModel, description: t("model.not_listed") }, ...options];
|
|
17017
|
+
}
|
|
15691
17018
|
modelChoiceLabel(option, currentModel) {
|
|
15692
17019
|
const label = option.description ? `${option.label} — ${option.description}` : option.label;
|
|
15693
17020
|
return option.id === currentModel ? `✓ ${label}` : label;
|
|
15694
17021
|
}
|
|
15695
17022
|
/** Preserve the existing cache merge rules for worker probes. */
|
|
15696
|
-
persistCliEnvProbeResult(backend, probed) {
|
|
17023
|
+
persistCliEnvProbeResult(backend, probed, profile = null) {
|
|
15697
17024
|
const env = { backend, probedAt: Date.now(), ...probed };
|
|
15698
17025
|
// An empty result must never overwrite a catalog we already have. Some
|
|
15699
17026
|
// probes hit the network (`agy models` fetches, 5s cap), so a slow moment
|
|
@@ -15702,14 +17029,14 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15702
17029
|
// antigravity cache replaced by an empty one. Keep the known models and
|
|
15703
17030
|
// let the fresher currentModel/version through.
|
|
15704
17031
|
if (!env.models?.length) {
|
|
15705
|
-
const previous = this.readCliEnv(backend);
|
|
17032
|
+
const previous = this.readCliEnv(backend, profile);
|
|
15706
17033
|
if (previous?.models?.length)
|
|
15707
17034
|
env.models = previous.models;
|
|
15708
17035
|
}
|
|
15709
17036
|
// Same protection for the extended catalog: one offline moment must not
|
|
15710
17037
|
// blank a good account list for the whole cache TTL.
|
|
15711
17038
|
if (!env.apiModels?.length) {
|
|
15712
|
-
const previous = this.readCliEnv(backend);
|
|
17039
|
+
const previous = this.readCliEnv(backend, profile);
|
|
15713
17040
|
if (previous?.apiModels?.length)
|
|
15714
17041
|
env.apiModels = previous.apiModels;
|
|
15715
17042
|
}
|
|
@@ -15717,12 +17044,12 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15717
17044
|
// keeps the cached levels only for that same binary: both versions known and equal, cache still valid. A help
|
|
15718
17045
|
// that was read and lists none ([]) is an answer and is written as is, so the fallback applies.
|
|
15719
17046
|
if (env.effortLevels === undefined) {
|
|
15720
|
-
const previous = this.readCliEnv(backend);
|
|
17047
|
+
const previous = this.readCliEnv(backend, profile);
|
|
15721
17048
|
if (previous?.effortLevels && previous.version && env.version && previous.version === env.version) {
|
|
15722
17049
|
env.effortLevels = previous.effortLevels;
|
|
15723
17050
|
}
|
|
15724
17051
|
}
|
|
15725
|
-
const path = this.cliEnvPath(backend);
|
|
17052
|
+
const path = this.cliEnvPath(backend, profile);
|
|
15726
17053
|
mkdirSync(dirname(path), { recursive: true });
|
|
15727
17054
|
writeFileSync(path, JSON.stringify(env, null, 2));
|
|
15728
17055
|
return env;
|
|
@@ -15744,6 +17071,18 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15744
17071
|
// indefinitely — each is wrapped by CLI_ENV_PROBE_DEADLINE_MS.
|
|
15745
17072
|
for (const b of backends)
|
|
15746
17073
|
void this.probeBackendBounded(b);
|
|
17074
|
+
// #2072: each Claude credential profile in use has its own account catalog. Only fleet.yaml's agents are walked
|
|
17075
|
+
// here; a ClassicBot room on a profile is probed on its first /model (catalogProfile knows rooms too).
|
|
17076
|
+
const profiles = new Set();
|
|
17077
|
+
for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
|
|
17078
|
+
if (this.backendNameForInstance(name) !== "claude-code")
|
|
17079
|
+
continue;
|
|
17080
|
+
const profile = this.catalogProfile("claude-code", name);
|
|
17081
|
+
if (profile)
|
|
17082
|
+
profiles.add(profile);
|
|
17083
|
+
}
|
|
17084
|
+
for (const profile of profiles)
|
|
17085
|
+
void this.probeBackendBounded("claude-code", { profile });
|
|
15747
17086
|
}
|
|
15748
17087
|
/** Best-effort model list for `/model`: cached CLI env first, else live probe. Never throws. */
|
|
15749
17088
|
async getModelOptions(instanceName, refresh = false, onLiveProbe) {
|
|
@@ -15757,7 +17096,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15757
17096
|
*/
|
|
15758
17097
|
async getModelOptionsWithSource(instanceName, opts = {}) {
|
|
15759
17098
|
const backendName = this.backendNameForInstance(instanceName);
|
|
15760
|
-
const
|
|
17099
|
+
const profile = this.catalogProfile(backendName, instanceName);
|
|
17100
|
+
const cached = this.readCliEnv(backendName, profile);
|
|
15761
17101
|
if (!opts.refresh && cached?.models.length && !this.cliEnvNeedsRefresh(cached)) {
|
|
15762
17102
|
return { models: cached.models, source: "cache" };
|
|
15763
17103
|
}
|
|
@@ -15768,7 +17108,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15768
17108
|
// Stale, missing, or a forced refresh → probe live (also refreshes the cache).
|
|
15769
17109
|
// A newly released model is invisible until this runs, which is why staleness
|
|
15770
17110
|
// triggers it rather than waiting for the 24h hard expiry or a cold start.
|
|
15771
|
-
const env = await this.probeBackendBounded(backendName, { refreshVendorCatalog: opts.refreshVendorCatalog });
|
|
17111
|
+
const env = await this.probeBackendBounded(backendName, { refreshVendorCatalog: opts.refreshVendorCatalog, profile });
|
|
15772
17112
|
if (env?.models.length)
|
|
15773
17113
|
return { models: env.models, source: "live" };
|
|
15774
17114
|
// Probe failed or timed out: the previous list is still the best answer.
|
|
@@ -15783,7 +17123,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
15783
17123
|
modelMenuChoices(instanceName, nonce, options, currentModel) {
|
|
15784
17124
|
const isClaude = this.backendNameForInstance(instanceName) === "claude-code";
|
|
15785
17125
|
const choices = [{ id: `${MODEL_SELECT_CALLBACK_PREFIX}${nonce}:__refresh__`, label: t("model.refresh") }];
|
|
15786
|
-
for (const o of options.slice(0, isClaude ? 23 : 24)) {
|
|
17126
|
+
for (const o of this.withCurrentModel(options, currentModel).slice(0, isClaude ? 23 : 24)) {
|
|
15787
17127
|
choices.push({ id: `${MODEL_SELECT_CALLBACK_PREFIX}${nonce}:${o.id}`, label: this.modelChoiceLabel(o, currentModel) });
|
|
15788
17128
|
}
|
|
15789
17129
|
if (isClaude)
|
|
@@ -16190,16 +17530,18 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
16190
17530
|
}
|
|
16191
17531
|
}
|
|
16192
17532
|
/** Cached-or-live account catalog behind "/model → more models" (claude). */
|
|
16193
|
-
async claudeApiModelOptions() {
|
|
16194
|
-
|
|
17533
|
+
async claudeApiModelOptions(instanceName) {
|
|
17534
|
+
// #2072: the account behind THIS instance — its credential profile's catalog, else the default login's.
|
|
17535
|
+
const profile = this.catalogProfile("claude-code", instanceName);
|
|
17536
|
+
const cached = this.readCliEnv("claude-code", profile);
|
|
16195
17537
|
if (cached?.apiModels?.length)
|
|
16196
17538
|
return cached.apiModels;
|
|
16197
|
-
const env = await this.probeBackendBounded("claude-code");
|
|
17539
|
+
const env = await this.probeBackendBounded("claude-code", { profile });
|
|
16198
17540
|
return env?.apiModels ?? [];
|
|
16199
17541
|
}
|
|
16200
17542
|
/** Replace a consumed "/model" menu with the full account catalog tier. */
|
|
16201
17543
|
async expandClaudeModelMenu(pending) {
|
|
16202
|
-
const expanded = await this.claudeApiModelOptions();
|
|
17544
|
+
const expanded = await this.claudeApiModelOptions(pending.instanceName);
|
|
16203
17545
|
if (!expanded.length) {
|
|
16204
17546
|
await pending.respond(t("model.more_unavailable")).catch(() => { });
|
|
16205
17547
|
return;
|
|
@@ -16627,7 +17969,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
16627
17969
|
return {
|
|
16628
17970
|
currentBackend: (name) => this.backendNameForInstance(name),
|
|
16629
17971
|
currentDisplay: (name) => `${this.backendNameForInstance(name)} · ${this.resolveInstanceModel(name).display}`,
|
|
16630
|
-
|
|
17972
|
+
availability: () => this.backendAvailabilityFor(instanceName),
|
|
16631
17973
|
models: (backend) => this.backendModelOptions(backend, opts),
|
|
16632
17974
|
// #1808: the same rule update_instance_config's switch applies (backendModelVerdict).
|
|
16633
17975
|
modelKnown: (backend, model) => this.backendModelVerdict(instanceName, backend, model).ok,
|
|
@@ -16726,10 +18068,76 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
16726
18068
|
// kiro-cli gates its own --effort by version at launch (a quiet console note otherwise); muse always passes it.
|
|
16727
18069
|
return () => true;
|
|
16728
18070
|
}
|
|
16729
|
-
/**
|
|
16730
|
-
|
|
16731
|
-
|
|
16732
|
-
|
|
18071
|
+
/**
|
|
18072
|
+
* #2072: what this host can run, from the published availability snapshot (backend-availability.ts). Read only: a
|
|
18073
|
+
* handler never starts a probe, not even in the background — launch, the timer, and /login install or sign-in do.
|
|
18074
|
+
*/
|
|
18075
|
+
backendAvailabilityRows() {
|
|
18076
|
+
return this.backendAvailability.snapshot();
|
|
18077
|
+
}
|
|
18078
|
+
/**
|
|
18079
|
+
* #2072 part 3: the models a Settings field offers for `backend` — the cached catalog (an instance's own credential
|
|
18080
|
+
* profile's, when it is named and has one), claude's account catalog included. Read only: never a probe.
|
|
18081
|
+
*/
|
|
18082
|
+
modelCatalogFor(backend, instance) {
|
|
18083
|
+
if (!KNOWN_BACKENDS.includes(backend) || backend === "mock")
|
|
18084
|
+
return [];
|
|
18085
|
+
const own = instance && Object.prototype.hasOwnProperty.call(this.fleetConfig?.instances ?? {}, instance) ? instance
|
|
18086
|
+
: instance && this.classicChannels?.getChannelIdByInstance(instance) !== undefined ? instance : null;
|
|
18087
|
+
const env = this.readCliEnv(backend, this.catalogProfile(backend, own));
|
|
18088
|
+
const seen = new Set(), out = [];
|
|
18089
|
+
for (const m of [...(env?.models ?? []), ...(env?.apiModels ?? [])])
|
|
18090
|
+
if (!seen.has(m.id)) {
|
|
18091
|
+
seen.add(m.id);
|
|
18092
|
+
out.push(m);
|
|
18093
|
+
}
|
|
18094
|
+
return out;
|
|
18095
|
+
}
|
|
18096
|
+
/**
|
|
18097
|
+
* #2072 (#2078 review): the snapshot as THIS instance would see it. Its sign-in on a backend is its own credential
|
|
18098
|
+
* profile's when it has one there — the host's default login says nothing about it. A profile's login is a file check
|
|
18099
|
+
* (credentialProfileLogin), no process.
|
|
18100
|
+
*/
|
|
18101
|
+
backendAvailabilityFor(instanceName) {
|
|
18102
|
+
return this.backendAvailabilityRows().map(row => {
|
|
18103
|
+
const profile = this.credentialProfileOf(instanceName, row.backend);
|
|
18104
|
+
if (!profile || (row.state !== "usable" && row.state !== "not_signed_in" && row.state !== "unknown") || !row.path)
|
|
18105
|
+
return row;
|
|
18106
|
+
let login = "unknown";
|
|
18107
|
+
try {
|
|
18108
|
+
login = credentialProfileLogin(this.dataDir, row.backend, profile).state;
|
|
18109
|
+
}
|
|
18110
|
+
catch { /* unknown */ }
|
|
18111
|
+
// Signed in there: usable for this instance. Signed out (or unknown): the host's default login says nothing about
|
|
18112
|
+
// it, so no "not signed in" claim from it — update_instance_config's profile gate refuses a signed-out profile
|
|
18113
|
+
// when applied, naming the profile and the command that signs it in.
|
|
18114
|
+
if (login === "logged-in")
|
|
18115
|
+
return { ...row, auth: "valid", state: "usable" };
|
|
18116
|
+
return row.state === "not_signed_in" ? { ...row, auth: "unknown", state: "unknown" } : row;
|
|
18117
|
+
});
|
|
18118
|
+
}
|
|
18119
|
+
/** The probes the snapshot runs (tests replace them: no CLI, no account, no network). */
|
|
18120
|
+
availabilityProbes = hostAvailabilityProbes;
|
|
18121
|
+
availabilityStore = null;
|
|
18122
|
+
availabilityTimer = null;
|
|
18123
|
+
get backendAvailability() {
|
|
18124
|
+
return this.availabilityStore ??= new BackendAvailabilityStore(KNOWN_BACKENDS.filter(b => b !== "mock" && !!BACKEND_INSTALLATION_INFO[b]), this.availabilityProbes, { onChange: () => this.noteAvailabilityPaths() });
|
|
18125
|
+
}
|
|
18126
|
+
/** A launch need not look the binary up again (a synchronous `which` on the loop) when the snapshot found it. */
|
|
18127
|
+
noteAvailabilityPaths() {
|
|
18128
|
+
for (const row of this.availabilityStore?.snapshot() ?? []) {
|
|
18129
|
+
const binary = BACKEND_INSTALLATION_INFO[row.backend]?.binary;
|
|
18130
|
+
if (binary)
|
|
18131
|
+
noteResolvedBinary(binary, row.state === "not_installed" ? null : row.path);
|
|
18132
|
+
}
|
|
18133
|
+
}
|
|
18134
|
+
/** Probe now and then every AVAILABILITY_STALE_MS; a pass that finds nothing changed starts no CLI. */
|
|
18135
|
+
startAvailabilityRefresh() {
|
|
18136
|
+
void this.backendAvailability.refresh();
|
|
18137
|
+
if (this.availabilityTimer)
|
|
18138
|
+
clearInterval(this.availabilityTimer);
|
|
18139
|
+
this.availabilityTimer = setInterval(() => { void this.backendAvailability.refresh(); }, AVAILABILITY_STALE_MS);
|
|
18140
|
+
this.availabilityTimer.unref?.();
|
|
16733
18141
|
}
|
|
16734
18142
|
/** The models `/model` would offer on a backend: the cached CLI env, else (live) a bounded probe. Never throws. */
|
|
16735
18143
|
async backendModelOptions(backend, opts) {
|
|
@@ -17071,9 +18479,11 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
17071
18479
|
}
|
|
17072
18480
|
return undefined;
|
|
17073
18481
|
}
|
|
18482
|
+
/** #2072: from the published snapshot (no `which` on the loop); not checked yet counts as installed (no false alarm). */
|
|
17074
18483
|
isBackendInstalled(backend) {
|
|
17075
|
-
|
|
17076
|
-
|
|
18484
|
+
if (!BACKEND_INSTALLATION_INFO[backend])
|
|
18485
|
+
return false;
|
|
18486
|
+
return this.backendAvailability.get(backend)?.state !== "not_installed";
|
|
17077
18487
|
}
|
|
17078
18488
|
getMissingBackendWarning(backend) {
|
|
17079
18489
|
if (!backend)
|
|
@@ -17295,6 +18705,14 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
17295
18705
|
catch (err) {
|
|
17296
18706
|
this.logger.warn({ err: err.message, instanceName: ch.instanceName }, "Dropping a removed room from web favorites failed");
|
|
17297
18707
|
}
|
|
18708
|
+
try {
|
|
18709
|
+
this.themeStore.forget(ch.instanceName);
|
|
18710
|
+
this.webAppearance.limiter.forget(ch.instanceName);
|
|
18711
|
+
this.effectToolsService?.forget(ch.instanceName);
|
|
18712
|
+
}
|
|
18713
|
+
catch (err) {
|
|
18714
|
+
this.logger.warn({ err: err.message, instanceName: ch.instanceName }, "Dropping a removed room's web theme failed");
|
|
18715
|
+
}
|
|
17298
18716
|
}
|
|
17299
18717
|
this.instanceWorldBinding.delete(ch.instanceName);
|
|
17300
18718
|
// #1716: say so in the reply when background work was ended with the stop.
|
|
@@ -17403,6 +18821,10 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
17403
18821
|
clearInterval(this.eventLogPruneTimer);
|
|
17404
18822
|
this.eventLogPruneTimer = null;
|
|
17405
18823
|
}
|
|
18824
|
+
if (this.guestRoomsTimer) {
|
|
18825
|
+
clearInterval(this.guestRoomsTimer);
|
|
18826
|
+
this.guestRoomsTimer = null;
|
|
18827
|
+
}
|
|
17406
18828
|
this.logService?.unwatchAll(); // #1218: a Log's watch timers end with the fleet
|
|
17407
18829
|
this.compactWatchService?.stopAll();
|
|
17408
18830
|
if (this.outboxPruneTimer) {
|
|
@@ -17502,6 +18924,10 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
17502
18924
|
this.adapters.clear();
|
|
17503
18925
|
this.controlClient?.stop();
|
|
17504
18926
|
this.controlClient = null;
|
|
18927
|
+
if (this.availabilityTimer) {
|
|
18928
|
+
clearInterval(this.availabilityTimer);
|
|
18929
|
+
this.availabilityTimer = null;
|
|
18930
|
+
}
|
|
17505
18931
|
if (this.healthServer) {
|
|
17506
18932
|
this.healthServerListening = false;
|
|
17507
18933
|
const server = this.healthServer;
|
|
@@ -19486,6 +20912,159 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19486
20912
|
this.rejectedHostsLogged.add(name);
|
|
19487
20913
|
this.logger.warn({ host: name }, "Web request refused: Host is not allowed (add it to web.allowed_hosts if this is a proxy you run)");
|
|
19488
20914
|
}
|
|
20915
|
+
/**
|
|
20916
|
+
* #1920 §3: the instances a guest session may see — derived on every request from the account's chat access, never
|
|
20917
|
+
* stored; nothing while `web.guests.enabled` is not true.
|
|
20918
|
+
* - Its connection's fleet topics and General (what it may talk to in chat): when that connection's access lets the
|
|
20919
|
+
* account in (AccessManager.isAllowed — allowed_users or paired). An `open` connection lets everyone in, so it gives
|
|
20920
|
+
* only the instances an admin named for its guests (`web.guests.open_instances`; the user's decision: least
|
|
20921
|
+
* privilege, as an open group has no list of people).
|
|
20922
|
+
* - A Telegram private ClassicBot room that is the account's own (its chat id is the user id).
|
|
20923
|
+
* - A ClassicBot group or guild room on its connection: only while its membership is verified (§3.2 — a "member"
|
|
20924
|
+
* answer read in the background, at most 15 minutes old; unknown, failed or stale hides it).
|
|
20925
|
+
* - Then an admin's narrowing (`web.guests.narrow`), which only takes away.
|
|
20926
|
+
* A fleet admin is not a guest: an admin outside the connection's access gets nothing here (admins sign in as admins).
|
|
20927
|
+
*/
|
|
20928
|
+
guestScope(owner) {
|
|
20929
|
+
const guests = this.fleetConfig?.web?.guests;
|
|
20930
|
+
if (!owner || guests?.enabled !== true)
|
|
20931
|
+
return NO_GUEST_SCOPE;
|
|
20932
|
+
const scope = new Set(this.guestReach(owner));
|
|
20933
|
+
const narrow = guests.narrow && Object.hasOwn(guests.narrow, `${owner.adapterId}:${owner.userId}`) ? guests.narrow[`${owner.adapterId}:${owner.userId}`] : undefined;
|
|
20934
|
+
if (narrow) {
|
|
20935
|
+
const keep = new Set(narrow);
|
|
20936
|
+
for (const name of [...scope])
|
|
20937
|
+
if (!keep.has(name))
|
|
20938
|
+
scope.delete(name);
|
|
20939
|
+
}
|
|
20940
|
+
return scope.size ? scope : NO_GUEST_SCOPE;
|
|
20941
|
+
}
|
|
20942
|
+
/**
|
|
20943
|
+
* #1920 (#2104 review): what an account reaches before an admin's narrowing — its connection's topics (an open one's
|
|
20944
|
+
* named agents), its own Telegram private room, its verified group rooms. Narrowing can only take from this set, so it
|
|
20945
|
+
* is what Settings offers to narrow to. Empty while guest sign-in is off.
|
|
20946
|
+
*/
|
|
20947
|
+
guestReach(owner) {
|
|
20948
|
+
const guests = this.fleetConfig?.web?.guests;
|
|
20949
|
+
const scope = new Set();
|
|
20950
|
+
if (guests?.enabled !== true)
|
|
20951
|
+
return scope;
|
|
20952
|
+
const own = (map, key) => (map && Object.hasOwn(map, key) ? map[key] : undefined);
|
|
20953
|
+
const world = this.worlds.get(owner.adapterId);
|
|
20954
|
+
if (world && world.accessManager.isAllowed(owner.userId)) {
|
|
20955
|
+
const named = world.accessManager.getMode() === "open" ? new Set(own(guests.open_instances, owner.adapterId) ?? []) : null;
|
|
20956
|
+
for (const name of Object.keys(this.fleetConfig?.instances ?? {})) {
|
|
20957
|
+
if (this.getInstanceAdapterId(name) !== owner.adapterId || this.isClassicInstance(name))
|
|
20958
|
+
continue;
|
|
20959
|
+
if (!named || named.has(name))
|
|
20960
|
+
scope.add(name);
|
|
20961
|
+
}
|
|
20962
|
+
}
|
|
20963
|
+
const rooms = this.classicChannels?.getAll() ?? [];
|
|
20964
|
+
for (const room of rooms) {
|
|
20965
|
+
if (this.isOwnPrivateRoom(owner, room))
|
|
20966
|
+
scope.add(room.instanceName);
|
|
20967
|
+
}
|
|
20968
|
+
const members = this.guestRooms();
|
|
20969
|
+
for (const room of guestGroupRooms(rooms, owner)) {
|
|
20970
|
+
if (members.verified(room, owner.userId))
|
|
20971
|
+
scope.add(room.instance);
|
|
20972
|
+
}
|
|
20973
|
+
return scope;
|
|
20974
|
+
}
|
|
20975
|
+
/**
|
|
20976
|
+
* #1920 §3.5: a guest session still admitted — current, with something in scope. A scope that became empty (guest
|
|
20977
|
+
* sign-in off, the account removed from the connection's access, everything narrowed away) ends the session here,
|
|
20978
|
+
* so the next request and the open stream find it gone.
|
|
20979
|
+
*/
|
|
20980
|
+
guestStillAdmitted(record) {
|
|
20981
|
+
return this.guestAdmission(record) === "ok";
|
|
20982
|
+
}
|
|
20983
|
+
/**
|
|
20984
|
+
* The same, with a third answer (§3.2): "pending" — nothing in scope now, but a room's membership is not read yet
|
|
20985
|
+
* (a restart, a room just created). The request is refused and the session kept; its read starts in the background.
|
|
20986
|
+
*/
|
|
20987
|
+
guestAdmission(record) {
|
|
20988
|
+
if (!this.webSessions || !this.webToken || !this.webSessions.isCurrent(record, tokenEpoch(this.webToken)))
|
|
20989
|
+
return "gone";
|
|
20990
|
+
const owner = record.owner;
|
|
20991
|
+
if (this.guestScope(owner).size)
|
|
20992
|
+
return "ok";
|
|
20993
|
+
if (owner && this.fleetConfig?.web?.guests?.enabled === true) {
|
|
20994
|
+
const members = this.guestRooms(), rooms = guestGroupRooms(this.classicChannels?.getAll() ?? [], owner);
|
|
20995
|
+
if (rooms.some((room) => members.pending(room, owner.userId))) {
|
|
20996
|
+
void this.refreshGuestRooms(owner, { mode: "triggered" }); // rate-limited per room (30 s), single-flight
|
|
20997
|
+
return "pending";
|
|
20998
|
+
}
|
|
20999
|
+
}
|
|
21000
|
+
this.enforceGuestSwitch();
|
|
21001
|
+
const ended = this.webSessions.revokeByHandle(record.handle);
|
|
21002
|
+
if (ended.found)
|
|
21003
|
+
this.logger.info({ adapterId: record.owner?.adapterId, durable: ended.durable }, "Guest web session ended: nothing left in its scope");
|
|
21004
|
+
return "gone";
|
|
21005
|
+
}
|
|
21006
|
+
/** #1920 §3.2: the membership answers; the read goes to the room's own connection, never waits past its deadline. */
|
|
21007
|
+
guestRooms() {
|
|
21008
|
+
this.guestRoomMembership ??= new GuestRoomMembership({
|
|
21009
|
+
now: () => performance.now(),
|
|
21010
|
+
read: (room, userId) => {
|
|
21011
|
+
const adapter = this.worlds.get(room.adapterId)?.adapter;
|
|
21012
|
+
return room.kind === "telegram" ? adapter?.isGroupMember?.(room.channelId, userId) : adapter?.canViewChannel?.(room.channelId, userId);
|
|
21013
|
+
},
|
|
21014
|
+
// Said once per key while its reads keep failing (no user id: the room and connection are what an admin fixes).
|
|
21015
|
+
onPersistentFailure: (room, failures) => this.logger.warn({ adapterId: room.adapterId, instance: room.instance, failures }, "Guest room membership keeps failing to read (the bot may lack the permission, or was removed); retrying with backoff up to 10 minutes"),
|
|
21016
|
+
onRecovered: (room) => this.logger.info({ adapterId: room.adapterId, instance: room.instance }, "Guest room membership reads again"),
|
|
21017
|
+
});
|
|
21018
|
+
return this.guestRoomMembership;
|
|
21019
|
+
}
|
|
21020
|
+
/** #1920 §3.2: read this guest's rooms that are due (GuestRoomMembership.refresh says when each mode reads). */
|
|
21021
|
+
async refreshGuestRooms(owner, opts = {}) {
|
|
21022
|
+
if (this.fleetConfig?.web?.guests?.enabled !== true)
|
|
21023
|
+
return;
|
|
21024
|
+
try {
|
|
21025
|
+
await this.guestRooms().refresh(owner, guestGroupRooms(this.classicChannels?.getAll() ?? [], owner), opts);
|
|
21026
|
+
}
|
|
21027
|
+
catch (err) {
|
|
21028
|
+
this.logger.warn({ err: err.message }, "Guest room membership could not be read");
|
|
21029
|
+
}
|
|
21030
|
+
}
|
|
21031
|
+
/** Every account with a live guest session, one after another (the guest caps bound them); one pass at a time. */
|
|
21032
|
+
async refreshAllGuestRooms() {
|
|
21033
|
+
if (this.guestRoomsPass || this.fleetConfig?.web?.guests?.enabled !== true || !this.webSessions)
|
|
21034
|
+
return;
|
|
21035
|
+
this.guestRoomsPass = true;
|
|
21036
|
+
try {
|
|
21037
|
+
for (const owner of this.webSessions.guestOwners())
|
|
21038
|
+
await this.refreshGuestRooms(owner);
|
|
21039
|
+
}
|
|
21040
|
+
finally {
|
|
21041
|
+
this.guestRoomsPass = false;
|
|
21042
|
+
}
|
|
21043
|
+
}
|
|
21044
|
+
guestRoomsPass = false;
|
|
21045
|
+
/**
|
|
21046
|
+
* #1920 §3.5: guest sign-in turned off ends every guest session — checked when the configuration is read or saved
|
|
21047
|
+
* and when the sessions are opened, so turning it back on never revives one.
|
|
21048
|
+
*/
|
|
21049
|
+
enforceGuestSwitch() {
|
|
21050
|
+
if (this.fleetConfig?.web?.guests?.enabled === true || !this.webSessions)
|
|
21051
|
+
return;
|
|
21052
|
+
const ended = this.webSessions.revokeAll((r) => r.tier === "guest");
|
|
21053
|
+
if (ended.count)
|
|
21054
|
+
this.logger.info({ count: ended.count, durable: ended.durable }, "Guest web sign-in is off: every guest session ended");
|
|
21055
|
+
// #1920 step 4b: and every guest's returning device — turning it back on lets no old browser ask for a code.
|
|
21056
|
+
const devices = this.returningDevices?.revokeGuest();
|
|
21057
|
+
if (devices?.count)
|
|
21058
|
+
this.logger.info({ count: devices.count, durable: devices.durable }, "Guest web sign-in is off: every guest's returning device forgotten");
|
|
21059
|
+
}
|
|
21060
|
+
/** #1920 §5.2: whether this instance is the account's own Telegram private ClassicBot room (its chat id is the user id). */
|
|
21061
|
+
guestOwnRoom(owner, instance) {
|
|
21062
|
+
return (this.classicChannels?.getAll() ?? []).some((room) => room.instanceName === instance && this.isOwnPrivateRoom(owner, room));
|
|
21063
|
+
}
|
|
21064
|
+
/** A private room's chat id is its one user's id (a group's is negative, so never equal); Telegram only. */
|
|
21065
|
+
isOwnPrivateRoom(owner, room) {
|
|
21066
|
+
return room.adapterId === owner.adapterId && room.channelId === owner.userId && inferClassicChannelType(room.channelId) === "telegram";
|
|
21067
|
+
}
|
|
19489
21068
|
/** Shared handler dispatcher; gateway admission is enforced by its separate listener. */
|
|
19490
21069
|
dispatchWebHttp(req, res, port, closing = false) {
|
|
19491
21070
|
try {
|
|
@@ -19516,6 +21095,8 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19516
21095
|
return;
|
|
19517
21096
|
}
|
|
19518
21097
|
const requestPath = new URL(req.url ?? "/", `http://localhost:${port}`).pathname;
|
|
21098
|
+
if (this.effectBootstrap.handle(req, res))
|
|
21099
|
+
return;
|
|
19519
21100
|
// Branding is public, after Host admission: automatic favicon requests
|
|
19520
21101
|
// must not become noisy web-token 401s in the browser console.
|
|
19521
21102
|
if (handleWebIconRequest(req, res, requestPath))
|
|
@@ -19546,6 +21127,40 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19546
21127
|
res.end(JSON.stringify({ error: decision.message }));
|
|
19547
21128
|
return;
|
|
19548
21129
|
}
|
|
21130
|
+
// #1920: a guest reaches only GUEST_ROUTES, within the scope derived for it now — default deny, before any
|
|
21131
|
+
// handler, on this listener and the public link's gateway alike (both come through here).
|
|
21132
|
+
if (decision.via === "session" && decision.session.tier === "guest") {
|
|
21133
|
+
const owner = decision.session.owner;
|
|
21134
|
+
const admitted = decision.session;
|
|
21135
|
+
const admission = this.guestAdmission(admitted);
|
|
21136
|
+
if (admission === "pending") {
|
|
21137
|
+
// §3.2: a room's membership is being read — try again shortly; the session stays.
|
|
21138
|
+
res.writeHead(503, { "Retry-After": "5" });
|
|
21139
|
+
res.end(JSON.stringify({ error: "guest_scope_pending" }));
|
|
21140
|
+
return;
|
|
21141
|
+
}
|
|
21142
|
+
if (admission === "gone") {
|
|
21143
|
+
res.writeHead(401);
|
|
21144
|
+
res.end(JSON.stringify({ error: "guest_scope_empty" }));
|
|
21145
|
+
return;
|
|
21146
|
+
}
|
|
21147
|
+
const verdict = guestRouteDecision(req.method ?? "GET", parsedUrl, this.guestScope(owner));
|
|
21148
|
+
if (verdict.kind === "deny") {
|
|
21149
|
+
res.writeHead(verdict.status);
|
|
21150
|
+
res.end(JSON.stringify({ error: verdict.error }));
|
|
21151
|
+
return;
|
|
21152
|
+
}
|
|
21153
|
+
// Phase 1b: the handlers that answer per recipient (the stream, the poll, a file) know it is a guest's, and
|
|
21154
|
+
// ask its scope anew each time; an emptied scope ends the session (and closes its stream).
|
|
21155
|
+
bindGuestRequest(req, { owner, scope: () => this.guestScope(owner), current: () => this.guestStillAdmitted(admitted),
|
|
21156
|
+
// #1920 §5.2: its own Telegram private room shows it everything; the kept messages place ticks and buttons.
|
|
21157
|
+
ownRoom: (instance) => this.guestOwnRoom(owner, instance),
|
|
21158
|
+
// §3.2: a stream that connects reads its rooms again (in the background; at most once a minute).
|
|
21159
|
+
streamOpened: () => { void this.refreshGuestRooms(owner, { mode: "force" }); },
|
|
21160
|
+
history: () => this.webChatHistory,
|
|
21161
|
+
// #1920 §5.1: guests chat unless the host made them read-only (web.guests.chat: false).
|
|
21162
|
+
chat: () => this.fleetConfig?.web?.guests?.chat !== false });
|
|
21163
|
+
}
|
|
19549
21164
|
}
|
|
19550
21165
|
if (req.method === "GET" && req.url === "/health") {
|
|
19551
21166
|
const health = this.getFleetHealth();
|
|
@@ -19936,6 +21551,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19936
21551
|
this.logger.warn({ code: err.code, port: settings.port }, "Preview listener unavailable; HTML previews are off");
|
|
19937
21552
|
this.previewListening = false;
|
|
19938
21553
|
this.previewListener = null;
|
|
21554
|
+
this.previewListenError = `${settings.port}: ${err.code ?? err.message}`;
|
|
19939
21555
|
});
|
|
19940
21556
|
// An optional listener never takes the fleet down: a port Node refuses outright throws here, synchronously.
|
|
19941
21557
|
try {
|
|
@@ -19946,6 +21562,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19946
21562
|
this.logger.warn({ err: err.message, port: settings.port }, "Preview listener cannot listen; HTML previews are off");
|
|
19947
21563
|
this.previewListening = false;
|
|
19948
21564
|
this.previewListener = null;
|
|
21565
|
+
this.previewListenError = `${settings.port}: ${err.code ?? err.message}`;
|
|
19949
21566
|
}
|
|
19950
21567
|
}
|
|
19951
21568
|
/** What a reload may change hot: web.preview, and the dashboard names (the shim's allow-list and frame-ancestors). */
|
|
@@ -19966,6 +21583,7 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19966
21583
|
}
|
|
19967
21584
|
stopPreviewListener() {
|
|
19968
21585
|
this.previewListening = false;
|
|
21586
|
+
this.previewListenError = null;
|
|
19969
21587
|
this.previewListener?.close();
|
|
19970
21588
|
this.previewListener = null;
|
|
19971
21589
|
}
|
|
@@ -19973,10 +21591,18 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19973
21591
|
previewForUi(hostHeader, secure) {
|
|
19974
21592
|
const listener = this.previewListening ? this.previewListener : null;
|
|
19975
21593
|
const decided = previewAvailability(listener ? listener.settings : null, hostHeader, secure, listener ? listener.origins : undefined);
|
|
21594
|
+
// Previews are on, but no listener answers: say why — its port could not be opened (the error, never "turned off"),
|
|
21595
|
+
// or it is not listening yet.
|
|
19976
21596
|
if (!listener && this.fleetConfig?.web?.preview !== false)
|
|
19977
|
-
decided
|
|
21597
|
+
Object.assign(decided, this.previewNotListening());
|
|
19978
21598
|
return { ...decided, boot: listener ? listener.bootId : null };
|
|
19979
21599
|
}
|
|
21600
|
+
previewNotListening() {
|
|
21601
|
+
const failed = this.previewListenError;
|
|
21602
|
+
return failed
|
|
21603
|
+
? { code: "listenFailed", detail: failed, reason: `Previews are unavailable: the fleet could not open its preview port (${failed}). Another program may be using it — set web.preview_port, then restart AgEnD.` }
|
|
21604
|
+
: { code: "notListening", reason: "Previews are not available on this fleet right now." };
|
|
21605
|
+
}
|
|
19980
21606
|
/**
|
|
19981
21607
|
* #1723: for one page of the public link (exposure `exposureId`, at `dashboardOrigin`): its own preview tunnel's
|
|
19982
21608
|
* origin once up, "starting" until then, why it failed if it did — or a configured web.preview_origin, used instead.
|
|
@@ -19991,8 +21617,10 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
19991
21617
|
const configured = typeof web?.preview_origin === "string" ? normalizeOrigin(web.preview_origin) : null;
|
|
19992
21618
|
if (configured) {
|
|
19993
21619
|
const listener = this.previewListening ? this.previewListener : null;
|
|
19994
|
-
if (!listener)
|
|
19995
|
-
|
|
21620
|
+
if (!listener) {
|
|
21621
|
+
const why = this.previewNotListening();
|
|
21622
|
+
return off(why.code, why.reason, why.detail ? { detail: why.detail } : {});
|
|
21623
|
+
}
|
|
19996
21624
|
if (!configured.startsWith("https:"))
|
|
19997
21625
|
return off("needHttps", "Previews need an https web.preview_origin when the dashboard is reached over https.");
|
|
19998
21626
|
return { dashboardOrigin, previewOrigin: configured, reason: null, code: null, boot: listener.bootId, frameSrc: `${configured}/frame` };
|
|
@@ -20024,6 +21652,9 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
20024
21652
|
// /api/profiles (resolveInstanceIdentity) — the sidebar groups, searches and labels with it on every page.
|
|
20025
21653
|
const classicRooms = new Map((this.classicChannels?.getAll() ?? []).map(ch => [ch.instanceName, ch]));
|
|
20026
21654
|
const profiles = profileIdentities(this.dataDir);
|
|
21655
|
+
// #1629 r4 §1: the identity card's version per instance (the page reads the card when it moves).
|
|
21656
|
+
const cards = humanCards(this.dataDir);
|
|
21657
|
+
const colors = identityColors(this.dataDir);
|
|
20027
21658
|
// #1630: decorative — whatever goes wrong deciding an avatar never costs the frame (every instance gets its first character).
|
|
20028
21659
|
let bots = { own: new Map(), speaking: new Map() };
|
|
20029
21660
|
try {
|
|
@@ -20083,9 +21714,28 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
20083
21714
|
display_name: identity.display_name || undefined,
|
|
20084
21715
|
avatar: image.avatar,
|
|
20085
21716
|
...(image.accent ? { accent: image.accent } : {}),
|
|
21717
|
+
// #1629: the agent's theme's picture and ring colour, for viewers who show agents' themes.
|
|
21718
|
+
...(image.themeAvatar ? { theme_avatar: image.themeAvatar } : {}),
|
|
21719
|
+
...(image.themeAccent ? { theme_accent: image.themeAccent } : {}),
|
|
21720
|
+
...(() => { try {
|
|
21721
|
+
const v = cardVersion(resolveCard(name, cards.get(name), this.themeStore.get(name).theme.card));
|
|
21722
|
+
return v ? { card_v: v } : {};
|
|
21723
|
+
}
|
|
21724
|
+
catch {
|
|
21725
|
+
return {};
|
|
21726
|
+
} })(),
|
|
21727
|
+
// #2118: only this Chat's placement content; guest projection drops global revisions.
|
|
21728
|
+
effect_chat_v: createHash("sha256").update(JSON.stringify(this.themeStore.get(name).placements.effects)).digest("hex").slice(0, 32),
|
|
21729
|
+
// #1958: the identity colour's tiers (the page resolves them: the agent's only while it shows agents' themes).
|
|
21730
|
+
color: { ...(colors.get(name)?.color ? { person: colors.get(name).color } : {}), ...(image.agentColor ? { agent: image.agentColor } : {}),
|
|
21731
|
+
...(image.roleColor ? { role: image.roleColor } : {}), auto: autoIdentityColor(name) },
|
|
21732
|
+
// #1958 decision 2: where it shows — a person's choice for this instance, the agent's; else the viewer's host default.
|
|
21733
|
+
color_show: { ...(colors.get(name)?.show ? { person: colors.get(name).show } : {}), ...(image.agentShow ? { agent: image.agentShow } : {}) },
|
|
20086
21734
|
description: identity.description || undefined,
|
|
20087
21735
|
role: identity.role || undefined,
|
|
20088
21736
|
tags: identity.tags,
|
|
21737
|
+
teams: instanceTeams(this.fleetConfig?.teams, name), // #2172: the sidebar groups a team's members under it
|
|
21738
|
+
last_reply: this.webChatHistory.lastAgentReply(name) ?? undefined, // #2179: its last reply to a person (ISO)
|
|
20089
21739
|
status: this.getInstanceStatus(name),
|
|
20090
21740
|
// `state` (presentation: may be awaiting_input) and `execution_state` (working / idle / stuck, or null —
|
|
20091
21741
|
// what the dashboard's activity events carry) come from instancePresentation (#1212).
|
|
@@ -20109,9 +21759,13 @@ Plus the operational skills (fleet-health, instance-lifecycle, scheduling, sessi
|
|
|
20109
21759
|
connections: (this.fleetConfig?.channels ?? (this.fleetConfig?.channel ? [this.fleetConfig.channel] : [])).length,
|
|
20110
21760
|
// #1665: the host preferences' revision — a page that has another re-reads /ui/prefs (no values in this frame).
|
|
20111
21761
|
prefs_rev: this.webPrefs.rev(),
|
|
21762
|
+
// #1629: the themes' revision — the page re-reads GET /ui/themes when it moves.
|
|
21763
|
+
themes_rev: this.themeStore.rev(),
|
|
20112
21764
|
// #1685: host memory pressure while it slows or holds new agents (the dashboard's indicator; macOS elevated is
|
|
20113
21765
|
// shown here rather than in chat). null when normal, unknown or advisory.
|
|
20114
21766
|
host_memory: this.hostMemoryIndicator(),
|
|
21767
|
+
// #2015: the largest processes while it lasts (name, pid, RSS, and whose: an instance, the fleet or tmux).
|
|
21768
|
+
...(this.hostMemoryIndicator() && this.memoryTop ? { host_memory_top: this.memoryTop.processes } : {}),
|
|
20115
21769
|
};
|
|
20116
21770
|
}
|
|
20117
21771
|
}
|